@vkontakte/videoplayer-core 2.0.123-dev.8ba72ee5.0 → 2.0.123-dev.92e9449d.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 +26 -25
- package/es2015.esm.js +23 -22
- package/es2018.cjs.js +25 -24
- package/es2018.esm.js +24 -23
- package/esnext.cjs.js +26 -25
- package/esnext.esm.js +26 -25
- package/evergreen.esm.js +21 -20
- package/package.json +2 -2
- package/types/providers/DashProvider/lib/buffer.d.ts +3 -1
- package/types/providers/DashProvider/lib/player.d.ts +1 -1
- package/types/providers/DashProvider/lib/sourceBufferTaskQueue.d.ts +1 -0
- package/types/utils/buffer/isSourceBufferValid.d.ts +3 -0
- package/types/utils/tuningConfig.d.ts +2 -1
package/es2018.cjs.js
CHANGED
|
@@ -1,72 +1,73 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.123-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.123-dev.92e9449d.0
|
|
3
|
+
* Thu, 26 Dec 2024 14:15:53 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-123/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var mS=Object.create;var Ka=Object.defineProperty;var bS=Object.getOwnPropertyDescriptor;var gS=Object.getOwnPropertyNames;var vS=Object.getPrototypeOf,SS=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),yS=(a,e)=>{for(var t in e)Ka(a,t,{get:e[t],enumerable:!0})},Fl=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of gS(e))!SS.call(a,i)&&i!==t&&Ka(a,i,{get:()=>e[i],enumerable:!(r=bS(e,i))||r.enumerable});return a};var Y=(a,e,t)=>(t=a!=null?mS(vS(a)):{},Fl(e||!a||!a.__esModule?Ka(t,"default",{value:a,enumerable:!0}):t,a)),TS=a=>Fl(Ka({},"__esModule",{value:!0}),a);var le=b((yn,ql)=>{"use strict";var di=function(a){return a&&a.Math===Math&&a};ql.exports=di(typeof globalThis=="object"&&globalThis)||di(typeof window=="object"&&window)||di(typeof self=="object"&&self)||di(typeof global=="object"&&global)||di(typeof yn=="object"&&yn)||function(){return this}()||Function("return this")()});var Te=b((XR,Ul)=>{"use strict";Ul.exports=function(a){try{return!!a()}catch(e){return!0}}});var pi=b((ZR,Hl)=>{"use strict";var IS=Te();Hl.exports=!IS(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Tn=b((e$,Wl)=>{"use strict";var ES=pi(),Ql=Function.prototype,jl=Ql.apply,Gl=Ql.call;Wl.exports=typeof Reflect=="object"&&Reflect.apply||(ES?Gl.bind(jl):function(){return Gl.apply(jl,arguments)})});var fe=b((t$,Kl)=>{"use strict";var Yl=pi(),zl=Function.prototype,In=zl.call,xS=Yl&&zl.bind.bind(In,In);Kl.exports=Yl?xS:function(a){return function(){return In.apply(a,arguments)}}});var ir=b((r$,Xl)=>{"use strict";var Jl=fe(),PS=Jl({}.toString),AS=Jl("".slice);Xl.exports=function(a){return AS(PS(a),8,-1)}});var En=b((i$,Zl)=>{"use strict";var wS=ir(),kS=fe();Zl.exports=function(a){if(wS(a)==="Function")return kS(a)}});var ue=b((a$,ec)=>{"use strict";var xn=typeof document=="object"&&document.all;ec.exports=typeof xn=="undefined"&&xn!==void 0?function(a){return typeof a=="function"||a===xn}:function(a){return typeof a=="function"}});var Oe=b((s$,tc)=>{"use strict";var RS=Te();tc.exports=!RS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ve=b((n$,rc)=>{"use strict";var $S=pi(),Za=Function.prototype.call;rc.exports=$S?Za.bind(Za):function(){return Za.apply(Za,arguments)}});var Pn=b(sc=>{"use strict";var ic={}.propertyIsEnumerable,ac=Object.getOwnPropertyDescriptor,LS=ac&&!ic.call({1:2},1);sc.f=LS?function(e){var t=ac(this,e);return!!t&&t.enumerable}:ic});var hi=b((u$,nc)=>{"use strict";nc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var uc=b((l$,oc)=>{"use strict";var MS=fe(),CS=Te(),DS=ir(),An=Object,OS=MS("".split);oc.exports=CS(function(){return!An("z").propertyIsEnumerable(0)})?function(a){return DS(a)==="String"?OS(a,""):An(a)}:An});var wr=b((c$,lc)=>{"use strict";lc.exports=function(a){return a==null}});var Ft=b((d$,cc)=>{"use strict";var VS=wr(),BS=TypeError;cc.exports=function(a){if(VS(a))throw new BS("Can't call method on "+a);return a}});var ar=b((p$,dc)=>{"use strict";var _S=uc(),NS=Ft();dc.exports=function(a){return _S(NS(a))}});var Be=b((h$,pc)=>{"use strict";var FS=ue();pc.exports=function(a){return typeof a=="object"?a!==null:FS(a)}});var kr=b((f$,hc)=>{"use strict";hc.exports={}});var vt=b((m$,mc)=>{"use strict";var wn=kr(),kn=le(),qS=ue(),fc=function(a){return qS(a)?a:void 0};mc.exports=function(a,e){return arguments.length<2?fc(wn[a])||fc(kn[a]):wn[a]&&wn[a][e]||kn[a]&&kn[a][e]}});var fi=b((b$,bc)=>{"use strict";var US=fe();bc.exports=US({}.isPrototypeOf)});var sr=b((g$,Sc)=>{"use strict";var HS=le(),gc=HS.navigator,vc=gc&&gc.userAgent;Sc.exports=vc?String(vc):""});var $n=b((v$,Pc)=>{"use strict";var xc=le(),Rn=sr(),yc=xc.process,Tc=xc.Deno,Ic=yc&&yc.versions||Tc&&Tc.version,Ec=Ic&&Ic.v8,Ze,es;Ec&&(Ze=Ec.split("."),es=Ze[0]>0&&Ze[0]<4?1:+(Ze[0]+Ze[1]));!es&&Rn&&(Ze=Rn.match(/Edge\/(\d+)/),(!Ze||Ze[1]>=74)&&(Ze=Rn.match(/Chrome\/(\d+)/),Ze&&(es=+Ze[1])));Pc.exports=es});var Ln=b((S$,wc)=>{"use strict";var Ac=$n(),jS=Te(),GS=le(),QS=GS.String;wc.exports=!!Object.getOwnPropertySymbols&&!jS(function(){var a=Symbol("symbol detection");return!QS(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Ac&&Ac<41})});var Mn=b((y$,kc)=>{"use strict";var WS=Ln();kc.exports=WS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Cn=b((T$,Rc)=>{"use strict";var YS=vt(),zS=ue(),KS=fi(),JS=Mn(),XS=Object;Rc.exports=JS?function(a){return typeof a=="symbol"}:function(a){var e=YS("Symbol");return zS(e)&&KS(e.prototype,XS(a))}});var mi=b((I$,$c)=>{"use strict";var ZS=String;$c.exports=function(a){try{return ZS(a)}catch(e){return"Object"}}});var ot=b((E$,Lc)=>{"use strict";var ey=ue(),ty=mi(),ry=TypeError;Lc.exports=function(a){if(ey(a))return a;throw new ry(ty(a)+" is not a function")}});var bi=b((x$,Mc)=>{"use strict";var iy=ot(),ay=wr();Mc.exports=function(a,e){var t=a[e];return ay(t)?void 0:iy(t)}});var Dc=b((P$,Cc)=>{"use strict";var Dn=Ve(),On=ue(),Vn=Be(),sy=TypeError;Cc.exports=function(a,e){var t,r;if(e==="string"&&On(t=a.toString)&&!Vn(r=Dn(t,a))||On(t=a.valueOf)&&!Vn(r=Dn(t,a))||e!=="string"&&On(t=a.toString)&&!Vn(r=Dn(t,a)))return r;throw new sy("Can't convert object to primitive value")}});var et=b((A$,Oc)=>{"use strict";Oc.exports=!0});var _c=b((w$,Bc)=>{"use strict";var Vc=le(),ny=Object.defineProperty;Bc.exports=function(a,e){try{ny(Vc,a,{value:e,configurable:!0,writable:!0})}catch(t){Vc[a]=e}return e}});var gi=b((k$,qc)=>{"use strict";var oy=et(),uy=le(),ly=_c(),Nc="__core-js_shared__",Fc=qc.exports=uy[Nc]||ly(Nc,{});(Fc.versions||(Fc.versions=[])).push({version:"3.38.0",mode:oy?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Bn=b((R$,Hc)=>{"use strict";var Uc=gi();Hc.exports=function(a,e){return Uc[a]||(Uc[a]=e||{})}});var Rr=b(($$,jc)=>{"use strict";var cy=Ft(),dy=Object;jc.exports=function(a){return dy(cy(a))}});var tt=b((L$,Gc)=>{"use strict";var py=fe(),hy=Rr(),fy=py({}.hasOwnProperty);Gc.exports=Object.hasOwn||function(e,t){return fy(hy(e),t)}});var _n=b((M$,Qc)=>{"use strict";var my=fe(),by=0,gy=Math.random(),vy=my(1 .toString);Qc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+vy(++by+gy,36)}});var Ie=b((C$,Yc)=>{"use strict";var Sy=le(),yy=Bn(),Wc=tt(),Ty=_n(),Iy=Ln(),Ey=Mn(),$r=Sy.Symbol,Nn=yy("wks"),xy=Ey?$r.for||$r:$r&&$r.withoutSetter||Ty;Yc.exports=function(a){return Wc(Nn,a)||(Nn[a]=Iy&&Wc($r,a)?$r[a]:xy("Symbol."+a)),Nn[a]}});var Xc=b((D$,Jc)=>{"use strict";var Py=Ve(),zc=Be(),Kc=Cn(),Ay=bi(),wy=Dc(),ky=Ie(),Ry=TypeError,$y=ky("toPrimitive");Jc.exports=function(a,e){if(!zc(a)||Kc(a))return a;var t=Ay(a,$y),r;if(t){if(e===void 0&&(e="default"),r=Py(t,a,e),!zc(r)||Kc(r))return r;throw new Ry("Can't convert object to primitive value")}return e===void 0&&(e="number"),wy(a,e)}});var Fn=b((O$,Zc)=>{"use strict";var Ly=Xc(),My=Cn();Zc.exports=function(a){var e=Ly(a,"string");return My(e)?e:e+""}});var ts=b((V$,td)=>{"use strict";var Cy=le(),ed=Be(),qn=Cy.document,Dy=ed(qn)&&ed(qn.createElement);td.exports=function(a){return Dy?qn.createElement(a):{}}});var Un=b((B$,rd)=>{"use strict";var Oy=Oe(),Vy=Te(),By=ts();rd.exports=!Oy&&!Vy(function(){return Object.defineProperty(By("div"),"a",{get:function(){return 7}}).a!==7})});var sd=b(ad=>{"use strict";var _y=Oe(),Ny=Ve(),Fy=Pn(),qy=hi(),Uy=ar(),Hy=Fn(),jy=tt(),Gy=Un(),id=Object.getOwnPropertyDescriptor;ad.f=_y?id:function(e,t){if(e=Uy(e),t=Hy(t),Gy)try{return id(e,t)}catch(r){}if(jy(e,t))return qy(!Ny(Fy.f,e,t),e[t])}});var Hn=b((N$,nd)=>{"use strict";var Qy=Te(),Wy=ue(),Yy=/#|\.prototype\./,vi=function(a,e){var t=Ky[zy(a)];return t===Xy?!0:t===Jy?!1:Wy(e)?Qy(e):!!e},zy=vi.normalize=function(a){return String(a).replace(Yy,".").toLowerCase()},Ky=vi.data={},Jy=vi.NATIVE="N",Xy=vi.POLYFILL="P";nd.exports=vi});var Lr=b((F$,ud)=>{"use strict";var od=En(),Zy=ot(),eT=pi(),tT=od(od.bind);ud.exports=function(a,e){return Zy(a),e===void 0?a:eT?tT(a,e):function(){return a.apply(e,arguments)}}});var jn=b((q$,ld)=>{"use strict";var rT=Oe(),iT=Te();ld.exports=rT&&iT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ut=b((U$,cd)=>{"use strict";var aT=Be(),sT=String,nT=TypeError;cd.exports=function(a){if(aT(a))return a;throw new nT(sT(a)+" is not an object")}});var nr=b(pd=>{"use strict";var oT=Oe(),uT=Un(),lT=jn(),rs=ut(),dd=Fn(),cT=TypeError,Gn=Object.defineProperty,dT=Object.getOwnPropertyDescriptor,Qn="enumerable",Wn="configurable",Yn="writable";pd.f=oT?lT?function(e,t,r){if(rs(e),t=dd(t),rs(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Yn in r&&!r[Yn]){var i=dT(e,t);i&&i[Yn]&&(e[t]=r.value,r={configurable:Wn in r?r[Wn]:i[Wn],enumerable:Qn in r?r[Qn]:i[Qn],writable:!1})}return Gn(e,t,r)}:Gn:function(e,t,r){if(rs(e),t=dd(t),rs(r),uT)try{return Gn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new cT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Mr=b((j$,hd)=>{"use strict";var pT=Oe(),hT=nr(),fT=hi();hd.exports=pT?function(a,e,t){return hT.f(a,e,fT(1,t))}:function(a,e,t){return a[e]=t,a}});var de=b((G$,md)=>{"use strict";var Si=le(),mT=Tn(),bT=En(),gT=ue(),vT=sd().f,ST=Hn(),Cr=kr(),yT=Lr(),Dr=Mr(),fd=tt();gi();var TT=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return mT(a,this,arguments)};return e.prototype=a.prototype,e};md.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Si:i?Si[t]:Si[t]&&Si[t].prototype,o=r?Cr:Cr[t]||Dr(Cr,t,{})[t],u=o.prototype,l,c,d,h,p,m,g,v,T;for(h in e)l=ST(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&fd(n,h),m=o[h],c&&(a.dontCallGetSet?(T=vT(n,h),g=T&&T.value):g=n[h]),p=c&&g?g:e[h],!(!l&&!s&&typeof m==typeof p)&&(a.bind&&c?v=yT(p,Si):a.wrap&&c?v=TT(p):s&&gT(p)?v=bT(p):v=p,(a.sham||p&&p.sham||m&&m.sham)&&Dr(v,"sham",!0),Dr(o,h,v),s&&(d=t+"Prototype",fd(Cr,d)||Dr(Cr,d,{}),Dr(Cr[d],h,p),a.real&&u&&(l||!u[h])&&Dr(u,h,p)))}});var gd=b((Q$,bd)=>{"use strict";var IT=Math.ceil,ET=Math.floor;bd.exports=Math.trunc||function(e){var t=+e;return(t>0?ET:IT)(t)}});var yi=b((W$,vd)=>{"use strict";var xT=gd();vd.exports=function(a){var e=+a;return e!==e||e===0?0:xT(e)}});var yd=b((Y$,Sd)=>{"use strict";var PT=yi(),AT=Math.max,wT=Math.min;Sd.exports=function(a,e){var t=PT(a);return t<0?AT(t+e,0):wT(t,e)}});var zn=b((z$,Td)=>{"use strict";var kT=yi(),RT=Math.min;Td.exports=function(a){var e=kT(a);return e>0?RT(e,9007199254740991):0}});var Or=b((K$,Id)=>{"use strict";var $T=zn();Id.exports=function(a){return $T(a.length)}});var Kn=b((J$,xd)=>{"use strict";var LT=ar(),MT=yd(),CT=Or(),Ed=function(a){return function(e,t,r){var i=LT(e),s=CT(i);if(s===0)return!a&&-1;var n=MT(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};xd.exports={includes:Ed(!0),indexOf:Ed(!1)}});var Ti=b((X$,Pd)=>{"use strict";Pd.exports=function(){}});var Ad=b(()=>{"use strict";var DT=de(),OT=Kn().includes,VT=Te(),BT=Ti(),_T=VT(function(){return!Array(1).includes()});DT({target:"Array",proto:!0,forced:_T},{includes:function(e){return OT(this,e,arguments.length>1?arguments[1]:void 0)}});BT("includes")});var qt=b((tL,wd)=>{"use strict";var NT=vt();wd.exports=NT});var Rd=b((rL,kd)=>{"use strict";Ad();var FT=qt();kd.exports=FT("Array","includes")});var Ld=b((iL,$d)=>{"use strict";var qT=Rd();$d.exports=qT});var lt=b((aL,Md)=>{"use strict";var UT=Ld();Md.exports=UT});var as=b((mL,Od)=>{"use strict";var jT=Bn(),GT=_n(),Dd=jT("keys");Od.exports=function(a){return Dd[a]||(Dd[a]=GT(a))}});var Bd=b((bL,Vd)=>{"use strict";var QT=Te();Vd.exports=!QT(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ss=b((gL,Nd)=>{"use strict";var WT=tt(),YT=ue(),zT=Rr(),KT=as(),JT=Bd(),_d=KT("IE_PROTO"),Jn=Object,XT=Jn.prototype;Nd.exports=JT?Jn.getPrototypeOf:function(a){var e=zT(a);if(WT(e,_d))return e[_d];var t=e.constructor;return YT(t)&&e instanceof t?t.prototype:e instanceof Jn?XT:null}});var ns=b((vL,Fd)=>{"use strict";Fd.exports={}});var Hd=b((SL,Ud)=>{"use strict";var ZT=fe(),Xn=tt(),eI=ar(),tI=Kn().indexOf,rI=ns(),qd=ZT([].push);Ud.exports=function(a,e){var t=eI(a),r=0,i=[],s;for(s in t)!Xn(rI,s)&&Xn(t,s)&&qd(i,s);for(;e.length>r;)Xn(t,s=e[r++])&&(~tI(i,s)||qd(i,s));return i}});var Zn=b((yL,jd)=>{"use strict";jd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var eo=b((TL,Gd)=>{"use strict";var iI=Hd(),aI=Zn();Gd.exports=Object.keys||function(e){return iI(e,aI)}});var to=b((IL,Kd)=>{"use strict";var Wd=Oe(),sI=Te(),Yd=fe(),nI=ss(),oI=eo(),uI=ar(),lI=Pn().f,zd=Yd(lI),cI=Yd([].push),dI=Wd&&sI(function(){var a=Object.create(null);return a[2]=2,!zd(a,2)}),Qd=function(a){return function(e){for(var t=uI(e),r=oI(t),i=dI&&nI(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Wd||(i?u in t:zd(t,u)))&&cI(o,a?[u,t[u]]:t[u]);return o}};Kd.exports={entries:Qd(!0),values:Qd(!1)}});var Jd=b(()=>{"use strict";var pI=de(),hI=to().entries;pI({target:"Object",stat:!0},{entries:function(e){return hI(e)}})});var Zd=b((PL,Xd)=>{"use strict";Jd();var fI=kr();Xd.exports=fI.Object.entries});var tp=b((AL,ep)=>{"use strict";var mI=Zd();ep.exports=mI});var Vr=b((wL,rp)=>{"use strict";var bI=tp();rp.exports=bI});var or=b((kL,ip)=>{"use strict";ip.exports={}});var np=b((RL,sp)=>{"use strict";var gI=le(),vI=ue(),ap=gI.WeakMap;sp.exports=vI(ap)&&/native code/.test(String(ap))});var so=b(($L,lp)=>{"use strict";var SI=np(),up=le(),yI=Be(),TI=Mr(),ro=tt(),io=gi(),II=as(),EI=ns(),op="Object already initialized",ao=up.TypeError,xI=up.WeakMap,os,Ii,us,PI=function(a){return us(a)?Ii(a):os(a,{})},AI=function(a){return function(e){var t;if(!yI(e)||(t=Ii(e)).type!==a)throw new ao("Incompatible receiver, "+a+" required");return t}};SI||io.state?(rt=io.state||(io.state=new xI),rt.get=rt.get,rt.has=rt.has,rt.set=rt.set,os=function(a,e){if(rt.has(a))throw new ao(op);return e.facade=a,rt.set(a,e),e},Ii=function(a){return rt.get(a)||{}},us=function(a){return rt.has(a)}):(ur=II("state"),EI[ur]=!0,os=function(a,e){if(ro(a,ur))throw new ao(op);return e.facade=a,TI(a,ur,e),e},Ii=function(a){return ro(a,ur)?a[ur]:{}},us=function(a){return ro(a,ur)});var rt,ur;lp.exports={set:os,get:Ii,has:us,enforce:PI,getterFor:AI}});var uo=b((LL,dp)=>{"use strict";var no=Oe(),wI=tt(),cp=Function.prototype,kI=no&&Object.getOwnPropertyDescriptor,oo=wI(cp,"name"),RI=oo&&function(){}.name==="something",$I=oo&&(!no||no&&kI(cp,"name").configurable);dp.exports={EXISTS:oo,PROPER:RI,CONFIGURABLE:$I}});var hp=b(pp=>{"use strict";var LI=Oe(),MI=jn(),CI=nr(),DI=ut(),OI=ar(),VI=eo();pp.f=LI&&!MI?Object.defineProperties:function(e,t){DI(e);for(var r=OI(t),i=VI(t),s=i.length,n=0,o;s>n;)CI.f(e,o=i[n++],r[o]);return e}});var lo=b((CL,fp)=>{"use strict";var BI=vt();fp.exports=BI("document","documentElement")});var fo=b((DL,Tp)=>{"use strict";var _I=ut(),NI=hp(),mp=Zn(),FI=ns(),qI=lo(),UI=ts(),HI=as(),bp=">",gp="<",po="prototype",ho="script",Sp=HI("IE_PROTO"),co=function(){},yp=function(a){return gp+ho+bp+a+gp+"/"+ho+bp},vp=function(a){a.write(yp("")),a.close();var e=a.parentWindow.Object;return a=null,e},jI=function(){var a=UI("iframe"),e="java"+ho+":",t;return a.style.display="none",qI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(yp("document.F=Object")),t.close(),t.F},ls,cs=function(){try{ls=new ActiveXObject("htmlfile")}catch(e){}cs=typeof document!="undefined"?document.domain&&ls?vp(ls):jI():vp(ls);for(var a=mp.length;a--;)delete cs[po][mp[a]];return cs()};FI[Sp]=!0;Tp.exports=Object.create||function(e,t){var r;return e!==null?(co[po]=_I(e),r=new co,co[po]=null,r[Sp]=e):r=cs(),t===void 0?r:NI.f(r,t)}});var Br=b((OL,Ip)=>{"use strict";var GI=Mr();Ip.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:GI(a,e,t),a}});var vo=b((VL,Pp)=>{"use strict";var QI=Te(),WI=ue(),YI=Be(),zI=fo(),Ep=ss(),KI=Br(),JI=Ie(),XI=et(),go=JI("iterator"),xp=!1,St,mo,bo;[].keys&&(bo=[].keys(),"next"in bo?(mo=Ep(Ep(bo)),mo!==Object.prototype&&(St=mo)):xp=!0);var ZI=!YI(St)||QI(function(){var a={};return St[go].call(a)!==a});ZI?St={}:XI&&(St=zI(St));WI(St[go])||KI(St,go,function(){return this});Pp.exports={IteratorPrototype:St,BUGGY_SAFARI_ITERATORS:xp}});var ds=b((BL,wp)=>{"use strict";var eE=Ie(),tE=eE("toStringTag"),Ap={};Ap[tE]="z";wp.exports=String(Ap)==="[object z]"});var Ei=b((_L,kp)=>{"use strict";var rE=ds(),iE=ue(),ps=ir(),aE=Ie(),sE=aE("toStringTag"),nE=Object,oE=ps(function(){return arguments}())==="Arguments",uE=function(a,e){try{return a[e]}catch(t){}};kp.exports=rE?ps:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=uE(e=nE(a),sE))=="string"?t:oE?ps(e):(r=ps(e))==="Object"&&iE(e.callee)?"Arguments":r}});var $p=b((NL,Rp)=>{"use strict";var lE=ds(),cE=Ei();Rp.exports=lE?{}.toString:function(){return"[object "+cE(this)+"]"}});var xi=b((FL,Mp)=>{"use strict";var dE=ds(),pE=nr().f,hE=Mr(),fE=tt(),mE=$p(),bE=Ie(),Lp=bE("toStringTag");Mp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(fE(i,Lp)||pE(i,Lp,{configurable:!0,value:e}),r&&!dE&&hE(i,"toString",mE))}});var Dp=b((qL,Cp)=>{"use strict";var gE=vo().IteratorPrototype,vE=fo(),SE=hi(),yE=xi(),TE=or(),IE=function(){return this};Cp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=vE(gE,{next:SE(+!r,t)}),yE(a,i,!1,!0),TE[i]=IE,a}});var Vp=b((UL,Op)=>{"use strict";var EE=fe(),xE=ot();Op.exports=function(a,e,t){try{return EE(xE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var _p=b((HL,Bp)=>{"use strict";var PE=Be();Bp.exports=function(a){return PE(a)||a===null}});var Fp=b((jL,Np)=>{"use strict";var AE=_p(),wE=String,kE=TypeError;Np.exports=function(a){if(AE(a))return a;throw new kE("Can't set "+wE(a)+" as a prototype")}});var So=b((GL,qp)=>{"use strict";var RE=Vp(),$E=Be(),LE=Ft(),ME=Fp();qp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=RE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return LE(i),ME(s),$E(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Xp=b((QL,Jp)=>{"use strict";var CE=de(),DE=Ve(),hs=et(),zp=uo(),OE=ue(),VE=Dp(),Up=ss(),Hp=So(),BE=xi(),_E=Mr(),yo=Br(),NE=Ie(),jp=or(),Kp=vo(),FE=zp.PROPER,qE=zp.CONFIGURABLE,Gp=Kp.IteratorPrototype,fs=Kp.BUGGY_SAFARI_ITERATORS,Pi=NE("iterator"),Qp="keys",Ai="values",Wp="entries",Yp=function(){return this};Jp.exports=function(a,e,t,r,i,s,n){VE(t,e,r);var o=function(T){if(T===i&&h)return h;if(!fs&&T&&T in c)return c[T];switch(T){case Qp:return function(){return new t(this,T)};case Ai:return function(){return new t(this,T)};case Wp:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Pi]||c["@@iterator"]||i&&c[i],h=!fs&&d||o(i),p=e==="Array"&&c.entries||d,m,g,v;if(p&&(m=Up(p.call(new a)),m!==Object.prototype&&m.next&&(!hs&&Up(m)!==Gp&&(Hp?Hp(m,Gp):OE(m[Pi])||yo(m,Pi,Yp)),BE(m,u,!0,!0),hs&&(jp[u]=Yp))),FE&&i===Ai&&d&&d.name!==Ai&&(!hs&&qE?_E(c,"name",Ai):(l=!0,h=function(){return DE(d,this)})),i)if(g={values:o(Ai),keys:s?h:o(Qp),entries:o(Wp)},n)for(v in g)(fs||l||!(v in c))&&yo(c,v,g[v]);else CE({target:e,proto:!0,forced:fs||l},g);return(!hs||n)&&c[Pi]!==h&&yo(c,Pi,h,{name:i}),jp[e]=h,g}});var eh=b((WL,Zp)=>{"use strict";Zp.exports=function(a,e){return{value:a,done:e}}});var Io=b((YL,sh)=>{"use strict";var UE=ar(),To=Ti(),th=or(),ih=so(),HE=nr().f,jE=Xp(),ms=eh(),GE=et(),QE=Oe(),ah="Array Iterator",WE=ih.set,YE=ih.getterFor(ah);sh.exports=jE(Array,"Array",function(a,e){WE(this,{type:ah,target:UE(a),index:0,kind:e})},function(){var a=YE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ms(void 0,!0);switch(a.kind){case"keys":return ms(t,!1);case"values":return ms(e[t],!1)}return ms([t,e[t]],!1)},"values");var rh=th.Arguments=th.Array;To("keys");To("values");To("entries");if(!GE&&QE&&rh.name!=="values")try{HE(rh,"name",{value:"values"})}catch(a){}});var oh=b((zL,nh)=>{"use strict";var zE=Ie(),KE=or(),JE=zE("iterator"),XE=Array.prototype;nh.exports=function(a){return a!==void 0&&(KE.Array===a||XE[JE]===a)}});var Eo=b((KL,lh)=>{"use strict";var ZE=Ei(),uh=bi(),ex=wr(),tx=or(),rx=Ie(),ix=rx("iterator");lh.exports=function(a){if(!ex(a))return uh(a,ix)||uh(a,"@@iterator")||tx[ZE(a)]}});var dh=b((JL,ch)=>{"use strict";var ax=Ve(),sx=ot(),nx=ut(),ox=mi(),ux=Eo(),lx=TypeError;ch.exports=function(a,e){var t=arguments.length<2?ux(a):e;if(sx(t))return nx(ax(t,a));throw new lx(ox(a)+" is not iterable")}});var fh=b((XL,hh)=>{"use strict";var cx=Ve(),ph=ut(),dx=bi();hh.exports=function(a,e,t){var r,i;ph(a);try{if(r=dx(a,"return"),!r){if(e==="throw")throw t;return t}r=cx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return ph(r),t}});var gs=b((ZL,vh)=>{"use strict";var px=Lr(),hx=Ve(),fx=ut(),mx=mi(),bx=oh(),gx=Or(),mh=fi(),vx=dh(),Sx=Eo(),bh=fh(),yx=TypeError,bs=function(a,e){this.stopped=a,this.result=e},gh=bs.prototype;vh.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=px(e,r),l,c,d,h,p,m,g,v=function(E){return l&&bh(l,"normal",E),new bs(!0,E)},T=function(E){return i?(fx(E),o?u(E[0],E[1],v):u(E[0],E[1])):o?u(E,v):u(E)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Sx(a),!c)throw new yx(mx(a)+" is not iterable");if(bx(c)){for(d=0,h=gx(a);h>d;d++)if(p=T(a[d]),p&&mh(gh,p))return p;return new bs(!1)}l=vx(a,c)}for(m=s?a.next:l.next;!(g=hx(m,l)).done;){try{p=T(g.value)}catch(E){bh(l,"throw",E)}if(typeof p=="object"&&p&&mh(gh,p))return p}return new bs(!1)}});var yh=b((eM,Sh)=>{"use strict";var Tx=Oe(),Ix=nr(),Ex=hi();Sh.exports=function(a,e,t){Tx?Ix.f(a,e,Ex(0,t)):a[e]=t}});var Th=b(()=>{"use strict";var xx=de(),Px=gs(),Ax=yh();xx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Px(e,function(r,i){Ax(t,r,i)},{AS_ENTRIES:!0}),t}})});var Eh=b((iM,Ih)=>{"use strict";Io();Th();var wx=kr();Ih.exports=wx.Object.fromEntries});var Ph=b((aM,xh)=>{"use strict";xh.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 wh=b(()=>{"use strict";Io();var kx=Ph(),Rx=le(),$x=xi(),Ah=or();for(vs in kx)$x(Rx[vs],vs),Ah[vs]=Ah.Array;var vs});var Rh=b((oM,kh)=>{"use strict";var Lx=Eh();wh();kh.exports=Lx});var xo=b((uM,$h)=>{"use strict";var Mx=Rh();$h.exports=Mx});var Lh=b(()=>{"use strict"});var Po=b((dM,Mh)=>{"use strict";var wi=le(),Cx=sr(),Dx=ir(),Ss=function(a){return Cx.slice(0,a.length)===a};Mh.exports=function(){return Ss("Bun/")?"BUN":Ss("Cloudflare-Workers")?"CLOUDFLARE":Ss("Deno/")?"DENO":Ss("Node.js/")?"NODE":wi.Bun&&typeof Bun.version=="string"?"BUN":wi.Deno&&typeof Deno.version=="object"?"DENO":Dx(wi.process)==="process"?"NODE":wi.window&&wi.document?"BROWSER":"REST"}()});var ys=b((pM,Ch)=>{"use strict";var Ox=Po();Ch.exports=Ox==="NODE"});var Oh=b((hM,Dh)=>{"use strict";var Vx=nr();Dh.exports=function(a,e,t){return Vx.f(a,e,t)}});var _h=b((fM,Bh)=>{"use strict";var Bx=vt(),_x=Oh(),Nx=Ie(),Fx=Oe(),Vh=Nx("species");Bh.exports=function(a){var e=Bx(a);Fx&&e&&!e[Vh]&&_x(e,Vh,{configurable:!0,get:function(){return this}})}});var Fh=b((mM,Nh)=>{"use strict";var qx=fi(),Ux=TypeError;Nh.exports=function(a,e){if(qx(e,a))return a;throw new Ux("Incorrect invocation")}});var wo=b((bM,qh)=>{"use strict";var Hx=fe(),jx=ue(),Ao=gi(),Gx=Hx(Function.toString);jx(Ao.inspectSource)||(Ao.inspectSource=function(a){return Gx(a)});qh.exports=Ao.inspectSource});var Ro=b((gM,Qh)=>{"use strict";var Qx=fe(),Wx=Te(),Uh=ue(),Yx=Ei(),zx=vt(),Kx=wo(),Hh=function(){},jh=zx("Reflect","construct"),ko=/^\s*(?:class|function)\b/,Jx=Qx(ko.exec),Xx=!ko.test(Hh),ki=function(e){if(!Uh(e))return!1;try{return jh(Hh,[],e),!0}catch(t){return!1}},Gh=function(e){if(!Uh(e))return!1;switch(Yx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Xx||!!Jx(ko,Kx(e))}catch(t){return!0}};Gh.sham=!0;Qh.exports=!jh||Wx(function(){var a;return ki(ki.call)||!ki(Object)||!ki(function(){a=!0})||a})?Gh:ki});var Yh=b((vM,Wh)=>{"use strict";var Zx=Ro(),eP=mi(),tP=TypeError;Wh.exports=function(a){if(Zx(a))return a;throw new tP(eP(a)+" is not a constructor")}});var $o=b((SM,Kh)=>{"use strict";var zh=ut(),rP=Yh(),iP=wr(),aP=Ie(),sP=aP("species");Kh.exports=function(a,e){var t=zh(a).constructor,r;return t===void 0||iP(r=zh(t)[sP])?e:rP(r)}});var Xh=b((yM,Jh)=>{"use strict";var nP=fe();Jh.exports=nP([].slice)});var ef=b((TM,Zh)=>{"use strict";var oP=TypeError;Zh.exports=function(a,e){if(a<e)throw new oP("Not enough arguments");return a}});var Lo=b((IM,tf)=>{"use strict";var uP=sr();tf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(uP)});var Fo=b((EM,df)=>{"use strict";var _e=le(),lP=Tn(),cP=Lr(),rf=ue(),dP=tt(),cf=Te(),af=lo(),pP=Xh(),sf=ts(),hP=ef(),fP=Lo(),mP=ys(),Bo=_e.setImmediate,_o=_e.clearImmediate,bP=_e.process,Mo=_e.Dispatch,gP=_e.Function,nf=_e.MessageChannel,vP=_e.String,Co=0,Ri={},of="onreadystatechange",$i,lr,Do,Oo;cf(function(){$i=_e.location});var No=function(a){if(dP(Ri,a)){var e=Ri[a];delete Ri[a],e()}},Vo=function(a){return function(){No(a)}},uf=function(a){No(a.data)},lf=function(a){_e.postMessage(vP(a),$i.protocol+"//"+$i.host)};(!Bo||!_o)&&(Bo=function(e){hP(arguments.length,1);var t=rf(e)?e:gP(e),r=pP(arguments,1);return Ri[++Co]=function(){lP(t,void 0,r)},lr(Co),Co},_o=function(e){delete Ri[e]},mP?lr=function(a){bP.nextTick(Vo(a))}:Mo&&Mo.now?lr=function(a){Mo.now(Vo(a))}:nf&&!fP?(Do=new nf,Oo=Do.port2,Do.port1.onmessage=uf,lr=cP(Oo.postMessage,Oo)):_e.addEventListener&&rf(_e.postMessage)&&!_e.importScripts&&$i&&$i.protocol!=="file:"&&!cf(lf)?(lr=lf,_e.addEventListener("message",uf,!1)):of in sf("script")?lr=function(a){af.appendChild(sf("script"))[of]=function(){af.removeChild(this),No(a)}}:lr=function(a){setTimeout(Vo(a),0)});df.exports={set:Bo,clear:_o}});var ff=b((xM,hf)=>{"use strict";var pf=le(),SP=Oe(),yP=Object.getOwnPropertyDescriptor;hf.exports=function(a){if(!SP)return pf[a];var e=yP(pf,a);return e&&e.value}});var qo=b((PM,bf)=>{"use strict";var mf=function(){this.head=null,this.tail=null};mf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};bf.exports=mf});var vf=b((AM,gf)=>{"use strict";var TP=sr();gf.exports=/ipad|iphone|ipod/i.test(TP)&&typeof Pebble!="undefined"});var yf=b((wM,Sf)=>{"use strict";var IP=sr();Sf.exports=/web0s(?!.*chrome)/i.test(IP)});var wf=b((kM,Af)=>{"use strict";var Nr=le(),EP=ff(),Tf=Lr(),Uo=Fo().set,xP=qo(),PP=Lo(),AP=vf(),wP=yf(),Ho=ys(),If=Nr.MutationObserver||Nr.WebKitMutationObserver,Ef=Nr.document,xf=Nr.process,Ts=Nr.Promise,Qo=EP("queueMicrotask"),_r,jo,Go,Is,Pf;Qo||(Li=new xP,Mi=function(){var a,e;for(Ho&&(a=xf.domain)&&a.exit();e=Li.get();)try{e()}catch(t){throw Li.head&&_r(),t}a&&a.enter()},!PP&&!Ho&&!wP&&If&&Ef?(jo=!0,Go=Ef.createTextNode(""),new If(Mi).observe(Go,{characterData:!0}),_r=function(){Go.data=jo=!jo}):!AP&&Ts&&Ts.resolve?(Is=Ts.resolve(void 0),Is.constructor=Ts,Pf=Tf(Is.then,Is),_r=function(){Pf(Mi)}):Ho?_r=function(){xf.nextTick(Mi)}:(Uo=Tf(Uo,Nr),_r=function(){Uo(Mi)}),Qo=function(a){Li.head||_r(),Li.add(a)});var Li,Mi;Af.exports=Qo});var Rf=b((RM,kf)=>{"use strict";kf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Es=b(($M,$f)=>{"use strict";$f.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var cr=b((LM,Lf)=>{"use strict";var kP=le();Lf.exports=kP.Promise});var Fr=b((MM,Of)=>{"use strict";var RP=le(),Ci=cr(),$P=ue(),LP=Hn(),MP=wo(),CP=Ie(),Mf=Po(),DP=et(),Wo=$n(),Cf=Ci&&Ci.prototype,OP=CP("species"),Yo=!1,Df=$P(RP.PromiseRejectionEvent),VP=LP("Promise",function(){var a=MP(Ci),e=a!==String(Ci);if(!e&&Wo===66||DP&&!(Cf.catch&&Cf.finally))return!0;if(!Wo||Wo<51||!/native code/.test(a)){var t=new Ci(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[OP]=r,Yo=t.then(function(){})instanceof r,!Yo)return!0}return!e&&(Mf==="BROWSER"||Mf==="DENO")&&!Df});Of.exports={CONSTRUCTOR:VP,REJECTION_EVENT:Df,SUBCLASSING:Yo}});var qr=b((CM,Bf)=>{"use strict";var Vf=ot(),BP=TypeError,_P=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new BP("Bad Promise constructor");e=r,t=i}),this.resolve=Vf(e),this.reject=Vf(t)};Bf.exports.f=function(a){return new _P(a)}});var rm=b(()=>{"use strict";var NP=de(),FP=et(),ws=ys(),Ut=le(),Gr=Ve(),_f=Br(),Nf=So(),qP=xi(),UP=_h(),HP=ot(),As=ue(),jP=Be(),GP=Fh(),QP=$o(),jf=Fo().set,Zo=wf(),WP=Rf(),YP=Es(),zP=qo(),Gf=so(),ks=cr(),eu=Fr(),Qf=qr(),Rs="Promise",Wf=eu.CONSTRUCTOR,KP=eu.REJECTION_EVENT,JP=eu.SUBCLASSING,zo=Gf.getterFor(Rs),XP=Gf.set,Ur=ks&&ks.prototype,dr=ks,xs=Ur,Yf=Ut.TypeError,Ko=Ut.document,tu=Ut.process,Jo=Qf.f,ZP=Jo,eA=!!(Ko&&Ko.createEvent&&Ut.dispatchEvent),zf="unhandledrejection",tA="rejectionhandled",Ff=0,Kf=1,rA=2,ru=1,Jf=2,Ps,qf,iA,Uf,Xf=function(a){var e;return jP(a)&&As(e=a.then)?e:!1},Zf=function(a,e){var t=e.value,r=e.state===Kf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Jf&&sA(e),e.rejection=ru),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Yf("Promise-chain cycle")):(l=Xf(u))?Gr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},em=function(a,e){a.notified||(a.notified=!0,Zo(function(){for(var t=a.reactions,r;r=t.get();)Zf(r,a);a.notified=!1,e&&!a.rejection&&aA(a)}))},tm=function(a,e,t){var r,i;eA?(r=Ko.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Ut.dispatchEvent(r)):r={promise:e,reason:t},!KP&&(i=Ut["on"+a])?i(r):a===zf&&WP("Unhandled promise rejection",t)},aA=function(a){Gr(jf,Ut,function(){var e=a.facade,t=a.value,r=Hf(a),i;if(r&&(i=YP(function(){ws?tu.emit("unhandledRejection",t,e):tm(zf,e,t)}),a.rejection=ws||Hf(a)?Jf:ru,i.error))throw i.value})},Hf=function(a){return a.rejection!==ru&&!a.parent},sA=function(a){Gr(jf,Ut,function(){var e=a.facade;ws?tu.emit("rejectionHandled",e):tm(tA,e,a.value)})},Hr=function(a,e,t){return function(r){a(e,r,t)}},jr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=rA,em(a,!0))},Xo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Yf("Promise can't be resolved itself");var r=Xf(e);r?Zo(function(){var i={done:!1};try{Gr(r,e,Hr(Xo,i,a),Hr(jr,i,a))}catch(s){jr(i,s,a)}}):(a.value=e,a.state=Kf,em(a,!1))}catch(i){jr({done:!1},i,a)}}};if(Wf&&(dr=function(e){GP(this,xs),HP(e),Gr(Ps,this);var t=zo(this);try{e(Hr(Xo,t),Hr(jr,t))}catch(r){jr(t,r)}},xs=dr.prototype,Ps=function(e){XP(this,{type:Rs,done:!1,notified:!1,parent:!1,reactions:new zP,rejection:!1,state:Ff,value:void 0})},Ps.prototype=_f(xs,"then",function(e,t){var r=zo(this),i=Jo(QP(this,dr));return r.parent=!0,i.ok=As(e)?e:!0,i.fail=As(t)&&t,i.domain=ws?tu.domain:void 0,r.state===Ff?r.reactions.add(i):Zo(function(){Zf(i,r)}),i.promise}),qf=function(){var a=new Ps,e=zo(a);this.promise=a,this.resolve=Hr(Xo,e),this.reject=Hr(jr,e)},Qf.f=Jo=function(a){return a===dr||a===iA?new qf(a):ZP(a)},!FP&&As(ks)&&Ur!==Object.prototype)){Uf=Ur.then,JP||_f(Ur,"then",function(e,t){var r=this;return new dr(function(i,s){Gr(Uf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Ur.constructor}catch(a){}Nf&&Nf(Ur,xs)}NP({global:!0,constructor:!0,wrap:!0,forced:Wf},{Promise:dr});qP(dr,Rs,!1,!0);UP(Rs)});var om=b((VM,nm)=>{"use strict";var nA=Ie(),am=nA("iterator"),sm=!1;try{im=0,iu={next:function(){return{done:!!im++}},return:function(){sm=!0}},iu[am]=function(){return this},Array.from(iu,function(){throw 2})}catch(a){}var im,iu;nm.exports=function(a,e){try{if(!e&&!sm)return!1}catch(i){return!1}var t=!1;try{var r={};r[am]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var au=b((BM,um)=>{"use strict";var oA=cr(),uA=om(),lA=Fr().CONSTRUCTOR;um.exports=lA||!uA(function(a){oA.all(a).then(void 0,function(){})})});var lm=b(()=>{"use strict";var cA=de(),dA=Ve(),pA=ot(),hA=qr(),fA=Es(),mA=gs(),bA=au();cA({target:"Promise",stat:!0,forced:bA},{all:function(e){var t=this,r=hA.f(t),i=r.resolve,s=r.reject,n=fA(function(){var o=pA(t.resolve),u=[],l=0,c=1;mA(e,function(d){var h=l++,p=!1;c++,dA(o,t,d).then(function(m){p||(p=!0,u[h]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var dm=b(()=>{"use strict";var gA=de(),vA=et(),SA=Fr().CONSTRUCTOR,nu=cr(),yA=vt(),TA=ue(),IA=Br(),cm=nu&&nu.prototype;gA({target:"Promise",proto:!0,forced:SA,real:!0},{catch:function(a){return this.then(void 0,a)}});!vA&&TA(nu)&&(su=yA("Promise").prototype.catch,cm.catch!==su&&IA(cm,"catch",su,{unsafe:!0}));var su});var pm=b(()=>{"use strict";var EA=de(),xA=Ve(),PA=ot(),AA=qr(),wA=Es(),kA=gs(),RA=au();EA({target:"Promise",stat:!0,forced:RA},{race:function(e){var t=this,r=AA.f(t),i=r.reject,s=wA(function(){var n=PA(t.resolve);kA(e,function(o){xA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var hm=b(()=>{"use strict";var $A=de(),LA=qr(),MA=Fr().CONSTRUCTOR;$A({target:"Promise",stat:!0,forced:MA},{reject:function(e){var t=LA.f(this),r=t.reject;return r(e),t.promise}})});var ou=b((QM,fm)=>{"use strict";var CA=ut(),DA=Be(),OA=qr();fm.exports=function(a,e){if(CA(a),DA(e)&&e.constructor===a)return e;var t=OA.f(a),r=t.resolve;return r(e),t.promise}});var gm=b(()=>{"use strict";var VA=de(),BA=vt(),mm=et(),_A=cr(),bm=Fr().CONSTRUCTOR,NA=ou(),FA=BA("Promise"),qA=mm&&!bm;VA({target:"Promise",stat:!0,forced:mm||bm},{resolve:function(e){return NA(qA&&this===FA?_A:this,e)}})});var vm=b(()=>{"use strict";rm();lm();dm();pm();hm();gm()});var Im=b(()=>{"use strict";var UA=de(),HA=et(),$s=cr(),jA=Te(),ym=vt(),Tm=ue(),GA=$o(),Sm=ou(),QA=Br(),lu=$s&&$s.prototype,WA=!!$s&&jA(function(){lu.finally.call({then:function(){}},function(){})});UA({target:"Promise",proto:!0,real:!0,forced:WA},{finally:function(a){var e=GA(this,ym("Promise")),t=Tm(a);return this.then(t?function(r){return Sm(e,a()).then(function(){return r})}:a,t?function(r){return Sm(e,a()).then(function(){throw r})}:a)}});!HA&&Tm($s)&&(uu=ym("Promise").prototype.finally,lu.finally!==uu&&QA(lu,"finally",uu,{unsafe:!0}));var uu});var xm=b((ZM,Em)=>{"use strict";Lh();vm();Im();var YA=qt();Em.exports=YA("Promise","finally")});var Am=b((eC,Pm)=>{"use strict";var zA=xm();Pm.exports=zA});var Ls=b((tC,wm)=>{"use strict";var KA=Am();wm.exports=KA});var Dm=b(()=>{"use strict";var tw=de(),rw=to().values;tw({target:"Object",stat:!0},{values:function(e){return rw(e)}})});var Vm=b((MC,Om)=>{"use strict";Dm();var iw=kr();Om.exports=iw.Object.values});var _m=b((CC,Bm)=>{"use strict";var aw=Vm();Bm.exports=aw});var Oi=b((DC,Nm)=>{"use strict";var sw=_m();Nm.exports=sw});var Hm=b(()=>{"use strict";var lw=de(),cw=Rr(),dw=Or(),pw=yi(),hw=Ti();lw({target:"Array",proto:!0},{at:function(e){var t=cw(this),r=dw(t),i=pw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});hw("at")});var Gm=b((a0,jm)=>{"use strict";Hm();var fw=qt();jm.exports=fw("Array","at")});var Wm=b((s0,Qm)=>{"use strict";var mw=Gm();Qm.exports=mw});var Qr=b((n0,Ym)=>{"use strict";var bw=Wm();Ym.exports=bw});var Au=b((xD,fb)=>{"use strict";var ww=ir();fb.exports=Array.isArray||function(e){return ww(e)==="Array"}});var bb=b((PD,mb)=>{"use strict";var kw=TypeError,Rw=9007199254740991;mb.exports=function(a){if(a>Rw)throw kw("Maximum allowed index exceeded");return a}});var Sb=b((AD,vb)=>{"use strict";var $w=Au(),Lw=Or(),Mw=bb(),Cw=Lr(),gb=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?Cw(n,o):!1,d,h;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&$w(d)?(h=Lw(d),u=gb(a,e,d,h,u,s-1)-1):(Mw(u+1),a[u]=d),u++),l++;return u};vb.exports=gb});var Eb=b((wD,Ib)=>{"use strict";var yb=Au(),Dw=Ro(),Ow=Be(),Vw=Ie(),Bw=Vw("species"),Tb=Array;Ib.exports=function(a){var e;return yb(a)&&(e=a.constructor,Dw(e)&&(e===Tb||yb(e.prototype))?e=void 0:Ow(e)&&(e=e[Bw],e===null&&(e=void 0))),e===void 0?Tb:e}});var Pb=b((kD,xb)=>{"use strict";var _w=Eb();xb.exports=function(a,e){return new(_w(a))(e===0?0:e)}});var Ab=b(()=>{"use strict";var Nw=de(),Fw=Sb(),qw=ot(),Uw=Rr(),Hw=Or(),jw=Pb();Nw({target:"Array",proto:!0},{flatMap:function(e){var t=Uw(this),r=Hw(t),i;return qw(e),i=jw(t,0),i.length=Fw(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var wb=b(()=>{"use strict";var Gw=Ti();Gw("flatMap")});var Rb=b((CD,kb)=>{"use strict";Ab();wb();var Qw=qt();kb.exports=Qw("Array","flatMap")});var Lb=b((DD,$b)=>{"use strict";var Ww=Rb();$b.exports=Ww});var wu=b((OD,Mb)=>{"use strict";var Yw=Lb();Mb.exports=Yw});var Qi=b((jD,Xb)=>{"use strict";var rk=Ei(),ik=String;Xb.exports=function(a){if(rk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return ik(a)}});var Ru=b((GD,Zb)=>{"use strict";Zb.exports=`
|
|
7
|
-
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var rg=b((QD,tg)=>{"use strict";var ak=fe(),sk=Ft(),nk=Qi(),Lu=Ru(),eg=ak("".replace),ok=RegExp("^["+Lu+"]+"),uk=RegExp("(^|[^"+Lu+"])["+Lu+"]+$"),$u=function(a){return function(e){var t=nk(sk(e));return a&1&&(t=eg(t,ok,"")),a&2&&(t=eg(t,uk,"$1")),t}};tg.exports={start:$u(1),end:$u(2),trim:$u(3)}});var ng=b((WD,sg)=>{"use strict";var lk=uo().PROPER,ck=Te(),ig=Ru(),ag="\u200B\x85\u180E";sg.exports=function(a){return ck(function(){return!!ig[a]()||ag[a]()!==ag||lk&&ig[a].name!==a})}});var Mu=b((YD,og)=>{"use strict";var dk=rg().start,pk=ng();og.exports=pk("trimStart")?function(){return dk(this)}:"".trimStart});var lg=b(()=>{"use strict";var hk=de(),ug=Mu();hk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==ug},{trimLeft:ug})});var dg=b(()=>{"use strict";lg();var fk=de(),cg=Mu();fk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==cg},{trimStart:cg})});var hg=b((ZD,pg)=>{"use strict";dg();var mk=qt();pg.exports=mk("String","trimLeft")});var mg=b((eO,fg)=>{"use strict";var bk=hg();fg.exports=bk});var gg=b((tO,bg)=>{"use strict";var gk=mg();bg.exports=gk});var Lg=b(()=>{"use strict"});var Mg=b(()=>{"use strict"});var Dg=b((TB,Cg)=>{"use strict";var Bk=Be(),_k=ir(),Nk=Ie(),Fk=Nk("match");Cg.exports=function(a){var e;return Bk(a)&&((e=a[Fk])!==void 0?!!e:_k(a)==="RegExp")}});var Vg=b((IB,Og)=>{"use strict";var qk=ut();Og.exports=function(){var a=qk(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var Ng=b((EB,_g)=>{"use strict";var Uk=Ve(),Hk=tt(),jk=fi(),Gk=Vg(),Bg=RegExp.prototype;_g.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Bg)&&!Hk(a,"flags")&&jk(Bg,a)?Uk(Gk,a):e}});var qg=b((xB,Fg)=>{"use strict";var Nu=fe(),Qk=Rr(),Wk=Math.floor,Bu=Nu("".charAt),Yk=Nu("".replace),_u=Nu("".slice),zk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Kk=/\$([$&'`]|\d{1,2})/g;Fg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=Kk;return i!==void 0&&(i=Qk(i),u=zk),Yk(s,u,function(l,c){var d;switch(Bu(c,0)){case"$":return"$";case"&":return a;case"`":return _u(e,0,t);case"'":return _u(e,n);case"<":d=i[_u(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=Wk(h/10);return p===0?l:p<=o?r[p-1]===void 0?Bu(c,1):r[p-1]+Bu(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var jg=b(()=>{"use strict";var Jk=de(),Xk=Ve(),qu=fe(),Ug=Ft(),Zk=ue(),eR=wr(),tR=Dg(),Zr=Qi(),rR=bi(),iR=Ng(),aR=qg(),sR=Ie(),nR=et(),oR=sR("replace"),uR=TypeError,Fu=qu("".indexOf),lR=qu("".replace),Hg=qu("".slice),cR=Math.max;Jk({target:"String",proto:!0},{replaceAll:function(e,t){var r=Ug(this),i,s,n,o,u,l,c,d,h,p,m=0,g="";if(!eR(e)){if(i=tR(e),i&&(s=Zr(Ug(iR(e))),!~Fu(s,"g")))throw new uR("`.replaceAll` does not allow non-global regexes");if(n=rR(e,oR),n)return Xk(n,e,r,t);if(nR&&i)return lR(Zr(r),e,t)}for(o=Zr(r),u=Zr(e),l=Zk(t),l||(t=Zr(t)),c=u.length,d=cR(1,c),h=Fu(o,u);h!==-1;)p=l?Zr(t(u,h,o)):aR(u,o,h,[],void 0,t),g+=Hg(o,m,h)+p,m=h+c,h=h+d>o.length?-1:Fu(o,u,h+d);return m<o.length&&(g+=Hg(o,m)),g}})});var Qg=b((wB,Gg)=>{"use strict";Lg();Mg();jg();var dR=qt();Gg.exports=dR("String","replaceAll")});var Yg=b((kB,Wg)=>{"use strict";var pR=Qg();Wg.exports=pR});var Kg=b((RB,zg)=>{"use strict";var hR=Yg();zg.exports=hR});var Xg=b(($B,Jg)=>{"use strict";var fR=yi(),mR=Qi(),bR=Ft(),gR=RangeError;Jg.exports=function(e){var t=mR(bR(this)),r="",i=fR(e);if(i<0||i===1/0)throw new gR("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var iv=b((LB,rv)=>{"use strict";var tv=fe(),vR=zn(),Zg=Qi(),SR=Xg(),yR=Ft(),TR=tv(SR),IR=tv("".slice),ER=Math.ceil,ev=function(a){return function(e,t,r){var i=Zg(yR(e)),s=vR(t),n=i.length,o=r===void 0?" ":Zg(r),u,l;return s<=n||o===""?i:(u=s-n,l=TR(o,ER(u/o.length)),l.length>u&&(l=IR(l,0,u)),a?i+l:l+i)}};rv.exports={start:ev(!1),end:ev(!0)}});var sv=b((MB,av)=>{"use strict";var xR=sr();av.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(xR)});var nv=b(()=>{"use strict";var PR=de(),AR=iv().start,wR=sv();PR({target:"String",proto:!0,forced:wR},{padStart:function(e){return AR(this,e,arguments.length>1?arguments[1]:void 0)}})});var uv=b((OB,ov)=>{"use strict";nv();var kR=qt();ov.exports=kR("String","padStart")});var cv=b((VB,lv)=>{"use strict";var RR=uv();lv.exports=RR});var pv=b((BB,dv)=>{"use strict";var $R=cv();dv.exports=$R});var YR={};yS(YR,{ChromecastState:()=>ci,HttpConnectionType:()=>Ja,Observable:()=>mt.Observable,PlaybackState:()=>Pe,Player:()=>Va,SDK_VERSION:()=>WR,Subject:()=>mt.Subject,Subscription:()=>mt.Subscription,Surface:()=>Xa,VERSION:()=>Sn,ValueSubject:()=>mt.ValueSubject,VideoFormat:()=>gt,VideoQuality:()=>mt.VideoQuality});module.exports=TS(YR);var Sn="2.0.123-dev.8ba72ee5.0";var Pe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Pe||{}),gt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(gt||{});var ci=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ci||{}),Ja=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Ja||{});var Xa=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Xa||{});var iS=Y(lt(),1);var F=require("@vkontakte/videoplayer-shared/es2018");var Cd=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var is=class{constructor(e){this.connection$=new F.ValueSubject(void 0);this.castState$=new F.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new F.Subject;this.realCastState$=new F.ValueSubject("NOT_AVAILABLE");this.subscription=new F.Subscription;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,F.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||Cd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:F.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,F.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,F.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,F.assertNever)(i.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,F.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,F.map)(i=>i.castState)),(0,F.observableFrom)([r.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(HT),(0,F.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,F.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();(0,F.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,F.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(0,F.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},HT=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,F.assertNever)(a)}};var al=Y(lt(),1),jv=Y(Vr(),1),Gv=Y(xo(),1);var Lm=Y(Ls(),1);var cu=require("@vkontakte/videoplayer-shared/es2018");var Ee=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,cu.assertNever)(t)}return a},Ms=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:(0,cu.assertNever)(e)}};var k=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var ct=require("@vkontakte/videoplayer-shared/es2018"),U=class{constructor(e){this.transitionStarted$=new ct.Subject;this.transitionEnded$=new ct.Subject;this.transitionUpdated$=new ct.Subject;this.forceChanged$=new ct.Subject;this.stateChangeStarted$=(0,ct.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,ct.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,ct.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 km=require("@vkontakte/videoplayer-shared/es2018"),Rm=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,km.assertNever)(a)}};var $=require("@vkontakte/videoplayer-shared/es2018");var JA=5,XA=5,ZA=500,$m=7e3,Di=class{constructor(e){this.subscription=new $.Subscription;this.loadMediaTimeoutSubscription=new $.Subscription;this.videoState=new U("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,$.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,$.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,$.assertNever)(e)}break}default:(0,$.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(Rm(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 $.Subscription;this.subscription.add(e),this.subscription.add((0,$.merge)(this.videoState.stateChangeStarted$.pipe((0,$.map)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,$.map)(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new $.Subject;e.add(i.pipe((0,$.debounce)(ZA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,$.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)>JA)&&i.next(o),s=o})),e.add((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<XA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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,$.assertNever)(n)}}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,$.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,$.observableFrom)(["init"])).pipe((0,$.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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];(0,$.assertNonNullable)(c);let d=(0,$.getHighestQuality)(Object.keys(c));(0,$.assertNonNullable)(d);let h=c[d];(0,$.assertNonNullable)(h),r=h,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,$.assertNonNullable)(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];(0,$.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,$.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,$.assertNonNullable)(c),r=Ee(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:$.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,$.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,$.isNonNullable)(o)&&(n.metadata.title=o),(0,$.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add((0,$.timeout)($m).subscribe(()=>s(`timeout(${$m})`)))});(0,Lm.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:$.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var xu=Y(lt(),1);var fu=require("@vkontakte/videoplayer-shared/es2018");var Mm=require("@vkontakte/videoplayer-shared/es2018"),Cm=a=>{try{a.pause(),a.playbackRate=0,(0,Mm.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Cs=require("@vkontakte/videoplayer-shared/es2018"),du=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)}},pu=window.WeakMap?new WeakMap:new du,hu=window.WeakMap?new WeakMap:new Map,ew=(a,e=20)=>{let t=0;return(0,Cs.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},we=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,fu.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),pu.set(t,r);let i=new Cs.Subscription;return i.add(ew(t,e)),hu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ke=a=>{let e=hu.get(a);e==null||e.unsubscribe(),hu.delete(a);let t=pu.get(a);pu.delete(a),t?(0,fu.clearVideoElement)(a):Cm(a)};var mu=Y(Oi(),1),L=require("@vkontakte/videoplayer-shared/es2018");var Ht=require("@vkontakte/videoplayer-shared/es2018"),Ds=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Ht.isNullable)(i),l=new Ht.Subscription;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},dt=(a,e,t)=>Ds(e,()=>a.loop,r=>{(0,Ht.isNonNullable)(r)&&(a.loop=r)},{onError:t}),Re=(a,e,t,r)=>Ds(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Ht.isNonNullable)(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Ge=(a,e,t,r)=>Ds(e,()=>a.playbackRate,i=>{(0,Ht.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),jt=Ds;var nw=a=>["__",a.language,a.label].join("|"),ow=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},bu=class a{constructor(){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(jt(t.internalTextTracks,()=>(0,mu.default)(this.internalTracks),s=>{(0,L.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(jt(t.externalTextTracks,()=>(0,mu.default)(this.externalTracks),s=>{(0,L.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(jt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(jt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,L.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,L.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,L.filterChanged)()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;(0,L.isNonNullable)(t.align)&&(i.align=t.align),(0,L.isNonNullable)(t.position)&&(i.position=t.position),(0,L.isNonNullable)(t.size)&&(i.size=t.size),(0,L.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:nw(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!ow(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,L.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,L.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Qe=bu;var Tt=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 Fm=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},gu=a=>{let e=Fm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},qm=a=>{let e=Fm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var C=require("@vkontakte/videoplayer-shared/es2018");var uw=3,Um=(a,e,t=uw)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var $e=a=>{let e=x=>(0,C.fromEvent)(a,x).pipe((0,C.mapTo)(void 0)),r=(0,C.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,C.fromEvent)(a,x))).pipe((0,C.map)(x=>x.type==="ended"?a.readyState<2:a.readyState<3),(0,C.filterChanged)()),i=(0,C.merge)((0,C.fromEvent)(a,"progress"),(0,C.fromEvent)(a,"timeupdate")).pipe((0,C.map)(()=>Um(a.buffered,a.currentTime))),s=C.clientChecker.isSafari?(0,C.combine)({play:e("play").pipe((0,C.once)()),playing:e("playing")}).pipe((0,C.mapTo)(void 0)):e("playing"),n=(0,C.fromEvent)(a,"volumechange").pipe((0,C.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,C.fromEvent)(a,"ratechange").pipe((0,C.map)(()=>a.playbackRate)),u=(0,C.fromEvent)(a,"error").pipe((0,C.filter)(()=>!!(a.error||a.played.length)),(0,C.map)(()=>{var w;let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:C.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:(w=a.error)!=null?w:void 0}})),l=(0,C.fromEvent)(a,"timeupdate").pipe((0,C.map)(()=>a.currentTime)),c=new C.Subject,d=.3,h;l.subscribe(x=>{a.loop&&(0,C.isNonNullable)(h)&&(0,C.isNonNullable)(x)&&h>=a.duration-d&&x<=d&&c.next(h),h=x});let p=e("pause").pipe((0,C.filter)(()=>!a.error&&h!==a.duration)),m=(0,C.fromEvent)(a,"enterpictureinpicture"),g=(0,C.fromEvent)(a,"leavepictureinpicture"),v=new C.ValueSubject(qm(a));m.subscribe(()=>v.next(!0)),g.subscribe(()=>v.next(!1));let T=new C.ValueSubject(gu(a));return(0,C.fromEvent)(a,"fullscreenchange").pipe((0,C.map)(()=>gu(a))).subscribe(T),{playing$:s,pause$:p,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,C.fromEvent)(a,"durationchange").pipe((0,C.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:T,enterPip$:m,leavePip$:g}};var It=require("@vkontakte/videoplayer-shared/es2018"),Gt=a=>{switch(a){case"mobile":return It.VideoQuality.Q_144P;case"lowest":return It.VideoQuality.Q_240P;case"low":return It.VideoQuality.Q_360P;case"sd":case"medium":return It.VideoQuality.Q_480P;case"hd":case"high":return It.VideoQuality.Q_720P;case"fullhd":case"full":return It.VideoQuality.Q_1080P;case"quadhd":case"quad":return It.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return It.VideoQuality.Q_2160P}};var Qt=Y(Qr(),1),Zm=Y(lt(),1),Os=Y(Vr(),1),M=require("@vkontakte/videoplayer-shared/es2018");var vu=!1,Et={},zm=a=>{vu=a},Km=()=>{Et={}},Jm=a=>{a(Et)},Vi=(a,e)=>{var t;vu&&(Et.meta=(t=Et.meta)!=null?t:{},Et.meta[a]=e)},Ae=class{constructor(e){this.name=e}next(e){var r,i;if(!vu)return;Et.series=(r=Et.series)!=null?r:{};let t=(i=Et.series[this.name])!=null?i:[];t.push([Date.now(),e]),Et.series[this.name]=t}};var gw=new Ae("best_bitrate"),eb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Su=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Bi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,M.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},tb='Assertion "ABR Tracks is empty array" failed',Vs=(a,e,t,r)=>{var u;let i=[...e].sort(Su(1)),s=[...t].sort(Su(1)),n=s.filter(l=>(0,M.isNonNullable)(l.bitrate)&&(0,M.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Qt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Qt.default)(s,-1);return o&&(0,Zm.default)(n,o)?o:n.length?(0,Qt.default)(n,-1):(0,Qt.default)(s,0)},Xm=a=>"quality"in a,rb=(a,e,t,r)=>{var n;let i=(0,M.isNonNullable)((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&(0,M.isNonNullable)(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,M.now)()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Xm(o)?"video":"audio",l=Xm(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
"use strict";var yS=Object.create;var ts=Object.defineProperty;var TS=Object.getOwnPropertyDescriptor;var IS=Object.getOwnPropertyNames;var ES=Object.getPrototypeOf,xS=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),PS=(a,e)=>{for(var t in e)ts(a,t,{get:e[t],enumerable:!0})},Wl=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of IS(e))!xS.call(a,i)&&i!==t&&ts(a,i,{get:()=>e[i],enumerable:!(r=TS(e,i))||r.enumerable});return a};var W=(a,e,t)=>(t=a!=null?yS(ES(a)):{},Wl(e||!a||!a.__esModule?ts(t,"default",{value:a,enumerable:!0}):t,a)),wS=a=>Wl(ts({},"__esModule",{value:!0}),a);var de=b((Pn,Yl)=>{"use strict";var gi=function(a){return a&&a.Math===Math&&a};Yl.exports=gi(typeof globalThis=="object"&&globalThis)||gi(typeof window=="object"&&window)||gi(typeof self=="object"&&self)||gi(typeof global=="object"&&global)||gi(typeof Pn=="object"&&Pn)||function(){return this}()||Function("return this")()});var Te=b((i$,zl)=>{"use strict";zl.exports=function(a){try{return!!a()}catch(e){return!0}}});var vi=b((a$,Kl)=>{"use strict";var AS=Te();Kl.exports=!AS(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var wn=b((s$,ec)=>{"use strict";var kS=vi(),Zl=Function.prototype,Jl=Zl.apply,Xl=Zl.call;ec.exports=typeof Reflect=="object"&&Reflect.apply||(kS?Xl.bind(Jl):function(){return Xl.apply(Jl,arguments)})});var me=b((n$,ic)=>{"use strict";var tc=vi(),rc=Function.prototype,An=rc.call,RS=tc&&rc.bind.bind(An,An);ic.exports=tc?RS:function(a){return function(){return An.apply(a,arguments)}}});var ur=b((o$,sc)=>{"use strict";var ac=me(),$S=ac({}.toString),LS=ac("".slice);sc.exports=function(a){return LS($S(a),8,-1)}});var kn=b((u$,nc)=>{"use strict";var MS=ur(),CS=me();nc.exports=function(a){if(MS(a)==="Function")return CS(a)}});var le=b((l$,oc)=>{"use strict";var Rn=typeof document=="object"&&document.all;oc.exports=typeof Rn=="undefined"&&Rn!==void 0?function(a){return typeof a=="function"||a===Rn}:function(a){return typeof a=="function"}});var Ve=b((c$,uc)=>{"use strict";var DS=Te();uc.exports=!DS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var _e=b((d$,lc)=>{"use strict";var OS=vi(),as=Function.prototype.call;lc.exports=OS?as.bind(as):function(){return as.apply(as,arguments)}});var $n=b(pc=>{"use strict";var cc={}.propertyIsEnumerable,dc=Object.getOwnPropertyDescriptor,BS=dc&&!cc.call({1:2},1);pc.f=BS?function(e){var t=dc(this,e);return!!t&&t.enumerable}:cc});var Si=b((h$,hc)=>{"use strict";hc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var mc=b((f$,fc)=>{"use strict";var VS=me(),_S=Te(),NS=ur(),Ln=Object,FS=VS("".split);fc.exports=_S(function(){return!Ln("z").propertyIsEnumerable(0)})?function(a){return NS(a)==="String"?FS(a,""):Ln(a)}:Ln});var Mr=b((m$,bc)=>{"use strict";bc.exports=function(a){return a==null}});var Ht=b((b$,gc)=>{"use strict";var qS=Mr(),US=TypeError;gc.exports=function(a){if(qS(a))throw new US("Can't call method on "+a);return a}});var lr=b((g$,vc)=>{"use strict";var HS=mc(),jS=Ht();vc.exports=function(a){return HS(jS(a))}});var Ne=b((v$,Sc)=>{"use strict";var GS=le();Sc.exports=function(a){return typeof a=="object"?a!==null:GS(a)}});var Cr=b((S$,yc)=>{"use strict";yc.exports={}});var yt=b((y$,Ic)=>{"use strict";var Mn=Cr(),Cn=de(),QS=le(),Tc=function(a){return QS(a)?a:void 0};Ic.exports=function(a,e){return arguments.length<2?Tc(Mn[a])||Tc(Cn[a]):Mn[a]&&Mn[a][e]||Cn[a]&&Cn[a][e]}});var yi=b((T$,Ec)=>{"use strict";var WS=me();Ec.exports=WS({}.isPrototypeOf)});var cr=b((I$,wc)=>{"use strict";var YS=de(),xc=YS.navigator,Pc=xc&&xc.userAgent;wc.exports=Pc?String(Pc):""});var On=b((E$,Mc)=>{"use strict";var Lc=de(),Dn=cr(),Ac=Lc.process,kc=Lc.Deno,Rc=Ac&&Ac.versions||kc&&kc.version,$c=Rc&&Rc.v8,tt,ss;$c&&(tt=$c.split("."),ss=tt[0]>0&&tt[0]<4?1:+(tt[0]+tt[1]));!ss&&Dn&&(tt=Dn.match(/Edge\/(\d+)/),(!tt||tt[1]>=74)&&(tt=Dn.match(/Chrome\/(\d+)/),tt&&(ss=+tt[1])));Mc.exports=ss});var Bn=b((x$,Dc)=>{"use strict";var Cc=On(),zS=Te(),KS=de(),JS=KS.String;Dc.exports=!!Object.getOwnPropertySymbols&&!zS(function(){var a=Symbol("symbol detection");return!JS(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Cc&&Cc<41})});var Vn=b((P$,Oc)=>{"use strict";var XS=Bn();Oc.exports=XS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var _n=b((w$,Bc)=>{"use strict";var ZS=yt(),ey=le(),ty=yi(),ry=Vn(),iy=Object;Bc.exports=ry?function(a){return typeof a=="symbol"}:function(a){var e=ZS("Symbol");return ey(e)&&ty(e.prototype,iy(a))}});var Ti=b((A$,Vc)=>{"use strict";var ay=String;Vc.exports=function(a){try{return ay(a)}catch(e){return"Object"}}});var ct=b((k$,_c)=>{"use strict";var sy=le(),ny=Ti(),oy=TypeError;_c.exports=function(a){if(sy(a))return a;throw new oy(ny(a)+" is not a function")}});var Ii=b((R$,Nc)=>{"use strict";var uy=ct(),ly=Mr();Nc.exports=function(a,e){var t=a[e];return ly(t)?void 0:uy(t)}});var qc=b(($$,Fc)=>{"use strict";var Nn=_e(),Fn=le(),qn=Ne(),cy=TypeError;Fc.exports=function(a,e){var t,r;if(e==="string"&&Fn(t=a.toString)&&!qn(r=Nn(t,a))||Fn(t=a.valueOf)&&!qn(r=Nn(t,a))||e!=="string"&&Fn(t=a.toString)&&!qn(r=Nn(t,a)))return r;throw new cy("Can't convert object to primitive value")}});var rt=b((L$,Uc)=>{"use strict";Uc.exports=!0});var Gc=b((M$,jc)=>{"use strict";var Hc=de(),dy=Object.defineProperty;jc.exports=function(a,e){try{dy(Hc,a,{value:e,configurable:!0,writable:!0})}catch(t){Hc[a]=e}return e}});var Ei=b((C$,Yc)=>{"use strict";var py=rt(),hy=de(),fy=Gc(),Qc="__core-js_shared__",Wc=Yc.exports=hy[Qc]||fy(Qc,{});(Wc.versions||(Wc.versions=[])).push({version:"3.38.0",mode:py?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Un=b((D$,Kc)=>{"use strict";var zc=Ei();Kc.exports=function(a,e){return zc[a]||(zc[a]=e||{})}});var Dr=b((O$,Jc)=>{"use strict";var my=Ht(),by=Object;Jc.exports=function(a){return by(my(a))}});var it=b((B$,Xc)=>{"use strict";var gy=me(),vy=Dr(),Sy=gy({}.hasOwnProperty);Xc.exports=Object.hasOwn||function(e,t){return Sy(vy(e),t)}});var Hn=b((V$,Zc)=>{"use strict";var yy=me(),Ty=0,Iy=Math.random(),Ey=yy(1 .toString);Zc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Ey(++Ty+Iy,36)}});var Ie=b((_$,td)=>{"use strict";var xy=de(),Py=Un(),ed=it(),wy=Hn(),Ay=Bn(),ky=Vn(),Or=xy.Symbol,jn=Py("wks"),Ry=ky?Or.for||Or:Or&&Or.withoutSetter||wy;td.exports=function(a){return ed(jn,a)||(jn[a]=Ay&&ed(Or,a)?Or[a]:Ry("Symbol."+a)),jn[a]}});var sd=b((N$,ad)=>{"use strict";var $y=_e(),rd=Ne(),id=_n(),Ly=Ii(),My=qc(),Cy=Ie(),Dy=TypeError,Oy=Cy("toPrimitive");ad.exports=function(a,e){if(!rd(a)||id(a))return a;var t=Ly(a,Oy),r;if(t){if(e===void 0&&(e="default"),r=$y(t,a,e),!rd(r)||id(r))return r;throw new Dy("Can't convert object to primitive value")}return e===void 0&&(e="number"),My(a,e)}});var Gn=b((F$,nd)=>{"use strict";var By=sd(),Vy=_n();nd.exports=function(a){var e=By(a,"string");return Vy(e)?e:e+""}});var ns=b((q$,ud)=>{"use strict";var _y=de(),od=Ne(),Qn=_y.document,Ny=od(Qn)&&od(Qn.createElement);ud.exports=function(a){return Ny?Qn.createElement(a):{}}});var Wn=b((U$,ld)=>{"use strict";var Fy=Ve(),qy=Te(),Uy=ns();ld.exports=!Fy&&!qy(function(){return Object.defineProperty(Uy("div"),"a",{get:function(){return 7}}).a!==7})});var pd=b(dd=>{"use strict";var Hy=Ve(),jy=_e(),Gy=$n(),Qy=Si(),Wy=lr(),Yy=Gn(),zy=it(),Ky=Wn(),cd=Object.getOwnPropertyDescriptor;dd.f=Hy?cd:function(e,t){if(e=Wy(e),t=Yy(t),Ky)try{return cd(e,t)}catch(r){}if(zy(e,t))return Qy(!jy(Gy.f,e,t),e[t])}});var Yn=b((j$,hd)=>{"use strict";var Jy=Te(),Xy=le(),Zy=/#|\.prototype\./,xi=function(a,e){var t=tT[eT(a)];return t===iT?!0:t===rT?!1:Xy(e)?Jy(e):!!e},eT=xi.normalize=function(a){return String(a).replace(Zy,".").toLowerCase()},tT=xi.data={},rT=xi.NATIVE="N",iT=xi.POLYFILL="P";hd.exports=xi});var Br=b((G$,md)=>{"use strict";var fd=kn(),aT=ct(),sT=vi(),nT=fd(fd.bind);md.exports=function(a,e){return aT(a),e===void 0?a:sT?nT(a,e):function(){return a.apply(e,arguments)}}});var zn=b((Q$,bd)=>{"use strict";var oT=Ve(),uT=Te();bd.exports=oT&&uT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var dt=b((W$,gd)=>{"use strict";var lT=Ne(),cT=String,dT=TypeError;gd.exports=function(a){if(lT(a))return a;throw new dT(cT(a)+" is not an object")}});var dr=b(Sd=>{"use strict";var pT=Ve(),hT=Wn(),fT=zn(),os=dt(),vd=Gn(),mT=TypeError,Kn=Object.defineProperty,bT=Object.getOwnPropertyDescriptor,Jn="enumerable",Xn="configurable",Zn="writable";Sd.f=pT?fT?function(e,t,r){if(os(e),t=vd(t),os(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Zn in r&&!r[Zn]){var i=bT(e,t);i&&i[Zn]&&(e[t]=r.value,r={configurable:Xn in r?r[Xn]:i[Xn],enumerable:Jn in r?r[Jn]:i[Jn],writable:!1})}return Kn(e,t,r)}:Kn:function(e,t,r){if(os(e),t=vd(t),os(r),hT)try{return Kn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new mT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Vr=b((z$,yd)=>{"use strict";var gT=Ve(),vT=dr(),ST=Si();yd.exports=gT?function(a,e,t){return vT.f(a,e,ST(1,t))}:function(a,e,t){return a[e]=t,a}});var he=b((K$,Id)=>{"use strict";var Pi=de(),yT=wn(),TT=kn(),IT=le(),ET=pd().f,xT=Yn(),_r=Cr(),PT=Br(),Nr=Vr(),Td=it();Ei();var wT=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return yT(a,this,arguments)};return e.prototype=a.prototype,e};Id.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Pi:i?Pi[t]:Pi[t]&&Pi[t].prototype,o=r?_r:_r[t]||Nr(_r,t,{})[t],u=o.prototype,l,c,d,p,h,m,g,v,I;for(p in e)l=xT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Td(n,p),m=o[p],c&&(a.dontCallGetSet?(I=ET(n,p),g=I&&I.value):g=n[p]),h=c&&g?g:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?v=PT(h,Pi):a.wrap&&c?v=wT(h):s&&IT(h)?v=TT(h):v=h,(a.sham||h&&h.sham||m&&m.sham)&&Nr(v,"sham",!0),Nr(o,p,v),s&&(d=t+"Prototype",Td(_r,d)||Nr(_r,d,{}),Nr(_r[d],p,h),a.real&&u&&(l||!u[p])&&Nr(u,p,h)))}});var xd=b((J$,Ed)=>{"use strict";var AT=Math.ceil,kT=Math.floor;Ed.exports=Math.trunc||function(e){var t=+e;return(t>0?kT:AT)(t)}});var wi=b((X$,Pd)=>{"use strict";var RT=xd();Pd.exports=function(a){var e=+a;return e!==e||e===0?0:RT(e)}});var Ad=b((Z$,wd)=>{"use strict";var $T=wi(),LT=Math.max,MT=Math.min;wd.exports=function(a,e){var t=$T(a);return t<0?LT(t+e,0):MT(t,e)}});var eo=b((eL,kd)=>{"use strict";var CT=wi(),DT=Math.min;kd.exports=function(a){var e=CT(a);return e>0?DT(e,9007199254740991):0}});var Fr=b((tL,Rd)=>{"use strict";var OT=eo();Rd.exports=function(a){return OT(a.length)}});var to=b((rL,Ld)=>{"use strict";var BT=lr(),VT=Ad(),_T=Fr(),$d=function(a){return function(e,t,r){var i=BT(e),s=_T(i);if(s===0)return!a&&-1;var n=VT(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Ld.exports={includes:$d(!0),indexOf:$d(!1)}});var Ai=b((iL,Md)=>{"use strict";Md.exports=function(){}});var Cd=b(()=>{"use strict";var NT=he(),FT=to().includes,qT=Te(),UT=Ai(),HT=qT(function(){return!Array(1).includes()});NT({target:"Array",proto:!0,forced:HT},{includes:function(e){return FT(this,e,arguments.length>1?arguments[1]:void 0)}});UT("includes")});var jt=b((nL,Dd)=>{"use strict";var jT=yt();Dd.exports=jT});var Bd=b((oL,Od)=>{"use strict";Cd();var GT=jt();Od.exports=GT("Array","includes")});var _d=b((uL,Vd)=>{"use strict";var QT=Bd();Vd.exports=QT});var at=b((lL,Nd)=>{"use strict";var WT=_d();Nd.exports=WT});var ls=b((yL,Ud)=>{"use strict";var zT=Un(),KT=Hn(),qd=zT("keys");Ud.exports=function(a){return qd[a]||(qd[a]=KT(a))}});var jd=b((TL,Hd)=>{"use strict";var JT=Te();Hd.exports=!JT(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var cs=b((IL,Qd)=>{"use strict";var XT=it(),ZT=le(),eI=Dr(),tI=ls(),rI=jd(),Gd=tI("IE_PROTO"),ro=Object,iI=ro.prototype;Qd.exports=rI?ro.getPrototypeOf:function(a){var e=eI(a);if(XT(e,Gd))return e[Gd];var t=e.constructor;return ZT(t)&&e instanceof t?t.prototype:e instanceof ro?iI:null}});var ds=b((EL,Wd)=>{"use strict";Wd.exports={}});var Kd=b((xL,zd)=>{"use strict";var aI=me(),io=it(),sI=lr(),nI=to().indexOf,oI=ds(),Yd=aI([].push);zd.exports=function(a,e){var t=sI(a),r=0,i=[],s;for(s in t)!io(oI,s)&&io(t,s)&&Yd(i,s);for(;e.length>r;)io(t,s=e[r++])&&(~nI(i,s)||Yd(i,s));return i}});var ao=b((PL,Jd)=>{"use strict";Jd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var so=b((wL,Xd)=>{"use strict";var uI=Kd(),lI=ao();Xd.exports=Object.keys||function(e){return uI(e,lI)}});var no=b((AL,ip)=>{"use strict";var ep=Ve(),cI=Te(),tp=me(),dI=cs(),pI=so(),hI=lr(),fI=$n().f,rp=tp(fI),mI=tp([].push),bI=ep&&cI(function(){var a=Object.create(null);return a[2]=2,!rp(a,2)}),Zd=function(a){return function(e){for(var t=hI(e),r=pI(t),i=bI&&dI(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!ep||(i?u in t:rp(t,u)))&&mI(o,a?[u,t[u]]:t[u]);return o}};ip.exports={entries:Zd(!0),values:Zd(!1)}});var ap=b(()=>{"use strict";var gI=he(),vI=no().entries;gI({target:"Object",stat:!0},{entries:function(e){return vI(e)}})});var np=b(($L,sp)=>{"use strict";ap();var SI=Cr();sp.exports=SI.Object.entries});var up=b((LL,op)=>{"use strict";var yI=np();op.exports=yI});var qr=b((ML,lp)=>{"use strict";var TI=up();lp.exports=TI});var pr=b((CL,cp)=>{"use strict";cp.exports={}});var hp=b((DL,pp)=>{"use strict";var II=de(),EI=le(),dp=II.WeakMap;pp.exports=EI(dp)&&/native code/.test(String(dp))});var co=b((OL,bp)=>{"use strict";var xI=hp(),mp=de(),PI=Ne(),wI=Vr(),oo=it(),uo=Ei(),AI=ls(),kI=ds(),fp="Object already initialized",lo=mp.TypeError,RI=mp.WeakMap,ps,ki,hs,$I=function(a){return hs(a)?ki(a):ps(a,{})},LI=function(a){return function(e){var t;if(!PI(e)||(t=ki(e)).type!==a)throw new lo("Incompatible receiver, "+a+" required");return t}};xI||uo.state?(st=uo.state||(uo.state=new RI),st.get=st.get,st.has=st.has,st.set=st.set,ps=function(a,e){if(st.has(a))throw new lo(fp);return e.facade=a,st.set(a,e),e},ki=function(a){return st.get(a)||{}},hs=function(a){return st.has(a)}):(hr=AI("state"),kI[hr]=!0,ps=function(a,e){if(oo(a,hr))throw new lo(fp);return e.facade=a,wI(a,hr,e),e},ki=function(a){return oo(a,hr)?a[hr]:{}},hs=function(a){return oo(a,hr)});var st,hr;bp.exports={set:ps,get:ki,has:hs,enforce:$I,getterFor:LI}});var fo=b((BL,vp)=>{"use strict";var po=Ve(),MI=it(),gp=Function.prototype,CI=po&&Object.getOwnPropertyDescriptor,ho=MI(gp,"name"),DI=ho&&function(){}.name==="something",OI=ho&&(!po||po&&CI(gp,"name").configurable);vp.exports={EXISTS:ho,PROPER:DI,CONFIGURABLE:OI}});var yp=b(Sp=>{"use strict";var BI=Ve(),VI=zn(),_I=dr(),NI=dt(),FI=lr(),qI=so();Sp.f=BI&&!VI?Object.defineProperties:function(e,t){NI(e);for(var r=FI(t),i=qI(t),s=i.length,n=0,o;s>n;)_I.f(e,o=i[n++],r[o]);return e}});var mo=b((_L,Tp)=>{"use strict";var UI=yt();Tp.exports=UI("document","documentElement")});var So=b((NL,kp)=>{"use strict";var HI=dt(),jI=yp(),Ip=ao(),GI=ds(),QI=mo(),WI=ns(),YI=ls(),Ep=">",xp="<",go="prototype",vo="script",wp=YI("IE_PROTO"),bo=function(){},Ap=function(a){return xp+vo+Ep+a+xp+"/"+vo+Ep},Pp=function(a){a.write(Ap("")),a.close();var e=a.parentWindow.Object;return a=null,e},zI=function(){var a=WI("iframe"),e="java"+vo+":",t;return a.style.display="none",QI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Ap("document.F=Object")),t.close(),t.F},fs,ms=function(){try{fs=new ActiveXObject("htmlfile")}catch(e){}ms=typeof document!="undefined"?document.domain&&fs?Pp(fs):zI():Pp(fs);for(var a=Ip.length;a--;)delete ms[go][Ip[a]];return ms()};GI[wp]=!0;kp.exports=Object.create||function(e,t){var r;return e!==null?(bo[go]=HI(e),r=new bo,bo[go]=null,r[wp]=e):r=ms(),t===void 0?r:jI.f(r,t)}});var Ur=b((FL,Rp)=>{"use strict";var KI=Vr();Rp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:KI(a,e,t),a}});var Eo=b((qL,Mp)=>{"use strict";var JI=Te(),XI=le(),ZI=Ne(),eE=So(),$p=cs(),tE=Ur(),rE=Ie(),iE=rt(),Io=rE("iterator"),Lp=!1,Tt,yo,To;[].keys&&(To=[].keys(),"next"in To?(yo=$p($p(To)),yo!==Object.prototype&&(Tt=yo)):Lp=!0);var aE=!ZI(Tt)||JI(function(){var a={};return Tt[Io].call(a)!==a});aE?Tt={}:iE&&(Tt=eE(Tt));XI(Tt[Io])||tE(Tt,Io,function(){return this});Mp.exports={IteratorPrototype:Tt,BUGGY_SAFARI_ITERATORS:Lp}});var bs=b((UL,Dp)=>{"use strict";var sE=Ie(),nE=sE("toStringTag"),Cp={};Cp[nE]="z";Dp.exports=String(Cp)==="[object z]"});var Ri=b((HL,Op)=>{"use strict";var oE=bs(),uE=le(),gs=ur(),lE=Ie(),cE=lE("toStringTag"),dE=Object,pE=gs(function(){return arguments}())==="Arguments",hE=function(a,e){try{return a[e]}catch(t){}};Op.exports=oE?gs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=hE(e=dE(a),cE))=="string"?t:pE?gs(e):(r=gs(e))==="Object"&&uE(e.callee)?"Arguments":r}});var Vp=b((jL,Bp)=>{"use strict";var fE=bs(),mE=Ri();Bp.exports=fE?{}.toString:function(){return"[object "+mE(this)+"]"}});var $i=b((GL,Np)=>{"use strict";var bE=bs(),gE=dr().f,vE=Vr(),SE=it(),yE=Vp(),TE=Ie(),_p=TE("toStringTag");Np.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(SE(i,_p)||gE(i,_p,{configurable:!0,value:e}),r&&!bE&&vE(i,"toString",yE))}});var qp=b((QL,Fp)=>{"use strict";var IE=Eo().IteratorPrototype,EE=So(),xE=Si(),PE=$i(),wE=pr(),AE=function(){return this};Fp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=EE(IE,{next:xE(+!r,t)}),PE(a,i,!1,!0),wE[i]=AE,a}});var Hp=b((WL,Up)=>{"use strict";var kE=me(),RE=ct();Up.exports=function(a,e,t){try{return kE(RE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Gp=b((YL,jp)=>{"use strict";var $E=Ne();jp.exports=function(a){return $E(a)||a===null}});var Wp=b((zL,Qp)=>{"use strict";var LE=Gp(),ME=String,CE=TypeError;Qp.exports=function(a){if(LE(a))return a;throw new CE("Can't set "+ME(a)+" as a prototype")}});var xo=b((KL,Yp)=>{"use strict";var DE=Hp(),OE=Ne(),BE=Ht(),VE=Wp();Yp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=DE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return BE(i),VE(s),OE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var sh=b((JL,ah)=>{"use strict";var _E=he(),NE=_e(),vs=rt(),rh=fo(),FE=le(),qE=qp(),zp=cs(),Kp=xo(),UE=$i(),HE=Vr(),Po=Ur(),jE=Ie(),Jp=pr(),ih=Eo(),GE=rh.PROPER,QE=rh.CONFIGURABLE,Xp=ih.IteratorPrototype,Ss=ih.BUGGY_SAFARI_ITERATORS,Li=jE("iterator"),Zp="keys",Mi="values",eh="entries",th=function(){return this};ah.exports=function(a,e,t,r,i,s,n){qE(t,e,r);var o=function(I){if(I===i&&p)return p;if(!Ss&&I&&I in c)return c[I];switch(I){case Zp:return function(){return new t(this,I)};case Mi:return function(){return new t(this,I)};case eh:return function(){return new t(this,I)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Li]||c["@@iterator"]||i&&c[i],p=!Ss&&d||o(i),h=e==="Array"&&c.entries||d,m,g,v;if(h&&(m=zp(h.call(new a)),m!==Object.prototype&&m.next&&(!vs&&zp(m)!==Xp&&(Kp?Kp(m,Xp):FE(m[Li])||Po(m,Li,th)),UE(m,u,!0,!0),vs&&(Jp[u]=th))),GE&&i===Mi&&d&&d.name!==Mi&&(!vs&&QE?HE(c,"name",Mi):(l=!0,p=function(){return NE(d,this)})),i)if(g={values:o(Mi),keys:s?p:o(Zp),entries:o(eh)},n)for(v in g)(Ss||l||!(v in c))&&Po(c,v,g[v]);else _E({target:e,proto:!0,forced:Ss||l},g);return(!vs||n)&&c[Li]!==p&&Po(c,Li,p,{name:i}),Jp[e]=p,g}});var oh=b((XL,nh)=>{"use strict";nh.exports=function(a,e){return{value:a,done:e}}});var Ao=b((ZL,ph)=>{"use strict";var WE=lr(),wo=Ai(),uh=pr(),ch=co(),YE=dr().f,zE=sh(),ys=oh(),KE=rt(),JE=Ve(),dh="Array Iterator",XE=ch.set,ZE=ch.getterFor(dh);ph.exports=zE(Array,"Array",function(a,e){XE(this,{type:dh,target:WE(a),index:0,kind:e})},function(){var a=ZE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ys(void 0,!0);switch(a.kind){case"keys":return ys(t,!1);case"values":return ys(e[t],!1)}return ys([t,e[t]],!1)},"values");var lh=uh.Arguments=uh.Array;wo("keys");wo("values");wo("entries");if(!KE&&JE&&lh.name!=="values")try{YE(lh,"name",{value:"values"})}catch(a){}});var fh=b((eM,hh)=>{"use strict";var ex=Ie(),tx=pr(),rx=ex("iterator"),ix=Array.prototype;hh.exports=function(a){return a!==void 0&&(tx.Array===a||ix[rx]===a)}});var ko=b((tM,bh)=>{"use strict";var ax=Ri(),mh=Ii(),sx=Mr(),nx=pr(),ox=Ie(),ux=ox("iterator");bh.exports=function(a){if(!sx(a))return mh(a,ux)||mh(a,"@@iterator")||nx[ax(a)]}});var vh=b((rM,gh)=>{"use strict";var lx=_e(),cx=ct(),dx=dt(),px=Ti(),hx=ko(),fx=TypeError;gh.exports=function(a,e){var t=arguments.length<2?hx(a):e;if(cx(t))return dx(lx(t,a));throw new fx(px(a)+" is not iterable")}});var Th=b((iM,yh)=>{"use strict";var mx=_e(),Sh=dt(),bx=Ii();yh.exports=function(a,e,t){var r,i;Sh(a);try{if(r=bx(a,"return"),!r){if(e==="throw")throw t;return t}r=mx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Sh(r),t}});var Is=b((aM,Ph)=>{"use strict";var gx=Br(),vx=_e(),Sx=dt(),yx=Ti(),Tx=fh(),Ix=Fr(),Ih=yi(),Ex=vh(),xx=ko(),Eh=Th(),Px=TypeError,Ts=function(a,e){this.stopped=a,this.result=e},xh=Ts.prototype;Ph.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=gx(e,r),l,c,d,p,h,m,g,v=function(E){return l&&Eh(l,"normal",E),new Ts(!0,E)},I=function(E){return i?(Sx(E),o?u(E[0],E[1],v):u(E[0],E[1])):o?u(E,v):u(E)};if(s)l=a.iterator;else if(n)l=a;else{if(c=xx(a),!c)throw new Px(yx(a)+" is not iterable");if(Tx(c)){for(d=0,p=Ix(a);p>d;d++)if(h=I(a[d]),h&&Ih(xh,h))return h;return new Ts(!1)}l=Ex(a,c)}for(m=s?a.next:l.next;!(g=vx(m,l)).done;){try{h=I(g.value)}catch(E){Eh(l,"throw",E)}if(typeof h=="object"&&h&&Ih(xh,h))return h}return new Ts(!1)}});var Ah=b((sM,wh)=>{"use strict";var wx=Ve(),Ax=dr(),kx=Si();wh.exports=function(a,e,t){wx?Ax.f(a,e,kx(0,t)):a[e]=t}});var kh=b(()=>{"use strict";var Rx=he(),$x=Is(),Lx=Ah();Rx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return $x(e,function(r,i){Lx(t,r,i)},{AS_ENTRIES:!0}),t}})});var $h=b((uM,Rh)=>{"use strict";Ao();kh();var Mx=Cr();Rh.exports=Mx.Object.fromEntries});var Mh=b((lM,Lh)=>{"use strict";Lh.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 Dh=b(()=>{"use strict";Ao();var Cx=Mh(),Dx=de(),Ox=$i(),Ch=pr();for(Es in Cx)Ox(Dx[Es],Es),Ch[Es]=Ch.Array;var Es});var Bh=b((pM,Oh)=>{"use strict";var Bx=$h();Dh();Oh.exports=Bx});var Ro=b((hM,Vh)=>{"use strict";var Vx=Bh();Vh.exports=Vx});var _h=b(()=>{"use strict"});var $o=b((bM,Nh)=>{"use strict";var Ci=de(),_x=cr(),Nx=ur(),xs=function(a){return _x.slice(0,a.length)===a};Nh.exports=function(){return xs("Bun/")?"BUN":xs("Cloudflare-Workers")?"CLOUDFLARE":xs("Deno/")?"DENO":xs("Node.js/")?"NODE":Ci.Bun&&typeof Bun.version=="string"?"BUN":Ci.Deno&&typeof Deno.version=="object"?"DENO":Nx(Ci.process)==="process"?"NODE":Ci.window&&Ci.document?"BROWSER":"REST"}()});var Ps=b((gM,Fh)=>{"use strict";var Fx=$o();Fh.exports=Fx==="NODE"});var Uh=b((vM,qh)=>{"use strict";var qx=dr();qh.exports=function(a,e,t){return qx.f(a,e,t)}});var Gh=b((SM,jh)=>{"use strict";var Ux=yt(),Hx=Uh(),jx=Ie(),Gx=Ve(),Hh=jx("species");jh.exports=function(a){var e=Ux(a);Gx&&e&&!e[Hh]&&Hx(e,Hh,{configurable:!0,get:function(){return this}})}});var Wh=b((yM,Qh)=>{"use strict";var Qx=yi(),Wx=TypeError;Qh.exports=function(a,e){if(Qx(e,a))return a;throw new Wx("Incorrect invocation")}});var Mo=b((TM,Yh)=>{"use strict";var Yx=me(),zx=le(),Lo=Ei(),Kx=Yx(Function.toString);zx(Lo.inspectSource)||(Lo.inspectSource=function(a){return Kx(a)});Yh.exports=Lo.inspectSource});var Do=b((IM,Zh)=>{"use strict";var Jx=me(),Xx=Te(),zh=le(),Zx=Ri(),eP=yt(),tP=Mo(),Kh=function(){},Jh=eP("Reflect","construct"),Co=/^\s*(?:class|function)\b/,rP=Jx(Co.exec),iP=!Co.test(Kh),Di=function(e){if(!zh(e))return!1;try{return Jh(Kh,[],e),!0}catch(t){return!1}},Xh=function(e){if(!zh(e))return!1;switch(Zx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return iP||!!rP(Co,tP(e))}catch(t){return!0}};Xh.sham=!0;Zh.exports=!Jh||Xx(function(){var a;return Di(Di.call)||!Di(Object)||!Di(function(){a=!0})||a})?Xh:Di});var tf=b((EM,ef)=>{"use strict";var aP=Do(),sP=Ti(),nP=TypeError;ef.exports=function(a){if(aP(a))return a;throw new nP(sP(a)+" is not a constructor")}});var Oo=b((xM,af)=>{"use strict";var rf=dt(),oP=tf(),uP=Mr(),lP=Ie(),cP=lP("species");af.exports=function(a,e){var t=rf(a).constructor,r;return t===void 0||uP(r=rf(t)[cP])?e:oP(r)}});var nf=b((PM,sf)=>{"use strict";var dP=me();sf.exports=dP([].slice)});var uf=b((wM,of)=>{"use strict";var pP=TypeError;of.exports=function(a,e){if(a<e)throw new pP("Not enough arguments");return a}});var Bo=b((AM,lf)=>{"use strict";var hP=cr();lf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(hP)});var Go=b((kM,vf)=>{"use strict";var Fe=de(),fP=wn(),mP=Br(),cf=le(),bP=it(),gf=Te(),df=mo(),gP=nf(),pf=ns(),vP=uf(),SP=Bo(),yP=Ps(),Uo=Fe.setImmediate,Ho=Fe.clearImmediate,TP=Fe.process,Vo=Fe.Dispatch,IP=Fe.Function,hf=Fe.MessageChannel,EP=Fe.String,_o=0,Oi={},ff="onreadystatechange",Bi,fr,No,Fo;gf(function(){Bi=Fe.location});var jo=function(a){if(bP(Oi,a)){var e=Oi[a];delete Oi[a],e()}},qo=function(a){return function(){jo(a)}},mf=function(a){jo(a.data)},bf=function(a){Fe.postMessage(EP(a),Bi.protocol+"//"+Bi.host)};(!Uo||!Ho)&&(Uo=function(e){vP(arguments.length,1);var t=cf(e)?e:IP(e),r=gP(arguments,1);return Oi[++_o]=function(){fP(t,void 0,r)},fr(_o),_o},Ho=function(e){delete Oi[e]},yP?fr=function(a){TP.nextTick(qo(a))}:Vo&&Vo.now?fr=function(a){Vo.now(qo(a))}:hf&&!SP?(No=new hf,Fo=No.port2,No.port1.onmessage=mf,fr=mP(Fo.postMessage,Fo)):Fe.addEventListener&&cf(Fe.postMessage)&&!Fe.importScripts&&Bi&&Bi.protocol!=="file:"&&!gf(bf)?(fr=bf,Fe.addEventListener("message",mf,!1)):ff in pf("script")?fr=function(a){df.appendChild(pf("script"))[ff]=function(){df.removeChild(this),jo(a)}}:fr=function(a){setTimeout(qo(a),0)});vf.exports={set:Uo,clear:Ho}});var Tf=b((RM,yf)=>{"use strict";var Sf=de(),xP=Ve(),PP=Object.getOwnPropertyDescriptor;yf.exports=function(a){if(!xP)return Sf[a];var e=PP(Sf,a);return e&&e.value}});var Qo=b(($M,Ef)=>{"use strict";var If=function(){this.head=null,this.tail=null};If.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};Ef.exports=If});var Pf=b((LM,xf)=>{"use strict";var wP=cr();xf.exports=/ipad|iphone|ipod/i.test(wP)&&typeof Pebble!="undefined"});var Af=b((MM,wf)=>{"use strict";var AP=cr();wf.exports=/web0s(?!.*chrome)/i.test(AP)});var Df=b((CM,Cf)=>{"use strict";var jr=de(),kP=Tf(),kf=Br(),Wo=Go().set,RP=Qo(),$P=Bo(),LP=Pf(),MP=Af(),Yo=Ps(),Rf=jr.MutationObserver||jr.WebKitMutationObserver,$f=jr.document,Lf=jr.process,ws=jr.Promise,Jo=kP("queueMicrotask"),Hr,zo,Ko,As,Mf;Jo||(Vi=new RP,_i=function(){var a,e;for(Yo&&(a=Lf.domain)&&a.exit();e=Vi.get();)try{e()}catch(t){throw Vi.head&&Hr(),t}a&&a.enter()},!$P&&!Yo&&!MP&&Rf&&$f?(zo=!0,Ko=$f.createTextNode(""),new Rf(_i).observe(Ko,{characterData:!0}),Hr=function(){Ko.data=zo=!zo}):!LP&&ws&&ws.resolve?(As=ws.resolve(void 0),As.constructor=ws,Mf=kf(As.then,As),Hr=function(){Mf(_i)}):Yo?Hr=function(){Lf.nextTick(_i)}:(Wo=kf(Wo,jr),Hr=function(){Wo(_i)}),Jo=function(a){Vi.head||Hr(),Vi.add(a)});var Vi,_i;Cf.exports=Jo});var Bf=b((DM,Of)=>{"use strict";Of.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ks=b((OM,Vf)=>{"use strict";Vf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var mr=b((BM,_f)=>{"use strict";var CP=de();_f.exports=CP.Promise});var Gr=b((VM,Uf)=>{"use strict";var DP=de(),Ni=mr(),OP=le(),BP=Yn(),VP=Mo(),_P=Ie(),Nf=$o(),NP=rt(),Xo=On(),Ff=Ni&&Ni.prototype,FP=_P("species"),Zo=!1,qf=OP(DP.PromiseRejectionEvent),qP=BP("Promise",function(){var a=VP(Ni),e=a!==String(Ni);if(!e&&Xo===66||NP&&!(Ff.catch&&Ff.finally))return!0;if(!Xo||Xo<51||!/native code/.test(a)){var t=new Ni(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[FP]=r,Zo=t.then(function(){})instanceof r,!Zo)return!0}return!e&&(Nf==="BROWSER"||Nf==="DENO")&&!qf});Uf.exports={CONSTRUCTOR:qP,REJECTION_EVENT:qf,SUBCLASSING:Zo}});var Qr=b((_M,jf)=>{"use strict";var Hf=ct(),UP=TypeError,HP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new UP("Bad Promise constructor");e=r,t=i}),this.resolve=Hf(e),this.reject=Hf(t)};jf.exports.f=function(a){return new HP(a)}});var lm=b(()=>{"use strict";var jP=he(),GP=rt(),Ms=Ps(),Gt=de(),Kr=_e(),Gf=Ur(),Qf=xo(),QP=$i(),WP=Gh(),YP=ct(),Ls=le(),zP=Ne(),KP=Wh(),JP=Oo(),Jf=Go().set,au=Df(),XP=Bf(),ZP=ks(),ew=Qo(),Xf=co(),Cs=mr(),su=Gr(),Zf=Qr(),Ds="Promise",em=su.CONSTRUCTOR,tw=su.REJECTION_EVENT,rw=su.SUBCLASSING,eu=Xf.getterFor(Ds),iw=Xf.set,Wr=Cs&&Cs.prototype,br=Cs,Rs=Wr,tm=Gt.TypeError,tu=Gt.document,nu=Gt.process,ru=Zf.f,aw=ru,sw=!!(tu&&tu.createEvent&&Gt.dispatchEvent),rm="unhandledrejection",nw="rejectionhandled",Wf=0,im=1,ow=2,ou=1,am=2,$s,Yf,uw,zf,sm=function(a){var e;return zP(a)&&Ls(e=a.then)?e:!1},nm=function(a,e){var t=e.value,r=e.state===im,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===am&&cw(e),e.rejection=ou),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new tm("Promise-chain cycle")):(l=sm(u))?Kr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},om=function(a,e){a.notified||(a.notified=!0,au(function(){for(var t=a.reactions,r;r=t.get();)nm(r,a);a.notified=!1,e&&!a.rejection&&lw(a)}))},um=function(a,e,t){var r,i;sw?(r=tu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Gt.dispatchEvent(r)):r={promise:e,reason:t},!tw&&(i=Gt["on"+a])?i(r):a===rm&&XP("Unhandled promise rejection",t)},lw=function(a){Kr(Jf,Gt,function(){var e=a.facade,t=a.value,r=Kf(a),i;if(r&&(i=ZP(function(){Ms?nu.emit("unhandledRejection",t,e):um(rm,e,t)}),a.rejection=Ms||Kf(a)?am:ou,i.error))throw i.value})},Kf=function(a){return a.rejection!==ou&&!a.parent},cw=function(a){Kr(Jf,Gt,function(){var e=a.facade;Ms?nu.emit("rejectionHandled",e):um(nw,e,a.value)})},Yr=function(a,e,t){return function(r){a(e,r,t)}},zr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=ow,om(a,!0))},iu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new tm("Promise can't be resolved itself");var r=sm(e);r?au(function(){var i={done:!1};try{Kr(r,e,Yr(iu,i,a),Yr(zr,i,a))}catch(s){zr(i,s,a)}}):(a.value=e,a.state=im,om(a,!1))}catch(i){zr({done:!1},i,a)}}};if(em&&(br=function(e){KP(this,Rs),YP(e),Kr($s,this);var t=eu(this);try{e(Yr(iu,t),Yr(zr,t))}catch(r){zr(t,r)}},Rs=br.prototype,$s=function(e){iw(this,{type:Ds,done:!1,notified:!1,parent:!1,reactions:new ew,rejection:!1,state:Wf,value:void 0})},$s.prototype=Gf(Rs,"then",function(e,t){var r=eu(this),i=ru(JP(this,br));return r.parent=!0,i.ok=Ls(e)?e:!0,i.fail=Ls(t)&&t,i.domain=Ms?nu.domain:void 0,r.state===Wf?r.reactions.add(i):au(function(){nm(i,r)}),i.promise}),Yf=function(){var a=new $s,e=eu(a);this.promise=a,this.resolve=Yr(iu,e),this.reject=Yr(zr,e)},Zf.f=ru=function(a){return a===br||a===uw?new Yf(a):aw(a)},!GP&&Ls(Cs)&&Wr!==Object.prototype)){zf=Wr.then,rw||Gf(Wr,"then",function(e,t){var r=this;return new br(function(i,s){Kr(zf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Wr.constructor}catch(a){}Qf&&Qf(Wr,Rs)}jP({global:!0,constructor:!0,wrap:!0,forced:em},{Promise:br});QP(br,Ds,!1,!0);WP(Ds)});var fm=b((qM,hm)=>{"use strict";var dw=Ie(),dm=dw("iterator"),pm=!1;try{cm=0,uu={next:function(){return{done:!!cm++}},return:function(){pm=!0}},uu[dm]=function(){return this},Array.from(uu,function(){throw 2})}catch(a){}var cm,uu;hm.exports=function(a,e){try{if(!e&&!pm)return!1}catch(i){return!1}var t=!1;try{var r={};r[dm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var lu=b((UM,mm)=>{"use strict";var pw=mr(),hw=fm(),fw=Gr().CONSTRUCTOR;mm.exports=fw||!hw(function(a){pw.all(a).then(void 0,function(){})})});var bm=b(()=>{"use strict";var mw=he(),bw=_e(),gw=ct(),vw=Qr(),Sw=ks(),yw=Is(),Tw=lu();mw({target:"Promise",stat:!0,forced:Tw},{all:function(e){var t=this,r=vw.f(t),i=r.resolve,s=r.reject,n=Sw(function(){var o=gw(t.resolve),u=[],l=0,c=1;yw(e,function(d){var p=l++,h=!1;c++,bw(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var vm=b(()=>{"use strict";var Iw=he(),Ew=rt(),xw=Gr().CONSTRUCTOR,du=mr(),Pw=yt(),ww=le(),Aw=Ur(),gm=du&&du.prototype;Iw({target:"Promise",proto:!0,forced:xw,real:!0},{catch:function(a){return this.then(void 0,a)}});!Ew&&ww(du)&&(cu=Pw("Promise").prototype.catch,gm.catch!==cu&&Aw(gm,"catch",cu,{unsafe:!0}));var cu});var Sm=b(()=>{"use strict";var kw=he(),Rw=_e(),$w=ct(),Lw=Qr(),Mw=ks(),Cw=Is(),Dw=lu();kw({target:"Promise",stat:!0,forced:Dw},{race:function(e){var t=this,r=Lw.f(t),i=r.reject,s=Mw(function(){var n=$w(t.resolve);Cw(e,function(o){Rw(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var ym=b(()=>{"use strict";var Ow=he(),Bw=Qr(),Vw=Gr().CONSTRUCTOR;Ow({target:"Promise",stat:!0,forced:Vw},{reject:function(e){var t=Bw.f(this),r=t.reject;return r(e),t.promise}})});var pu=b((JM,Tm)=>{"use strict";var _w=dt(),Nw=Ne(),Fw=Qr();Tm.exports=function(a,e){if(_w(a),Nw(e)&&e.constructor===a)return e;var t=Fw.f(a),r=t.resolve;return r(e),t.promise}});var xm=b(()=>{"use strict";var qw=he(),Uw=yt(),Im=rt(),Hw=mr(),Em=Gr().CONSTRUCTOR,jw=pu(),Gw=Uw("Promise"),Qw=Im&&!Em;qw({target:"Promise",stat:!0,forced:Im||Em},{resolve:function(e){return jw(Qw&&this===Gw?Hw:this,e)}})});var Pm=b(()=>{"use strict";lm();bm();vm();Sm();ym();xm()});var Rm=b(()=>{"use strict";var Ww=he(),Yw=rt(),Os=mr(),zw=Te(),Am=yt(),km=le(),Kw=Oo(),wm=pu(),Jw=Ur(),fu=Os&&Os.prototype,Xw=!!Os&&zw(function(){fu.finally.call({then:function(){}},function(){})});Ww({target:"Promise",proto:!0,real:!0,forced:Xw},{finally:function(a){var e=Kw(this,Am("Promise")),t=km(a);return this.then(t?function(r){return wm(e,a()).then(function(){return r})}:a,t?function(r){return wm(e,a()).then(function(){throw r})}:a)}});!Yw&&km(Os)&&(hu=Am("Promise").prototype.finally,fu.finally!==hu&&Jw(fu,"finally",hu,{unsafe:!0}));var hu});var Lm=b((a0,$m)=>{"use strict";_h();Pm();Rm();var Zw=jt();$m.exports=Zw("Promise","finally")});var Cm=b((s0,Mm)=>{"use strict";var eA=Lm();Mm.exports=eA});var Bs=b((n0,Dm)=>{"use strict";var tA=Cm();Dm.exports=tA});var qm=b(()=>{"use strict";var nA=he(),oA=no().values;nA({target:"Object",stat:!0},{values:function(e){return oA(e)}})});var Hm=b((V0,Um)=>{"use strict";qm();var uA=Cr();Um.exports=uA.Object.values});var Gm=b((_0,jm)=>{"use strict";var lA=Hm();jm.exports=lA});var Jr=b((N0,Qm)=>{"use strict";var cA=Gm();Qm.exports=cA});var Km=b(()=>{"use strict";var fA=he(),mA=Dr(),bA=Fr(),gA=wi(),vA=Ai();fA({target:"Array",proto:!0},{at:function(e){var t=mA(this),r=bA(t),i=gA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});vA("at")});var Xm=b((lC,Jm)=>{"use strict";Km();var SA=jt();Jm.exports=SA("Array","at")});var eb=b((cC,Zm)=>{"use strict";var yA=Xm();Zm.exports=yA});var Xr=b((dC,tb)=>{"use strict";var TA=eb();tb.exports=TA});var Lu=b((RD,Tb)=>{"use strict";var MA=ur();Tb.exports=Array.isArray||function(e){return MA(e)==="Array"}});var Eb=b(($D,Ib)=>{"use strict";var CA=TypeError,DA=9007199254740991;Ib.exports=function(a){if(a>DA)throw CA("Maximum allowed index exceeded");return a}});var wb=b((LD,Pb)=>{"use strict";var OA=Lu(),BA=Fr(),VA=Eb(),_A=Br(),xb=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?_A(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&OA(d)?(p=BA(d),u=xb(a,e,d,p,u,s-1)-1):(VA(u+1),a[u]=d),u++),l++;return u};Pb.exports=xb});var $b=b((MD,Rb)=>{"use strict";var Ab=Lu(),NA=Do(),FA=Ne(),qA=Ie(),UA=qA("species"),kb=Array;Rb.exports=function(a){var e;return Ab(a)&&(e=a.constructor,NA(e)&&(e===kb||Ab(e.prototype))?e=void 0:FA(e)&&(e=e[UA],e===null&&(e=void 0))),e===void 0?kb:e}});var Mb=b((CD,Lb)=>{"use strict";var HA=$b();Lb.exports=function(a,e){return new(HA(a))(e===0?0:e)}});var Cb=b(()=>{"use strict";var jA=he(),GA=wb(),QA=ct(),WA=Dr(),YA=Fr(),zA=Mb();jA({target:"Array",proto:!0},{flatMap:function(e){var t=WA(this),r=YA(t),i;return QA(e),i=zA(t,0),i.length=GA(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Db=b(()=>{"use strict";var KA=Ai();KA("flatMap")});var Bb=b((_D,Ob)=>{"use strict";Cb();Db();var JA=jt();Ob.exports=JA("Array","flatMap")});var _b=b((ND,Vb)=>{"use strict";var XA=Bb();Vb.exports=XA});var Mu=b((FD,Nb)=>{"use strict";var ZA=_b();Nb.exports=ZA});var Ji=b((zD,sg)=>{"use strict";var ok=Ri(),uk=String;sg.exports=function(a){if(ok(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return uk(a)}});var Du=b((KD,ng)=>{"use strict";ng.exports=`
|
|
7
|
+
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var lg=b((JD,ug)=>{"use strict";var lk=me(),ck=Ht(),dk=Ji(),Bu=Du(),og=lk("".replace),pk=RegExp("^["+Bu+"]+"),hk=RegExp("(^|[^"+Bu+"])["+Bu+"]+$"),Ou=function(a){return function(e){var t=dk(ck(e));return a&1&&(t=og(t,pk,"")),a&2&&(t=og(t,hk,"$1")),t}};ug.exports={start:Ou(1),end:Ou(2),trim:Ou(3)}});var hg=b((XD,pg)=>{"use strict";var fk=fo().PROPER,mk=Te(),cg=Du(),dg="\u200B\x85\u180E";pg.exports=function(a){return mk(function(){return!!cg[a]()||dg[a]()!==dg||fk&&cg[a].name!==a})}});var Vu=b((ZD,fg)=>{"use strict";var bk=lg().start,gk=hg();fg.exports=gk("trimStart")?function(){return bk(this)}:"".trimStart});var bg=b(()=>{"use strict";var vk=he(),mg=Vu();vk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==mg},{trimLeft:mg})});var vg=b(()=>{"use strict";bg();var Sk=he(),gg=Vu();Sk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==gg},{trimStart:gg})});var yg=b((aO,Sg)=>{"use strict";vg();var yk=jt();Sg.exports=yk("String","trimLeft")});var Ig=b((sO,Tg)=>{"use strict";var Tk=yg();Tg.exports=Tk});var xg=b((nO,Eg)=>{"use strict";var Ik=Ig();Eg.exports=Ik});var _g=b(()=>{"use strict"});var Ng=b(()=>{"use strict"});var qg=b((wV,Fg)=>{"use strict";var Uk=Ne(),Hk=ur(),jk=Ie(),Gk=jk("match");Fg.exports=function(a){var e;return Uk(a)&&((e=a[Gk])!==void 0?!!e:Hk(a)==="RegExp")}});var Hg=b((AV,Ug)=>{"use strict";var Qk=dt();Ug.exports=function(){var a=Qk(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var Qg=b((kV,Gg)=>{"use strict";var Wk=_e(),Yk=it(),zk=yi(),Kk=Hg(),jg=RegExp.prototype;Gg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in jg)&&!Yk(a,"flags")&&zk(jg,a)?Wk(Kk,a):e}});var Yg=b((RV,Wg)=>{"use strict";var ju=me(),Jk=Dr(),Xk=Math.floor,Uu=ju("".charAt),Zk=ju("".replace),Hu=ju("".slice),eR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,tR=/\$([$&'`]|\d{1,2})/g;Wg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=tR;return i!==void 0&&(i=Jk(i),u=eR),Zk(s,u,function(l,c){var d;switch(Uu(c,0)){case"$":return"$";case"&":return a;case"`":return Hu(e,0,t);case"'":return Hu(e,n);case"<":d=i[Hu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=Xk(p/10);return h===0?l:h<=o?r[h-1]===void 0?Uu(c,1):r[h-1]+Uu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var Jg=b(()=>{"use strict";var rR=he(),iR=_e(),Qu=me(),zg=Ht(),aR=le(),sR=Mr(),nR=qg(),si=Ji(),oR=Ii(),uR=Qg(),lR=Yg(),cR=Ie(),dR=rt(),pR=cR("replace"),hR=TypeError,Gu=Qu("".indexOf),fR=Qu("".replace),Kg=Qu("".slice),mR=Math.max;rR({target:"String",proto:!0},{replaceAll:function(e,t){var r=zg(this),i,s,n,o,u,l,c,d,p,h,m=0,g="";if(!sR(e)){if(i=nR(e),i&&(s=si(zg(uR(e))),!~Gu(s,"g")))throw new hR("`.replaceAll` does not allow non-global regexes");if(n=oR(e,pR),n)return iR(n,e,r,t);if(dR&&i)return fR(si(r),e,t)}for(o=si(r),u=si(e),l=aR(t),l||(t=si(t)),c=u.length,d=mR(1,c),p=Gu(o,u);p!==-1;)h=l?si(t(u,p,o)):lR(u,o,p,[],void 0,t),g+=Kg(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Gu(o,u,p+d);return m<o.length&&(g+=Kg(o,m)),g}})});var Zg=b((MV,Xg)=>{"use strict";_g();Ng();Jg();var bR=jt();Xg.exports=bR("String","replaceAll")});var tv=b((CV,ev)=>{"use strict";var gR=Zg();ev.exports=gR});var iv=b((DV,rv)=>{"use strict";var vR=tv();rv.exports=vR});var sv=b((OV,av)=>{"use strict";var SR=wi(),yR=Ji(),TR=Ht(),IR=RangeError;av.exports=function(e){var t=yR(TR(this)),r="",i=SR(e);if(i<0||i===1/0)throw new IR("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var cv=b((BV,lv)=>{"use strict";var uv=me(),ER=eo(),nv=Ji(),xR=sv(),PR=Ht(),wR=uv(xR),AR=uv("".slice),kR=Math.ceil,ov=function(a){return function(e,t,r){var i=nv(PR(e)),s=ER(t),n=i.length,o=r===void 0?" ":nv(r),u,l;return s<=n||o===""?i:(u=s-n,l=wR(o,kR(u/o.length)),l.length>u&&(l=AR(l,0,u)),a?i+l:l+i)}};lv.exports={start:ov(!1),end:ov(!0)}});var pv=b((VV,dv)=>{"use strict";var RR=cr();dv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(RR)});var hv=b(()=>{"use strict";var $R=he(),LR=cv().start,MR=pv();$R({target:"String",proto:!0,forced:MR},{padStart:function(e){return LR(this,e,arguments.length>1?arguments[1]:void 0)}})});var mv=b((FV,fv)=>{"use strict";hv();var CR=jt();fv.exports=CR("String","padStart")});var gv=b((qV,bv)=>{"use strict";var DR=mv();bv.exports=DR});var Sv=b((UV,vv)=>{"use strict";var OR=gv();vv.exports=OR});var ZR={};PS(ZR,{ChromecastState:()=>bi,HttpConnectionType:()=>rs,Observable:()=>gt.Observable,PlaybackState:()=>Pe,Player:()=>Ua,SDK_VERSION:()=>XR,Subject:()=>gt.Subject,Subscription:()=>gt.Subscription,Surface:()=>is,VERSION:()=>xn,ValueSubject:()=>gt.ValueSubject,VideoFormat:()=>St,VideoQuality:()=>gt.VideoQuality});module.exports=wS(ZR);var xn="2.0.123-dev.92e9449d.0";var Pe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Pe||{}),St=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(St||{});var bi=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(bi||{}),rs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(rs||{});var is=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(is||{});var dS=W(at(),1);var F=require("@vkontakte/videoplayer-shared/es2018");var Fd=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var us=class{constructor(e){this.connection$=new F.ValueSubject(void 0);this.castState$=new F.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new F.Subject;this.realCastState$=new F.ValueSubject("NOT_AVAILABLE");this.subscription=new F.Subscription;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,F.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||Fd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:F.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,F.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,F.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,F.assertNever)(i.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,F.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,F.map)(i=>i.castState)),(0,F.observableFrom)([r.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(YT),(0,F.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,F.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();(0,F.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,F.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(0,F.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},YT=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,F.assertNever)(a)}};var dl=W(at(),1),Xv=W(qr(),1),Zv=W(Ro(),1);var _m=W(Bs(),1);var mu=require("@vkontakte/videoplayer-shared/es2018");var Ee=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:(0,mu.assertNever)(t)}return a},Vs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:(0,mu.assertNever)(e)}};var A=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var pt=require("@vkontakte/videoplayer-shared/es2018"),U=class{constructor(e){this.transitionStarted$=new pt.Subject;this.transitionEnded$=new pt.Subject;this.transitionUpdated$=new pt.Subject;this.forceChanged$=new pt.Subject;this.stateChangeStarted$=(0,pt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,pt.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,pt.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 Om=require("@vkontakte/videoplayer-shared/es2018"),Bm=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Om.assertNever)(a)}};var $=require("@vkontakte/videoplayer-shared/es2018");var rA=5,iA=5,aA=500,Vm=7e3,Fi=class{constructor(e){this.subscription=new $.Subscription;this.loadMediaTimeoutSubscription=new $.Subscription;this.videoState=new U("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,$.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,$.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,$.assertNever)(e)}break}default:(0,$.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(Bm(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 $.Subscription;this.subscription.add(e),this.subscription.add((0,$.merge)(this.videoState.stateChangeStarted$.pipe((0,$.map)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,$.map)(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new $.Subject;e.add(i.pipe((0,$.debounce)(aA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,$.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)>rA)&&i.next(o),s=o})),e.add((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<iA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,$.assertNever)(n)}}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,$.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,$.observableFrom)(["init"])).pipe((0,$.debounce)(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];(0,$.assertNonNullable)(c);let d=(0,$.getHighestQuality)(Object.keys(c));(0,$.assertNonNullable)(d);let p=c[d];(0,$.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,$.assertNonNullable)(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];(0,$.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,$.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,$.assertNonNullable)(c),r=Ee(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:$.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,$.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,$.isNonNullable)(o)&&(n.metadata.title=o),(0,$.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add((0,$.timeout)(Vm).subscribe(()=>s(`timeout(${Vm})`)))});(0,_m.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:$.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Ru=W(at(),1);var Su=require("@vkontakte/videoplayer-shared/es2018");var Nm=require("@vkontakte/videoplayer-shared/es2018"),Fm=a=>{try{a.pause(),a.playbackRate=0,(0,Nm.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var _s=require("@vkontakte/videoplayer-shared/es2018"),bu=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)}},gu=window.WeakMap?new WeakMap:new bu,vu=window.WeakMap?new WeakMap:new Map,sA=(a,e=20)=>{let t=0;return(0,_s.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},ke=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,Su.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),gu.set(t,r);let i=new _s.Subscription;return i.add(sA(t,e)),vu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Re=a=>{let e=vu.get(a);e==null||e.unsubscribe(),vu.delete(a);let t=gu.get(a);gu.delete(a),t?(0,Su.clearVideoElement)(a):Fm(a)};var yu=W(Jr(),1),L=require("@vkontakte/videoplayer-shared/es2018");var Qt=require("@vkontakte/videoplayer-shared/es2018"),Ns=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Qt.isNullable)(i),l=new Qt.Subscription;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ht=(a,e,t)=>Ns(e,()=>a.loop,r=>{(0,Qt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),$e=(a,e,t,r)=>Ns(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Qt.isNonNullable)(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Qe=(a,e,t,r)=>Ns(e,()=>a.playbackRate,i=>{(0,Qt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Wt=Ns;var dA=a=>["__",a.language,a.label].join("|"),pA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Tu=class a{constructor(){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Wt(t.internalTextTracks,()=>(0,yu.default)(this.internalTracks),s=>{(0,L.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Wt(t.externalTextTracks,()=>(0,yu.default)(this.externalTracks),s=>{(0,L.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Wt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Wt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,L.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,L.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,L.filterChanged)()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;(0,L.isNonNullable)(t.align)&&(i.align=t.align),(0,L.isNonNullable)(t.position)&&(i.position=t.position),(0,L.isNonNullable)(t.size)&&(i.size=t.size),(0,L.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:dA(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!pA(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,L.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,L.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},We=Tu;var Et=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 Wm=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Iu=a=>{let e=Wm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Ym=a=>{let e=Wm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var C=require("@vkontakte/videoplayer-shared/es2018");var hA=3,zm=(a,e,t=hA)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Le=a=>{let e=x=>(0,C.fromEvent)(a,x).pipe((0,C.mapTo)(void 0)),r=(0,C.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,C.fromEvent)(a,x))).pipe((0,C.map)(x=>x.type==="ended"?a.readyState<2:a.readyState<3),(0,C.filterChanged)()),i=(0,C.merge)((0,C.fromEvent)(a,"progress"),(0,C.fromEvent)(a,"timeupdate")).pipe((0,C.map)(()=>zm(a.buffered,a.currentTime))),s=C.clientChecker.isSafari?(0,C.combine)({play:e("play").pipe((0,C.once)()),playing:e("playing")}).pipe((0,C.mapTo)(void 0)):e("playing"),n=(0,C.fromEvent)(a,"volumechange").pipe((0,C.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,C.fromEvent)(a,"ratechange").pipe((0,C.map)(()=>a.playbackRate)),u=(0,C.fromEvent)(a,"error").pipe((0,C.filter)(()=>!!(a.error||a.played.length)),(0,C.map)(()=>{var k;let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:C.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:(k=a.error)!=null?k:void 0}})),l=(0,C.fromEvent)(a,"timeupdate").pipe((0,C.map)(()=>a.currentTime)),c=new C.Subject,d=.3,p;l.subscribe(x=>{a.loop&&(0,C.isNonNullable)(p)&&(0,C.isNonNullable)(x)&&p>=a.duration-d&&x<=d&&c.next(p),p=x});let h=e("pause").pipe((0,C.filter)(()=>!a.error&&p!==a.duration)),m=(0,C.fromEvent)(a,"enterpictureinpicture"),g=(0,C.fromEvent)(a,"leavepictureinpicture"),v=new C.ValueSubject(Ym(a));m.subscribe(()=>v.next(!0)),g.subscribe(()=>v.next(!1));let I=new C.ValueSubject(Iu(a));return(0,C.fromEvent)(a,"fullscreenchange").pipe((0,C.map)(()=>Iu(a))).subscribe(I),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,C.fromEvent)(a,"durationchange").pipe((0,C.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:I,enterPip$:m,leavePip$:g}};var xt=require("@vkontakte/videoplayer-shared/es2018"),Yt=a=>{switch(a){case"mobile":return xt.VideoQuality.Q_144P;case"lowest":return xt.VideoQuality.Q_240P;case"low":return xt.VideoQuality.Q_360P;case"sd":case"medium":return xt.VideoQuality.Q_480P;case"hd":case"high":return xt.VideoQuality.Q_720P;case"fullhd":case"full":return xt.VideoQuality.Q_1080P;case"quadhd":case"quad":return xt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return xt.VideoQuality.Q_2160P}};var zt=W(Xr(),1),nb=W(at(),1),Fs=W(qr(),1),M=require("@vkontakte/videoplayer-shared/es2018");var Eu=!1,Pt={},rb=a=>{Eu=a},ib=()=>{Pt={}},ab=a=>{a(Pt)},qi=(a,e)=>{var t;Eu&&(Pt.meta=(t=Pt.meta)!=null?t:{},Pt.meta[a]=e)},we=class{constructor(e){this.name=e}next(e){var r,i;if(!Eu)return;Pt.series=(r=Pt.series)!=null?r:{};let t=(i=Pt.series[this.name])!=null?i:[];t.push([Date.now(),e]),Pt.series[this.name]=t}};var IA=new we("best_bitrate"),ob=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var xu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ui=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,M.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ub='Assertion "ABR Tracks is empty array" failed',qs=(a,e,t,r)=>{var u;let i=[...e].sort(xu(1)),s=[...t].sort(xu(1)),n=s.filter(l=>(0,M.isNonNullable)(l.bitrate)&&(0,M.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,zt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,zt.default)(s,-1);return o&&(0,nb.default)(n,o)?o:n.length?(0,zt.default)(n,-1):(0,zt.default)(s,0)},sb=a=>"quality"in a,lb=(a,e,t,r)=>{var n;let i=(0,M.isNonNullable)((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&(0,M.isNonNullable)(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,M.now)()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=sb(o)?"video":"audio",l=sb(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
|
-
`}),o}return r==null||r.recordSwitch(t),t},
|
|
9
|
+
`}),o}return r==null||r.recordSwitch(t),t},EA=(a,e)=>Math.log(e)/Math.log(a),Kt=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{var X,D,_,ie,pe,R;(0,M.assertNotEmptyArray)(a,ub);let g=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let P=window.devicePixelRatio;if(r.pixelRatioMultiplier)g*=r.pixelRatioMultiplier*(P-1)+1;else{let q=r.pixelRatioLogBase,[N=0,fe=0,He=0]=r.pixelRatioLogCoefficients,Dt=EA(q,N*P+fe)+He;Number.isFinite(Dt)&&(g*=Dt)}}let v=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*g,height:e.height*g}:void 0,I=r.considerPlaybackRate&&(0,M.isNonNullable)(o)?o:1,E=a.filter(P=>!(0,M.isInvariantQuality)(P.quality)).sort((P,q)=>(0,M.isHigher)(P.quality,q.quality)?-1:1),x=(X=(0,zt.default)(E,-1))==null?void 0:X.quality,k=(D=(0,zt.default)(E,0))==null?void 0:D.quality,w=(0,M.isNullable)(i)||(0,M.isNonNullable)(i.min)&&(0,M.isNonNullable)(i.max)&&(0,M.isLower)(i.max,i.min)||(0,M.isNonNullable)(i.min)&&k&&(0,M.isHigher)(i.min,k)||(0,M.isNonNullable)(i.max)&&x&&(0,M.isLower)(i.max,x),j=I*ob(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),Q={},Y=E.filter(P=>{let q=!0;if(v)if(P.size)q=P.size.width<=v.width&&P.size.height<=v.height;else{let ye=v&&(0,M.videoSizeToQuality)(v);q=ye?(0,M.isLowerOrEqual)(P.quality,ye):!0}if(!q)return Q[P.quality]="FitsContainer",!1;let N=h||t;if(!((0,M.isNonNullable)(N)&&isFinite(N)&&(0,M.isNonNullable)(P.bitrate)?N-s>=P.bitrate*j:!0))return Q[P.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&(0,M.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,M.isInvariantQuality)(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,M.isHigher)(P.quality,u.quality))return Q[P.quality]="Buffer",!1;if(!!d&&(0,M.isHigherOrEqual)(P.quality,d))return Q[P.quality]="DroppedFramesLimit",!1;if(!!p&&(0,M.isHigherOrEqual)(P.quality,p))return Q[P.quality]="StallsLimit",!1;let Z=w||((0,M.isNullable)(i.max)||(0,M.isLowerOrEqual)(P.quality,i.max))&&((0,M.isNullable)(i.min)||(0,M.isHigherOrEqual)(P.quality,i.min)),Se=(0,M.isNonNullable)(c)&&!c?(0,M.isLowerOrEqual)(P.quality,r.backgroundVideoQualityLimit):!0;return!Z||!Se?(Q[P.quality]="FitsQualityLimits",!1):!0})[0];Y&&Y.bitrate&&IA.next(Y.bitrate);let J=(_=Y!=null?Y:(0,zt.default)(E,-1))!=null?_:a[0];return J.quality!==((ie=l==null?void 0:l.last)==null?void 0:ie.quality)&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${a.map(P
|
|
12
|
+
${a.map(P=>{var q,N;return`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate}, size: ${(q=P.size)==null?void 0:q.width}:${(N=P.size)==null?void 0:N.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,Fs.default)(r!=null?r:{}).map(([P,q])=>`${P}: ${q}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
|
-
|
|
20
|
+
containerSizeFactor: ${g},
|
|
21
|
+
containerSizeLimit: ${(pe=v==null?void 0:v.width)!=null?pe:0} x ${(R=v==null?void 0:v.height)!=null?R:0},
|
|
21
22
|
estimatedThroughput: ${t},
|
|
22
|
-
stallsPredictedThroughput: ${
|
|
23
|
+
stallsPredictedThroughput: ${h},
|
|
23
24
|
reserve: ${s},
|
|
24
25
|
playbackRate: ${o},
|
|
25
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${I},
|
|
26
27
|
forwardBufferHealth: ${n},
|
|
27
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${j},
|
|
28
29
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
29
30
|
droppedVideoMaxQualityLimit: ${d},
|
|
30
|
-
stallsVideoMaxQualityLimit: ${
|
|
31
|
-
limitsAreInvalid: ${
|
|
31
|
+
stallsVideoMaxQualityLimit: ${p},
|
|
32
|
+
limitsAreInvalid: ${w},
|
|
32
33
|
maxQualityLimit: ${i==null?void 0:i.max},
|
|
33
34
|
minQualityLimit: ${i==null?void 0:i.min},
|
|
34
35
|
|
|
35
36
|
[limited video tracks]
|
|
36
|
-
${(0,
|
|
37
|
+
${(0,Fs.default)(Q).map(([P,q])=>`${P}: ${q}`).join(`
|
|
37
38
|
`)||"All tracks are available"}
|
|
38
39
|
|
|
39
|
-
[best video track] ${
|
|
40
|
+
[best video track] ${Y==null?void 0:Y.quality}
|
|
40
41
|
[selected video track] ${J==null?void 0:J.quality}
|
|
41
|
-
`}),
|
|
42
|
+
`}),lb(r,m,J,l)},cb=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var I;(0,M.assertNotEmptyArray)(t,ub);let c=i.considerPlaybackRate&&(0,M.isNonNullable)(s)?s:1,d=[...t].sort(xu(-1)),p=a.bitrate;(0,M.assertNonNullable)(p);let h=c*ob(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,g=qs(a,e,t,i.minVideoAudioRatio),v=l||r;return(0,M.isNonNullable)(v)&&isFinite(v)&&(m=d.find(E=>(0,M.isNonNullable)(E.bitrate)&&(0,M.isNonNullable)(g==null?void 0:g.bitrate)?v-p>=E.bitrate*h&&E.bitrate>=g.bitrate:!1)),m||(m=g),(m==null?void 0:m.bitrate)!==((I=o==null?void 0:o.last)==null?void 0:I.bitrate)&&u({message:`
|
|
42
43
|
[AUDIO TRACKS ABR]
|
|
43
44
|
[available audio tracks]
|
|
44
45
|
${t.map(E=>`{ id: ${E.id}, bitrate: ${E.bitrate} }`).join(`
|
|
45
46
|
`)}
|
|
46
47
|
|
|
47
48
|
[tuning]
|
|
48
|
-
${(0,
|
|
49
|
+
${(0,Fs.default)(i!=null?i:{}).map(([E,x])=>`${E}: ${x}`).join(`
|
|
49
50
|
`)}
|
|
50
51
|
|
|
51
52
|
[limit params]
|
|
52
53
|
estimatedThroughput: ${r},
|
|
53
54
|
stallsPredictedThroughput: ${l},
|
|
54
|
-
reserve: ${
|
|
55
|
+
reserve: ${p},
|
|
55
56
|
playbackRate: ${s},
|
|
56
57
|
playbackRateFactor: ${c},
|
|
57
58
|
forwardBufferHealth: ${n},
|
|
58
|
-
bitrateFactor: ${
|
|
59
|
+
bitrateFactor: ${h},
|
|
59
60
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
60
61
|
|
|
61
62
|
[selected audio track] ${m==null?void 0:m.id}
|
|
62
|
-
`}),m&&rb(i,u,m,o)};var me=a=>new URL(a).hostname;var O=require("@vkontakte/videoplayer-shared/es2018");var sb=Y(lt(),1),ab=a=>{if(a instanceof DOMException&&(0,sb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Le=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!ab(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return ab(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};var Ne=require("@vkontakte/videoplayer-shared/es2018");var nb=Y(Oi(),1),pt=require("@vkontakte/videoplayer-shared/es2018");function be(){return(0,pt.now)()}function yu(a){return be()-a}function Tu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ob(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Wr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",m=7e3,g=2e3,v=()=>{if(u)return;(0,pt.assertNonNullable)(c);let B=yu(c),D;if(B<g){D=g-B,setTimeout(v,D);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new i,_()},T=B=>(s=B,X),E=B=>(d=B,X),x=()=>(p="json",X),w=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,d&&d(),t&&t()}},A=B=>(h=B,X),_=()=>{c=be(),n=new i,n.open("get",a);let B=0,D,re=0,ce=()=>((0,pt.assertNonNullable)(c),Math.max(c,Math.max(D||0,re||0)));if(s&&n.addEventListener("progress",R=>{let P=be();s.updateChunk&&R.loaded>B&&(s.updateChunk(ce(),R.loaded-B),B=R.loaded,D=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;(0,pt.assertNonNullable)(n);let R=n.status;if(R>=200&&R<300){if(n.response.byteLength&&s){let P=n.response.byteLength-B;P&&s.updateChunk&&s.updateChunk(ce(),P)}n.responseType==="json"&&!(0,nb.default)(n.response).length?w():(d&&d(),e(n.response))}else w()}),n.addEventListener("error",()=>{w()}),h){let R=()=>{(0,pt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(re=be(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=p,n.send(),X},X={withBitrateReporting:T,withParallel:A,withJSONResponse:x,withRetryCount:B=>(l=B,X),withRetryInterval:(B,D)=>((0,pt.isNonNullable)(B)&&(g=B),(0,pt.isNonNullable)(D)&&(m=D),X),withTimeout:B=>(o=B,X),withFinally:E,send:_,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return X}var _i=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var ub=Y(Oi(),1);var Ni=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=be(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=be()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Wr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=be()}_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=be();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(){(0,ub.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var lb=require("@vkontakte/videoplayer-shared/es2018"),Bs=1e4,Iu=3;var yw=6e4,Tw=10,Iw=1,Ew=500,Fi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new lb.Subject,this.chunkRateEstimator=new _i(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Tu(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=Tu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ne.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{ob(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ni(Iu,Bs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let w=s&&(!c||c===this.rep);return w||t("Not running!"),w},h=(w,A,_)=>{u&&u.abort(),u=Wr(this.urlResolver.resolve(w,!1),A,_,()=>this._retryCallback()).withTimeout(Bs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Iu).withFinally(()=>{u=null}).send()},p=(w,A,_)=>{(0,Ne.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),A,_,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=w=>{let A=r.playbackRate;r.playbackRate!==w&&(t(`Playback rate switch: ${A}=>${w}`),r.playbackRate=w)},g=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let _=be()-1e4,Q=0;for(let N=0;N<this.bufferStates.length;N++){let J=this.bufferStates[N];w=Math.min(w,J.buf),J.ts<_&&Q++}this.bufferStates.splice(0,Q),t(`update playback rate; minBuffer=${w} drop=${Q} jitter=${this.sourceJitter}`);let ie=w-Iw;this.sourceJitter>=0?ie-=this.sourceJitter/2:this.sourceJitter-=1,ie>3?m(1.15):ie>1?m(1.1):ie>.3?m(1.05):m(1)}},T=w=>{let A,_=()=>A&&A.start?A.start.length:0,Q=R=>A.start[R]/1e3,ie=R=>A.dur[R]/1e3,N=R=>A.fragIndex+R,J=(R,P)=>({chunkIdx:N(R),startTS:Q(R),dur:ie(R),discontinuity:P}),X=()=>{let R=0;if(A&&A.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,j=P;this.sourceJitter>1&&(j+=this.sourceJitter-1);let pe=A.dur.length-1;for(;pe>=0&&(j-=A.dur[pe],!(j<=0));--pe);R=Math.min(pe,A.dur.length-1-W),R=Math.max(R,0)}return J(R,!0)},B=R=>{let P=_();if(!(P<=0)){if((0,Ne.isNonNullable)(R)){for(let W=0;W<P;W++)if(Q(W)>R)return J(W)}return X()}},D=R=>{let P=_(),W=R?R.chunkIdx+1:0,j=W-A.fragIndex;if(!(P<=0)){if(!R||j<0||j-P>Tw)return t(`Resync: offset=${j} bChunks=${P} chunk=`+JSON.stringify(R)),X();if(!(j>=P))return J(W-A.fragIndex,!1)}},re=(R,P,W)=>{l&&l.abort(),l=Wr(this.urlResolver.resolve(R,!0,this.lowLatency),P,W,()=>this._retryCallback()).withTimeout(Bs).withRetryCount(Iu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,P)=>{re(w,W=>{if(!d())return;A=W;let j=!!A.lowLatency;j!==this.lowLatency&&g(j);let pe=0;for(let Ue=0;Ue<A.dur.length;++Ue)pe+=A.dur[Ue];pe>0&&((0,Ne.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(pe/A.dur.length)),i({name:"index",zeroTime:A.zeroTime,shiftDuration:A.shiftDuration}),this.sourceJitter=A.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,A.jitter/1e3)):1,R(B(P))},()=>this._handleNetworkError())},nextChunk:D}},E=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ne.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:w=>{let{videoElement:A,logger:_}=this.params,Q=T(e.jidxUrl),ie,N,J,X,B=0,D,re,ce,R=()=>{D&&(clearTimeout(D),D=void 0);let Z=Math.max(Ew,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ve=B+Z,Se=be(),He=Math.min(1e4,ve-Se);B=Se;let Ct=()=>{l||d()&&Q.seek(()=>{d()&&(B=be(),P(),R())})};He>0?D=window.setTimeout(()=>{this.paused?R():Ct()},He):Ct()},P=()=>{let Z;for(;Z=Q.nextChunk(X);)X=Z,Mt(Z);let ve=Q.nextChunk(J);if(ve){if(J&&ve.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?R():(E(),this._initPlayerWith(e));return}Ue(ve)}else R()},W=(Z,ve)=>{if(!d()||!this.sourceBuffer)return;let Se,He,Ct,Sr=Dt=>{window.setTimeout(()=>{d()&&W(Z,ve)},Dt)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),Sr(100);else{let Dt=be(),Xt=A.currentTime;!this.paused&&A.buffered.length>1&&re===Xt&&Dt-ce>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),re!==Xt&&(re=Xt,ce=Dt);let yr=this._getBufferSizeSec();if(yr>30)_(`Buffered ${yr} seconds; delaying appendBuffer`),Sr(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:Dt,buf:yr}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ve&&ve()}catch(ai){if(ai.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),Ct=this.sourceBuffer.buffered.length,Ct!==0&&(Se=this.sourceBuffer.buffered.start(0),He=Xt,He-Se>4&&this.sourceBuffer.remove(Se,He-3)),Sr(1e3);else throw ai}}},j=()=>{N&&ie&&(_([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(J)]),W(N,function(){N=null,P()}))},pe=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),Ue=Z=>{d()&&p(pe(Z),(ve,Se)=>{if(d()){if(Se/=1e3,N=ve,J=Z,n=Z.startTS,Se){let He=Math.min(10,Z.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*He:He}j()}},()=>this._handleNetworkError())},Mt=Z=>{d()&&((0,Ne.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(pe(Z),!1)))},vr=Z=>{d()&&(e.cachedHeader=Z,W(Z,()=>{ie=!0,j()}))};s=!0,Q.seek(Z=>{if(d()){if(B=be(),!Z){R();return}X=Z,!(0,Ne.isNullable)(w)||Z.startTS>w?Ue(Z):(J=Z,P())}},w),e.cachedHeader?vr(e.cachedHeader):h(e.headerUrl,vr,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,Ne.isNonNullable)(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Ne.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ne.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let m=be();if(this.chunkRateEstimator.addInterval(h,m,p)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:v}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&yu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=be();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Wr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Bs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Le(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},yw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var cb=Y(Vr(),1),ne=require("@vkontakte/videoplayer-shared/es2018"),Eu=class{constructor(){this.onDroopedVideoFramesLimit$=new ne.Subject;this.subscription=new ne.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ne.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,ne.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,ne.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,ne.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ne.interval)(this.droppedFramesChecker.checkTime).pipe((0,ne.filter)(()=>this.playing),(0,ne.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,ne.debounce)(this.droppedFramesChecker.checkTime)),r=(0,ne.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,cb.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,ne.isLower)(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},_s=Eu;var Ns=require("@vkontakte/videoplayer-shared/es2018"),db=require("@vkontakte/videoplayer-shared/es2018");var qi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var xw=(a,e)=>new Ns.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||qi()))},{...r,...e});i.observe(a);let s=(0,db.fromEvent)(document,"visibilitychange").pipe((0,Ns.map)(n=>!document.hidden||qi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),We=xw;var Pw=["paused","playing","ready"],Aw=["paused","playing","ready"],Ui=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new U("stopped");this.representations$=new O.ValueSubject([]);this.textTracksManager=new Qe;this.droppedFramesManager=new _s;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new Tt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:O.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Gt(u.name))!=null?r:(0,O.videoSizeToQuality)(u.video),d=u.bitrate/1e3,h={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,O.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,xu.default)(Aw,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,xu.default)(Pw,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Ee(this.params.source.url,u))}return;default:return(0,O.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(me(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=$e(this.video);this.subscription.add(this.representations$.pipe((0,O.map)(i=>i.map(({track:s})=>s)),(0,O.filter)(i=>!!i.length),(0,O.once)()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,O.filterChanged)(),(0,O.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(dt(this.video,this.params.desiredState.isLooped,t)).add(Re(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ge(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(We(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&(0,O.videoQualityToHeight)(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,O.assertNever)(i.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ke(this.video)}createLiveDashPlayer(){let e=new Fi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,O.isNonNullable)(t)?t:Wt(e.map(({track:g})=>g),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let g=(m=e.find(({track:v})=>v.id===s))==null?void 0:m.representation;(0,O.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;(0,O.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ee(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var pb=Ui;var Dv=Y(lt(),1);var ht=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var q=require("@vkontakte/videoplayer-shared/es2018");var Fs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Yr=class extends Fs{constructor(){super(),this.listeners||Fs.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Hi=class{constructor(){Object.defineProperty(this,"signal",{value:new Yr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Hi.prototype[Symbol.toStringTag]="AbortController",Yr.prototype[Symbol.toStringTag]="AbortSignal");function qs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Pu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!qs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var ji=qs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),hb=ji?Pu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,xt=ji?hb.fetch:window.fetch,TD=ji?hb.Request:window.Request,Fe=ji?Hi:window.AbortController,ID=ji?Yr:window.AbortSignal;var Xu=Y(wu(),1);var Ks=Y(Qr(),1);var Pt=()=>window.ManagedMediaSource||window.MediaSource,Us=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Cb=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Db=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ft=require("@vkontakte/videoplayer-shared/es2018"),Ye=document.createElement("video"),Jw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Xw='video/mp4; codecs="hev1.1.6.L93.B0"',Gb='video/webm; codecs="vp09.00.10.08"',Qb='video/webm; codecs="av01.0.00M.08"',Zw='audio/mp4; codecs="mp4a.40.2"',ek='audio/webm; codecs="opus"',Ob,Vb,Gi={mms:Us(),mse:Cb(),hls:!!((Ob=Ye.canPlayType)!=null&&Ob.call(Ye,"application/x-mpegurl")||(Vb=Ye.canPlayType)!=null&&Vb.call(Ye,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Bb,_b,Me={mp4:!!((Bb=Ye.canPlayType)!=null&&Bb.call(Ye,"video/mp4")),webm:!!((_b=Ye.canPlayType)!=null&&_b.call(Ye,"video/webm")),cmaf:!0},js,Nb,Gs,Fb,Qs,qb,Ws,Ub,Ys,Hb,zs,jb,Ce={h264:!!((Nb=(js=Pt())==null?void 0:js.isTypeSupported)!=null&&Nb.call(js,Jw)),h265:!!((Fb=(Gs=Pt())==null?void 0:Gs.isTypeSupported)!=null&&Fb.call(Gs,Xw)),vp9:!!((qb=(Qs=Pt())==null?void 0:Qs.isTypeSupported)!=null&&qb.call(Qs,Gb)),av1:!!((Ub=(Ws=Pt())==null?void 0:Ws.isTypeSupported)!=null&&Ub.call(Ws,Qb)),aac:!!((Hb=(Ys=Pt())==null?void 0:Ys.isTypeSupported)!=null&&Hb.call(Ys,Zw)),opus:!!((jb=(zs=Pt())==null?void 0:zs.isTypeSupported)!=null&&jb.call(zs,ek))},zr=(Ce.h264||Ce.h265)&&Ce.aac,pr,tk=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Qb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Gb}})]);pr={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{tk()}catch(a){console.error(a)}var Kr=Gi.hls&&Me.mp4,Wb=()=>Object.keys(Ce).filter(a=>Ce[a]),Yb=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Gi.mse&&(!r||!!window.MediaStreamTrack)||Gi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Me.mp4&&zr;case"DASH_WEBM":return i&&Me.webm&&Ce.vp9&&Ce.opus;case"DASH_WEBM_AV1":return i&&Me.webm&&Ce.av1&&Ce.opus;case"DASH_STREAMS":return i&&(Me.mp4&&zr||Me.webm&&(Ce.vp9||Ce.av1)&&(Ce.opus||Ce.aac));case"DASH_LIVE":return i&&Me.mp4&&zr;case"DASH_LIVE_CMAF":return i&&Me.mp4&&zr&&Me.cmaf;case"DASH_ONDEMAND":return i&&Me.mp4&&zr;case"HLS":case"HLS_ONDEMAND":return Kr||e&&i&&Me.mp4&&zr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Kr;case"MPEG":return Me.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Gi.webrtc&&Gi.ws&&Ce.h264&&(Me.mp4||Me.webm);default:return(0,ft.assertNever)(s)}})},Hs=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return pr?pr[t].smooth?[t,e]:pr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return pr?pr[t].powerEfficient?[t,e]:pr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,ft.assertNever)(a)}return[e,t]},zb=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Hs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ft.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...Hs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Hs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Hs(a),...i,"HLS","HLS_ONDEMAND"];default:(0,ft.assertNever)(e)}return Kr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Kb=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=ft.clientChecker.isMac&&ft.clientChecker.isSafari;if(ft.clientChecker.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,ft.assertNever)(a)}else Kr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},ku=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Jb=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Ks.default)(t.value.split("."),0)}for(let t of a){let r=(0,Ks.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,Ks.default)(e.value.split("."),0)};var vg=Y(gg(),1),Jr=require("@vkontakte/videoplayer-shared/es2018"),Sg=a=>{if(!a)return{id:"EmptyResponse",category:Jr.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Jr.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,vg.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Jr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Jr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Jr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Yt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};var S=require("@vkontakte/videoplayer-shared/es2018");var Js=Y(lt(),1),ti=Y(Qr(),1),Xs=Y(wu(),1);var vk=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},Sk=a=>window.clearTimeout(a),yg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Tg=!yg(window.requestIdleCallback)||!yg(window.cancelIdleCallback),Cu=Tg?vk:window.requestIdleCallback,Wi=Tg?Sk:window.cancelIdleCallback;var Av=Y(Ls(),1);var ze=require("@vkontakte/videoplayer-shared/es2018"),yk=18,Ig=!1;try{Ig=ze.clientChecker.isSafari&&!!ze.clientChecker.macVersion&&ze.clientChecker.macVersion<=yk}catch(a){console.error(a)}var Du=class{constructor(e){this.bufferFull$=new ze.Subject;this.error$=new ze.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:ze.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;Ig&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:ze.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,ze.assertNever)(t)}}},Eg=Du;var Ou=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var I=require("@vkontakte/videoplayer-shared/es2018");var ee=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Xr=class extends ee{};var Yi=class extends ee{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var zi=class extends ee{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var Ki=class extends ee{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oe=class extends ee{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ji=class extends oe{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Xi=class extends ee{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Zi=class extends ee{constructor(e,t){super(e,t),this.data=this.content}};var hr=class extends oe{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ea=class extends ee{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ta=class extends ee{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends oe{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ia=class extends oe{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var aa=class extends oe{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var sa=class extends ee{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var na=class extends oe{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var oa=class extends ee{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ua=class extends ee{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var la=class extends oe{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ca=class extends ee{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var da=class extends oe{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var pa=class extends oe{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 ha=class extends oe{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Ik={ftyp:zi,moov:Ki,mvhd:Ji,moof:Xi,mdat:Zi,sidx:hr,trak:ea,mdia:sa,mfhd:la,tkhd:na,traf:ca,tfhd:da,tfdt:pa,trun:ha,minf:oa,sv3d:ta,st3d:ra,prhd:ia,proj:ua,equi:aa,uuid:Yi,unknown:Xr},At=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=Ik[e];return r?new r(t,new a):new Xr(t,new a)}};var zt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var xk=new TextDecoder("ascii"),Pk=a=>xk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Ak=a=>{let e=new hr(a,new At),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},wk=(a,e)=>{let r=new At().parse(a),i=new zt(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},kk=a=>{let t=new At().parse(a),r=new zt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},Rk=a=>{var i;let t=new At().parse(a);return(i=new zt(t).find("sidx"))==null?void 0:i.timescale},$k=(a,e)=>{let r=new At().parse(a),s=new zt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Lk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new At().parse(a),i=new zt(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},xg={validateData:Pk,parseInit:Lk,getIndexRange:()=>{},parseSegments:Ak,parseFeedableSegmentChunk:wk,getChunkEndTime:$k,getServerLatencyTimestamps:kk,getTimescaleFromIndex:Rk};var ma=Y(lt(),1),wt=require("@vkontakte/videoplayer-shared/es2018");var Ag=require("@vkontakte/videoplayer-shared/es2018");var Pg={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"}},wg=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=fa(a,t),i=r in Pg,s=i?Pg[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=fa(u),d=l*2**((o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},fa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},it=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return fa(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,Ag.assertNever)(e)}},fr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=wg(r);if(!e(i))return;i.type==="master"&&fr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},kg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=wg(a);return fr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=it(o,n):s===17026?t=it(o,n):s===17029&&(r=it(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Rg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Mk=[231,22612,22743,167,171,163,160,175],Ck=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return fr(a,({tag:h,type:p,value:m,valueSize:g})=>{if(h===21419){let v=it(m,p);l=fa(v)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+g):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=it(m,p):h===17545?i=it(m,p):h===21420&&l===475249515?u=it(m,p):h===374648427?fr(m,({tag:v,type:T,value:E})=>v===30321?(c=it(E,T)===1,!1):!0):s&&n&&(0,ma.default)(Rg,h)&&(o=!0),!o}),(0,wt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,wt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,wt.assertNonNullable)(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Dk=a=>{if((0,wt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Ok=(a,e)=>{let t=!1,r=!1,i=o=>(0,wt.isNonNullable)(o.time)&&(0,wt.isNonNullable)(o.position),s=[],n;return fr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=it(l,u));break;case 183:break;case 241:n&&(n.position=it(l,u));break;default:t&&(0,ma.default)(Rg,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Vk=a=>{let e=0,t=!1;try{fr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ma.default)(Mk,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ma.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},$g={validateData:kg,parseInit:Ck,getIndexRange:Dk,parseSegments:Ok,parseFeedableSegmentChunk:Vk};var ba=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return $g;case"mp4":return xg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Hu=Y(Kg(),1),gv=Y(Vr(),1),vv=Y(pv(),1),Sv=Y(Qr(),1);var hv=Y(lt(),1),Uu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,hv.default)(["6E","7A","F4"],o)}}return!1};var ei=require("@vkontakte/videoplayer-shared/es2018");var fv=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var mv=a=>{var e;try{let t=LR(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function LR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
63
|
+
`}),m&&lb(i,u,m,o)};var be=a=>new URL(a).hostname;var O=require("@vkontakte/videoplayer-shared/es2018");var pb=W(at(),1),db=a=>{if(a instanceof DOMException&&(0,pb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Me=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!db(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return db(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};var qe=require("@vkontakte/videoplayer-shared/es2018");var hb=W(Jr(),1),ft=require("@vkontakte/videoplayer-shared/es2018");function ge(){return(0,ft.now)()}function Pu(a){return ge()-a}function wu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function fb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Zr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,g=2e3,v=()=>{if(u)return;(0,ft.assertNonNullable)(c);let D=Pu(c),_;if(D<g){_=g-D,setTimeout(v,_);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new i,j()},I=D=>(s=D,X),E=D=>(d=D,X),x=()=>(h="json",X),k=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,d&&d(),t&&t()}},w=D=>(p=D,X),j=()=>{c=ge(),n=new i,n.open("get",a);let D=0,_,ie=0,pe=()=>((0,ft.assertNonNullable)(c),Math.max(c,Math.max(_||0,ie||0)));if(s&&n.addEventListener("progress",R=>{let P=ge();s.updateChunk&&R.loaded>D&&(s.updateChunk(pe(),R.loaded-D),D=R.loaded,_=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>k())),n.addEventListener("load",()=>{if(u)return;(0,ft.assertNonNullable)(n);let R=n.status;if(R>=200&&R<300){if(n.response.byteLength&&s){let P=n.response.byteLength-D;P&&s.updateChunk&&s.updateChunk(pe(),P)}n.responseType==="json"&&!(0,hb.default)(n.response).length?k():(d&&d(),e(n.response))}else k()}),n.addEventListener("error",()=>{k()}),p){let R=()=>{(0,ft.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ie=ge(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=h,n.send(),X},X={withBitrateReporting:I,withParallel:w,withJSONResponse:x,withRetryCount:D=>(l=D,X),withRetryInterval:(D,_)=>((0,ft.isNonNullable)(D)&&(g=D),(0,ft.isNonNullable)(_)&&(m=_),X),withTimeout:D=>(o=D,X),withFinally:E,send:j,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return X}var Hi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var mb=W(Jr(),1);var ji=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ge(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ge()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Zr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ge()}_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=ge();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(){(0,mb.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var bb=require("@vkontakte/videoplayer-shared/es2018"),Us=1e4,Au=3;var PA=6e4,wA=10,AA=1,kA=500,Gi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new bb.Subject,this.chunkRateEstimator=new Hi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=wu(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=wu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,qe.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{fb(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ji(Au,Us,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let k=s&&(!c||c===this.rep);return k||t("Not running!"),k},p=(k,w,j)=>{u&&u.abort(),u=Zr(this.urlResolver.resolve(k,!1),w,j,()=>this._retryCallback()).withTimeout(Us).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Au).withFinally(()=>{u=null}).send()},h=(k,w,j)=>{(0,qe.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(k,!1),w,j,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=k=>{let w=r.playbackRate;r.playbackRate!==k&&(t(`Playback rate switch: ${w}=>${k}`),r.playbackRate=k)},g=k=>{this.lowLatency=k,t(`lowLatency changed to ${k}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let k=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let j=ge()-1e4,Q=0;for(let Y=0;Y<this.bufferStates.length;Y++){let J=this.bufferStates[Y];k=Math.min(k,J.buf),J.ts<j&&Q++}this.bufferStates.splice(0,Q),t(`update playback rate; minBuffer=${k} drop=${Q} jitter=${this.sourceJitter}`);let ee=k-AA;this.sourceJitter>=0?ee-=this.sourceJitter/2:this.sourceJitter-=1,ee>3?m(1.15):ee>1?m(1.1):ee>.3?m(1.05):m(1)}},I=k=>{let w,j=()=>w&&w.start?w.start.length:0,Q=R=>w.start[R]/1e3,ee=R=>w.dur[R]/1e3,Y=R=>w.fragIndex+R,J=(R,P)=>({chunkIdx:Y(R),startTS:Q(R),dur:ee(R),discontinuity:P}),X=()=>{let R=0;if(w&&w.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,N=P;this.sourceJitter>1&&(N+=this.sourceJitter-1);let fe=w.dur.length-1;for(;fe>=0&&(N-=w.dur[fe],!(N<=0));--fe);R=Math.min(fe,w.dur.length-1-q),R=Math.max(R,0)}return J(R,!0)},D=R=>{let P=j();if(!(P<=0)){if((0,qe.isNonNullable)(R)){for(let q=0;q<P;q++)if(Q(q)>R)return J(q)}return X()}},_=R=>{let P=j(),q=R?R.chunkIdx+1:0,N=q-w.fragIndex;if(!(P<=0)){if(!R||N<0||N-P>wA)return t(`Resync: offset=${N} bChunks=${P} chunk=`+JSON.stringify(R)),X();if(!(N>=P))return J(q-w.fragIndex,!1)}},ie=(R,P,q)=>{l&&l.abort(),l=Zr(this.urlResolver.resolve(R,!0,this.lowLatency),P,q,()=>this._retryCallback()).withTimeout(Us).withRetryCount(Au).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,P)=>{ie(k,q=>{if(!d())return;w=q;let N=!!w.lowLatency;N!==this.lowLatency&&g(N);let fe=0;for(let He=0;He<w.dur.length;++He)fe+=w.dur[He];fe>0&&((0,qe.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(fe/w.dur.length)),i({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,R(D(P))},()=>this._handleNetworkError())},nextChunk:_}},E=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,qe.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:k=>{let{videoElement:w,logger:j}=this.params,Q=I(e.jidxUrl),ee,Y,J,X,D=0,_,ie,pe,R=()=>{_&&(clearTimeout(_),_=void 0);let Z=Math.max(kA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=D+Z,ye=ge(),je=Math.min(1e4,Se-ye);D=ye;let Ot=()=>{l||d()&&Q.seek(()=>{d()&&(D=ge(),P(),R())})};je>0?_=window.setTimeout(()=>{this.paused?R():Ot()},je):Ot()},P=()=>{let Z;for(;Z=Q.nextChunk(X);)X=Z,Dt(Z);let Se=Q.nextChunk(J);if(Se){if(J&&Se.discontinuity){j("Detected discontinuity; restarting playback"),this.paused?R():(E(),this._initPlayerWith(e));return}He(Se)}else R()},q=(Z,Se)=>{if(!d()||!this.sourceBuffer)return;let ye,je,Ot,xr=Bt=>{window.setTimeout(()=>{d()&&q(Z,Se)},Bt)};if(this.sourceBuffer.updating)j("Source buffer is updating; delaying appendBuffer"),xr(100);else{let Bt=ge(),tr=w.currentTime;!this.paused&&w.buffered.length>1&&ie===tr&&Bt-pe>500&&(j("Stall suspected; trying to fix"),this._fixupStall()),ie!==tr&&(ie=tr,pe=Bt);let Pr=this._getBufferSizeSec();if(Pr>30)j(`Buffered ${Pr} seconds; delaying appendBuffer`),xr(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:Bt,buf:Pr}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(li){if(li.name==="QuotaExceededError")j("QuotaExceededError; delaying appendBuffer"),Ot=this.sourceBuffer.buffered.length,Ot!==0&&(ye=this.sourceBuffer.buffered.start(0),je=tr,je-ye>4&&this.sourceBuffer.remove(ye,je-3)),xr(1e3);else throw li}}},N=()=>{Y&&ee&&(j([`Appending chunk, sz=${Y.byteLength}:`,JSON.stringify(J)]),q(Y,function(){Y=null,P()}))},fe=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),He=Z=>{d()&&h(fe(Z),(Se,ye)=>{if(d()){if(ye/=1e3,Y=Se,J=Z,n=Z.startTS,ye){let je=Math.min(10,Z.dur/ye);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*je:je}N()}},()=>this._handleNetworkError())},Dt=Z=>{d()&&((0,qe.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(fe(Z),!1)))},Er=Z=>{d()&&(e.cachedHeader=Z,q(Z,()=>{ee=!0,N()}))};s=!0,Q.seek(Z=>{if(d()){if(D=ge(),!Z){R();return}X=Z,!(0,qe.isNullable)(k)||Z.startTS>k?He(Z):(J=Z,P())}},k),e.cachedHeader?Er(e.cachedHeader):p(e.headerUrl,Er,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,qe.isNonNullable)(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,qe.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,qe.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=ge();if(this.chunkRateEstimator.addInterval(p,m,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Pu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ge();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Zr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Us).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;Me(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},PA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var gb=W(qr(),1),oe=require("@vkontakte/videoplayer-shared/es2018"),ku=class{constructor(){this.onDroopedVideoFramesLimit$=new oe.Subject;this.subscription=new oe.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new oe.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,oe.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,oe.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,oe.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,oe.interval)(this.droppedFramesChecker.checkTime).pipe((0,oe.filter)(()=>this.playing),(0,oe.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,oe.debounce)(this.droppedFramesChecker.checkTime)),r=(0,oe.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,gb.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,oe.isLower)(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Hs=ku;var js=require("@vkontakte/videoplayer-shared/es2018"),vb=require("@vkontakte/videoplayer-shared/es2018");var Qi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var RA=(a,e)=>new js.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Qi()))},{...r,...e});i.observe(a);let s=(0,vb.fromEvent)(document,"visibilitychange").pipe((0,js.map)(n=>!document.hidden||Qi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ye=RA;var $A=["paused","playing","ready"],LA=["paused","playing","ready"],Wi=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new U("stopped");this.representations$=new O.ValueSubject([]);this.textTracksManager=new We;this.droppedFramesManager=new Hs;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new Et;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:O.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Yt(u.name))!=null?r:(0,O.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p={...u.video};if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,O.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Ru.default)(LA,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Ru.default)($A,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Ee(this.params.source.url,u))}return;default:return(0,O.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=ke(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(be(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Le(this.video);this.subscription.add(this.representations$.pipe((0,O.map)(i=>i.map(({track:s})=>s)),(0,O.filter)(i=>!!i.length),(0,O.once)()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,O.filterChanged)(),(0,O.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(ht(this.video,this.params.desiredState.isLooped,t)).add($e(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Qe(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ye(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&(0,O.videoQualityToHeight)(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,O.assertNever)(i.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Re(this.video)}createLiveDashPlayer(){let e=new Gi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,O.isNonNullable)(t)?t:Kt(e.map(({track:g})=>g),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let g=(m=e.find(({track:v})=>v.id===s))==null?void 0:m.representation;(0,O.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;(0,O.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ee(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Sb=Wi;var Uv=W(at(),1);var mt=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var V=require("@vkontakte/videoplayer-shared/es2018");var Gs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ei=class extends Gs{constructor(){super(),this.listeners||Gs.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)}},Yi=class{constructor(){Object.defineProperty(this,"signal",{value:new ei,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Yi.prototype[Symbol.toStringTag]="AbortController",ei.prototype[Symbol.toStringTag]="AbortSignal");function Qs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function $u(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Qs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var zi=Qs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),yb=zi?$u({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,wt=zi?yb.fetch:window.fetch,wD=zi?yb.Request:window.Request,Ue=zi?Yi:window.AbortController,AD=zi?ei:window.AbortSignal;var sl=W(Mu(),1);var tn=W(Xr(),1);var At=()=>window.ManagedMediaSource||window.MediaSource,Ws=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Fb=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},qb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var bt=require("@vkontakte/videoplayer-shared/es2018"),ze=document.createElement("video"),rk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ik='video/mp4; codecs="hev1.1.6.L93.B0"',Xb='video/webm; codecs="vp09.00.10.08"',Zb='video/webm; codecs="av01.0.00M.08"',ak='audio/mp4; codecs="mp4a.40.2"',sk='audio/webm; codecs="opus"',Ub,Hb,Ki={mms:Ws(),mse:Fb(),hls:!!((Ub=ze.canPlayType)!=null&&Ub.call(ze,"application/x-mpegurl")||(Hb=ze.canPlayType)!=null&&Hb.call(ze,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},jb,Gb,Ce={mp4:!!((jb=ze.canPlayType)!=null&&jb.call(ze,"video/mp4")),webm:!!((Gb=ze.canPlayType)!=null&&Gb.call(ze,"video/webm")),cmaf:!0},zs,Qb,Ks,Wb,Js,Yb,Xs,zb,Zs,Kb,en,Jb,De={h264:!!((Qb=(zs=At())==null?void 0:zs.isTypeSupported)!=null&&Qb.call(zs,rk)),h265:!!((Wb=(Ks=At())==null?void 0:Ks.isTypeSupported)!=null&&Wb.call(Ks,ik)),vp9:!!((Yb=(Js=At())==null?void 0:Js.isTypeSupported)!=null&&Yb.call(Js,Xb)),av1:!!((zb=(Xs=At())==null?void 0:Xs.isTypeSupported)!=null&&zb.call(Xs,Zb)),aac:!!((Kb=(Zs=At())==null?void 0:Zs.isTypeSupported)!=null&&Kb.call(Zs,ak)),opus:!!((Jb=(en=At())==null?void 0:en.isTypeSupported)!=null&&Jb.call(en,sk))},ti=(De.h264||De.h265)&&De.aac,gr,nk=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Zb}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Xb}})]);gr={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{nk()}catch(a){console.error(a)}var ri=Ki.hls&&Ce.mp4,eg=()=>Object.keys(De).filter(a=>De[a]),tg=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Ki.mse&&(!r||!!window.MediaStreamTrack)||Ki.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Ce.mp4&&ti;case"DASH_WEBM":return i&&Ce.webm&&De.vp9&&De.opus;case"DASH_WEBM_AV1":return i&&Ce.webm&&De.av1&&De.opus;case"DASH_STREAMS":return i&&(Ce.mp4&&ti||Ce.webm&&(De.vp9||De.av1)&&(De.opus||De.aac));case"DASH_LIVE":return i&&Ce.mp4&&ti;case"DASH_LIVE_CMAF":return i&&Ce.mp4&&ti&&Ce.cmaf;case"DASH_ONDEMAND":return i&&Ce.mp4&&ti;case"HLS":case"HLS_ONDEMAND":return ri||e&&i&&Ce.mp4&&ti;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ri;case"MPEG":return Ce.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Ki.webrtc&&Ki.ws&&De.h264&&(Ce.mp4||Ce.webm);default:return(0,bt.assertNever)(s)}})},Ys=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return gr?gr[t].smooth?[t,e]:gr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return gr?gr[t].powerEfficient?[t,e]:gr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,bt.assertNever)(a)}return[e,t]},rg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Ys(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(bt.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...Ys(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ys(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ys(a),...i,"HLS","HLS_ONDEMAND"];default:(0,bt.assertNever)(e)}return ri?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},ig=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=bt.clientChecker.isMac&&bt.clientChecker.isSafari;if(bt.clientChecker.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,bt.assertNever)(a)}else ri&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Cu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ag=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,tn.default)(t.value.split("."),0)}for(let t of a){let r=(0,tn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,tn.default)(e.value.split("."),0)};var Pg=W(xg(),1),ii=require("@vkontakte/videoplayer-shared/es2018"),wg=a=>{if(!a)return{id:"EmptyResponse",category:ii.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ii.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,Pg.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ii.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ii.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ii.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Jt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};var S=require("@vkontakte/videoplayer-shared/es2018");var rn=W(at(),1),ni=W(Xr(),1),an=W(Mu(),1);var Ek=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},xk=a=>window.clearTimeout(a),Ag=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),kg=!Ag(window.requestIdleCallback)||!Ag(window.cancelIdleCallback),_u=kg?Ek:window.requestIdleCallback,Xi=kg?xk:window.cancelIdleCallback;var Dv=W(Bs(),1);var Ke=require("@vkontakte/videoplayer-shared/es2018"),Pk=18,Rg=!1;try{Rg=Ke.clientChecker.isSafari&&!!Ke.clientChecker.macVersion&&Ke.clientChecker.macVersion<=Pk}catch(a){console.error(a)}var Nu=class{constructor(e){this.bufferFull$=new Ke.Subject;this.error$=new Ke.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Ke.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};Rg&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ke.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:(0,Ke.assertNever)(t)}}},$g=Nu;var Fu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var T=require("@vkontakte/videoplayer-shared/es2018");var te=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var ai=class extends te{};var Zi=class extends te{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ea=class extends te{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ta=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ue=class extends te{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ra=class extends ue{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ia=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var aa=class extends te{constructor(e,t){super(e,t),this.data=this.content}};var vr=class extends ue{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var sa=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var na=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oa=class extends ue{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ua=class extends ue{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var la=class extends ue{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ca=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var da=class extends ue{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var pa=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ha=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fa=class extends ue{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ma=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ba=class extends ue{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ga=class extends ue{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 va=class extends ue{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Ak={ftyp:ea,moov:ta,mvhd:ra,moof:ia,mdat:aa,sidx:vr,trak:sa,mdia:ca,mfhd:fa,tkhd:da,traf:ma,tfhd:ba,tfdt:ga,trun:va,minf:pa,sv3d:na,st3d:oa,prhd:ua,proj:ha,equi:la,uuid:Zi,unknown:ai},kt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=Ak[e];return r?new r(t,new a):new ai(t,new a)}};var Xt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Rk=new TextDecoder("ascii"),$k=a=>Rk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Lk=a=>{let e=new vr(a,new kt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},Mk=(a,e)=>{let r=new kt().parse(a),i=new Xt(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},Ck=a=>{let t=new kt().parse(a),r=new Xt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},Dk=a=>{var i;let t=new kt().parse(a);return(i=new Xt(t).find("sidx"))==null?void 0:i.timescale},Ok=(a,e)=>{let r=new kt().parse(a),s=new Xt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Bk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new kt().parse(a),i=new Xt(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Lg={validateData:$k,parseInit:Bk,getIndexRange:()=>{},parseSegments:Lk,parseFeedableSegmentChunk:Mk,getChunkEndTime:Ok,getServerLatencyTimestamps:Ck,getTimescaleFromIndex:Dk};var ya=W(at(),1),Rt=require("@vkontakte/videoplayer-shared/es2018");var Cg=require("@vkontakte/videoplayer-shared/es2018");var Mg={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"}},Dg=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Sa(a,t),i=r in Mg,s=i?Mg[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Sa(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Sa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},nt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Sa(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,Cg.assertNever)(e)}},Sr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Dg(r);if(!e(i))return;i.type==="master"&&Sr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Og=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Dg(a);return Sr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=nt(o,n):s===17026?t=nt(o,n):s===17029&&(r=nt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Bg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Vk=[231,22612,22743,167,171,163,160,175],_k=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Sr(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let v=nt(m,h);l=Sa(v)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=nt(m,h):p===17545?i=nt(m,h):p===21420&&l===475249515?u=nt(m,h):p===374648427?Sr(m,({tag:v,type:I,value:E})=>v===30321?(c=nt(E,I)===1,!1):!0):s&&n&&(0,ya.default)(Bg,p)&&(o=!0),!o}),(0,Rt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Rt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Rt.assertNonNullable)(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Nk=a=>{if((0,Rt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Fk=(a,e)=>{let t=!1,r=!1,i=o=>(0,Rt.isNonNullable)(o.time)&&(0,Rt.isNonNullable)(o.position),s=[],n;return Sr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=nt(l,u));break;case 183:break;case 241:n&&(n.position=nt(l,u));break;default:t&&(0,ya.default)(Bg,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},qk=a=>{let e=0,t=!1;try{Sr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ya.default)(Vk,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ya.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Vg={validateData:Og,parseInit:_k,getIndexRange:Nk,parseSegments:Fk,parseFeedableSegmentChunk:qk};var Ta=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Vg;case"mp4":return Lg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Zu=W(iv(),1),Rv=W(qr(),1),$v=W(Sv(),1),Lv=W(Xr(),1),el=W(Jr(),1);var yv=W(at(),1),Wu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,yv.default)(["6E","7A","F4"],o)}}return!1};var Ea=require("@vkontakte/videoplayer-shared/es2018");var Tv=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Iv=a=>{var e;try{let t=BR(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function BR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
63
64
|
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
64
65
|
(-(?<script>[a-z]{4}))?
|
|
65
66
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
66
67
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
67
68
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
68
69
|
(?:-(?<privateuse>(?:${e})))?
|
|
69
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var bv=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},kt=(a,e)=>{let t=a;t=(0,Hu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,gv.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Hu.default)(t,n,(o,u)=>(0,ei.isNullable)(s)?o:(0,ei.isNullable)(u)?s:(0,vv.default)(s,parseInt(u,10),"0"))}return t},yv=(a,e)=>{var A,_,Q,ie,N,J,X,B,D,re,ce,R,P,W,j,pe,Ue,Mt,vr,Z,ve,Se,He,Ct,Sr,Dt,Xt,yr,ai,ol,ul,ll,cl,dl,pl,hl,fl,ml,bl,gl,vl,Sl,yl,Tl,Il,El,xl,Pl,Al,wl,kl,Rl,$l,Ll,Ml,Cl,Dl,Ol,Vl,Bl;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(ye=>{var Ba,Ot;return(Ot=(Ba=ye.textContent)==null?void 0:Ba.trim())!=null?Ot:""}),u=(A=(0,Sv.default)(o,0))!=null?A:"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,p,m=s.getAttribute("mediaPresentationDuration"),g=n.getAttribute("duration"),v=s.getElementsByTagName("vk:Attrs")[0],T=v==null?void 0:v.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)p=bv(m);else if(g){let ye=bv(g);(0,ei.isNonNullable)(ye)&&(p=ye)}else T&&(p=parseInt(T,10));let E=0,x=(Q=(_=s.getAttribute("profiles"))==null?void 0:_.split(","))!=null?Q:[];for(let ye of l){let Ba=(ie=ye.getAttribute("id"))!=null?ie:"id"+(E++).toString(10),Ot=(N=ye.getAttribute("mimeType"))!=null?N:"",fn=(J=ye.getAttribute("codecs"))!=null?J:"",mn=(X=ye.getAttribute("contentType"))!=null?X:Ot==null?void 0:Ot.split("/")[0],aS=(D=(B=ye.getAttribute("profiles"))==null?void 0:B.split(","))!=null?D:[],_l=(ce=mv((re=ye.getAttribute("lang"))!=null?re:""))!=null?ce:{},sS=(W=(P=(R=ye.querySelector("Label"))==null?void 0:R.textContent)==null?void 0:P.trim())!=null?W:void 0,nS=ye.querySelectorAll("Representation"),oS=ye.querySelector("SegmentTemplate"),uS=(pe=(j=ye.querySelector("Role"))==null?void 0:j.getAttribute("value"))!=null?pe:void 0,si=mn,he={id:Ba,language:_l.language,isDefault:uS==="main",label:sS,codecs:fn,hdr:si==="video"&&Uu(fn),mime:Ot,representations:[]};for(let ae of nS){let lS=(Ue=ae.getAttribute("lang"))!=null?Ue:void 0,cS=(Mt=ae.getAttribute("label"))!=null?Mt:void 0,dS=(ve=(Z=(vr=ae.querySelector("BaseURL"))==null?void 0:vr.textContent)==null?void 0:Z.trim())!=null?ve:"",_a=new URL(dS||u,e).toString(),Tr=(Se=ae.getAttribute("mimeType"))!=null?Se:Ot,Na=(Ct=(He=ae.getAttribute("codecs"))!=null?He:fn)!=null?Ct:"",Fa;if(mn==="text"){let Vt=ae.getAttribute("id")||"",qa=((Sr=_l.privateuse)==null?void 0:Sr.includes("x-auto"))||Vt.includes("_auto"),Zt=ae.querySelector("SegmentTemplate");if(Zt){let ni={representationId:(Dt=ae.getAttribute("id"))!=null?Dt:void 0,bandwidth:(Xt=ae.getAttribute("bandwidth"))!=null?Xt:void 0},Ua=parseInt((yr=ae.getAttribute("bandwidth"))!=null?yr:"",10)/1e3,Ha=(ol=parseInt((ai=Zt.getAttribute("startNumber"))!=null?ai:"",10))!=null?ol:1,Ir=parseInt((ul=Zt.getAttribute("timescale"))!=null?ul:"",10),bn=(ll=Zt.querySelectorAll("SegmentTimeline S"))!=null?ll:[],Er=Zt.getAttribute("media");if(!Er)continue;let ja=[],Ga=0,Qa="",xr=0,oi=Ha,xe=0;for(let Je of bn){let er=parseInt((cl=Je.getAttribute("d"))!=null?cl:"",10),je=parseInt((dl=Je.getAttribute("r"))!=null?dl:"",10)||0,Bt=parseInt((pl=Je.getAttribute("t"))!=null?pl:"",10);xe=Number.isFinite(Bt)?Bt:xe;let tr=er/Ir*1e3,_t=xe/Ir*1e3;for(let st=0;st<je+1;st++){let Nt=kt(Er,{...ni,segmentNumber:oi.toString(10),segmentTime:(xe+st*er).toString(10)}),Pr=(_t!=null?_t:0)+st*tr,li=Pr+tr;oi++,ja.push({time:{from:Pr,to:li},url:Nt})}xe+=(je+1)*er,Ga+=(je+1)*tr}xr=xe/Ir*1e3,Qa=kt(Er,{...ni,segmentNumber:oi.toString(10),segmentTime:xe.toString(10)});let ui={time:{from:xr,to:1/0},url:Qa},bt={type:"template",baseUrl:_a,segmentTemplateUrl:Er,initUrl:"",totalSegmentsDurationMs:Ga,segments:ja,nextSegmentBeyondManifest:ui,timescale:Ir};Fa={id:Vt,kind:"text",segmentReference:bt,profiles:[],duration:p,bitrate:Ua,mime:"",codecs:"",width:0,height:0,isAuto:qa}}else Fa={id:Vt,isAuto:qa,kind:"text",url:_a}}else{let Vt=(fl=(hl=ae.getAttribute("contentType"))!=null?hl:Tr==null?void 0:Tr.split("/")[0])!=null?fl:mn,qa=(bl=(ml=ye.getAttribute("profiles"))==null?void 0:ml.split(","))!=null?bl:[],Zt=parseInt((gl=ae.getAttribute("width"))!=null?gl:"",10),ni=parseInt((vl=ae.getAttribute("height"))!=null?vl:"",10),Ua=parseInt((Sl=ae.getAttribute("bandwidth"))!=null?Sl:"",10)/1e3,Ha=(yl=ae.getAttribute("frameRate"))!=null?yl:"",Ir=(Tl=ae.getAttribute("quality"))!=null?Tl:void 0,bn=Ha?fv(Ha):void 0,Er=(Il=ae.getAttribute("id"))!=null?Il:"id"+(E++).toString(10),ja=Vt==="video"?`${ni}p`:Vt==="audio"?`${Ua}Kbps`:Na,Ga=`${Er}@${ja}`,Qa=[...x,...aS,...qa],xr,oi=ae.querySelector("SegmentBase"),xe=(El=ae.querySelector("SegmentTemplate"))!=null?El:oS;if(oi){let bt=(Pl=(xl=ae.querySelector("SegmentBase Initialization"))==null?void 0:xl.getAttribute("range"))!=null?Pl:"",[Je,er]=bt.split("-").map(Nt=>parseInt(Nt,10)),je={from:Je,to:er},Bt=(Al=ae.querySelector("SegmentBase"))==null?void 0:Al.getAttribute("indexRange"),[tr,_t]=Bt?Bt.split("-").map(Nt=>parseInt(Nt,10)):[],st=Bt?{from:tr,to:_t}:void 0;xr={type:"byteRange",url:_a,initRange:je,indexRange:st}}else if(xe){let bt={representationId:(wl=ae.getAttribute("id"))!=null?wl:void 0,bandwidth:(kl=ae.getAttribute("bandwidth"))!=null?kl:void 0},Je=parseInt((Rl=xe.getAttribute("timescale"))!=null?Rl:"",10),er=($l=xe.getAttribute("initialization"))!=null?$l:"",je=xe.getAttribute("media"),Bt=(Ml=parseInt((Ll=xe.getAttribute("startNumber"))!=null?Ll:"",10))!=null?Ml:1,tr=kt(er,bt);if(!je)throw new ReferenceError("No media attribute in SegmentTemplate");let _t=(Cl=xe.querySelectorAll("SegmentTimeline S"))!=null?Cl:[],st=[],Nt=0,Pr="",li=0;if(_t.length){let Wa=Bt,Xe=0;for(let Ar of _t){let nt=parseInt((Dl=Ar.getAttribute("d"))!=null?Dl:"",10),rr=parseInt((Ol=Ar.getAttribute("r"))!=null?Ol:"",10)||0,Ya=parseInt((Vl=Ar.getAttribute("t"))!=null?Vl:"",10);Xe=Number.isFinite(Ya)?Ya:Xe;let gn=nt/Je*1e3,vn=Xe/Je*1e3;for(let za=0;za<rr+1;za++){let hS=kt(je,{...bt,segmentNumber:Wa.toString(10),segmentTime:(Xe+za*nt).toString(10)}),Nl=(vn!=null?vn:0)+za*gn,fS=Nl+gn;Wa++,st.push({time:{from:Nl,to:fS},url:hS})}Xe+=(rr+1)*nt,Nt+=(rr+1)*gn}li=Xe/Je*1e3,Pr=kt(je,{...bt,segmentNumber:Wa.toString(10),segmentTime:Xe.toString(10)})}else if((0,ei.isNonNullable)(p)){let Xe=parseInt((Bl=xe.getAttribute("duration"))!=null?Bl:"",10)/Je*1e3,Ar=Math.ceil(p/Xe),nt=0;for(let rr=1;rr<Ar;rr++){let Ya=kt(je,{...bt,segmentNumber:rr.toString(10),segmentTime:nt.toString(10)});st.push({time:{from:nt,to:nt+Xe},url:Ya}),nt+=Xe}li=nt,Pr=kt(je,{...bt,segmentNumber:Ar.toString(10),segmentTime:nt.toString(10)})}let pS={time:{from:li,to:1/0},url:Pr};xr={type:"template",baseUrl:_a,segmentTemplateUrl:je,initUrl:tr,totalSegmentsDurationMs:Nt,segments:st,nextSegmentBeyondManifest:pS,timescale:Je}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Vt||!Tr)continue;let ui={video:"video",audio:"audio",text:"text"}[Vt];if(!ui)continue;si||(si=ui),Fa={id:Ga,kind:ui,segmentReference:xr,profiles:Qa,duration:p,bitrate:Ua,mime:Tr,codecs:Na,width:Zt,height:ni,fps:bn,quality:Ir}}he.language||(he.language=lS),he.label||(he.label=cS),he.mime||(he.mime=Tr),he.codecs||(he.codecs=Na),he.hdr||(he.hdr=si==="video"&&Uu(Na)),he.representations.push(Fa)}si&&i[si].push(he)}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,streams:i,baseUrls:o}};var Qu=Y(Qr(),1);var Tv=require("@vkontakte/videoplayer-shared/es2018"),Iv=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Gt(s):void 0)!=null?u:(0,Tv.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Ev=({id:a,bitrate:e})=>({id:a,bitrate:e}),xv=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Pv=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Wu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Qu.default)(r.split("."),0),isDefault:i}),Yu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Qu.default)(i.split("."),0)}),zu=a=>"url"in a,qe=a=>a.type==="template",ga=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var va=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new I.ValueSubject(0);this.currentSegmentLength$=new I.ValueSubject(0);this.onLastSegment$=new I.ValueSubject(!1);this.fullyBuffered$=new I.ValueSubject(!1);this.playingRepresentation$=new I.ValueSubject(void 0);this.playingRepresentationInit$=new I.ValueSubject(void 0);this.error$=new I.Subject;this.gaps=[];this.subscription=new I.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Fe;this.switchAbortController=new Fe;this.destroyAbortController=new Fe;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,I.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 Eg(this.sourceBuffer),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Ou(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=ht(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,I.assertNonNullable)(r,"No init buffer for starting representation"),(0,I.assertNonNullable)(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchToOld=(0,I.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,I.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,I.isNullable)(s)||(0,I.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,I.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,I.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Xs.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!qe(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);(0,I.assertNonNullable)(i);let s=this.segments.get(r);(0,I.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,I.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Fe,(0,I.abortable)(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);(0,I.assertNonNullable)(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if((0,I.isNullable)(o)||(0,I.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),(0,I.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,I.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Fe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if((0,I.isNullable)(e)||(0,I.isNullable)(this.downloadingRepresentationId)||(0,I.isNullable)(this.playingRepresentationId)||(0,I.isNullable)(this.sourceBuffer)||(0,I.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,I.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=ht(this.sourceBuffer.buffered,e),p=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=i.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&Ou(this.sourceBuffer.buffered)>=this.bufferLimit){let d=ht(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,Js.default)(o,i))d="high";else{let h=(0,ti.default)(o,0);h&&h.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&ht(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ti.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;(0,I.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,Xs.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,Xs.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];for(let o of t){if(!o||!qe(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,ti.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(h=>Math.floor(c)>=Math.floor(h.time.from)&&Math.floor(c)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(d+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,I.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!qe(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=kt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Wi&&Wi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Wi&&Wi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:h,to:p}},m)=>{let g=h<=r&&p>=r,v=h>r||g||m===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=r+T||p<=r+T;return(d==="none"||d==="partially_ejected"&&v&&E&&this.sourceBuffer&&!(Yt(this.sourceBuffer.buffered,h)&&Yt(this.sourceBuffer.buffered,p)))&&v&&E});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=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,r="auto"){qe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,I.abortable)(o,async function*(){let c=(0,I.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:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,I.now)(),!c)return;let d=new DataView(c),h=ba(t.mime);if(!isFinite(i.segment.time.to)){let g=t.segmentReference.timescale;i.segment.time.to=h.getChunkEndTime(d,g)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),ga(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())qe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="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:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,I.abortable)(n,async function*(){let u=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,I.fromEvent)(window,"online").pipe((0,I.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=(0,I.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ga(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(qe(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ti.default)(e,0).byte.from,to:(0,ti.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,I.now)(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qe(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,I.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Js.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=ba(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let c=l.byte.from-r,d=l.byte.to-r,h=d-c+1,p=c<i,m=d<=i;if(!p)continue;let g=ba(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+c,h);await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,i-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:g.parseFeedableSegmentChunk(v);T!=null&&T.byteLength&&(l.status="partially_fed",u.feedingBytes+=T.byteLength,await this.sourceBufferTaskQueue.append(T,s)&&!s.aborted?(u.fedBytes+=T.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&((0,I.assertNonNullable)(this.sourceBuffer),Yt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Yt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",zu(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");(0,I.assertNonNullable)(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Cu(()=>(0,Av.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,I.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ba(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&qe(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),r&&this.error$.next({id:"LoadInits",category:I.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){if(!this.sourceBuffer||!this.playingRepresentationId||(0,I.isNullable)(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push({...u.time}),i=n(i);let l=zu(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)(0,Js.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,I.isNullable)(e)?0:ht(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){(0,I.assertNonNullable)(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Cu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:I.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,I.isNullable)(this.sourceBuffer)||(0,I.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Sa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var wv=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};var z=require("@vkontakte/videoplayer-shared/es2018");var kv=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Zs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new z.ValueSubject(void 0);this.lastConnectionReused$=new z.ValueSubject(void 0);this.lastRequestFirstBytes$=new z.ValueSubject(void 0);this.abortAllController=new Fe;this.subscription=new z.Subscription;this.fetchManifest=(0,z.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Sa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=kv(r));let i=yield xt(r,{signal:this.abortAllController.signal}).catch(ya);return i?(t.log("success",(0,z.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,z.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,z.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var X,B;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let D=new URL(l,location.href);D.searchParams.append("bytes",`${r.from}-${r.to}`),l=D.toString();break}default:(0,z.assertNever)(t)}this.requestQuic&&(l=Sa(l));let h=this.abortAllController.signal,p;if(n){let D=new Fe;if(p=(0,z.merge)((0,z.fromEvent)(this.abortAllController.signal,"abort"),(0,z.fromEvent)(n,"abort")).subscribe(()=>{try{D.abort()}catch(re){ya(re)}}),this.abortAllController.signal.aborted||n.aborted)try{D.abort()}catch(re){ya(re)}h=D.signal}let m=(0,z.now)();d.log("startRequest",(0,z.flattenObject)({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:m}));let g=yield xt(l,{priority:s,headers:c,signal:h}).catch(ya),v=(0,z.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),p==null||p.unsubscribe(),null;if((X=this.throughputEstimator)==null||X.addRawRtt(v-m),!g.ok||!g.body){p==null||p.unsubscribe();let D=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:D}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){p==null||p.unsubscribe();let D=(0,z.now)(),re={requestStartedAt:m,requestEndedAt:D,duration:D-m};return d.log("endRequest",(0,z.flattenObject)(re)),d.end(),g.arrayBuffer()}let[T,E]=g.body.tee(),x=T.getReader();o&&((B=this.throughputEstimator)==null||B.trackStream(E,u));let w=0,A=new Uint8Array(0),_=!1,Q=D=>{p==null||p.unsubscribe(),_=!0,ya(D)},ie=(0,z.abortable)(h,async function*({done:D,value:re}){if(w===0&&this.lastRequestFirstBytes$.next((0,z.now)()-m),h.aborted){p==null||p.unsubscribe();return}if(!D&&re){let ce=new Uint8Array(A.length+re.length);ce.set(A),ce.set(re,A.length),A=ce,w+=re.byteLength,i==null||i(new DataView(A.buffer),w),yield x==null?void 0:x.read().then(ie,Q)}}.bind(this));yield x==null?void 0:x.read().then(ie,Q),p==null||p.unsubscribe();let N=(0,z.now)(),J={failed:_,requestStartedAt:m,requestEndedAt:N,duration:N-m};return _?(d.error("endRequest",(0,z.flattenObject)(J)),d.end(),null):(d.log("endRequest",(0,z.flattenObject)(J)),d.end(),A.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,z.abortable)(this.abortAllController.signal,async function*(e,t,r){var T;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let h=new DataView(d,i-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=(T=e.indexRange)!=null?T:t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let E=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!E)return null;g=new DataView(E)}let v=t.parseSegments(g,p,m);return{init:p,dataView:new DataView(d),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,z.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=wv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,z.assertNever)(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ya=a=>{if(!ga(a))throw a};var mr=(a,e,t)=>t*e+(1-t)*a,Ku=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Rv=(a,e,t,r)=>{let i=0,s=t,n=Ku(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};var Ta=require("@vkontakte/videoplayer-shared/es2018"),Kt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ta.ValueSubject(e.initial),this.debounced$=new Ta.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ae(`raw_${t}`),this.smoothedSeries$=new Ae(`smoothed_${t}`),this.reportedSeries$=new Ae(`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 i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,Ta.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 en=class extends Kt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=mr(this.slow,e,this.params.emaAlphaSlow),this.fast=mr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var tn=class extends Kt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ku(this.pastMeasures,this.takenMeasures);this.emaSmoothed=mr(this.emaSmoothed,e,this.params.emaAlpha);let r=Rv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var rn=class extends Kt{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?mr(this.smoothed,t,this.params.emaAlpha):t}};var br=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new en({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new tn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new rn({initial:e,label:"liveEdgeDelay",...t})}};var Ju=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var an=require("@vkontakte/videoplayer-shared/es2018");var Ia=class a{constructor(e,t){this.currentRepresentation$=new an.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,an.isNullable)(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&qe(t.segmentReference))}};var DR=["timeupdate","progress","play","seeked","stalled","waiting"],OR=["timeupdate","progress","loadeddata","playing","seeked"];var sn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new U("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLatency$=new S.ValueSubject(void 0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.isLowLatency$=new S.ValueSubject(!1);this.isActiveLowLatency$=new S.ValueSubject(!1);this.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new Fe;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ee(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=yv(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Sg(e))!=null?n:{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,h,p,m;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((m=(p=Pt())==null?void 0:p.isTypeSupported)!=null&&m.call(p,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:m})=>r(u,p,m)),d=new Set(c.map(({codecs:p})=>p)),h=Jb(d);if(h&&(i[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,m=i.video.some(v=>v.hdr),g=i.video.some(v=>!v.hdr);S.clientChecker.isHDR&&p&&m?i.video=i.video.filter(v=>v.hdr):g&&(i.video=i.video.filter(v=>!v.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){var h;this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,S.fromEvent)(p,"error").pipe((0,S.filter)(m=>{var g;return!!((g=this.element)!=null&&g.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Db():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Us())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new va("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((m,g)=>[...m,...g.representations],[]);this.audioBufferManager=new va("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ia.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ia(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,S.interval)(1e3).subscribe(p=>{var m;if((m=this.element)!=null&&m.paused){let g=Ms(this.manifestUrlString,2);this.manifestUrlString=Ee(this.manifestUrlString,g+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...OR.map(p=>(0,S.fromEvent)(this.element,p))).pipe((0,S.map)(p=>this.element?ht(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(m=>Ju(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:m,isActiveLowLatency:g})=>g&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add((0,S.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,S.filter)(({isLive:m})=>m),(0,S.map)(m=>({...m})),(0,S.filterChanged)((m,g)=>g.bufferLength<m.bufferLength),(0,S.map)(({rtt:m,bufferLength:g,segmentServerLatency:v})=>{let T=Ms(this.manifestUrlString,2);return(m/2+g+v+T)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:m,isActiveLowLatency:g})=>{if(!g)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=m-v,w=1;Math.abs(x)>T&&(w=1+Math.sign(x)*E),Ju(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var v,T;let g=0;if(m){let E=((T=(v=this.element)==null?void 0:v.currentTime)!=null?T:0)*1e3;g=Math.min(...this.bufferManagers.map(w=>{var A,_;return(_=(A=w.getLiveSegmentsToLoadState(this.manifest))==null?void 0:A.to)!=null?_:E}))-E}this.liveLoadBufferLength$.getValue()!==g&&this.liveLoadBufferLength$.next(g)}));let p=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:g})=>{if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let v=this.element.playbackRate,T=Ms(this.manifestUrlString,2),E=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(E,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,_=isFinite(m)?m:g,Q=this.isActiveLowLatency$.getValue(),ie=E<=this.tuning.live.activeLiveDelay&&T===0;this.isActiveLowLatency$.next(Q&&ie);let N="none";if(Q?N="active_low_latency":this.isLowLatency$.getValue()&&ie?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(J=>J.proceedLowLatencyLive()),N="active_low_latency"):T!==0&&_<x?N="live_forward_buffering":_<x+A&&(N="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),N==="live_forward_buffering"||N==="live_with_target_offset"){let J=p-(x+w),X=this.normolizeLiveOffset(Math.trunc(T+J/v)),B=Math.abs(X-T),D;!m||B<=this.tuning.dashCmafLive.offsetCalculationError?D=T:X>0&&B>this.tuning.dashCmafLive.offsetCalculationError?D=X:D=0,this.manifestUrlString=Ee(this.manifestUrlString,D,2)}N!=="none"&&N!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=(0,S.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.filter)(({allBuffersFull:p,someBufferEnded:m})=>p&&m))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(p=this.source)==null||p.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var m;return(m=this.source)==null?void 0:m.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...(0,Xu.default)((0,Xu.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let m=[];return p.duration&&m.push(p.duration),qe(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&(0,S.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Zs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=br.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=Ee(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...DR.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Yt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,m,g,v,T,E,x,w,A,_;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=(0,S.now)(),n=100,o=(m=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(E=(T=this.videoBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?E:0,c=(w=(x=this.audioBufferManager)==null?void 0:x.getForwardBufferDuration())!=null?w:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let Q=this.element.currentTime*1e3;(A=this.videoBufferManager)==null||A.maintain(Q),(_=this.audioBufferManager)==null||_.maintain(Q),i.position=Q}this.tracer.log("stallIntervalCallback",(0,S.flattenObject)(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u;(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Yt(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,S.flattenObject)({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,S.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,S.flattenObject)(t)))}}};var nn=class{constructor(e,t){this.fov=e,this.orientation=t}};var on=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 i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Lv=`attribute vec2 a_vertex;
|
|
70
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var zu=W(Xr(),1);var Ev=require("@vkontakte/videoplayer-shared/es2018"),xv=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Yt(s):void 0)!=null?u:(0,Ev.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Pv=({id:a,bitrate:e})=>({id:a,bitrate:e}),wv=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Av=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Ku=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,zu.default)(r.split("."),0),isDefault:i}),Ju=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,zu.default)(i.split("."),0)}),Xu=a=>"url"in a,Ae=a=>a.type==="template",Ia=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var kv=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},$t=(a,e)=>{let t=a;t=(0,Zu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Rv.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Zu.default)(t,n,(o,u)=>(0,Ea.isNullable)(s)?o:(0,Ea.isNullable)(u)?s:(0,$v.default)(s,parseInt(u,10),"0"))}return t},Mv=(a,e)=>{var w,j,Q,ee,Y,J,X,D,_,ie,pe,R,P,q,N,fe,He,Dt,Er,Z,Se,ye,je,Ot,xr,Bt,tr,Pr,li,fl,ml,bl,gl,vl,Sl,yl,Tl,Il,El,xl,Pl,wl,Al,kl,Rl,$l,Ll,Ml,Cl,Dl,Ol,Bl,Vl,_l,Nl,Fl,ql,Ul,Hl,jl;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Xe=>{var se,rr;return(rr=(se=Xe.textContent)==null?void 0:se.trim())!=null?rr:""}),o=(w=(0,Lv.default)(n,0))!=null?w:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],m=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g=[...s.getElementsByTagName("Period")],v=g.reduce((Xe,se)=>({...Xe,[se.id]:se.children}),{}),I=g.reduce((Xe,se)=>({...Xe,[se.id]:se.getAttribute("duration")}),{});p?d=kv(p):(0,el.default)(I).filter(Xe=>Xe).length&&!u?d=(0,el.default)(I).reduce((Xe,se)=>{var rr;return Xe+((rr=kv(se))!=null?rr:0)},0):m&&(d=parseInt(m,10));let E=0,x=(Q=(j=s.getAttribute("profiles"))==null?void 0:j.split(","))!=null?Q:[];for(let Xe of g.map(se=>se.id))for(let se of v[Xe]){let rr=(ee=se.getAttribute("id"))!=null?ee:"id"+(E++).toString(10),ci=(Y=se.getAttribute("mimeType"))!=null?Y:"",Sn=(J=se.getAttribute("codecs"))!=null?J:"",yn=(X=se.getAttribute("contentType"))!=null?X:ci==null?void 0:ci.split("/")[0],pS=(_=(D=se.getAttribute("profiles"))==null?void 0:D.split(","))!=null?_:[],Gl=(pe=Iv((ie=se.getAttribute("lang"))!=null?ie:""))!=null?pe:{},hS=(q=(P=(R=se.querySelector("Label"))==null?void 0:R.textContent)==null?void 0:P.trim())!=null?q:void 0,fS=se.querySelectorAll("Representation"),mS=se.querySelector("SegmentTemplate"),bS=(fe=(N=se.querySelector("Role"))==null?void 0:N.getAttribute("value"))!=null?fe:void 0,wr=yn,ce={id:rr,language:Gl.language,isDefault:bS==="main",label:hS,codecs:Sn,hdr:wr==="video"&&Wu(Sn),mime:ci,representations:[]};for(let ae of fS){let Vt=(He=ae.getAttribute("lang"))!=null?He:void 0,di=(Dt=ae.getAttribute("label"))!=null?Dt:void 0,Ha=(Se=(Z=(Er=ae.querySelector("BaseURL"))==null?void 0:Er.textContent)==null?void 0:Z.trim())!=null?Se:"",ir=new URL(Ha||o,e).toString(),_t=(ye=ae.getAttribute("mimeType"))!=null?ye:ci,ja=(Ot=(je=ae.getAttribute("codecs"))!=null?je:Sn)!=null?Ot:"",Ga;if(yn==="text"){let Nt=ae.getAttribute("id")||"",Qa=((xr=Gl.privateuse)==null?void 0:xr.includes("x-auto"))||Nt.includes("_auto"),ar=ae.querySelector("SegmentTemplate");if(ar){let pi={representationId:(Bt=ae.getAttribute("id"))!=null?Bt:void 0,bandwidth:(tr=ae.getAttribute("bandwidth"))!=null?tr:void 0},Wa=parseInt((Pr=ae.getAttribute("bandwidth"))!=null?Pr:"",10)/1e3,Ya=(fl=parseInt((li=ar.getAttribute("startNumber"))!=null?li:"",10))!=null?fl:1,Ar=parseInt((ml=ar.getAttribute("timescale"))!=null?ml:"",10),Tn=(bl=ar.querySelectorAll("SegmentTimeline S"))!=null?bl:[],kr=ar.getAttribute("media");if(!kr)continue;let za=[],Ka=0,Ja="",Rr=0,hi=Ya,xe=0;for(let Ze of Tn){let sr=parseInt((gl=Ze.getAttribute("d"))!=null?gl:"",10),Ge=parseInt((vl=Ze.getAttribute("r"))!=null?vl:"",10)||0,Ft=parseInt((Sl=Ze.getAttribute("t"))!=null?Sl:"",10);xe=Number.isFinite(Ft)?Ft:xe;let nr=sr/Ar*1e3,qt=xe/Ar*1e3;for(let ut=0;ut<Ge+1;ut++){let Ut=$t(kr,{...pi,segmentNumber:hi.toString(10),segmentTime:(xe+ut*sr).toString(10)}),$r=(qt!=null?qt:0)+ut*nr,mi=$r+nr;hi++,za.push({time:{from:$r,to:mi},url:Ut})}xe+=(Ge+1)*sr,Ka+=(Ge+1)*nr}Rr=xe/Ar*1e3,Ja=$t(kr,{...pi,segmentNumber:hi.toString(10),segmentTime:xe.toString(10)});let fi={time:{from:Rr,to:1/0},url:Ja},vt={type:"template",baseUrl:ir,segmentTemplateUrl:kr,initUrl:"",totalSegmentsDurationMs:Ka,segments:za,nextSegmentBeyondManifest:fi,timescale:Ar};Ga={id:Nt,kind:"text",segmentReference:vt,profiles:[],duration:d,bitrate:Wa,mime:"",codecs:"",width:0,height:0,isAuto:Qa}}else Ga={id:Nt,isAuto:Qa,kind:"text",url:ir}}else{let Nt=(Tl=(yl=ae.getAttribute("contentType"))!=null?yl:_t==null?void 0:_t.split("/")[0])!=null?Tl:yn,Qa=(El=(Il=se.getAttribute("profiles"))==null?void 0:Il.split(","))!=null?El:[],ar=parseInt((xl=ae.getAttribute("width"))!=null?xl:"",10),pi=parseInt((Pl=ae.getAttribute("height"))!=null?Pl:"",10),Wa=parseInt((wl=ae.getAttribute("bandwidth"))!=null?wl:"",10)/1e3,Ya=(Al=ae.getAttribute("frameRate"))!=null?Al:"",Ar=(kl=ae.getAttribute("quality"))!=null?kl:void 0,Tn=Ya?Tv(Ya):void 0,kr=(Rl=ae.getAttribute("id"))!=null?Rl:"id"+(E++).toString(10),za=Nt==="video"?`${pi}p`:Nt==="audio"?`${Wa}Kbps`:ja,Ka=`${kr}@${za}`,Ja=[...x,...pS,...Qa],Rr,hi=ae.querySelector("SegmentBase"),xe=($l=ae.querySelector("SegmentTemplate"))!=null?$l:mS;if(hi){let vt=(Ml=(Ll=ae.querySelector("SegmentBase Initialization"))==null?void 0:Ll.getAttribute("range"))!=null?Ml:"",[Ze,sr]=vt.split("-").map(Ut=>parseInt(Ut,10)),Ge={from:Ze,to:sr},Ft=(Cl=ae.querySelector("SegmentBase"))==null?void 0:Cl.getAttribute("indexRange"),[nr,qt]=Ft?Ft.split("-").map(Ut=>parseInt(Ut,10)):[],ut=Ft?{from:nr,to:qt}:void 0;Rr={type:"byteRange",url:ir,initRange:Ge,indexRange:ut}}else if(xe){let vt={representationId:(Dl=ae.getAttribute("id"))!=null?Dl:void 0,bandwidth:(Ol=ae.getAttribute("bandwidth"))!=null?Ol:void 0},Ze=parseInt((Bl=xe.getAttribute("timescale"))!=null?Bl:"",10),sr=(Vl=xe.getAttribute("initialization"))!=null?Vl:"",Ge=xe.getAttribute("media"),Ft=(Nl=parseInt((_l=xe.getAttribute("startNumber"))!=null?_l:"",10))!=null?Nl:1,nr=$t(sr,vt);if(!Ge)throw new ReferenceError("No media attribute in SegmentTemplate");let qt=(Fl=xe.querySelectorAll("SegmentTimeline S"))!=null?Fl:[],ut=[],Ut=0,$r="",mi=0;if(qt.length){let Xa=Ft,et=0;for(let Lr of qt){let lt=parseInt((ql=Lr.getAttribute("d"))!=null?ql:"",10),or=parseInt((Ul=Lr.getAttribute("r"))!=null?Ul:"",10)||0,Za=parseInt((Hl=Lr.getAttribute("t"))!=null?Hl:"",10);et=Number.isFinite(Za)?Za:et;let In=lt/Ze*1e3,En=et/Ze*1e3;for(let es=0;es<or+1;es++){let vS=$t(Ge,{...vt,segmentNumber:Xa.toString(10),segmentTime:(et+es*lt).toString(10)}),Ql=(En!=null?En:0)+es*In,SS=Ql+In;Xa++,ut.push({time:{from:Ql,to:SS},url:vS})}et+=(or+1)*lt,Ut+=(or+1)*In}mi=et/Ze*1e3,$r=$t(Ge,{...vt,segmentNumber:Xa.toString(10),segmentTime:et.toString(10)})}else if((0,Ea.isNonNullable)(d)){let et=parseInt((jl=xe.getAttribute("duration"))!=null?jl:"",10)/Ze*1e3,Lr=Math.ceil(d/et),lt=0;for(let or=1;or<Lr;or++){let Za=$t(Ge,{...vt,segmentNumber:or.toString(10),segmentTime:lt.toString(10)});ut.push({time:{from:lt,to:lt+et},url:Za}),lt+=et}mi=lt,$r=$t(Ge,{...vt,segmentNumber:Lr.toString(10),segmentTime:lt.toString(10)})}let gS={time:{from:mi,to:1/0},url:$r};Rr={type:"template",baseUrl:ir,segmentTemplateUrl:Ge,initUrl:nr,totalSegmentsDurationMs:Ut,segments:ut,nextSegmentBeyondManifest:gS,timescale:Ze}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Nt||!_t)continue;let fi={video:"video",audio:"audio",text:"text"}[Nt];if(!fi)continue;wr||(wr=fi),Ga={id:Ka,kind:fi,segmentReference:Rr,profiles:Ja,duration:d,bitrate:Wa,mime:_t,codecs:ja,width:ar,height:pi,fps:Tn,quality:Ar}}ce.language||(ce.language=Vt),ce.label||(ce.label=di),ce.mime||(ce.mime=_t),ce.codecs||(ce.codecs=ja),ce.hdr||(ce.hdr=wr==="video"&&Wu(ja)),ce.representations.push(Ga)}if(wr){let ae=i[wr].find(Vt=>Vt.id===ce.id);if(ae&&ce.representations.every(Vt=>Ae(Vt.segmentReference)))for(let Vt of ae.representations){let di=ce.representations.find(_t=>_t.id===Vt.id),Ha=di==null?void 0:di.segmentReference,ir=Vt.segmentReference;ir.segments.push(...Ha.segments),ir.nextSegmentBeyondManifest=Ha.nextSegmentBeyondManifest}else i[wr].push(ce)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var Cv=W(at(),1),rl=require("@vkontakte/videoplayer-shared/es2018"),Oe=(a,e)=>(0,rl.isNonNullable)(a)&&(0,rl.isNonNullable)(e)&&a.readyState==="open"&&(0,Cv.default)([...a.activeSourceBuffers],e);var xa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new T.ValueSubject(0);this.currentLowLatencySegmentLength$=new T.ValueSubject(0);this.currentSegmentLength$=new T.ValueSubject(0);this.onLastSegment$=new T.ValueSubject(!1);this.fullyBuffered$=new T.ValueSubject(!1);this.playingRepresentation$=new T.ValueSubject(void 0);this.playingRepresentationInit$=new T.ValueSubject(void 0);this.error$=new T.Subject;this.gaps=[];this.subscription=new T.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ue;this.switchAbortController=new Ue;this.destroyAbortController=new Ue;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,T.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new $g(this.sourceBuffer),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Oe(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Fu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=mt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,T.assertNonNullable)(r,"No init buffer for starting representation"),(0,T.assertNonNullable)(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchToOld=(0,T.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,T.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,T.isNullable)(s)||(0,T.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,T.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Oe(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,T.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,an.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!Ae(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);(0,T.assertNonNullable)(i);let s=this.segments.get(r);(0,T.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,T.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Ue,(0,T.abortable)(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);(0,T.assertNonNullable)(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if((0,T.isNullable)(o)||(0,T.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),(0,T.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Oe(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,T.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,T.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ue,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,T.isNullable)(e)||(0,T.isNullable)(this.downloadingRepresentationId)||(0,T.isNullable)(this.playingRepresentationId)||(0,T.isNullable)(this.sourceBuffer)||!Oe(this.mediaSource,this.sourceBuffer)||(0,T.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,T.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);(0,T.isNonNullable)(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=mt(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Fu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=mt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,rn.default)(o,i))l="high";else{let c=(0,ni.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&mt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ni.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;(0,T.isNonNullable)(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,an.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,an.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ae(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ni.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,T.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!Ae(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=$t(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Xi&&Xi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Xi&&Xi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let g=p<=r&&h>=r,v=p>r||g||m===0&&r===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&p<=r+I||h<=r+I;return(d==="none"||d==="partially_ejected"&&v&&E&&this.sourceBuffer&&Oe(this.mediaSource,this.sourceBuffer)&&!(Jt(this.sourceBuffer.buffered,p)&&Jt(this.sourceBuffer.buffered,h)))&&v&&E});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){Ae(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,T.abortable)(o,async function*(){let c=(0,T.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:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,T.now)(),!c)return;let d=new DataView(c),p=Ta(t.mime);if(!isFinite(i.segment.time.to)){let g=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,g)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ia(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ae(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="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:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,T.abortable)(n,async function*(){let u=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,T.fromEvent)(window,"online").pipe((0,T.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=(0,T.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ia(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ae(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ni.default)(e,0).byte.from,to:(0,ni.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ae(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,rn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Ta(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<i,m=d<=i;if(!h)continue;let g=Ta(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-c),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),I=u.loadedBytes===p?v:g.parseFeedableSegmentChunk(v);I!=null&&I.byteLength&&(l.status="partially_fed",u.feedingBytes+=I.byteLength,await this.sourceBufferTaskQueue.append(I,s)&&!s.aborted?(u.fedBytes+=I.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var r;if(!((0,T.isNullable)(this.sourceBuffer)||!Oe(this.mediaSource,this.sourceBuffer))){!this.isLive&&T.clientChecker.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Jt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Jt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Xu(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=_u(()=>(0,Dv.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,T.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ta(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ae(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:T.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!Oe(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,T.isNullable)(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push({...u.time}),i=n(i);let l=Xu(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,rn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!Oe(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!Oe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!Oe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,T.isNullable)(e)?0:mt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Oe(this.mediaSource,this.sourceBuffer)))for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Oe(this.mediaSource,this.sourceBuffer))){for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=_u(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:T.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,T.isNullable)(this.sourceBuffer)||!Oe(this.mediaSource,this.sourceBuffer)||(0,T.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Pa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Ov=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};var z=require("@vkontakte/videoplayer-shared/es2018");var Bv=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var sn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new z.ValueSubject(void 0);this.lastConnectionReused$=new z.ValueSubject(void 0);this.lastRequestFirstBytes$=new z.ValueSubject(void 0);this.abortAllController=new Ue;this.subscription=new z.Subscription;this.fetchManifest=(0,z.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Pa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Bv(r));let i=yield wt(r,{signal:this.abortAllController.signal}).catch(wa);return i?(t.log("success",(0,z.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,z.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,z.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var X,D;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(l,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),l=_.toString();break}default:(0,z.assertNever)(t)}this.requestQuic&&(l=Pa(l));let p=this.abortAllController.signal,h;if(n){let _=new Ue;if(h=(0,z.merge)((0,z.fromEvent)(this.abortAllController.signal,"abort"),(0,z.fromEvent)(n,"abort")).subscribe(()=>{try{_.abort()}catch(ie){wa(ie)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(ie){wa(ie)}p=_.signal}let m=(0,z.now)();d.log("startRequest",(0,z.flattenObject)({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:m}));let g=yield wt(l,{priority:s,headers:c,signal:p}).catch(wa),v=(0,z.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((X=this.throughputEstimator)==null||X.addRawRtt(v-m),!g.ok||!g.body){h==null||h.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:_}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){h==null||h.unsubscribe();let _=(0,z.now)(),ie={requestStartedAt:m,requestEndedAt:_,duration:_-m};return d.log("endRequest",(0,z.flattenObject)(ie)),d.end(),g.arrayBuffer()}let[I,E]=g.body.tee(),x=I.getReader();o&&((D=this.throughputEstimator)==null||D.trackStream(E,u));let k=0,w=new Uint8Array(0),j=!1,Q=_=>{h==null||h.unsubscribe(),j=!0,wa(_)},ee=(0,z.abortable)(p,async function*({done:_,value:ie}){if(k===0&&this.lastRequestFirstBytes$.next((0,z.now)()-m),p.aborted){h==null||h.unsubscribe();return}if(!_&&ie){let pe=new Uint8Array(w.length+ie.length);pe.set(w),pe.set(ie,w.length),w=pe,k+=ie.byteLength,i==null||i(new DataView(w.buffer),k),yield x==null?void 0:x.read().then(ee,Q)}}.bind(this));yield x==null?void 0:x.read().then(ee,Q),h==null||h.unsubscribe();let Y=(0,z.now)(),J={failed:j,requestStartedAt:m,requestEndedAt:Y,duration:Y-m};return j?(d.error("endRequest",(0,z.flattenObject)(J)),d.end(),null):(d.log("endRequest",(0,z.flattenObject)(J)),d.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,z.abortable)(this.abortAllController.signal,async function*(e,t,r){var I;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(I=e.indexRange)!=null?I:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let E=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!E)return null;g=new DataView(E)}let v=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,z.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=Ov(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,z.assertNever)(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},wa=a=>{if(!Ia(a))throw a};var yr=(a,e,t)=>t*e+(1-t)*a,il=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Vv=(a,e,t,r)=>{let i=0,s=t,n=il(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};var Aa=require("@vkontakte/videoplayer-shared/es2018"),Zt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Aa.ValueSubject(e.initial),this.debounced$=new Aa.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new we(`raw_${t}`),this.smoothedSeries$=new we(`smoothed_${t}`),this.reportedSeries$=new we(`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 i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,Aa.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 nn=class extends Zt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=yr(this.slow,e,this.params.emaAlphaSlow),this.fast=yr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var on=class extends Zt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=il(this.pastMeasures,this.takenMeasures);this.emaSmoothed=yr(this.emaSmoothed,e,this.params.emaAlpha);let r=Vv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var un=class extends Zt{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?yr(this.smoothed,t,this.params.emaAlpha):t}};var Tr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new nn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new on({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new un({initial:e,label:"liveEdgeDelay",...t})}};var al=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var ln=require("@vkontakte/videoplayer-shared/es2018");var ka=class a{constructor(e,t){this.currentRepresentation$=new ln.ValueSubject(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!(0,ln.isNullable)(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ae(t.segmentReference))}};var NR=["timeupdate","progress","play","seeked","stalled","waiting"],FR=["timeupdate","progress","loadeddata","playing","seeked"];var cn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new U("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLatency$=new S.ValueSubject(void 0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.isLowLatency$=new S.ValueSubject(!1);this.isActiveLowLatency$=new S.ValueSubject(!1);this.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new Ue;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ee(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Mv(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=wg(e))!=null?n:{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((m=(h=At())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),d=new Set(c.map(({codecs:h})=>h)),p=ag(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(v=>v.hdr),g=i.video.some(v=>!v.hdr);S.clientChecker.isHDR&&h&&m?i.video=i.video.filter(v=>v.hdr):g&&(i.video=i.video.filter(v=>!v.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,S.fromEvent)(p,"error").pipe((0,S.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?qb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ws())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new xa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new xa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ka.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ka(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,S.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=Vs(this.manifestUrlString,2);this.manifestUrlString=Ee(this.manifestUrlString,m+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...FR.map(p=>(0,S.fromEvent)(this.element,p))).pipe((0,S.map)(p=>this.element?mt(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(h=>al(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add((0,S.combine)({isActiveLowLatency:this.isActiveLowLatency$.pipe((0,S.filterChanged)()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe((0,S.filter)(({isActiveLowLatency:h,currentLowLatencySegmentLength:m})=>h&&!!m)).subscribe(({currentLowLatencySegmentLength:h})=>{let m=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add((0,S.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,S.filter)(({isLive:h})=>h),(0,S.map)(h=>({...h})),(0,S.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,S.map)(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let v=Vs(this.manifestUrlString,2);return(h/2+m+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:m})=>{if(!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=h-g,x=1;Math.abs(E)>v&&(x=1+Math.sign(E)*I),al(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,v;let m=0;if(h){let I=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;m=Math.min(...this.bufferManagers.map(x=>{var k,w;return(w=(k=x.getLiveSegmentsToLoadState(this.manifest))==null?void 0:k.to)!=null?w:I}))-I}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=Vs(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,w=isFinite(h)?h:m,j=this.isActiveLowLatency$.getValue(),Q=I<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(j&&Q);let ee="none";if(j?ee="active_low_latency":this.isLowLatency$.getValue()&&Q?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(Y=>Y.proceedLowLatencyLive()),ee="active_low_latency"):v!==0&&w<E?ee="live_forward_buffering":w<E+k&&(ee="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),ee==="live_forward_buffering"||ee==="live_with_target_offset"){let Y=p-(E+x),J=this.normolizeLiveOffset(Math.trunc(v+Y/g)),X=Math.abs(J-v),D;!h||X<=this.tuning.dashCmafLive.offsetCalculationError?D=v:J>0&&X>this.tuning.dashCmafLive.offsetCalculationError?D=J:D=0,this.manifestUrlString=Ee(this.manifestUrlString,D,2)}ee!=="none"&&ee!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=(0,S.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.filter)(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,sl.default)((0,sl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Ae(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,S.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new sn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=Tr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=Ee(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...NR.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Jt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,g,v,I,E,x,k,w,j;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=(0,S.now)(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(E=(I=this.videoBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?E:0,c=(k=(x=this.audioBufferManager)==null?void 0:x.getForwardBufferDuration())!=null?k:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let Q=this.element.currentTime*1e3;(w=this.videoBufferManager)==null||w.maintain(Q),(j=this.audioBufferManager)==null||j.maintain(Q),i.position=Q}this.tracer.log("stallIntervalCallback",(0,S.flattenObject)(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}async seek(e,t){var i,s,n,o,u;(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Jt(this.element.buffered,r)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,S.flattenObject)({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,S.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,S.flattenObject)(t)))}}};var dn=class{constructor(e,t){this.fov=e,this.orientation=t}};var pn=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 i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Nv=`attribute vec2 a_vertex;
|
|
70
71
|
attribute vec2 a_texel;
|
|
71
72
|
|
|
72
73
|
varying vec2 v_texel;
|
|
@@ -77,7 +78,7 @@ void main(void) {
|
|
|
77
78
|
// save texel vector to pass to fragment shader
|
|
78
79
|
v_texel = a_texel;
|
|
79
80
|
}
|
|
80
|
-
`;var
|
|
81
|
+
`;var Fv=`#ifdef GL_ES
|
|
81
82
|
precision highp float;
|
|
82
83
|
precision highp int;
|
|
83
84
|
#else
|
|
@@ -120,5 +121,5 @@ void main(void) {
|
|
|
120
121
|
// sample using new coordinates
|
|
121
122
|
gl_FragColor = texture2D(u_texture, tc);
|
|
122
123
|
}
|
|
123
|
-
`;var un=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new nn(this.params.fov,this.params.orientation),this.cameraRotationManager=new on(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Lv,this.gl.VERTEX_SHADER),r=this.createShader(Mv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,h=t+i;return[s,n,o,u,l,c,d,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 ge=require("@vkontakte/videoplayer-shared/es2018"),Zu=class{constructor(){this.isSeeked$=new ge.ValueSubject(!1);this.isBuffering$=new ge.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new ge.Subscription}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,ge.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,ge.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,ge.combine)({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if((0,ge.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:i,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,ge.now)(),h=n&&this.currentStallsCount>=n,p=i&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,m=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(h||p||m)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,ge.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,ge.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Cv=Zu;var De=require("@vkontakte/videoplayer-shared/es2018"),ln=class{constructor(){this.subscription=new De.Subscription;this.pipSize$=new De.ValueSubject(void 0);this.videoSize$=new De.ValueSubject(void 0);this.elementSize$=new De.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=De.noop}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,De.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,De.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,De.map)(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var gr=class{constructor(e){this.subscription=new q.Subscription;this.videoState=new U("stopped");this.textTracksManager=new Qe;this.droppedFramesManager=new _s;this.stallsManager=new Cv;this.elementSizeManager=new ln;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Bi;this.audioTrackSwitchHistory=new Bi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,q.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new un(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=we(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(me(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new sn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=$e(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:q.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,q.filter)(c=>!!c.length),(0,q.once)()).subscribe(c=>{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:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,q.map)(c=>c.to.state!=="none"),(0,q.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,q.filterChanged)()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,q.filter)(q.isNonNullable),(0,q.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,q.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ge(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(We(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,q.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let m of d.audio){p.push(Wu(m));let g=[];for(let v of m.representations){let T=Ev(v);g.push(T),this.audioTracksMap.set(T,{stream:m,representation:v})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(Yu(p));let m=[];for(let g of p.representations){let v=Iv({...g,streamId:p.id});v&&(m.push(v),this.videoTracksMap.set(v,{stream:p,representation:g}))}this.videoStreamsMap.set(p,m)}this.params.output.availableVideoStreams$.next(h);for(let p of d.text)for(let m of p.representations){let g=xv(p,m);this.textTracksMap.set(g,{stream:p,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&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:q.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,q.merge)(this.player.currentStallDuration$,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.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,q.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Dv.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[p,m]=h,g=[...this.videoTracksMap.keys()].find(T=>{var E;return((E=this.videoTracksMap.get(T))==null?void 0:E.representation.id)===p.id});(0,q.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")this.player.initRepresentations(p.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(o),m){let T=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,T).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,q.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:p}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===p.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Yu(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,q.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:p}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===p.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Wu(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,h;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe((0,q.map)(({to:c})=>c==="ready"),(0,q.filterChanged)());this.subscription.add((0,q.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,q.merge)(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,q.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var _,Q,ie,N,J,X,B,D,re,ce,R,P,W;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(_=e.videoTrack.getState())==null?void 0:_.id,n=[...this.videoTracksMap.keys()].find(({id:j})=>j===i),o=t.currentVideoTrack$.getValue(),u=((N=(ie=e.videoStream.getState())!=null?ie:n&&((Q=this.videoTracksMap.get(n))==null?void 0:Q.stream))!=null?N:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:j})=>j===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ht(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(J=e.audioStream.getState())!=null?J:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(X=[...this.audioStreamsMap.keys()].find(({id:j})=>j===(m==null?void 0:m.id)))!=null?X:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let j=Vs(n,c,(B=this.audioStreamsMap.get(g))!=null?B:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(D=j==null?void 0:j.bitrate)!=null?D:-1/0)}if(o){let j=Vs(o,c,(re=this.audioStreamsMap.get(g))!=null?re:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(ce=j==null?void 0:j.bitrate)!=null?ce:-1/0)}}let T=Wt(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:p,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),E=r?T!=null?T:n:n!=null?n:T,x=g&&ib(E,c,(R=this.audioStreamsMap.get(g))!=null?R:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),w=(P=this.videoTracksMap.get(E))==null?void 0:P.representation,A=x&&((W=this.audioTracksMap.get(x))==null?void 0:W.representation);if(w&&A)return[w,A];if(w&&!A&&this.audioTracksMap.size===0)return[w,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ke(this.video),this.tracer.end()}};var xa=class extends gr{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 Jt=require("@vkontakte/videoplayer-shared/es2018");var Pa=class extends gr{constructor(e){super(e),this.liveOffset=new Tt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe((0,Jt.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,Jt.combine)({interval:(0,Jt.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add((0,Jt.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,Jt.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Pv(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Ov=Y(Ls(),1);var G=require("@vkontakte/videoplayer-shared/es2018"),at={};var ri=(a,e)=>new G.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Aa=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new U("initializing");this.textTracksManager=new Qe;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,G.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,G.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,G.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,G.assertNever)(e)}break;default:(0,G.assertNever)(t)}};this.video=we(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(me(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ke(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:G.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Ov.default)(import("hls.js").then(i=>{e||(at.Hls=i.default,at.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,G.assertNonNullable)(at.Hls,"hls.js not loaded"),this.hls=new at.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,G.assertNonNullable)(at.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:G.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=$e(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(dt(this.video,e.isLooped,r)),this.subscription.add(Re(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ge(this.video,e.playbackRate,i.playbackRateState$,r)),s(We(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,G.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ri(this.hls,at.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:G.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(ri(this.hls,at.Events.MANIFEST_PARSED).pipe((0,G.map)(({levels:l})=>l.reduce((c,d)=>{var E,x;let h=d.name||d.height.toString(10),{width:p,height:m}=d,g=(x=Gt((E=d.attrs.QUALITY)!=null?E:""))!=null?x:(0,G.videoSizeToQuality)({width:p,height:m});if(!g)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:h.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:v};return this.trackLevels.set(h,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(ri(this.hls,at.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang;c.push({id:h,url:p,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ri(this.hls,at.Events.LEVEL_LOADING).pipe((0,G.map)(({url:l})=>me(l))),t.hostname$),s(ri(this.hls,at.Events.FRAG_CHANGED),l=>{var h,p,m,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(jt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=ri(this.hls,at.Events.LEVEL_SWITCHED).pipe((0,G.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,G.filter)(G.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(jt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,G.isNullable)(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,G.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0)}};var Vv="X-Playback-Duration",el=async a=>{var i;let e=await xt(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Vv)?parseInt(e.headers.get(Vv),10):void 0};var H=require("@vkontakte/videoplayer-shared/es2018");var rl=Y(xo(),1);var cn=require("@vkontakte/videoplayer-shared/es2018");var FR=a=>{let e=null;if(a.QUALITY&&(e=Gt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=(0,cn.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},qR=(a,e)=>{var s,n;let t=a.split(`
|
|
124
|
-
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,rl.default)(l[1].split(",").map(E=>E.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=FR(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[E,x]=d.RESOLUTION.split("x").map(w=>parseInt(w,10));E&&x&&(v={width:E,height:x})}let T=new URL(t[++o],e).toString();p&&r.push({id:h,quality:p,url:T,bandwidth:m,size:v,fps:g})}if(c){let d=(0,rl.default)(c[1].split(",").map(g=>g.split("=")).map(([g,v])=>[g,v.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,m=d.NAME;h&&p&&i.push({type:"internal",id:p,label:m,language:p,url:h,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},UR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),tl=0,Bv=async(a,e=a,t)=>{let i=await(await xt(a)).text();tl+=1;try{let{qualityManifests:s,textTracks:n}=qR(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(tl<=t.manifestRetryMaxCount)return await UR((0,cn.getExponentialDelay)(tl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Bv(a,e,t)}return{qualityManifests:[],textTracks:[]}},dn=Bv;var wa=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new U("stopped");this.textTracksManager=new Qe;this.manifests$=new H.ValueSubject([]);this.liveOffset=new Tt;this.manifestStartTime$=new H.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,H.assertNever)(t)}};var t;this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:H.VideoQuality.INVARIANT,url:this.params.source.url},dn(Ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:H.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:H.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(me(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new H.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:H.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=$e(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ge(this.video,t.playbackRate,i.playbackRateState$,r)),s(We(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,H.filterChanged)(),(0,H.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,H.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(me(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)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,H.combine)({startTime:this.manifestStartTime$.pipe((0,H.filter)(H.isNonNullable)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe((0,H.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,H.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var o,u;let e=this.selectManifest();if((0,H.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,h]of[[l,"mq"],[c,"lq"]]){let p=String(parseFloat(d||""));h&&d&&i.searchParams.set(h,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ee(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),el(n).then(l=>{var c;if(!(0,H.isNullable)(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if((0,H.isNullable)(d)||!isFinite(d))try{xt(n).then(h=>h.text()).then(h=>{var m;let p=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:m[1];if(p){let g=new URL(p,n).toString();el(g).then(v=>{(0,H.isNullable)(v)||this.maxSeekBackTime$.next(v)})}})}catch(h){}}})}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};var K=require("@vkontakte/videoplayer-shared/es2018");var ka=class{constructor(e){this.subscription=new K.Subscription;this.videoState=new U("stopped");this.textTracksManager=new Qe;this.manifests$=new K.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,K.assertNever)(t)}};this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:K.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(me(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),dn(Ee(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:K.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:K.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=$e(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,K.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(dt(this.video,t.isLooped,r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ge(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,K.isNonNullable)(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let g=this.manifests$.getValue().find(v=>v.id===m);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(me(g.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,K.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!K.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,K.merge)((0,K.fromEvent)(o,"addtrack"),(0,K.fromEvent)(o,"removetrack"),(0,K.fromEvent)(o,"change"),(0,K.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,K.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,K.observableFrom)(["init"])).pipe((0,K.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,K.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(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}};var _v=Y(Vr(),1),Ra=Y(Oi(),1);var te=require("@vkontakte/videoplayer-shared/es2018");var $a=class{constructor(e){this.subscription=new te.Subscription;this.videoState=new U("stopped");this.trackUrls={};this.textTracksManager=new Qe;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,te.assertNever)(e)}};this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),(0,_v.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Ra.default)(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:te.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=$e(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,te.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(dt(this.video,t.isLooped,r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ge(this.video,t.playbackRate,i.playbackRateState$,r)),s(We(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,te.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,te.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,te.observableFrom)(["init"])).pipe((0,te.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ke(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,te.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,te.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Sa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(me(t))}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:te.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Ra.default)(this.trackUrls).find(d=>!(0,te.isInvariantQuality)(d.track.quality)&&(0,te.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&(0,te.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=(0,Ra.default)(this.trackUrls).filter(p=>!(0,te.isInvariantQuality)(p.track.quality)&&(0,te.isHigher)(p.track.quality,e)),h=d.length;h&&(t=d[h-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Ra.default)(this.trackUrls).map(l=>l.track);t=Wt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput: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 se=require("@vkontakte/videoplayer-shared/es2018");var Fv=require("@vkontakte/videoplayer-shared/es2018"),Nv=["stun:videostun.mycdn.me:80"],HR=1e3,jR=3,il=()=>null,pn=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=il;this.externalStopCallback=il;this.externalErrorCallback=il;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:Nv}]};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:Fv.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(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),HR)}normalizeOptions(e={}){let t={stunServerList:Nv,maxRetryNumber:jR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var La=class{constructor(e){this.videoState=new U("stopped");this.maxSeekBackTime$=new se.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"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,se.assertNever)(e)}};this.subscription=new se.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=we(e.container,e.tuning),this.liveStreamClient=new pn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ke(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:se.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,se.merge)(this.videoState.stateChangeStarted$.pipe((0,se.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,se.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=$e(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(We(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Re(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,se.assertNever)(n.to)}},r)).add((0,se.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,se.observableFrom)(["init"])).pipe((0,se.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(me(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:se.VideoQuality.INVARIANT}),this.video.srcObject=e,k(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:se.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:se.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ma=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared/es2018");var Rt=require("@vkontakte/videoplayer-shared/es2018"),qv=a=>new Rt.Observable(e=>{let t=new Rt.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Rt.map)(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Rt.map)(({type:l})=>l!==void 0)),n=new Rt.Subject,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Ke=require("@vkontakte/videoplayer-shared/es2018");function Uv(){return new(window.AudioContext||window.webkitAudioContext)}var Hv=require("@vkontakte/videoplayer-shared/es2018");var Ca=class Ca{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new Fe;this.subscriptions=new Ke.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Ke.filter)(s=>!!s.type),(0,Ke.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){Hv.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Ke.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Ke.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,Ke.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=Uv();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(await r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Ca.errorId,category:Ke.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ca.errorId} exception`,thrown:e})}};Ca.errorId="VolumeMultiplierManager";var ii=Ca;var GR={chunkDuration:5e3,maxParallelRequests:5},Da=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,soundProhibitedEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),liveLatency$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject("")};this.subscription=new y.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Yb([...Kb(this.params.tuning),...zb(this.params.tuning)],this.params.tuning).filter(l=>(0,y.isNonNullable)(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,al.default)(i,l)),...t.filter(l=>(0,al.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new Ma(s);let n=[...ku(!0),...ku(!1)];this.chromecastFormatsIterator=new Ma(n.filter(l=>(0,y.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ii.isSupported()&&(this.volumeMultiplierManager=new ii(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,y.assertNonNullable)(o),new xa({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Pa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),Kr||!this.params.tuning.useHlsJs?new ka({...n,source:o}):new Aa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new wa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new $a({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new pb({...n,source:o,config:{...GR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new La({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new Di({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,Gv.default)((0,jv.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,r=0;return e.add((0,y.merge)(this.providerOutput.error$.pipe((0,y.filter)(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),qv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(i=>({id:`ProviderHangup:${i}`,category:y.ErrorCategory.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===y.ErrorCategory.NETWORK,u=i.category===y.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var V=require("@vkontakte/videoplayer-shared/es2018");var QR=5e3,Qv="one_video_throughput",Wv="one_video_rtt",$t=window.navigator.connection,Yv=()=>{let a=$t==null?void 0:$t.downlink;if((0,V.isNonNullable)(a)&&a!==10)return a*1e3},zv=()=>{let a=$t==null?void 0:$t.rtt;if((0,V.isNonNullable)(a)&&a!==3e3)return a},Kv=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},sl=class a{constructor(e){this.subscription=new V.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(Qv)||(e.useBrowserEstimation?Yv():void 0)||QR,r=(s=(i=a.load(Wv))!=null?i:e.useBrowserEstimation?zv():void 0)!=null?s:0;if(this.throughput$=new V.ValueSubject(t),this.rtt$=new V.ValueSubject(r),this.rttAdjustedThroughput$=new V.ValueSubject(Kv(t,r,e.rttPenaltyRequestSize)),this.throughput=br.getSmoothedValue(t,-1,e),this.rtt=br.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=Yv();u&&this.throughput.next(u);let l=zv();(0,V.isNonNullable)(l)&&this.rtt.next(l)};$t&&"onchange"in $t&&this.subscription.add((0,V.fromEvent)($t,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{V.safeStorage.set(Qv,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{V.safeStorage.set(Wv,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,V.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,V.map)(({throughput:n,rtt:o})=>Kv(n,o,e.rttPenaltyRequestSize)),(0,V.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,V.now)(),i=new V.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,V.fromEvent)(e,"progress").pipe((0,V.once)()).subscribe(s=>{t=s.loaded,r=(0,V.now)()}));break;case 1:case 0:i.add((0,V.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,V.now)()}));break}i.add((0,V.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,V.now)(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=(0,V.now)(),n=0,o=(0,V.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(i,(0,V.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=(0,V.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=(0,V.now)()}else n+=d.byteLength;o=(0,V.now)()}else i+=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==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=V.safeStorage.get(e);if((0,V.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},Jv=sl;var Oa=require("@vkontakte/videoplayer-shared/es2018"),Xv={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:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Oa.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Oa.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{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:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",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,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,exposeInternalsToGlobal:!1},Zv=a=>{var e;return{...(0,Oa.fillWithDefault)(a,Xv),configName:[...(e=a.configName)!=null?e:[],...Xv.configName]}};var f=require("@vkontakte/videoplayer-shared/es2018");var Lt=require("@vkontakte/videoplayer-shared/es2018"),nl=({seekState:a,position$:e})=>(0,Lt.merge)(a.stateChangeEnded$.pipe((0,Lt.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Lt.filter)(Lt.isNonNullable)),e.pipe((0,Lt.filter)(()=>a.getState().state==="none")));var eS=require("@vkontakte/videoplayer-shared/es2018"),tS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,eS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var hn=require("@vkontakte/videoplayer-shared/es2018"),rS=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,hn.filter)(i=>i.length>0),(0,hn.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Va=class{constructor(e={configName:[]},t=f.Tracer.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new U("stopped"),seekState:new U({state:"none"}),volume:new U({volume:1,muted:!1}),videoTrack:new U(void 0),videoStream:new U(void 0),audioStream:new U(void 0),autoVideoTrackSwitching:new U(!0),autoVideoTrackLimits:new U({}),isLooped:new U(!1),isLowLatency:new U(!1),playbackRate:new U(1),externalTextTracks:new U([]),internalTextTracks:new U([]),currentTextTrack:new U(void 0),textTrackCuesSettings:new U({}),cameraOrientation:new U({x:0,y:0})};this.info={playbackState$:new f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),liveLatency$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:Jm};if(this.initLogs(),this.tuning=Zv(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new is({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Jv(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,m)=>{let g=typeof m;return(0,iS.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:f.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n,o;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",(0,f.flattenObject)(r)),this.domContainer=tS(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new Da({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(o=this.internalsExposure)==null||o.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!qi()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;(0,f.assertNonNullable)(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return rS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,f.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,f.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,f.isInvariantQuality)(u)?1:(0,f.isInvariantQuality)(l)?-1:(0,f.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:nl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(nl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>r.next(!1)));let i=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Wt(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),Km(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>zm(r)),this.providerContainer.current$.subscribe(({type:r})=>Vi("provider",r)),e.duration$.subscribe(r=>Vi("duration",r)),e.availableVideoTracks$.pipe((0,f.filter)(r=>!!r.length),(0,f.once)()).subscribe(r=>Vi("tracks",r)),this.events.fatalError$.subscribe(new Ae("fatalError")),this.events.managedError$.subscribe(new Ae("managedError")),e.position$.subscribe(new Ae("position")),e.currentVideoTrack$.pipe((0,f.map)(r=>r==null?void 0:r.quality)).subscribe(new Ae("quality")),this.info.currentBuffer$.subscribe(new Ae("buffer")),e.isBuffering$.subscribe(new Ae("isBuffering"))].forEach(r=>this.subscription.add(r)),Vi("codecs",Wb())}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,f.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),(0,f.filterChanged)((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(r=>r>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(r=>r>0),(0,f.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(r=>r.end>0),(0,f.filterChanged)((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:r,rtt:i})=>!!r&&!!i),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(i)})})};this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var mt=require("@vkontakte/videoplayer-shared/es2018"),WR=`@vkontakte/videoplayer-core@${Sn}`;
|
|
124
|
+
`;var hn=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new dn(this.params.fov,this.params.orientation),this.cameraRotationManager=new pn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Nv,this.gl.VERTEX_SHADER),r=this.createShader(Fv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var ve=require("@vkontakte/videoplayer-shared/es2018"),nl=class{constructor(){this.isSeeked$=new ve.ValueSubject(!1);this.isBuffering$=new ve.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new ve.Subscription}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,ve.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,ve.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,ve.combine)({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if((0,ve.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:i,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,ve.now)(),p=n&&this.currentStallsCount>=n,h=i&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,m=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(p||h||m)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,ve.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,ve.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},qv=nl;var Be=require("@vkontakte/videoplayer-shared/es2018"),fn=class{constructor(){this.subscription=new Be.Subscription;this.pipSize$=new Be.ValueSubject(void 0);this.videoSize$=new Be.ValueSubject(void 0);this.elementSize$=new Be.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Be.noop}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,Be.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,Be.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Be.map)(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Ir=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new U("stopped");this.textTracksManager=new We;this.droppedFramesManager=new Hs;this.stallsManager=new qv;this.elementSizeManager=new fn;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.audioTrackSwitchHistory=new Ui;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&A(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,V.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new hn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.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=ke(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(be(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new cn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Le(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:V.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,V.filter)(c=>!!c.length),(0,V.once)()).subscribe(c=>{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:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,V.map)(c=>c.to.state!=="none"),(0,V.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,V.filterChanged)()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,V.filter)(V.isNonNullable),(0,V.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,V.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ht(this.video,t.isLooped,i)),this.subscription.add($e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,V.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of d.audio){h.push(Ku(m));let g=[];for(let v of m.representations){let I=Pv(v);g.push(I),this.audioTracksMap.set(I,{stream:m,representation:v})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Ju(h));let m=[];for(let g of h.representations){let v=xv({...g,streamId:h.id});v&&(m.push(v),this.videoTracksMap.set(v,{stream:h,representation:g}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let m of h.representations){let g=wv(h,m);this.textTracksMap.set(g,{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&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:V.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,V.merge)(this.player.currentStallDuration$,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.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,V.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Uv.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,m]=p,g=[...this.videoTracksMap.keys()].find(I=>{var E;return((E=this.videoTracksMap.get(I))==null?void 0:E.representation.id)===h.id});(0,V.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")this.player.initRepresentations(h.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),m){let I=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,I).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,V.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Ju(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,V.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Ku(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe((0,V.map)(({to:c})=>c==="ready"),(0,V.filterChanged)());this.subscription.add((0,V.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,V.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add((0,V.merge)(u,this.player.state$.stateChangeEnded$,(0,V.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,V.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,V.observableFrom)(["init"])).pipe((0,V.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var j,Q,ee,Y,J,X,D,_,ie,pe,R,P,q;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(j=e.videoTrack.getState())==null?void 0:j.id,n=[...this.videoTracksMap.keys()].find(({id:N})=>N===i),o=t.currentVideoTrack$.getValue(),u=((Y=(ee=e.videoStream.getState())!=null?ee:n&&((Q=this.videoTracksMap.get(n))==null?void 0:Q.stream))!=null?Y:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:N})=>N===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=mt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(J=e.audioStream.getState())!=null?J:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(X=[...this.audioStreamsMap.keys()].find(({id:N})=>N===(m==null?void 0:m.id)))!=null?X:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let N=qs(n,c,(D=this.audioStreamsMap.get(g))!=null?D:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(_=N==null?void 0:N.bitrate)!=null?_:-1/0)}if(o){let N=qs(o,c,(ie=this.audioStreamsMap.get(g))!=null?ie:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(pe=N==null?void 0:N.bitrate)!=null?pe:-1/0)}}let I=Kt(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),E=r?I!=null?I:n:n!=null?n:I,x=g&&cb(E,c,(R=this.audioStreamsMap.get(g))!=null?R:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),k=(P=this.videoTracksMap.get(E))==null?void 0:P.representation,w=x&&((q=this.audioTracksMap.get(x))==null?void 0:q.representation);if(k&&w)return[k,w];if(k&&!w&&this.audioTracksMap.size===0)return[k,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:V.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Re(this.video),this.tracer.end()}};var $a=class extends Ir{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var er=require("@vkontakte/videoplayer-shared/es2018");var La=class extends Ir{constructor(e){super(e),this.liveOffset=new Et,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe((0,er.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,er.combine)({interval:(0,er.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add((0,er.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,er.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Av(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Hv=W(Bs(),1);var G=require("@vkontakte/videoplayer-shared/es2018"),ot={};var oi=(a,e)=>new G.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ma=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new U("initializing");this.textTracksManager=new We;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,G.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,G.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,G.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,G.assertNever)(e)}break;default:(0,G.assertNever)(t)}};this.video=ke(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(be(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Re(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:G.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Hv.default)(import("hls.js").then(i=>{e||(ot.Hls=i.default,ot.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,G.assertNonNullable)(ot.Hls,"hls.js not loaded"),this.hls=new ot.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,G.assertNonNullable)(ot.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:G.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Le(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(ht(this.video,e.isLooped,r)),this.subscription.add($e(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Qe(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ye(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,G.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(oi(this.hls,ot.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:G.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(oi(this.hls,ot.Events.MANIFEST_PARSED).pipe((0,G.map)(({levels:l})=>l.reduce((c,d)=>{var E,x;let p=d.name||d.height.toString(10),{width:h,height:m}=d,g=(x=Yt((E=d.attrs.QUALITY)!=null?E:""))!=null?x:(0,G.videoSizeToQuality)({width:h,height:m});if(!g)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,I={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:v};return this.trackLevels.set(p,{track:I,level:d}),c.push(I),c},[]))),t.availableVideoTracks$),s(oi(this.hls,ot.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(oi(this.hls,ot.Events.LEVEL_LOADING).pipe((0,G.map)(({url:l})=>be(l))),t.hostname$),s(oi(this.hls,ot.Events.FRAG_CHANGED),l=>{var p,h,m,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Wt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=oi(this.hls,ot.Events.LEVEL_SWITCHED).pipe((0,G.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,G.filter)(G.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Wt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,G.isNullable)(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,G.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0)}};var jv="X-Playback-Duration",ol=async a=>{var i;let e=await wt(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(jv)?parseInt(e.headers.get(jv),10):void 0};var H=require("@vkontakte/videoplayer-shared/es2018");var ll=W(Ro(),1);var mn=require("@vkontakte/videoplayer-shared/es2018");var GR=a=>{let e=null;if(a.QUALITY&&(e=Yt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=(0,mn.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},QR=(a,e)=>{var s,n;let t=a.split(`
|
|
125
|
+
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,ll.default)(l[1].split(",").map(E=>E.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=GR(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[E,x]=d.RESOLUTION.split("x").map(k=>parseInt(k,10));E&&x&&(v={width:E,height:x})}let I=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:I,bandwidth:m,size:v,fps:g})}if(c){let d=(0,ll.default)(c[1].split(",").map(g=>g.split("=")).map(([g,v])=>[g,v.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&i.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},WR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),ul=0,Gv=async(a,e=a,t)=>{let i=await(await wt(a)).text();ul+=1;try{let{qualityManifests:s,textTracks:n}=QR(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(ul<=t.manifestRetryMaxCount)return await WR((0,mn.getExponentialDelay)(ul-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Gv(a,e,t)}return{qualityManifests:[],textTracks:[]}},bn=Gv;var Ca=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new U("stopped");this.textTracksManager=new We;this.manifests$=new H.ValueSubject([]);this.liveOffset=new Et;this.manifestStartTime$=new H.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,H.assertNever)(t)}};var t;this.params=e,this.video=ke(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:H.VideoQuality.INVARIANT,url:this.params.source.url},bn(Ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:H.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:H.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(be(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new H.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:H.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Le(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add($e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ye(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,H.filterChanged)(),(0,H.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,H.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(be(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,H.combine)({startTime:this.manifestStartTime$.pipe((0,H.filter)(H.isNonNullable)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe((0,H.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,H.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){var o,u;let e=this.selectManifest();if((0,H.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ee(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ol(n).then(l=>{var c;if(!(0,H.isNullable)(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if((0,H.isNullable)(d)||!isFinite(d))try{wt(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let g=new URL(h,n).toString();ol(g).then(v=>{(0,H.isNullable)(v)||this.maxSeekBackTime$.next(v)})}})}catch(p){}}})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};var K=require("@vkontakte/videoplayer-shared/es2018");var Da=class{constructor(e){this.subscription=new K.Subscription;this.videoState=new U("stopped");this.textTracksManager=new We;this.manifests$=new K.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,K.assertNever)(t)}};this.params=e,this.video=ke(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:K.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(be(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),bn(Ee(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:K.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:K.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Le(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,K.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ht(this.video,t.isLooped,r)),this.subscription.add($e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,K.isNonNullable)(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let g=this.manifests$.getValue().find(v=>v.id===m);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(be(g.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,K.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!K.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,K.merge)((0,K.fromEvent)(o,"addtrack"),(0,K.fromEvent)(o,"removetrack"),(0,K.fromEvent)(o,"change"),(0,K.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,K.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,K.observableFrom)(["init"])).pipe((0,K.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,K.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:K.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Qv=W(qr(),1),Oa=W(Jr(),1);var re=require("@vkontakte/videoplayer-shared/es2018");var Ba=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new U("stopped");this.trackUrls={};this.textTracksManager=new We;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,re.assertNever)(e)}};this.params=e,this.video=ke(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Qv.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Oa.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:re.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Le(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,re.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ht(this.video,t.isLooped,r)),this.subscription.add($e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ye(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,re.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,re.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Re(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,re.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,re.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Pa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(be(t))}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Oa.default)(this.trackUrls).find(d=>!(0,re.isInvariantQuality)(d.track.quality)&&(0,re.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&(0,re.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=(0,Oa.default)(this.trackUrls).filter(h=>!(0,re.isInvariantQuality)(h.track.quality)&&(0,re.isHigher)(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Oa.default)(this.trackUrls).map(l=>l.track);t=Kt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};var ne=require("@vkontakte/videoplayer-shared/es2018");var Yv=require("@vkontakte/videoplayer-shared/es2018"),Wv=["stun:videostun.mycdn.me:80"],YR=1e3,zR=3,cl=()=>null,gn=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=cl;this.externalStopCallback=cl;this.externalErrorCallback=cl;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:Wv}]};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:Yv.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(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),YR)}normalizeOptions(e={}){let t={stunServerList:Wv,maxRetryNumber:zR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Va=class{constructor(e){this.videoState=new U("stopped");this.maxSeekBackTime$=new ne.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,ne.assertNever)(e)}};this.subscription=new ne.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ke(e.container,e.tuning),this.liveStreamClient=new gn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Re(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ne.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,ne.merge)(this.videoState.stateChangeStarted$.pipe((0,ne.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ne.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Le(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Ye(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add($e(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,ne.assertNever)(n.to)}},r)).add((0,ne.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ne.observableFrom)(["init"])).pipe((0,ne.debounce)(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(be(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:ne.VideoQuality.INVARIANT}),this.video.srcObject=e,A(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:ne.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ne.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var _a=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared/es2018");var Lt=require("@vkontakte/videoplayer-shared/es2018"),zv=a=>new Lt.Observable(e=>{let t=new Lt.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Lt.map)(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Lt.map)(({type:l})=>l!==void 0)),n=new Lt.Subject,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var Je=require("@vkontakte/videoplayer-shared/es2018");function Kv(){return new(window.AudioContext||window.webkitAudioContext)}var Jv=require("@vkontakte/videoplayer-shared/es2018");var Na=class Na{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new Ue;this.subscriptions=new Je.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Je.filter)(s=>!!s.type),(0,Je.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){Jv.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Je.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Je.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,Je.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=Kv();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(await r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Na.errorId,category:Je.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Na.errorId} exception`,thrown:e})}};Na.errorId="VolumeMultiplierManager";var ui=Na;var KR={chunkDuration:5e3,maxParallelRequests:5},Fa=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,soundProhibitedEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),liveLatency$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject("")};this.subscription=new y.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=tg([...ig(this.params.tuning),...rg(this.params.tuning)],this.params.tuning).filter(l=>(0,y.isNonNullable)(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,dl.default)(i,l)),...t.filter(l=>(0,dl.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new _a(s);let n=[...Cu(!0),...Cu(!1)];this.chromecastFormatsIterator=new _a(n.filter(l=>(0,y.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ui.isSupported()&&(this.volumeMultiplierManager=new ui(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,y.assertNonNullable)(o),new $a({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new La({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),ri||!this.params.tuning.useHlsJs?new Da({...n,source:o}):new Ma({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ca({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ba({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Sb({...n,source:o,config:{...KR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Va({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new Fi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,Zv.default)((0,Xv.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,r=0;return e.add((0,y.merge)(this.providerOutput.error$.pipe((0,y.filter)(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),zv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(i=>({id:`ProviderHangup:${i}`,category:y.ErrorCategory.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===y.ErrorCategory.NETWORK,u=i.category===y.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var B=require("@vkontakte/videoplayer-shared/es2018");var JR=5e3,eS="one_video_throughput",tS="one_video_rtt",Mt=window.navigator.connection,rS=()=>{let a=Mt==null?void 0:Mt.downlink;if((0,B.isNonNullable)(a)&&a!==10)return a*1e3},iS=()=>{let a=Mt==null?void 0:Mt.rtt;if((0,B.isNonNullable)(a)&&a!==3e3)return a},aS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},pl=class a{constructor(e){this.subscription=new B.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(eS)||(e.useBrowserEstimation?rS():void 0)||JR,r=(s=(i=a.load(tS))!=null?i:e.useBrowserEstimation?iS():void 0)!=null?s:0;if(this.throughput$=new B.ValueSubject(t),this.rtt$=new B.ValueSubject(r),this.rttAdjustedThroughput$=new B.ValueSubject(aS(t,r,e.rttPenaltyRequestSize)),this.throughput=Tr.getSmoothedValue(t,-1,e),this.rtt=Tr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=rS();u&&this.throughput.next(u);let l=iS();(0,B.isNonNullable)(l)&&this.rtt.next(l)};Mt&&"onchange"in Mt&&this.subscription.add((0,B.fromEvent)(Mt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{B.safeStorage.set(eS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{B.safeStorage.set(tS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,B.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,B.map)(({throughput:n,rtt:o})=>aS(n,o,e.rttPenaltyRequestSize)),(0,B.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,B.now)(),i=new B.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,B.fromEvent)(e,"progress").pipe((0,B.once)()).subscribe(s=>{t=s.loaded,r=(0,B.now)()}));break;case 1:case 0:i.add((0,B.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,B.now)()}));break}i.add((0,B.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,B.now)(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=(0,B.now)(),n=0,o=(0,B.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(i,(0,B.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,B.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=(0,B.now)()}else n+=d.byteLength;o=(0,B.now)()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,B.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,B.now)()-o,this.concurrentDownloads.size),n=0,o=(0,B.now)());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=B.safeStorage.get(e);if((0,B.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},sS=pl;var qa=require("@vkontakte/videoplayer-shared/es2018"),nS={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:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:qa.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:qa.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{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:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",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,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,exposeInternalsToGlobal:!1},oS=a=>{var e;return{...(0,qa.fillWithDefault)(a,nS),configName:[...(e=a.configName)!=null?e:[],...nS.configName]}};var f=require("@vkontakte/videoplayer-shared/es2018");var Ct=require("@vkontakte/videoplayer-shared/es2018"),hl=({seekState:a,position$:e})=>(0,Ct.merge)(a.stateChangeEnded$.pipe((0,Ct.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Ct.filter)(Ct.isNonNullable)),e.pipe((0,Ct.filter)(()=>a.getState().state==="none")));var uS=require("@vkontakte/videoplayer-shared/es2018"),lS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,uS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var vn=require("@vkontakte/videoplayer-shared/es2018"),cS=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,vn.filter)(i=>i.length>0),(0,vn.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Ua=class{constructor(e={configName:[]},t=f.Tracer.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new U("stopped"),seekState:new U({state:"none"}),volume:new U({volume:1,muted:!1}),videoTrack:new U(void 0),videoStream:new U(void 0),audioStream:new U(void 0),autoVideoTrackSwitching:new U(!0),autoVideoTrackLimits:new U({}),isLooped:new U(!1),isLowLatency:new U(!1),playbackRate:new U(1),externalTextTracks:new U([]),internalTextTracks:new U([]),currentTextTrack:new U(void 0),textTrackCuesSettings:new U({}),cameraOrientation:new U({x:0,y:0})};this.info={playbackState$:new f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),liveLatency$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:ab};if(this.initLogs(),this.tuning=oS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new us({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new sS(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let g=typeof m;return(0,dS.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:f.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n,o;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",(0,f.flattenObject)(r)),this.domContainer=lS(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new Fa({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(o=this.internalsExposure)==null||o.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Qi()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;(0,f.assertNonNullable)(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return cS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,f.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,f.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,f.isInvariantQuality)(u)?1:(0,f.isInvariantQuality)(l)?-1:(0,f.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:hl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(hl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe((0,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>r.next(!1)));let i=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Kt(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),ib(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>rb(r)),this.providerContainer.current$.subscribe(({type:r})=>qi("provider",r)),e.duration$.subscribe(r=>qi("duration",r)),e.availableVideoTracks$.pipe((0,f.filter)(r=>!!r.length),(0,f.once)()).subscribe(r=>qi("tracks",r)),this.events.fatalError$.subscribe(new we("fatalError")),this.events.managedError$.subscribe(new we("managedError")),e.position$.subscribe(new we("position")),e.currentVideoTrack$.pipe((0,f.map)(r=>r==null?void 0:r.quality)).subscribe(new we("quality")),this.info.currentBuffer$.subscribe(new we("buffer")),e.isBuffering$.subscribe(new we("isBuffering"))].forEach(r=>this.subscription.add(r)),qi("codecs",eg())}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,f.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),(0,f.filterChanged)((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(r=>r>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(r=>r>0),(0,f.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(r=>r.end>0),(0,f.filterChanged)((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:r,rtt:i})=>!!r&&!!i),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(i)})})};this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var gt=require("@vkontakte/videoplayer-shared/es2018"),XR=`@vkontakte/videoplayer-core@${xn}`;
|