@vkontakte/videoplayer-core 2.0.112 → 2.0.113-dev.53b63d90.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 +22 -22
- package/es2015.esm.js +22 -22
- package/es2018.cjs.js +22 -22
- package/es2018.esm.js +21 -21
- package/esnext.cjs.js +19 -19
- package/esnext.esm.js +18 -18
- package/evergreen.esm.js +15 -15
- package/package.json +2 -2
- package/types/providers/DashProvider/baseDashProvider.d.ts +0 -6
- package/types/providers/DashProvider/lib/LiveTextManager.d.ts +21 -0
- package/types/providers/DashProvider/lib/buffer.d.ts +3 -0
- package/types/providers/DashProvider/lib/player.d.ts +6 -5
- package/types/providers/DashProvider/lib/types.d.ts +6 -0
- package/types/providers/DashProvider/lib/utils.d.ts +3 -5
- package/types/utils/tuningConfig.d.ts +3 -1
package/es2015.cjs.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.113-dev.53b63d90.0
|
|
3
|
+
* Wed, 02 Oct 2024 14:10:44 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-113/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var ig=Object.create;var Qr=Object.defineProperty,ag=Object.defineProperties,sg=Object.getOwnPropertyDescriptor,ng=Object.getOwnPropertyDescriptors,og=Object.getOwnPropertyNames,Ia=Object.getOwnPropertySymbols,ug=Object.getPrototypeOf,Js=Object.prototype.hasOwnProperty,Ku=Object.prototype.propertyIsEnumerable;var cg=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var it=Math.pow,zu=(a,e,t)=>e in a?Qr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,C=(a,e)=>{for(var t in e||(e={}))Js.call(e,t)&&zu(a,t,e[t]);if(Ia)for(var t of Ia(e))Ku.call(e,t)&&zu(a,t,e[t]);return a},z=(a,e)=>ag(a,ng(e));var Ju=(a,e)=>{var t={};for(var r in a)Js.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&Ia)for(var r of Ia(a))e.indexOf(r)<0&&Ku.call(a,r)&&(t[r]=a[r]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),lg=(a,e)=>{for(var t in e)Qr(a,t,{get:e[t],enumerable:!0})},Xu=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of og(e))!Js.call(a,i)&&i!==t&&Qr(a,i,{get:()=>e[i],enumerable:!(r=sg(e,i))||r.enumerable});return a};var ze=(a,e,t)=>(t=a!=null?ig(ug(a)):{},Xu(e||!a||!a.__esModule?Qr(t,"default",{value:a,enumerable:!0}):t,a)),dg=a=>Xu(Qr({},"__esModule",{value:!0}),a);var O=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(c){i(c)}},n=u=>{try{o(t.throw(u))}catch(c){i(c)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),Xs=function(a,e){this[0]=a,this[1]=e},me=(a,e,t)=>{var r=(n,o,u,c)=>{try{var l=t[n](o),d=(o=l.value)instanceof Xs,p=l.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,c):u({value:h,done:p})).catch(h=>r("throw",h,u,c))}catch(h){c(h)}},i=n=>s[n]=o=>new Promise((u,c)=>r(n,o,u,c)),s={};return t=t.apply(a,e),s[cg("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var De=b((IA,ec)=>{"use strict";ec.exports=function(a){try{return!!a()}catch(e){return!0}}});var Kr=b((EA,tc)=>{"use strict";var hg=De();tc.exports=!hg(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Pe=b((xA,ac)=>{"use strict";var rc=Kr(),ic=Function.prototype,en=ic.call,fg=rc&&ic.bind.bind(en,en);ac.exports=rc?fg:function(a){return function(){return en.apply(a,arguments)}}});var pr=b((PA,nc)=>{"use strict";var sc=Pe(),mg=sc({}.toString),bg=sc("".slice);nc.exports=function(a){return bg(mg(a),8,-1)}});var uc=b((AA,oc)=>{"use strict";var gg=Pe(),Sg=De(),vg=pr(),tn=Object,yg=gg("".split);oc.exports=Sg(function(){return!tn("z").propertyIsEnumerable(0)})?function(a){return vg(a)==="String"?yg(a,""):tn(a)}:tn});var hr=b((wA,cc)=>{"use strict";cc.exports=function(a){return a==null}});var Jr=b((kA,lc)=>{"use strict";var Tg=hr(),Ig=TypeError;lc.exports=function(a){if(Tg(a))throw new Ig("Can't call method on "+a);return a}});var fr=b((RA,dc)=>{"use strict";var Eg=uc(),xg=Jr();dc.exports=function(a){return Eg(xg(a))}});var rn=b(($A,pc)=>{"use strict";pc.exports=function(){}});var jt=b((LA,hc)=>{"use strict";hc.exports={}});var le=b((an,fc)=>{"use strict";var Xr=function(a){return a&&a.Math===Math&&a};fc.exports=Xr(typeof globalThis=="object"&&globalThis)||Xr(typeof window=="object"&&window)||Xr(typeof self=="object"&&self)||Xr(typeof global=="object"&&global)||Xr(typeof an=="object"&&an)||function(){return this}()||Function("return this")()});var ce=b((MA,mc)=>{"use strict";var sn=typeof document=="object"&&document.all;mc.exports=typeof sn=="undefined"&&sn!==void 0?function(a){return typeof a=="function"||a===sn}:function(a){return typeof a=="function"}});var Sc=b((CA,gc)=>{"use strict";var Pg=le(),Ag=ce(),bc=Pg.WeakMap;gc.exports=Ag(bc)&&/native code/.test(String(bc))});var Fe=b((DA,vc)=>{"use strict";var wg=ce();vc.exports=function(a){return typeof a=="object"?a!==null:wg(a)}});var qe=b((BA,yc)=>{"use strict";var kg=De();yc.exports=!kg(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Aa=b((OA,Ic)=>{"use strict";var Rg=le(),Tc=Fe(),nn=Rg.document,$g=Tc(nn)&&Tc(nn.createElement);Ic.exports=function(a){return $g?nn.createElement(a):{}}});var on=b((VA,Ec)=>{"use strict";var Lg=qe(),Mg=De(),Cg=Aa();Ec.exports=!Lg&&!Mg(function(){return Object.defineProperty(Cg("div"),"a",{get:function(){return 7}}).a!==7})});var un=b((_A,xc)=>{"use strict";var Dg=qe(),Bg=De();xc.exports=Dg&&Bg(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var at=b((NA,Pc)=>{"use strict";var Og=Fe(),Vg=String,_g=TypeError;Pc.exports=function(a){if(Og(a))return a;throw new _g(Vg(a)+" is not an object")}});var Be=b((FA,Ac)=>{"use strict";var Ng=Kr(),wa=Function.prototype.call;Ac.exports=Ng?wa.bind(wa):function(){return wa.apply(wa,arguments)}});var ka=b((qA,wc)=>{"use strict";wc.exports={}});var pt=b((UA,Rc)=>{"use strict";var cn=ka(),ln=le(),Fg=ce(),kc=function(a){return Fg(a)?a:void 0};Rc.exports=function(a,e){return arguments.length<2?kc(cn[a])||kc(ln[a]):cn[a]&&cn[a][e]||ln[a]&&ln[a][e]}});var Zr=b((HA,$c)=>{"use strict";var qg=Pe();$c.exports=qg({}.isPrototypeOf)});var mr=b((jA,Cc)=>{"use strict";var Ug=le(),Lc=Ug.navigator,Mc=Lc&&Lc.userAgent;Cc.exports=Mc?String(Mc):""});var pn=b((GA,Nc)=>{"use strict";var _c=le(),dn=mr(),Dc=_c.process,Bc=_c.Deno,Oc=Dc&&Dc.versions||Bc&&Bc.version,Vc=Oc&&Oc.v8,Ke,Ra;Vc&&(Ke=Vc.split("."),Ra=Ke[0]>0&&Ke[0]<4?1:+(Ke[0]+Ke[1]));!Ra&&dn&&(Ke=dn.match(/Edge\/(\d+)/),(!Ke||Ke[1]>=74)&&(Ke=dn.match(/Chrome\/(\d+)/),Ke&&(Ra=+Ke[1])));Nc.exports=Ra});var hn=b((WA,qc)=>{"use strict";var Fc=pn(),Hg=De(),jg=le(),Gg=jg.String;qc.exports=!!Object.getOwnPropertySymbols&&!Hg(function(){var a=Symbol("symbol detection");return!Gg(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Fc&&Fc<41})});var fn=b((YA,Uc)=>{"use strict";var Wg=hn();Uc.exports=Wg&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var mn=b((QA,Hc)=>{"use strict";var Yg=pt(),Qg=ce(),zg=Zr(),Kg=fn(),Jg=Object;Hc.exports=Kg?function(a){return typeof a=="symbol"}:function(a){var e=Yg("Symbol");return Qg(e)&&zg(e.prototype,Jg(a))}});var ei=b((zA,jc)=>{"use strict";var Xg=String;jc.exports=function(a){try{return Xg(a)}catch(e){return"Object"}}});var ht=b((KA,Gc)=>{"use strict";var Zg=ce(),eS=ei(),tS=TypeError;Gc.exports=function(a){if(Zg(a))return a;throw new tS(eS(a)+" is not a function")}});var ti=b((JA,Wc)=>{"use strict";var rS=ht(),iS=hr();Wc.exports=function(a,e){var t=a[e];return iS(t)?void 0:rS(t)}});var Qc=b((XA,Yc)=>{"use strict";var bn=Be(),gn=ce(),Sn=Fe(),aS=TypeError;Yc.exports=function(a,e){var t,r;if(e==="string"&&gn(t=a.toString)&&!Sn(r=bn(t,a))||gn(t=a.valueOf)&&!Sn(r=bn(t,a))||e!=="string"&&gn(t=a.toString)&&!Sn(r=bn(t,a)))return r;throw new aS("Can't convert object to primitive value")}});var Je=b((ZA,zc)=>{"use strict";zc.exports=!0});var Xc=b((ew,Jc)=>{"use strict";var Kc=le(),sS=Object.defineProperty;Jc.exports=function(a,e){try{sS(Kc,a,{value:e,configurable:!0,writable:!0})}catch(t){Kc[a]=e}return e}});var ri=b((tw,tl)=>{"use strict";var nS=Je(),oS=le(),uS=Xc(),Zc="__core-js_shared__",el=tl.exports=oS[Zc]||uS(Zc,{});(el.versions||(el.versions=[])).push({version:"3.38.0",mode:nS?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var vn=b((rw,il)=>{"use strict";var rl=ri();il.exports=function(a,e){return rl[a]||(rl[a]=e||{})}});var ii=b((iw,al)=>{"use strict";var cS=Jr(),lS=Object;al.exports=function(a){return lS(cS(a))}});var Xe=b((aw,sl)=>{"use strict";var dS=Pe(),pS=ii(),hS=dS({}.hasOwnProperty);sl.exports=Object.hasOwn||function(e,t){return hS(pS(e),t)}});var yn=b((sw,nl)=>{"use strict";var fS=Pe(),mS=0,bS=Math.random(),gS=fS(1 .toString);nl.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+gS(++mS+bS,36)}});var ye=b((nw,ul)=>{"use strict";var SS=le(),vS=vn(),ol=Xe(),yS=yn(),TS=hn(),IS=fn(),br=SS.Symbol,Tn=vS("wks"),ES=IS?br.for||br:br&&br.withoutSetter||yS;ul.exports=function(a){return ol(Tn,a)||(Tn[a]=TS&&ol(br,a)?br[a]:ES("Symbol."+a)),Tn[a]}});var pl=b((ow,dl)=>{"use strict";var xS=Be(),cl=Fe(),ll=mn(),PS=ti(),AS=Qc(),wS=ye(),kS=TypeError,RS=wS("toPrimitive");dl.exports=function(a,e){if(!cl(a)||ll(a))return a;var t=PS(a,RS),r;if(t){if(e===void 0&&(e="default"),r=xS(t,a,e),!cl(r)||ll(r))return r;throw new kS("Can't convert object to primitive value")}return e===void 0&&(e="number"),AS(a,e)}});var In=b((uw,hl)=>{"use strict";var $S=pl(),LS=mn();hl.exports=function(a){var e=$S(a,"string");return LS(e)?e:e+""}});var Gt=b(ml=>{"use strict";var MS=qe(),CS=on(),DS=un(),$a=at(),fl=In(),BS=TypeError,En=Object.defineProperty,OS=Object.getOwnPropertyDescriptor,xn="enumerable",Pn="configurable",An="writable";ml.f=MS?DS?function(e,t,r){if($a(e),t=fl(t),$a(r),typeof e=="function"&&t==="prototype"&&"value"in r&&An in r&&!r[An]){var i=OS(e,t);i&&i[An]&&(e[t]=r.value,r={configurable:Pn in r?r[Pn]:i[Pn],enumerable:xn in r?r[xn]:i[xn],writable:!1})}return En(e,t,r)}:En:function(e,t,r){if($a(e),t=fl(t),$a(r),CS)try{return En(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new BS("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var ai=b((lw,bl)=>{"use strict";bl.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var gr=b((dw,gl)=>{"use strict";var VS=qe(),_S=Gt(),NS=ai();gl.exports=VS?function(a,e,t){return _S.f(a,e,NS(1,t))}:function(a,e,t){return a[e]=t,a}});var La=b((pw,vl)=>{"use strict";var FS=vn(),qS=yn(),Sl=FS("keys");vl.exports=function(a){return Sl[a]||(Sl[a]=qS(a))}});var Ma=b((hw,yl)=>{"use strict";yl.exports={}});var $n=b((fw,El)=>{"use strict";var US=Sc(),Il=le(),HS=Fe(),jS=gr(),wn=Xe(),kn=ri(),GS=La(),WS=Ma(),Tl="Object already initialized",Rn=Il.TypeError,YS=Il.WeakMap,Ca,si,Da,QS=function(a){return Da(a)?si(a):Ca(a,{})},zS=function(a){return function(e){var t;if(!HS(e)||(t=si(e)).type!==a)throw new Rn("Incompatible receiver, "+a+" required");return t}};US||kn.state?(Ze=kn.state||(kn.state=new YS),Ze.get=Ze.get,Ze.has=Ze.has,Ze.set=Ze.set,Ca=function(a,e){if(Ze.has(a))throw new Rn(Tl);return e.facade=a,Ze.set(a,e),e},si=function(a){return Ze.get(a)||{}},Da=function(a){return Ze.has(a)}):(Wt=GS("state"),WS[Wt]=!0,Ca=function(a,e){if(wn(a,Wt))throw new Rn(Tl);return e.facade=a,jS(a,Wt,e),e},si=function(a){return wn(a,Wt)?a[Wt]:{}},Da=function(a){return wn(a,Wt)});var Ze,Wt;El.exports={set:Ca,get:si,has:Da,enforce:QS,getterFor:zS}});var Ln=b((mw,wl)=>{"use strict";var KS=Kr(),Al=Function.prototype,xl=Al.apply,Pl=Al.call;wl.exports=typeof Reflect=="object"&&Reflect.apply||(KS?Pl.bind(xl):function(){return Pl.apply(xl,arguments)})});var Mn=b((bw,kl)=>{"use strict";var JS=pr(),XS=Pe();kl.exports=function(a){if(JS(a)==="Function")return XS(a)}});var Ml=b(Ll=>{"use strict";var Rl={}.propertyIsEnumerable,$l=Object.getOwnPropertyDescriptor,ZS=$l&&!Rl.call({1:2},1);Ll.f=ZS?function(e){var t=$l(this,e);return!!t&&t.enumerable}:Rl});var Bl=b(Dl=>{"use strict";var ev=qe(),tv=Be(),rv=Ml(),iv=ai(),av=fr(),sv=In(),nv=Xe(),ov=on(),Cl=Object.getOwnPropertyDescriptor;Dl.f=ev?Cl:function(e,t){if(e=av(e),t=sv(t),ov)try{return Cl(e,t)}catch(r){}if(nv(e,t))return iv(!tv(rv.f,e,t),e[t])}});var Cn=b((vw,Ol)=>{"use strict";var uv=De(),cv=ce(),lv=/#|\.prototype\./,ni=function(a,e){var t=pv[dv(a)];return t===fv?!0:t===hv?!1:cv(e)?uv(e):!!e},dv=ni.normalize=function(a){return String(a).replace(lv,".").toLowerCase()},pv=ni.data={},hv=ni.NATIVE="N",fv=ni.POLYFILL="P";Ol.exports=ni});var oi=b((yw,_l)=>{"use strict";var Vl=Mn(),mv=ht(),bv=Kr(),gv=Vl(Vl.bind);_l.exports=function(a,e){return mv(a),e===void 0?a:bv?gv(a,e):function(){return a.apply(e,arguments)}}});var Ue=b((Tw,Fl)=>{"use strict";var ui=le(),Sv=Ln(),vv=Mn(),yv=ce(),Tv=Bl().f,Iv=Cn(),Sr=ka(),Ev=oi(),vr=gr(),Nl=Xe();ri();var xv=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 Sv(a,this,arguments)};return e.prototype=a.prototype,e};Fl.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?ui:i?ui[t]:ui[t]&&ui[t].prototype,o=r?Sr:Sr[t]||vr(Sr,t,{})[t],u=o.prototype,c,l,d,p,h,m,g,S,T;for(p in e)c=Iv(r?p:t+(i?".":"#")+p,a.forced),l=!c&&n&&Nl(n,p),m=o[p],l&&(a.dontCallGetSet?(T=Tv(n,p),g=T&&T.value):g=n[p]),h=l&&g?g:e[p],!(!c&&!s&&typeof m==typeof h)&&(a.bind&&l?S=Ev(h,ui):a.wrap&&l?S=xv(h):s&&yv(h)?S=vv(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&vr(S,"sham",!0),vr(o,p,S),s&&(d=t+"Prototype",Nl(Sr,d)||vr(Sr,d,{}),vr(Sr[d],p,h),a.real&&u&&(c||!u[p])&&vr(u,p,h)))}});var Hl=b((Iw,Ul)=>{"use strict";var Dn=qe(),Pv=Xe(),ql=Function.prototype,Av=Dn&&Object.getOwnPropertyDescriptor,Bn=Pv(ql,"name"),wv=Bn&&function(){}.name==="something",kv=Bn&&(!Dn||Dn&&Av(ql,"name").configurable);Ul.exports={EXISTS:Bn,PROPER:wv,CONFIGURABLE:kv}});var Gl=b((Ew,jl)=>{"use strict";var Rv=Math.ceil,$v=Math.floor;jl.exports=Math.trunc||function(e){var t=+e;return(t>0?$v:Rv)(t)}});var Ba=b((xw,Wl)=>{"use strict";var Lv=Gl();Wl.exports=function(a){var e=+a;return e!==e||e===0?0:Lv(e)}});var Ql=b((Pw,Yl)=>{"use strict";var Mv=Ba(),Cv=Math.max,Dv=Math.min;Yl.exports=function(a,e){var t=Mv(a);return t<0?Cv(t+e,0):Dv(t,e)}});var Kl=b((Aw,zl)=>{"use strict";var Bv=Ba(),Ov=Math.min;zl.exports=function(a){var e=Bv(a);return e>0?Ov(e,9007199254740991):0}});var Oa=b((ww,Jl)=>{"use strict";var Vv=Kl();Jl.exports=function(a){return Vv(a.length)}});var ed=b((kw,Zl)=>{"use strict";var _v=fr(),Nv=Ql(),Fv=Oa(),Xl=function(a){return function(e,t,r){var i=_v(e),s=Fv(i);if(s===0)return!a&&-1;var n=Nv(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}};Zl.exports={includes:Xl(!0),indexOf:Xl(!1)}});var id=b((Rw,rd)=>{"use strict";var qv=Pe(),On=Xe(),Uv=fr(),Hv=ed().indexOf,jv=Ma(),td=qv([].push);rd.exports=function(a,e){var t=Uv(a),r=0,i=[],s;for(s in t)!On(jv,s)&&On(t,s)&&td(i,s);for(;e.length>r;)On(t,s=e[r++])&&(~Hv(i,s)||td(i,s));return i}});var Vn=b(($w,ad)=>{"use strict";ad.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var nd=b((Lw,sd)=>{"use strict";var Gv=id(),Wv=Vn();sd.exports=Object.keys||function(e){return Gv(e,Wv)}});var ud=b(od=>{"use strict";var Yv=qe(),Qv=un(),zv=Gt(),Kv=at(),Jv=fr(),Xv=nd();od.f=Yv&&!Qv?Object.defineProperties:function(e,t){Kv(e);for(var r=Jv(t),i=Xv(t),s=i.length,n=0,o;s>n;)zv.f(e,o=i[n++],r[o]);return e}});var _n=b((Cw,cd)=>{"use strict";var Zv=pt();cd.exports=Zv("document","documentElement")});var Un=b((Dw,bd)=>{"use strict";var ey=at(),ty=ud(),ld=Vn(),ry=Ma(),iy=_n(),ay=Aa(),sy=La(),dd=">",pd="<",Fn="prototype",qn="script",fd=sy("IE_PROTO"),Nn=function(){},md=function(a){return pd+qn+dd+a+pd+"/"+qn+dd},hd=function(a){a.write(md("")),a.close();var e=a.parentWindow.Object;return a=null,e},ny=function(){var a=ay("iframe"),e="java"+qn+":",t;return a.style.display="none",iy.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(md("document.F=Object")),t.close(),t.F},Va,_a=function(){try{Va=new ActiveXObject("htmlfile")}catch(e){}_a=typeof document!="undefined"?document.domain&&Va?hd(Va):ny():hd(Va);for(var a=ld.length;a--;)delete _a[Fn][ld[a]];return _a()};ry[fd]=!0;bd.exports=Object.create||function(e,t){var r;return e!==null?(Nn[Fn]=ey(e),r=new Nn,Nn[Fn]=null,r[fd]=e):r=_a(),t===void 0?r:ty.f(r,t)}});var Sd=b((Bw,gd)=>{"use strict";var oy=De();gd.exports=!oy(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var jn=b((Ow,yd)=>{"use strict";var uy=Xe(),cy=ce(),ly=ii(),dy=La(),py=Sd(),vd=dy("IE_PROTO"),Hn=Object,hy=Hn.prototype;yd.exports=py?Hn.getPrototypeOf:function(a){var e=ly(a);if(uy(e,vd))return e[vd];var t=e.constructor;return cy(t)&&e instanceof t?t.prototype:e instanceof Hn?hy:null}});var yr=b((Vw,Td)=>{"use strict";var fy=gr();Td.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:fy(a,e,t),a}});var Qn=b((_w,xd)=>{"use strict";var my=De(),by=ce(),gy=Fe(),Sy=Un(),Id=jn(),vy=yr(),yy=ye(),Ty=Je(),Yn=yy("iterator"),Ed=!1,ft,Gn,Wn;[].keys&&(Wn=[].keys(),"next"in Wn?(Gn=Id(Id(Wn)),Gn!==Object.prototype&&(ft=Gn)):Ed=!0);var Iy=!gy(ft)||my(function(){var a={};return ft[Yn].call(a)!==a});Iy?ft={}:Ty&&(ft=Sy(ft));by(ft[Yn])||vy(ft,Yn,function(){return this});xd.exports={IteratorPrototype:ft,BUGGY_SAFARI_ITERATORS:Ed}});var Na=b((Nw,Ad)=>{"use strict";var Ey=ye(),xy=Ey("toStringTag"),Pd={};Pd[xy]="z";Ad.exports=String(Pd)==="[object z]"});var ci=b((Fw,wd)=>{"use strict";var Py=Na(),Ay=ce(),Fa=pr(),wy=ye(),ky=wy("toStringTag"),Ry=Object,$y=Fa(function(){return arguments}())==="Arguments",Ly=function(a,e){try{return a[e]}catch(t){}};wd.exports=Py?Fa:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=Ly(e=Ry(a),ky))=="string"?t:$y?Fa(e):(r=Fa(e))==="Object"&&Ay(e.callee)?"Arguments":r}});var Rd=b((qw,kd)=>{"use strict";var My=Na(),Cy=ci();kd.exports=My?{}.toString:function(){return"[object "+Cy(this)+"]"}});var li=b((Uw,Ld)=>{"use strict";var Dy=Na(),By=Gt().f,Oy=gr(),Vy=Xe(),_y=Rd(),Ny=ye(),$d=Ny("toStringTag");Ld.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(Vy(i,$d)||By(i,$d,{configurable:!0,value:e}),r&&!Dy&&Oy(i,"toString",_y))}});var Cd=b((Hw,Md)=>{"use strict";var Fy=Qn().IteratorPrototype,qy=Un(),Uy=ai(),Hy=li(),jy=jt(),Gy=function(){return this};Md.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=qy(Fy,{next:Uy(+!r,t)}),Hy(a,i,!1,!0),jy[i]=Gy,a}});var Bd=b((jw,Dd)=>{"use strict";var Wy=Pe(),Yy=ht();Dd.exports=function(a,e,t){try{return Wy(Yy(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Vd=b((Gw,Od)=>{"use strict";var Qy=Fe();Od.exports=function(a){return Qy(a)||a===null}});var Nd=b((Ww,_d)=>{"use strict";var zy=Vd(),Ky=String,Jy=TypeError;_d.exports=function(a){if(zy(a))return a;throw new Jy("Can't set "+Ky(a)+" as a prototype")}});var zn=b((Yw,Fd)=>{"use strict";var Xy=Bd(),Zy=Fe(),eT=Jr(),tT=Nd();Fd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Xy(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return eT(i),tT(s),Zy(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Jd=b((Qw,Kd)=>{"use strict";var rT=Ue(),iT=Be(),qa=Je(),Qd=Hl(),aT=ce(),sT=Cd(),qd=jn(),Ud=zn(),nT=li(),oT=gr(),Kn=yr(),uT=ye(),Hd=jt(),zd=Qn(),cT=Qd.PROPER,lT=Qd.CONFIGURABLE,jd=zd.IteratorPrototype,Ua=zd.BUGGY_SAFARI_ITERATORS,di=uT("iterator"),Gd="keys",pi="values",Wd="entries",Yd=function(){return this};Kd.exports=function(a,e,t,r,i,s,n){sT(t,e,r);var o=function(T){if(T===i&&p)return p;if(!Ua&&T&&T in l)return l[T];switch(T){case Gd:return function(){return new t(this,T)};case pi:return function(){return new t(this,T)};case Wd:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,l=a.prototype,d=l[di]||l["@@iterator"]||i&&l[i],p=!Ua&&d||o(i),h=e==="Array"&&l.entries||d,m,g,S;if(h&&(m=qd(h.call(new a)),m!==Object.prototype&&m.next&&(!qa&&qd(m)!==jd&&(Ud?Ud(m,jd):aT(m[di])||Kn(m,di,Yd)),nT(m,u,!0,!0),qa&&(Hd[u]=Yd))),cT&&i===pi&&d&&d.name!==pi&&(!qa&&lT?oT(l,"name",pi):(c=!0,p=function(){return iT(d,this)})),i)if(g={values:o(pi),keys:s?p:o(Gd),entries:o(Wd)},n)for(S in g)(Ua||c||!(S in l))&&Kn(l,S,g[S]);else rT({target:e,proto:!0,forced:Ua||c},g);return(!qa||n)&&l[di]!==p&&Kn(l,di,p,{name:i}),Hd[e]=p,g}});var Zd=b((zw,Xd)=>{"use strict";Xd.exports=function(a,e){return{value:a,done:e}}});var Xn=b((Kw,ap)=>{"use strict";var dT=fr(),Jn=rn(),ep=jt(),rp=$n(),pT=Gt().f,hT=Jd(),Ha=Zd(),fT=Je(),mT=qe(),ip="Array Iterator",bT=rp.set,gT=rp.getterFor(ip);ap.exports=hT(Array,"Array",function(a,e){bT(this,{type:ip,target:dT(a),index:0,kind:e})},function(){var a=gT(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ha(void 0,!0);switch(a.kind){case"keys":return Ha(t,!1);case"values":return Ha(e[t],!1)}return Ha([t,e[t]],!1)},"values");var tp=ep.Arguments=ep.Array;Jn("keys");Jn("values");Jn("entries");if(!fT&&mT&&tp.name!=="values")try{pT(tp,"name",{value:"values"})}catch(a){}});var np=b((Jw,sp)=>{"use strict";var ST=ye(),vT=jt(),yT=ST("iterator"),TT=Array.prototype;sp.exports=function(a){return a!==void 0&&(vT.Array===a||TT[yT]===a)}});var Zn=b((Xw,up)=>{"use strict";var IT=ci(),op=ti(),ET=hr(),xT=jt(),PT=ye(),AT=PT("iterator");up.exports=function(a){if(!ET(a))return op(a,AT)||op(a,"@@iterator")||xT[IT(a)]}});var lp=b((Zw,cp)=>{"use strict";var wT=Be(),kT=ht(),RT=at(),$T=ei(),LT=Zn(),MT=TypeError;cp.exports=function(a,e){var t=arguments.length<2?LT(a):e;if(kT(t))return RT(wT(t,a));throw new MT($T(a)+" is not iterable")}});var hp=b((ek,pp)=>{"use strict";var CT=Be(),dp=at(),DT=ti();pp.exports=function(a,e,t){var r,i;dp(a);try{if(r=DT(a,"return"),!r){if(e==="throw")throw t;return t}r=CT(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return dp(r),t}});var Ga=b((tk,gp)=>{"use strict";var BT=oi(),OT=Be(),VT=at(),_T=ei(),NT=np(),FT=Oa(),fp=Zr(),qT=lp(),UT=Zn(),mp=hp(),HT=TypeError,ja=function(a,e){this.stopped=a,this.result=e},bp=ja.prototype;gp.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=BT(e,r),c,l,d,p,h,m,g,S=function(P){return c&&mp(c,"normal",P),new ja(!0,P)},T=function(P){return i?(VT(P),o?u(P[0],P[1],S):u(P[0],P[1])):o?u(P,S):u(P)};if(s)c=a.iterator;else if(n)c=a;else{if(l=UT(a),!l)throw new HT(_T(a)+" is not iterable");if(NT(l)){for(d=0,p=FT(a);p>d;d++)if(h=T(a[d]),h&&fp(bp,h))return h;return new ja(!1)}c=qT(a,l)}for(m=s?a.next:c.next;!(g=OT(m,c)).done;){try{h=T(g.value)}catch(P){mp(c,"throw",P)}if(typeof h=="object"&&h&&fp(bp,h))return h}return new ja(!1)}});var vp=b((rk,Sp)=>{"use strict";var jT=qe(),GT=Gt(),WT=ai();Sp.exports=function(a,e,t){jT?GT.f(a,e,WT(0,t)):a[e]=t}});var yp=b(()=>{"use strict";var YT=Ue(),QT=Ga(),zT=vp();YT({target:"Object",stat:!0},{fromEntries:function(e){var t={};return QT(e,function(r,i){zT(t,r,i)},{AS_ENTRIES:!0}),t}})});var Ip=b((sk,Tp)=>{"use strict";Xn();yp();var KT=ka();Tp.exports=KT.Object.fromEntries});var xp=b((nk,Ep)=>{"use strict";Ep.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Ap=b(()=>{"use strict";Xn();var JT=xp(),XT=le(),ZT=li(),Pp=jt();for(Wa in JT)ZT(XT[Wa],Wa),Pp[Wa]=Pp.Array;var Wa});var kp=b((ck,wp)=>{"use strict";var eI=Ip();Ap();wp.exports=eI});var eo=b((lk,Rp)=>{"use strict";var tI=kp();Rp.exports=tI});var $p=b(()=>{"use strict"});var to=b((hk,Lp)=>{"use strict";var hi=le(),rI=mr(),iI=pr(),Ya=function(a){return rI.slice(0,a.length)===a};Lp.exports=function(){return Ya("Bun/")?"BUN":Ya("Cloudflare-Workers")?"CLOUDFLARE":Ya("Deno/")?"DENO":Ya("Node.js/")?"NODE":hi.Bun&&typeof Bun.version=="string"?"BUN":hi.Deno&&typeof Deno.version=="object"?"DENO":iI(hi.process)==="process"?"NODE":hi.window&&hi.document?"BROWSER":"REST"}()});var Qa=b((fk,Mp)=>{"use strict";var aI=to();Mp.exports=aI==="NODE"});var Dp=b((mk,Cp)=>{"use strict";var sI=Gt();Cp.exports=function(a,e,t){return sI.f(a,e,t)}});var Vp=b((bk,Op)=>{"use strict";var nI=pt(),oI=Dp(),uI=ye(),cI=qe(),Bp=uI("species");Op.exports=function(a){var e=nI(a);cI&&e&&!e[Bp]&&oI(e,Bp,{configurable:!0,get:function(){return this}})}});var Np=b((gk,_p)=>{"use strict";var lI=Zr(),dI=TypeError;_p.exports=function(a,e){if(lI(e,a))return a;throw new dI("Incorrect invocation")}});var io=b((Sk,Fp)=>{"use strict";var pI=Pe(),hI=ce(),ro=ri(),fI=pI(Function.toString);hI(ro.inspectSource)||(ro.inspectSource=function(a){return fI(a)});Fp.exports=ro.inspectSource});var Wp=b((vk,Gp)=>{"use strict";var mI=Pe(),bI=De(),qp=ce(),gI=ci(),SI=pt(),vI=io(),Up=function(){},Hp=SI("Reflect","construct"),ao=/^\s*(?:class|function)\b/,yI=mI(ao.exec),TI=!ao.test(Up),fi=function(e){if(!qp(e))return!1;try{return Hp(Up,[],e),!0}catch(t){return!1}},jp=function(e){if(!qp(e))return!1;switch(gI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return TI||!!yI(ao,vI(e))}catch(t){return!0}};jp.sham=!0;Gp.exports=!Hp||bI(function(){var a;return fi(fi.call)||!fi(Object)||!fi(function(){a=!0})||a})?jp:fi});var Qp=b((yk,Yp)=>{"use strict";var II=Wp(),EI=ei(),xI=TypeError;Yp.exports=function(a){if(II(a))return a;throw new xI(EI(a)+" is not a constructor")}});var so=b((Tk,Kp)=>{"use strict";var zp=at(),PI=Qp(),AI=hr(),wI=ye(),kI=wI("species");Kp.exports=function(a,e){var t=zp(a).constructor,r;return t===void 0||AI(r=zp(t)[kI])?e:PI(r)}});var Xp=b((Ik,Jp)=>{"use strict";var RI=Pe();Jp.exports=RI([].slice)});var eh=b((Ek,Zp)=>{"use strict";var $I=TypeError;Zp.exports=function(a,e){if(a<e)throw new $I("Not enough arguments");return a}});var no=b((xk,th)=>{"use strict";var LI=mr();th.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(LI)});var bo=b((Pk,lh)=>{"use strict";var Oe=le(),MI=Ln(),CI=oi(),rh=ce(),DI=Xe(),ch=De(),ih=_n(),BI=Xp(),ah=Aa(),OI=eh(),VI=no(),_I=Qa(),ho=Oe.setImmediate,fo=Oe.clearImmediate,NI=Oe.process,oo=Oe.Dispatch,FI=Oe.Function,sh=Oe.MessageChannel,qI=Oe.String,uo=0,mi={},nh="onreadystatechange",bi,Yt,co,lo;ch(function(){bi=Oe.location});var mo=function(a){if(DI(mi,a)){var e=mi[a];delete mi[a],e()}},po=function(a){return function(){mo(a)}},oh=function(a){mo(a.data)},uh=function(a){Oe.postMessage(qI(a),bi.protocol+"//"+bi.host)};(!ho||!fo)&&(ho=function(e){OI(arguments.length,1);var t=rh(e)?e:FI(e),r=BI(arguments,1);return mi[++uo]=function(){MI(t,void 0,r)},Yt(uo),uo},fo=function(e){delete mi[e]},_I?Yt=function(a){NI.nextTick(po(a))}:oo&&oo.now?Yt=function(a){oo.now(po(a))}:sh&&!VI?(co=new sh,lo=co.port2,co.port1.onmessage=oh,Yt=CI(lo.postMessage,lo)):Oe.addEventListener&&rh(Oe.postMessage)&&!Oe.importScripts&&bi&&bi.protocol!=="file:"&&!ch(uh)?(Yt=uh,Oe.addEventListener("message",oh,!1)):nh in ah("script")?Yt=function(a){ih.appendChild(ah("script"))[nh]=function(){ih.removeChild(this),mo(a)}}:Yt=function(a){setTimeout(po(a),0)});lh.exports={set:ho,clear:fo}});var hh=b((Ak,ph)=>{"use strict";var dh=le(),UI=qe(),HI=Object.getOwnPropertyDescriptor;ph.exports=function(a){if(!UI)return dh[a];var e=HI(dh,a);return e&&e.value}});var go=b((wk,mh)=>{"use strict";var fh=function(){this.head=null,this.tail=null};fh.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}}};mh.exports=fh});var gh=b((kk,bh)=>{"use strict";var jI=mr();bh.exports=/ipad|iphone|ipod/i.test(jI)&&typeof Pebble!="undefined"});var vh=b((Rk,Sh)=>{"use strict";var GI=mr();Sh.exports=/web0s(?!.*chrome)/i.test(GI)});var Ah=b(($k,Ph)=>{"use strict";var Ir=le(),WI=hh(),yh=oi(),So=bo().set,YI=go(),QI=no(),zI=gh(),KI=vh(),vo=Qa(),Th=Ir.MutationObserver||Ir.WebKitMutationObserver,Ih=Ir.document,Eh=Ir.process,za=Ir.Promise,Io=WI("queueMicrotask"),Tr,yo,To,Ka,xh;Io||(gi=new YI,Si=function(){var a,e;for(vo&&(a=Eh.domain)&&a.exit();e=gi.get();)try{e()}catch(t){throw gi.head&&Tr(),t}a&&a.enter()},!QI&&!vo&&!KI&&Th&&Ih?(yo=!0,To=Ih.createTextNode(""),new Th(Si).observe(To,{characterData:!0}),Tr=function(){To.data=yo=!yo}):!zI&&za&&za.resolve?(Ka=za.resolve(void 0),Ka.constructor=za,xh=yh(Ka.then,Ka),Tr=function(){xh(Si)}):vo?Tr=function(){Eh.nextTick(Si)}:(So=yh(So,Ir),Tr=function(){So(Si)}),Io=function(a){gi.head||Tr(),gi.add(a)});var gi,Si;Ph.exports=Io});var kh=b((Lk,wh)=>{"use strict";wh.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ja=b((Mk,Rh)=>{"use strict";Rh.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Qt=b((Ck,$h)=>{"use strict";var JI=le();$h.exports=JI.Promise});var Er=b((Dk,Dh)=>{"use strict";var XI=le(),vi=Qt(),ZI=ce(),eE=Cn(),tE=io(),rE=ye(),Lh=to(),iE=Je(),Eo=pn(),Mh=vi&&vi.prototype,aE=rE("species"),xo=!1,Ch=ZI(XI.PromiseRejectionEvent),sE=eE("Promise",function(){var a=tE(vi),e=a!==String(vi);if(!e&&Eo===66||iE&&!(Mh.catch&&Mh.finally))return!0;if(!Eo||Eo<51||!/native code/.test(a)){var t=new vi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[aE]=r,xo=t.then(function(){})instanceof r,!xo)return!0}return!e&&(Lh==="BROWSER"||Lh==="DENO")&&!Ch});Dh.exports={CONSTRUCTOR:sE,REJECTION_EVENT:Ch,SUBCLASSING:xo}});var xr=b((Bk,Oh)=>{"use strict";var Bh=ht(),nE=TypeError,oE=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new nE("Bad Promise constructor");e=r,t=i}),this.resolve=Bh(e),this.reject=Bh(t)};Oh.exports.f=function(a){return new oE(a)}});var tf=b(()=>{"use strict";var uE=Ue(),cE=Je(),ts=Qa(),Lt=le(),kr=Be(),Vh=yr(),_h=zn(),lE=li(),dE=Vp(),pE=ht(),es=ce(),hE=Fe(),fE=Np(),mE=so(),Hh=bo().set,Ro=Ah(),bE=kh(),gE=Ja(),SE=go(),jh=$n(),rs=Qt(),$o=Er(),Gh=xr(),is="Promise",Wh=$o.CONSTRUCTOR,vE=$o.REJECTION_EVENT,yE=$o.SUBCLASSING,Po=jh.getterFor(is),TE=jh.set,Pr=rs&&rs.prototype,zt=rs,Xa=Pr,Yh=Lt.TypeError,Ao=Lt.document,Lo=Lt.process,wo=Gh.f,IE=wo,EE=!!(Ao&&Ao.createEvent&&Lt.dispatchEvent),Qh="unhandledrejection",xE="rejectionhandled",Nh=0,zh=1,PE=2,Mo=1,Kh=2,Za,Fh,AE,qh,Jh=function(a){var e;return hE(a)&&es(e=a.then)?e:!1},Xh=function(a,e){var t=e.value,r=e.state===zh,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,l;try{i?(r||(e.rejection===Kh&&kE(e),e.rejection=Mo),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),l=!0)),u===a.promise?n(new Yh("Promise-chain cycle")):(c=Jh(u))?kr(c,u,s,n):s(u)):n(t)}catch(d){o&&!l&&o.exit(),n(d)}},Zh=function(a,e){a.notified||(a.notified=!0,Ro(function(){for(var t=a.reactions,r;r=t.get();)Xh(r,a);a.notified=!1,e&&!a.rejection&&wE(a)}))},ef=function(a,e,t){var r,i;EE?(r=Ao.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Lt.dispatchEvent(r)):r={promise:e,reason:t},!vE&&(i=Lt["on"+a])?i(r):a===Qh&&bE("Unhandled promise rejection",t)},wE=function(a){kr(Hh,Lt,function(){var e=a.facade,t=a.value,r=Uh(a),i;if(r&&(i=gE(function(){ts?Lo.emit("unhandledRejection",t,e):ef(Qh,e,t)}),a.rejection=ts||Uh(a)?Kh:Mo,i.error))throw i.value})},Uh=function(a){return a.rejection!==Mo&&!a.parent},kE=function(a){kr(Hh,Lt,function(){var e=a.facade;ts?Lo.emit("rejectionHandled",e):ef(xE,e,a.value)})},Ar=function(a,e,t){return function(r){a(e,r,t)}},wr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=PE,Zh(a,!0))},ko=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Yh("Promise can't be resolved itself");var r=Jh(e);r?Ro(function(){var i={done:!1};try{kr(r,e,Ar(ko,i,a),Ar(wr,i,a))}catch(s){wr(i,s,a)}}):(a.value=e,a.state=zh,Zh(a,!1))}catch(i){wr({done:!1},i,a)}}};if(Wh&&(zt=function(e){fE(this,Xa),pE(e),kr(Za,this);var t=Po(this);try{e(Ar(ko,t),Ar(wr,t))}catch(r){wr(t,r)}},Xa=zt.prototype,Za=function(e){TE(this,{type:is,done:!1,notified:!1,parent:!1,reactions:new SE,rejection:!1,state:Nh,value:void 0})},Za.prototype=Vh(Xa,"then",function(e,t){var r=Po(this),i=wo(mE(this,zt));return r.parent=!0,i.ok=es(e)?e:!0,i.fail=es(t)&&t,i.domain=ts?Lo.domain:void 0,r.state===Nh?r.reactions.add(i):Ro(function(){Xh(i,r)}),i.promise}),Fh=function(){var a=new Za,e=Po(a);this.promise=a,this.resolve=Ar(ko,e),this.reject=Ar(wr,e)},Gh.f=wo=function(a){return a===zt||a===AE?new Fh(a):IE(a)},!cE&&es(rs)&&Pr!==Object.prototype)){qh=Pr.then,yE||Vh(Pr,"then",function(e,t){var r=this;return new zt(function(i,s){kr(qh,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Pr.constructor}catch(a){}_h&&_h(Pr,Xa)}uE({global:!0,constructor:!0,wrap:!0,forced:Wh},{Promise:zt});lE(zt,is,!1,!0);dE(is)});var of=b((_k,nf)=>{"use strict";var RE=ye(),af=RE("iterator"),sf=!1;try{rf=0,Co={next:function(){return{done:!!rf++}},return:function(){sf=!0}},Co[af]=function(){return this},Array.from(Co,function(){throw 2})}catch(a){}var rf,Co;nf.exports=function(a,e){try{if(!e&&!sf)return!1}catch(i){return!1}var t=!1;try{var r={};r[af]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Do=b((Nk,uf)=>{"use strict";var $E=Qt(),LE=of(),ME=Er().CONSTRUCTOR;uf.exports=ME||!LE(function(a){$E.all(a).then(void 0,function(){})})});var cf=b(()=>{"use strict";var CE=Ue(),DE=Be(),BE=ht(),OE=xr(),VE=Ja(),_E=Ga(),NE=Do();CE({target:"Promise",stat:!0,forced:NE},{all:function(e){var t=this,r=OE.f(t),i=r.resolve,s=r.reject,n=VE(function(){var o=BE(t.resolve),u=[],c=0,l=1;_E(e,function(d){var p=c++,h=!1;l++,DE(o,t,d).then(function(m){h||(h=!0,u[p]=m,--l||i(u))},s)}),--l||i(u)});return n.error&&s(n.value),r.promise}})});var df=b(()=>{"use strict";var FE=Ue(),qE=Je(),UE=Er().CONSTRUCTOR,Oo=Qt(),HE=pt(),jE=ce(),GE=yr(),lf=Oo&&Oo.prototype;FE({target:"Promise",proto:!0,forced:UE,real:!0},{catch:function(a){return this.then(void 0,a)}});!qE&&jE(Oo)&&(Bo=HE("Promise").prototype.catch,lf.catch!==Bo&&GE(lf,"catch",Bo,{unsafe:!0}));var Bo});var pf=b(()=>{"use strict";var WE=Ue(),YE=Be(),QE=ht(),zE=xr(),KE=Ja(),JE=Ga(),XE=Do();WE({target:"Promise",stat:!0,forced:XE},{race:function(e){var t=this,r=zE.f(t),i=r.reject,s=KE(function(){var n=QE(t.resolve);JE(e,function(o){YE(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var hf=b(()=>{"use strict";var ZE=Ue(),ex=xr(),tx=Er().CONSTRUCTOR;ZE({target:"Promise",stat:!0,forced:tx},{reject:function(e){var t=ex.f(this),r=t.reject;return r(e),t.promise}})});var Vo=b((Qk,ff)=>{"use strict";var rx=at(),ix=Fe(),ax=xr();ff.exports=function(a,e){if(rx(a),ix(e)&&e.constructor===a)return e;var t=ax.f(a),r=t.resolve;return r(e),t.promise}});var gf=b(()=>{"use strict";var sx=Ue(),nx=pt(),mf=Je(),ox=Qt(),bf=Er().CONSTRUCTOR,ux=Vo(),cx=nx("Promise"),lx=mf&&!bf;sx({target:"Promise",stat:!0,forced:mf||bf},{resolve:function(e){return ux(lx&&this===cx?ox:this,e)}})});var Sf=b(()=>{"use strict";tf();cf();df();pf();hf();gf()});var If=b(()=>{"use strict";var dx=Ue(),px=Je(),as=Qt(),hx=De(),yf=pt(),Tf=ce(),fx=so(),vf=Vo(),mx=yr(),No=as&&as.prototype,bx=!!as&&hx(function(){No.finally.call({then:function(){}},function(){})});dx({target:"Promise",proto:!0,real:!0,forced:bx},{finally:function(a){var e=fx(this,yf("Promise")),t=Tf(a);return this.then(t?function(r){return vf(e,a()).then(function(){return r})}:a,t?function(r){return vf(e,a()).then(function(){throw r})}:a)}});!px&&Tf(as)&&(_o=yf("Promise").prototype.finally,No.finally!==_o&&mx(No,"finally",_o,{unsafe:!0}));var _o});var ss=b((tR,Ef)=>{"use strict";var gx=pt();Ef.exports=gx});var Pf=b((rR,xf)=>{"use strict";$p();Sf();If();var Sx=ss();xf.exports=Sx("Promise","finally")});var wf=b((iR,Af)=>{"use strict";var vx=Pf();Af.exports=vx});var ns=b((aR,kf)=>{"use strict";var yx=wf();kf.exports=yx});var _f=b(()=>{"use strict";var kx=Ue(),Rx=ii(),$x=Oa(),Lx=Ba(),Mx=rn();kx({target:"Array",proto:!0},{at:function(e){var t=Rx(this),r=$x(t),i=Lx(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});Mx("at")});var Ff=b((r$,Nf)=>{"use strict";_f();var Cx=ss();Nf.exports=Cx("Array","at")});var Uf=b((i$,qf)=>{"use strict";var Dx=Ff();qf.exports=Dx});var Ti=b((a$,Hf)=>{"use strict";var Bx=Uf();Hf.exports=Bx});var Dm=b(()=>{"use strict"});var Bm=b(()=>{"use strict"});var Vm=b((ZC,Om)=>{"use strict";var mP=Fe(),bP=pr(),gP=ye(),SP=gP("match");Om.exports=function(a){var e;return mP(a)&&((e=a[SP])!==void 0?!!e:bP(a)==="RegExp")}});var Nm=b((eD,_m)=>{"use strict";var vP=ci(),yP=String;_m.exports=function(a){if(vP(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return yP(a)}});var qm=b((tD,Fm)=>{"use strict";var TP=at();Fm.exports=function(){var a=TP(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 jm=b((rD,Hm)=>{"use strict";var IP=Be(),EP=Xe(),xP=Zr(),PP=qm(),Um=RegExp.prototype;Hm.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Um)&&!EP(a,"flags")&&xP(Um,a)?IP(PP,a):e}});var Wm=b((iD,Gm)=>{"use strict";var uu=Pe(),AP=ii(),wP=Math.floor,nu=uu("".charAt),kP=uu("".replace),ou=uu("".slice),RP=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,$P=/\$([$&'`]|\d{1,2})/g;Gm.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=$P;return i!==void 0&&(i=AP(i),u=RP),kP(s,u,function(c,l){var d;switch(nu(l,0)){case"$":return"$";case"&":return a;case"`":return ou(e,0,t);case"'":return ou(e,n);case"<":d=i[ou(l,1,-1)];break;default:var p=+l;if(p===0)return c;if(p>o){var h=wP(p/10);return h===0?c:h<=o?r[h-1]===void 0?nu(l,1):r[h-1]+nu(l,1):c}d=r[p-1]}return d===void 0?"":d})}});var zm=b(()=>{"use strict";var LP=Ue(),MP=Be(),lu=Pe(),Ym=Jr(),CP=ce(),DP=hr(),BP=Vm(),_r=Nm(),OP=ti(),VP=jm(),_P=Wm(),NP=ye(),FP=Je(),qP=NP("replace"),UP=TypeError,cu=lu("".indexOf),HP=lu("".replace),Qm=lu("".slice),jP=Math.max;LP({target:"String",proto:!0},{replaceAll:function(e,t){var r=Ym(this),i,s,n,o,u,c,l,d,p,h,m=0,g="";if(!DP(e)){if(i=BP(e),i&&(s=_r(Ym(VP(e))),!~cu(s,"g")))throw new UP("`.replaceAll` does not allow non-global regexes");if(n=OP(e,qP),n)return MP(n,e,r,t);if(FP&&i)return HP(_r(r),e,t)}for(o=_r(r),u=_r(e),c=CP(t),c||(t=_r(t)),l=u.length,d=jP(1,l),p=cu(o,u);p!==-1;)h=c?_r(t(u,p,o)):_P(u,o,p,[],void 0,t),g+=Qm(o,m,p)+h,m=p+l,p=p+d>o.length?-1:cu(o,u,p+d);return m<o.length&&(g+=Qm(o,m)),g}})});var Jm=b((nD,Km)=>{"use strict";Dm();Bm();zm();var GP=ss();Km.exports=GP("String","replaceAll")});var Zm=b((oD,Xm)=>{"use strict";var WP=Jm();Xm.exports=WP});var tb=b((uD,eb)=>{"use strict";var YP=Zm();eb.exports=YP});var uA={};lg(uA,{ChromecastState:()=>zr,HttpConnectionType:()=>Ea,Observable:()=>lt.Observable,PlaybackState:()=>ve,Player:()=>ba,SDK_VERSION:()=>oA,Subject:()=>lt.Subject,Subscription:()=>lt.Subscription,Surface:()=>xa,VERSION:()=>Zs,ValueSubject:()=>lt.ValueSubject,VideoFormat:()=>dt,VideoQuality:()=>lt.VideoQuality});module.exports=dg(uA);var Zs="2.0.112";var ve=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ve||{}),dt=(I=>(I.MPEG="MPEG",I.DASH="DASH",I.DASH_SEP="DASH_SEP",I.DASH_SEP_VK="DASH_SEP",I.DASH_WEBM="DASH_WEBM",I.DASH_WEBM_AV1="DASH_WEBM_AV1",I.DASH_STREAMS="DASH_STREAMS",I.DASH_WEBM_VK="DASH_WEBM",I.DASH_ONDEMAND="DASH_ONDEMAND",I.DASH_ONDEMAND_VK="DASH_ONDEMAND",I.DASH_LIVE="DASH_LIVE",I.DASH_LIVE_CMAF="DASH_LIVE_CMAF",I.DASH_LIVE_WEBM="DASH_LIVE_WEBM",I.HLS="HLS",I.HLS_ONDEMAND="HLS_ONDEMAND",I.HLS_JS="HLS",I.HLS_LIVE="HLS_LIVE",I.HLS_LIVE_CMAF="HLS_LIVE_CMAF",I.WEB_RTC_LIVE="WEB_RTC_LIVE",I))(dt||{});var zr=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(zr||{}),Ea=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Ea||{});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 q=require("@vkontakte/videoplayer-shared");var Zu=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Pa=class{constructor(e){this.connection$=new q.ValueSubject(void 0);this.castState$=new q.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new q.Subject;this.realCastState$=new q.ValueSubject("NOT_AVAILABLE");this.subscription=new q.Subscription;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,q.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Zu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:q.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,q.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,q.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,q.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,q.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,q.assertNever)(i.sessionState)}})).add((0,q.merge)((0,q.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,q.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,q.map)(i=>i.castState)),(0,q.observableFrom)([r.getCastState()])).pipe((0,q.filterChanged)(),(0,q.map)(pg),(0,q.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,q.isNonNullable)(this.connection$.getValue());if(s&&!n){let c=r.getCurrentSession();(0,q.assertNonNullable)(c);let l=c.getCastDevice(),d=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,q.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(0,q.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:q.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},pg=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,q.assertNever)(a)}};var xb=ze(eo(),1);var Mf=ze(ns(),1);var Fo=require("@vkontakte/videoplayer-shared");var Se=(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,Fo.assertNever)(t)}return a},qo=(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,Fo.assertNever)(e)}};var w=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var st=require("@vkontakte/videoplayer-shared"),j=class{constructor(e){this.transitionStarted$=new st.Subject;this.transitionEnded$=new st.Subject;this.transitionUpdated$=new st.Subject;this.forceChanged$=new st.Subject;this.stateChangeStarted$=(0,st.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,st.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||(0,st.isNonNullable)(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Rf=require("@vkontakte/videoplayer-shared"),$f=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,Rf.assertNever)(a)}};var $=require("@vkontakte/videoplayer-shared");var Tx=5,Ix=5,Ex=500,Lf=7e3,yi=class{constructor(e){this.subscription=new $.Subscription;this.loadMediaTimeoutSubscription=new $.Subscription;this.videoState=new j("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,$.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($f(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)(Ex)).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)>Tx)&&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<Ix&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,$.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"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&w(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var c;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let l=t[e];(0,$.assertNonNullable)(l);let d=(0,$.getHighestQuality)(Object.keys(l));(0,$.assertNonNullable)(d);let p=l[d];(0,$.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,$.assertNonNullable)(l),r=l.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 l=t[e];(0,$.assertNonNullable)(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),r=l.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,$.assertNonNullable)(l),r=Se(l.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:$.ErrorCategory.VIDEO_PIPELINE,message:l,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((c=this.params.meta.videoId)!=null?c: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)(Lf).subscribe(()=>s(`timeout(${Lf})`)))});(0,Mf.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},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 Go=require("@vkontakte/videoplayer-shared");var Cf=require("@vkontakte/videoplayer-shared"),Df=a=>{try{a.pause(),a.playbackRate=0,(0,Cf.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var os=require("@vkontakte/videoplayer-shared"),Uo=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Ho=window.WeakMap?new WeakMap:new Uo,jo=window.WeakMap?new WeakMap:new Map,xx=(a,e=20)=>{let t=0;return(0,os.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ae=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,Go.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),Ho.set(t,r);let i=new os.Subscription;return i.add(xx(t,e)),jo.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},we=a=>{let e=jo.get(a);e==null||e.unsubscribe(),jo.delete(a);let t=Ho.get(a);Ho.delete(a),t?(0,Go.clearVideoElement)(a):Df(a)};var L=require("@vkontakte/videoplayer-shared");var Mt=require("@vkontakte/videoplayer-shared"),us=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Mt.isNullable)(i),c=new Mt.Subscription;return i&&c.add(i.subscribe(l=>{let d=a.getState();r(l,d)&&a.setState(l)},s)),r(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(l=>{t(l.to),u&&a.setState(l.to)},s)),c},nt=(a,e,t)=>us(e,()=>a.loop,r=>{(0,Mt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),ke=(a,e,t,r)=>us(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Mt.isNonNullable)(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),He=(a,e,t,r)=>us(e,()=>a.playbackRate,i=>{(0,Mt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ct=us;var Px=a=>["__",a.language,a.label].join("|"),Ax=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Wo=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(Ct(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,L.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Ct(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,L.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Ct(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Ct(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,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 c,l,d,p,h;let u=(l=(c=o.target)==null?void 0:c.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,L.fromEvent)(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;(0,L.isNonNullable)(t.align)&&(i.align=t.align),(0,L.isNonNullable)(t.position)&&(i.position=t.position),(0,L.isNonNullable)(t.size)&&(i.size=t.size),(0,L.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,i=e.id?e.id:Px(e),s=this.externalTracks.has(i),n=i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(i))==null?void 0:o.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(u=this.internalTracks.get(i))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!Ax(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,L.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,L.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},je=Wo;var bt=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 Bf=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},Yo=a=>{let e=Bf(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Of=a=>{let e=Bf(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var D=require("@vkontakte/videoplayer-shared");var wx=3,Vf=(a,e,t=wx)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Re=a=>{let e=I=>(0,D.fromEvent)(a,I).pipe((0,D.mapTo)(void 0)),r=(0,D.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>(0,D.fromEvent)(a,I))).pipe((0,D.map)(I=>I.type==="ended"?a.readyState<2:a.readyState<3),(0,D.filterChanged)()),i=(0,D.merge)((0,D.fromEvent)(a,"progress"),(0,D.fromEvent)(a,"timeupdate")).pipe((0,D.map)(()=>Vf(a.buffered,a.currentTime))),s=D.clientChecker.isSafari?(0,D.combine)({play:e("play").pipe((0,D.once)()),playing:e("playing")}).pipe((0,D.mapTo)(void 0)):e("playing"),n=(0,D.fromEvent)(a,"volumechange").pipe((0,D.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,D.fromEvent)(a,"ratechange").pipe((0,D.map)(()=>a.playbackRate)),u=(0,D.fromEvent)(a,"error").pipe((0,D.filter)(()=>!!(a.error||a.played.length)),(0,D.map)(()=>{var E;let I=a.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:D.ErrorCategory.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),c=(0,D.fromEvent)(a,"timeupdate").pipe((0,D.map)(()=>a.currentTime)),l=new D.Subject,d=.3,p;c.subscribe(I=>{a.loop&&(0,D.isNonNullable)(p)&&(0,D.isNonNullable)(I)&&p>=a.duration-d&&I<=d&&l.next(p),p=I});let h=e("pause").pipe((0,D.filter)(()=>!a.error&&p!==a.duration)),m=(0,D.fromEvent)(a,"enterpictureinpicture"),g=(0,D.fromEvent)(a,"leavepictureinpicture"),S=new D.ValueSubject(Of(a));m.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let T=new D.ValueSubject(Yo(a));return(0,D.fromEvent)(a,"fullscreenchange").pipe((0,D.map)(()=>Yo(a))).subscribe(T),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:(0,D.fromEvent)(a,"durationchange").pipe((0,D.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:T}};var gt=require("@vkontakte/videoplayer-shared"),Dt=a=>{switch(a){case"mobile":return gt.VideoQuality.Q_144P;case"lowest":return gt.VideoQuality.Q_240P;case"low":return gt.VideoQuality.Q_360P;case"sd":case"medium":return gt.VideoQuality.Q_480P;case"hd":case"high":return gt.VideoQuality.Q_720P;case"fullhd":case"full":return gt.VideoQuality.Q_1080P;case"quadhd":case"quad":return gt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return gt.VideoQuality.Q_2160P}};var Kt=ze(Ti(),1),B=require("@vkontakte/videoplayer-shared");var Qo=!1,St={},jf=a=>{Qo=a},Gf=()=>{St={}},Wf=a=>{a(St)},Ii=(a,e)=>{var t;Qo&&(St.meta=(t=St.meta)!=null?t:{},St.meta[a]=e)},Te=class{constructor(e){this.name=e}next(e){var r,i;if(!Qo)return;St.series=(r=St.series)!=null?r:{};let t=(i=St.series[this.name])!=null?i:[];t.push([Date.now(),e]),St.series[this.name]=t}};var Ox=new Te("best_bitrate"),Qf=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var zo=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ei=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,B.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},zf='Assertion "ABR Tracks is empty array" failed',cs=(a,e,t,r)=>{var u;let i=[...e].sort(zo(1)),s=[...t].sort(zo(1)),n=s.filter(c=>(0,B.isNonNullable)(c.bitrate)&&(0,B.isNonNullable)(a.bitrate)?a.bitrate/c.bitrate>r:!0),o=(u=(0,Kt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Kt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Kt.default)(n,-1):(0,Kt.default)(s,0)},Yf=a=>"quality"in a,Kf=(a,e,t,r)=>{let i=t&&r&&r.history[t.id]&&(0,B.now)()-r.history[t.id]<=a.trackCooldown&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!i&&r.recordSelection(t),i&&(r!=null&&r.last)){let s=r.last;r==null||r.recordSwitch(s);let n=Yf(s)?"video":"audio",o=Yf(s)?s.quality:s.bitrate;return e({message:`
|
|
6
|
+
"use strict";var fg=Object.create;var nr=Object.defineProperty,mg=Object.defineProperties,bg=Object.getOwnPropertyDescriptor,gg=Object.getOwnPropertyDescriptors,Sg=Object.getOwnPropertyNames,Na=Object.getOwnPropertySymbols,vg=Object.getPrototypeOf,dn=Object.prototype.hasOwnProperty,gl=Object.prototype.propertyIsEnumerable;var yg=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var ot=Math.pow,bl=(a,e,t)=>e in a?nr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,R=(a,e)=>{for(var t in e||(e={}))dn.call(e,t)&&bl(a,t,e[t]);if(Na)for(var t of Na(e))gl.call(e,t)&&bl(a,t,e[t]);return a},j=(a,e)=>mg(a,gg(e));var Sl=(a,e)=>{var t={};for(var i in a)dn.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&Na)for(var i of Na(a))e.indexOf(i)<0&&gl.call(a,i)&&(t[i]=a[i]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Tg=(a,e)=>{for(var t in e)nr(a,t,{get:e[t],enumerable:!0})},vl=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Sg(e))!dn.call(a,r)&&r!==t&&nr(a,r,{get:()=>e[r],enumerable:!(i=bg(e,r))||i.enumerable});return a};var Xe=(a,e,t)=>(t=a!=null?fg(vg(a)):{},vl(e||!a||!a.__esModule?nr(t,"default",{value:a,enumerable:!0}):t,a)),Ig=a=>vl(nr({},"__esModule",{value:!0}),a);var V=(a,e,t)=>new Promise((i,r)=>{var s=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),pn=function(a,e){this[0]=a,this[1]=e},me=(a,e,t)=>{var i=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof pn,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?i(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>i("throw",h,u,l))}catch(h){l(h)}},r=n=>s[n]=o=>new Promise((u,l)=>i(n,o,u,l)),s={};return t=t.apply(a,e),s[yg("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var Be=b((BA,Tl)=>{"use strict";Tl.exports=function(a){try{return!!a()}catch(e){return!0}}});var ur=b((OA,Il)=>{"use strict";var xg=Be();Il.exports=!xg(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Ae=b((VA,Pl)=>{"use strict";var El=ur(),xl=Function.prototype,fn=xl.call,Pg=El&&xl.bind.bind(fn,fn);Pl.exports=El?Pg:function(a){return function(){return fn.apply(a,arguments)}}});var Ii=b((_A,wl)=>{"use strict";var Al=Ae(),Ag=Al({}.toString),wg=Al("".slice);wl.exports=function(a){return wg(Ag(a),8,-1)}});var Rl=b((NA,kl)=>{"use strict";var kg=Ae(),Rg=Be(),$g=Ii(),mn=Object,Lg=kg("".split);kl.exports=Rg(function(){return!mn("z").propertyIsEnumerable(0)})?function(a){return $g(a)==="String"?Lg(a,""):mn(a)}:mn});var Ei=b((FA,$l)=>{"use strict";$l.exports=function(a){return a==null}});var lr=b((qA,Ll)=>{"use strict";var Mg=Ei(),Cg=TypeError;Ll.exports=function(a){if(Mg(a))throw new Cg("Can't call method on "+a);return a}});var xi=b((UA,Ml)=>{"use strict";var Dg=Rl(),Bg=lr();Ml.exports=function(a){return Dg(Bg(a))}});var bn=b((HA,Cl)=>{"use strict";Cl.exports=function(){}});var Xt=b((jA,Dl)=>{"use strict";Dl.exports={}});var de=b((gn,Bl)=>{"use strict";var cr=function(a){return a&&a.Math===Math&&a};Bl.exports=cr(typeof globalThis=="object"&&globalThis)||cr(typeof window=="object"&&window)||cr(typeof self=="object"&&self)||cr(typeof global=="object"&&global)||cr(typeof gn=="object"&&gn)||function(){return this}()||Function("return this")()});var ce=b((GA,Ol)=>{"use strict";var Sn=typeof document=="object"&&document.all;Ol.exports=typeof Sn=="undefined"&&Sn!==void 0?function(a){return typeof a=="function"||a===Sn}:function(a){return typeof a=="function"}});var Nl=b((WA,_l)=>{"use strict";var Og=de(),Vg=ce(),Vl=Og.WeakMap;_l.exports=Vg(Vl)&&/native code/.test(String(Vl))});var Ue=b((YA,Fl)=>{"use strict";var _g=ce();Fl.exports=function(a){return typeof a=="object"?a!==null:_g(a)}});var He=b((QA,ql)=>{"use strict";var Ng=Be();ql.exports=!Ng(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ha=b((zA,Hl)=>{"use strict";var Fg=de(),Ul=Ue(),vn=Fg.document,qg=Ul(vn)&&Ul(vn.createElement);Hl.exports=function(a){return qg?vn.createElement(a):{}}});var yn=b((KA,jl)=>{"use strict";var Ug=He(),Hg=Be(),jg=Ha();jl.exports=!Ug&&!Hg(function(){return Object.defineProperty(jg("div"),"a",{get:function(){return 7}}).a!==7})});var Tn=b((JA,Gl)=>{"use strict";var Gg=He(),Wg=Be();Gl.exports=Gg&&Wg(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ut=b((XA,Wl)=>{"use strict";var Yg=Ue(),Qg=String,zg=TypeError;Wl.exports=function(a){if(Yg(a))return a;throw new zg(Qg(a)+" is not an object")}});var Oe=b((ZA,Yl)=>{"use strict";var Kg=ur(),ja=Function.prototype.call;Yl.exports=Kg?ja.bind(ja):function(){return ja.apply(ja,arguments)}});var Ga=b((ew,Ql)=>{"use strict";Ql.exports={}});var St=b((tw,Kl)=>{"use strict";var In=Ga(),En=de(),Jg=ce(),zl=function(a){return Jg(a)?a:void 0};Kl.exports=function(a,e){return arguments.length<2?zl(In[a])||zl(En[a]):In[a]&&In[a][e]||En[a]&&En[a][e]}});var dr=b((iw,Jl)=>{"use strict";var Xg=Ae();Jl.exports=Xg({}.isPrototypeOf)});var Pi=b((rw,ec)=>{"use strict";var Zg=de(),Xl=Zg.navigator,Zl=Xl&&Xl.userAgent;ec.exports=Zl?String(Zl):""});var Pn=b((aw,nc)=>{"use strict";var sc=de(),xn=Pi(),tc=sc.process,ic=sc.Deno,rc=tc&&tc.versions||ic&&ic.version,ac=rc&&rc.v8,Ze,Wa;ac&&(Ze=ac.split("."),Wa=Ze[0]>0&&Ze[0]<4?1:+(Ze[0]+Ze[1]));!Wa&&xn&&(Ze=xn.match(/Edge\/(\d+)/),(!Ze||Ze[1]>=74)&&(Ze=xn.match(/Chrome\/(\d+)/),Ze&&(Wa=+Ze[1])));nc.exports=Wa});var An=b((sw,uc)=>{"use strict";var oc=Pn(),eS=Be(),tS=de(),iS=tS.String;uc.exports=!!Object.getOwnPropertySymbols&&!eS(function(){var a=Symbol("symbol detection");return!iS(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&oc&&oc<41})});var wn=b((nw,lc)=>{"use strict";var rS=An();lc.exports=rS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var kn=b((ow,cc)=>{"use strict";var aS=St(),sS=ce(),nS=dr(),oS=wn(),uS=Object;cc.exports=oS?function(a){return typeof a=="symbol"}:function(a){var e=aS("Symbol");return sS(e)&&nS(e.prototype,uS(a))}});var pr=b((uw,dc)=>{"use strict";var lS=String;dc.exports=function(a){try{return lS(a)}catch(e){return"Object"}}});var vt=b((lw,pc)=>{"use strict";var cS=ce(),dS=pr(),pS=TypeError;pc.exports=function(a){if(cS(a))return a;throw new pS(dS(a)+" is not a function")}});var hr=b((cw,hc)=>{"use strict";var hS=vt(),fS=Ei();hc.exports=function(a,e){var t=a[e];return fS(t)?void 0:hS(t)}});var mc=b((dw,fc)=>{"use strict";var Rn=Oe(),$n=ce(),Ln=Ue(),mS=TypeError;fc.exports=function(a,e){var t,i;if(e==="string"&&$n(t=a.toString)&&!Ln(i=Rn(t,a))||$n(t=a.valueOf)&&!Ln(i=Rn(t,a))||e!=="string"&&$n(t=a.toString)&&!Ln(i=Rn(t,a)))return i;throw new mS("Can't convert object to primitive value")}});var et=b((pw,bc)=>{"use strict";bc.exports=!0});var vc=b((hw,Sc)=>{"use strict";var gc=de(),bS=Object.defineProperty;Sc.exports=function(a,e){try{bS(gc,a,{value:e,configurable:!0,writable:!0})}catch(t){gc[a]=e}return e}});var fr=b((fw,Ic)=>{"use strict";var gS=et(),SS=de(),vS=vc(),yc="__core-js_shared__",Tc=Ic.exports=SS[yc]||vS(yc,{});(Tc.versions||(Tc.versions=[])).push({version:"3.38.0",mode:gS?"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 Mn=b((mw,xc)=>{"use strict";var Ec=fr();xc.exports=function(a,e){return Ec[a]||(Ec[a]=e||{})}});var mr=b((bw,Pc)=>{"use strict";var yS=lr(),TS=Object;Pc.exports=function(a){return TS(yS(a))}});var tt=b((gw,Ac)=>{"use strict";var IS=Ae(),ES=mr(),xS=IS({}.hasOwnProperty);Ac.exports=Object.hasOwn||function(e,t){return xS(ES(e),t)}});var Cn=b((Sw,wc)=>{"use strict";var PS=Ae(),AS=0,wS=Math.random(),kS=PS(1 .toString);wc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+kS(++AS+wS,36)}});var Te=b((vw,Rc)=>{"use strict";var RS=de(),$S=Mn(),kc=tt(),LS=Cn(),MS=An(),CS=wn(),Ai=RS.Symbol,Dn=$S("wks"),DS=CS?Ai.for||Ai:Ai&&Ai.withoutSetter||LS;Rc.exports=function(a){return kc(Dn,a)||(Dn[a]=MS&&kc(Ai,a)?Ai[a]:DS("Symbol."+a)),Dn[a]}});var Cc=b((yw,Mc)=>{"use strict";var BS=Oe(),$c=Ue(),Lc=kn(),OS=hr(),VS=mc(),_S=Te(),NS=TypeError,FS=_S("toPrimitive");Mc.exports=function(a,e){if(!$c(a)||Lc(a))return a;var t=OS(a,FS),i;if(t){if(e===void 0&&(e="default"),i=BS(t,a,e),!$c(i)||Lc(i))return i;throw new NS("Can't convert object to primitive value")}return e===void 0&&(e="number"),VS(a,e)}});var Bn=b((Tw,Dc)=>{"use strict";var qS=Cc(),US=kn();Dc.exports=function(a){var e=qS(a,"string");return US(e)?e:e+""}});var Zt=b(Oc=>{"use strict";var HS=He(),jS=yn(),GS=Tn(),Ya=ut(),Bc=Bn(),WS=TypeError,On=Object.defineProperty,YS=Object.getOwnPropertyDescriptor,Vn="enumerable",_n="configurable",Nn="writable";Oc.f=HS?GS?function(e,t,i){if(Ya(e),t=Bc(t),Ya(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Nn in i&&!i[Nn]){var r=YS(e,t);r&&r[Nn]&&(e[t]=i.value,i={configurable:_n in i?i[_n]:r[_n],enumerable:Vn in i?i[Vn]:r[Vn],writable:!1})}return On(e,t,i)}:On:function(e,t,i){if(Ya(e),t=Bc(t),Ya(i),jS)try{return On(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new WS("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var br=b((Ew,Vc)=>{"use strict";Vc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var wi=b((xw,_c)=>{"use strict";var QS=He(),zS=Zt(),KS=br();_c.exports=QS?function(a,e,t){return zS.f(a,e,KS(1,t))}:function(a,e,t){return a[e]=t,a}});var Qa=b((Pw,Fc)=>{"use strict";var JS=Mn(),XS=Cn(),Nc=JS("keys");Fc.exports=function(a){return Nc[a]||(Nc[a]=XS(a))}});var za=b((Aw,qc)=>{"use strict";qc.exports={}});var Hn=b((ww,jc)=>{"use strict";var ZS=Nl(),Hc=de(),ev=Ue(),tv=wi(),Fn=tt(),qn=fr(),iv=Qa(),rv=za(),Uc="Object already initialized",Un=Hc.TypeError,av=Hc.WeakMap,Ka,gr,Ja,sv=function(a){return Ja(a)?gr(a):Ka(a,{})},nv=function(a){return function(e){var t;if(!ev(e)||(t=gr(e)).type!==a)throw new Un("Incompatible receiver, "+a+" required");return t}};ZS||qn.state?(it=qn.state||(qn.state=new av),it.get=it.get,it.has=it.has,it.set=it.set,Ka=function(a,e){if(it.has(a))throw new Un(Uc);return e.facade=a,it.set(a,e),e},gr=function(a){return it.get(a)||{}},Ja=function(a){return it.has(a)}):(ei=iv("state"),rv[ei]=!0,Ka=function(a,e){if(Fn(a,ei))throw new Un(Uc);return e.facade=a,tv(a,ei,e),e},gr=function(a){return Fn(a,ei)?a[ei]:{}},Ja=function(a){return Fn(a,ei)});var it,ei;jc.exports={set:Ka,get:gr,has:Ja,enforce:sv,getterFor:nv}});var jn=b((kw,Qc)=>{"use strict";var ov=ur(),Yc=Function.prototype,Gc=Yc.apply,Wc=Yc.call;Qc.exports=typeof Reflect=="object"&&Reflect.apply||(ov?Wc.bind(Gc):function(){return Wc.apply(Gc,arguments)})});var Gn=b((Rw,zc)=>{"use strict";var uv=Ii(),lv=Ae();zc.exports=function(a){if(uv(a)==="Function")return lv(a)}});var Zc=b(Xc=>{"use strict";var Kc={}.propertyIsEnumerable,Jc=Object.getOwnPropertyDescriptor,cv=Jc&&!Kc.call({1:2},1);Xc.f=cv?function(e){var t=Jc(this,e);return!!t&&t.enumerable}:Kc});var id=b(td=>{"use strict";var dv=He(),pv=Oe(),hv=Zc(),fv=br(),mv=xi(),bv=Bn(),gv=tt(),Sv=yn(),ed=Object.getOwnPropertyDescriptor;td.f=dv?ed:function(e,t){if(e=mv(e),t=bv(t),Sv)try{return ed(e,t)}catch(i){}if(gv(e,t))return fv(!pv(hv.f,e,t),e[t])}});var Wn=b((Mw,rd)=>{"use strict";var vv=Be(),yv=ce(),Tv=/#|\.prototype\./,Sr=function(a,e){var t=Ev[Iv(a)];return t===Pv?!0:t===xv?!1:yv(e)?vv(e):!!e},Iv=Sr.normalize=function(a){return String(a).replace(Tv,".").toLowerCase()},Ev=Sr.data={},xv=Sr.NATIVE="N",Pv=Sr.POLYFILL="P";rd.exports=Sr});var vr=b((Cw,sd)=>{"use strict";var ad=Gn(),Av=vt(),wv=ur(),kv=ad(ad.bind);sd.exports=function(a,e){return Av(a),e===void 0?a:wv?kv(a,e):function(){return a.apply(e,arguments)}}});var je=b((Dw,od)=>{"use strict";var yr=de(),Rv=jn(),$v=Gn(),Lv=ce(),Mv=id().f,Cv=Wn(),ki=Ga(),Dv=vr(),Ri=wi(),nd=tt();fr();var Bv=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return Rv(a,this,arguments)};return e.prototype=a.prototype,e};od.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?yr:r?yr[t]:yr[t]&&yr[t].prototype,o=i?ki:ki[t]||Ri(ki,t,{})[t],u=o.prototype,l,c,d,p,h,m,g,S,T;for(p in e)l=Cv(i?p:t+(r?".":"#")+p,a.forced),c=!l&&n&&nd(n,p),m=o[p],c&&(a.dontCallGetSet?(T=Mv(n,p),g=T&&T.value):g=n[p]),h=c&&g?g:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?S=Dv(h,yr):a.wrap&&c?S=Bv(h):s&&Lv(h)?S=$v(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&Ri(S,"sham",!0),Ri(o,p,S),s&&(d=t+"Prototype",nd(ki,d)||Ri(ki,d,{}),Ri(ki[d],p,h),a.real&&u&&(l||!u[p])&&Ri(u,p,h)))}});var cd=b((Bw,ld)=>{"use strict";var Yn=He(),Ov=tt(),ud=Function.prototype,Vv=Yn&&Object.getOwnPropertyDescriptor,Qn=Ov(ud,"name"),_v=Qn&&function(){}.name==="something",Nv=Qn&&(!Yn||Yn&&Vv(ud,"name").configurable);ld.exports={EXISTS:Qn,PROPER:_v,CONFIGURABLE:Nv}});var pd=b((Ow,dd)=>{"use strict";var Fv=Math.ceil,qv=Math.floor;dd.exports=Math.trunc||function(e){var t=+e;return(t>0?qv:Fv)(t)}});var Xa=b((Vw,hd)=>{"use strict";var Uv=pd();hd.exports=function(a){var e=+a;return e!==e||e===0?0:Uv(e)}});var md=b((_w,fd)=>{"use strict";var Hv=Xa(),jv=Math.max,Gv=Math.min;fd.exports=function(a,e){var t=Hv(a);return t<0?jv(t+e,0):Gv(t,e)}});var gd=b((Nw,bd)=>{"use strict";var Wv=Xa(),Yv=Math.min;bd.exports=function(a){var e=Wv(a);return e>0?Yv(e,9007199254740991):0}});var Za=b((Fw,Sd)=>{"use strict";var Qv=gd();Sd.exports=function(a){return Qv(a.length)}});var Td=b((qw,yd)=>{"use strict";var zv=xi(),Kv=md(),Jv=Za(),vd=function(a){return function(e,t,i){var r=zv(e),s=Jv(r);if(s===0)return!a&&-1;var n=Kv(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};yd.exports={includes:vd(!0),indexOf:vd(!1)}});var xd=b((Uw,Ed)=>{"use strict";var Xv=Ae(),zn=tt(),Zv=xi(),ey=Td().indexOf,ty=za(),Id=Xv([].push);Ed.exports=function(a,e){var t=Zv(a),i=0,r=[],s;for(s in t)!zn(ty,s)&&zn(t,s)&&Id(r,s);for(;e.length>i;)zn(t,s=e[i++])&&(~ey(r,s)||Id(r,s));return r}});var Kn=b((Hw,Pd)=>{"use strict";Pd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var wd=b((jw,Ad)=>{"use strict";var iy=xd(),ry=Kn();Ad.exports=Object.keys||function(e){return iy(e,ry)}});var Rd=b(kd=>{"use strict";var ay=He(),sy=Tn(),ny=Zt(),oy=ut(),uy=xi(),ly=wd();kd.f=ay&&!sy?Object.defineProperties:function(e,t){oy(e);for(var i=uy(t),r=ly(t),s=r.length,n=0,o;s>n;)ny.f(e,o=r[n++],i[o]);return e}});var Jn=b((Ww,$d)=>{"use strict";var cy=St();$d.exports=cy("document","documentElement")});var to=b((Yw,Vd)=>{"use strict";var dy=ut(),py=Rd(),Ld=Kn(),hy=za(),fy=Jn(),my=Ha(),by=Qa(),Md=">",Cd="<",Zn="prototype",eo="script",Bd=by("IE_PROTO"),Xn=function(){},Od=function(a){return Cd+eo+Md+a+Cd+"/"+eo+Md},Dd=function(a){a.write(Od("")),a.close();var e=a.parentWindow.Object;return a=null,e},gy=function(){var a=my("iframe"),e="java"+eo+":",t;return a.style.display="none",fy.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Od("document.F=Object")),t.close(),t.F},es,ts=function(){try{es=new ActiveXObject("htmlfile")}catch(e){}ts=typeof document!="undefined"?document.domain&&es?Dd(es):gy():Dd(es);for(var a=Ld.length;a--;)delete ts[Zn][Ld[a]];return ts()};hy[Bd]=!0;Vd.exports=Object.create||function(e,t){var i;return e!==null?(Xn[Zn]=dy(e),i=new Xn,Xn[Zn]=null,i[Bd]=e):i=ts(),t===void 0?i:py.f(i,t)}});var Nd=b((Qw,_d)=>{"use strict";var Sy=Be();_d.exports=!Sy(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ro=b((zw,qd)=>{"use strict";var vy=tt(),yy=ce(),Ty=mr(),Iy=Qa(),Ey=Nd(),Fd=Iy("IE_PROTO"),io=Object,xy=io.prototype;qd.exports=Ey?io.getPrototypeOf:function(a){var e=Ty(a);if(vy(e,Fd))return e[Fd];var t=e.constructor;return yy(t)&&e instanceof t?t.prototype:e instanceof io?xy:null}});var $i=b((Kw,Ud)=>{"use strict";var Py=wi();Ud.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:Py(a,e,t),a}});var oo=b((Jw,Gd)=>{"use strict";var Ay=Be(),wy=ce(),ky=Ue(),Ry=to(),Hd=ro(),$y=$i(),Ly=Te(),My=et(),no=Ly("iterator"),jd=!1,yt,ao,so;[].keys&&(so=[].keys(),"next"in so?(ao=Hd(Hd(so)),ao!==Object.prototype&&(yt=ao)):jd=!0);var Cy=!ky(yt)||Ay(function(){var a={};return yt[no].call(a)!==a});Cy?yt={}:My&&(yt=Ry(yt));wy(yt[no])||$y(yt,no,function(){return this});Gd.exports={IteratorPrototype:yt,BUGGY_SAFARI_ITERATORS:jd}});var is=b((Xw,Yd)=>{"use strict";var Dy=Te(),By=Dy("toStringTag"),Wd={};Wd[By]="z";Yd.exports=String(Wd)==="[object z]"});var Tr=b((Zw,Qd)=>{"use strict";var Oy=is(),Vy=ce(),rs=Ii(),_y=Te(),Ny=_y("toStringTag"),Fy=Object,qy=rs(function(){return arguments}())==="Arguments",Uy=function(a,e){try{return a[e]}catch(t){}};Qd.exports=Oy?rs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=Uy(e=Fy(a),Ny))=="string"?t:qy?rs(e):(i=rs(e))==="Object"&&Vy(e.callee)?"Arguments":i}});var Kd=b((ek,zd)=>{"use strict";var Hy=is(),jy=Tr();zd.exports=Hy?{}.toString:function(){return"[object "+jy(this)+"]"}});var Ir=b((tk,Xd)=>{"use strict";var Gy=is(),Wy=Zt().f,Yy=wi(),Qy=tt(),zy=Kd(),Ky=Te(),Jd=Ky("toStringTag");Xd.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(Qy(r,Jd)||Wy(r,Jd,{configurable:!0,value:e}),i&&!Gy&&Yy(r,"toString",zy))}});var ep=b((ik,Zd)=>{"use strict";var Jy=oo().IteratorPrototype,Xy=to(),Zy=br(),eT=Ir(),tT=Xt(),iT=function(){return this};Zd.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=Xy(Jy,{next:Zy(+!i,t)}),eT(a,r,!1,!0),tT[r]=iT,a}});var ip=b((rk,tp)=>{"use strict";var rT=Ae(),aT=vt();tp.exports=function(a,e,t){try{return rT(aT(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var ap=b((ak,rp)=>{"use strict";var sT=Ue();rp.exports=function(a){return sT(a)||a===null}});var np=b((sk,sp)=>{"use strict";var nT=ap(),oT=String,uT=TypeError;sp.exports=function(a){if(nT(a))return a;throw new uT("Can't set "+oT(a)+" as a prototype")}});var uo=b((nk,op)=>{"use strict";var lT=ip(),cT=Ue(),dT=lr(),pT=np();op.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=lT(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return dT(r),pT(s),cT(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Sp=b((ok,gp)=>{"use strict";var hT=je(),fT=Oe(),as=et(),mp=cd(),mT=ce(),bT=ep(),up=ro(),lp=uo(),gT=Ir(),ST=wi(),lo=$i(),vT=Te(),cp=Xt(),bp=oo(),yT=mp.PROPER,TT=mp.CONFIGURABLE,dp=bp.IteratorPrototype,ss=bp.BUGGY_SAFARI_ITERATORS,Er=vT("iterator"),pp="keys",xr="values",hp="entries",fp=function(){return this};gp.exports=function(a,e,t,i,r,s,n){bT(t,e,i);var o=function(T){if(T===r&&p)return p;if(!ss&&T&&T in c)return c[T];switch(T){case pp:return function(){return new t(this,T)};case xr:return function(){return new t(this,T)};case hp:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Er]||c["@@iterator"]||r&&c[r],p=!ss&&d||o(r),h=e==="Array"&&c.entries||d,m,g,S;if(h&&(m=up(h.call(new a)),m!==Object.prototype&&m.next&&(!as&&up(m)!==dp&&(lp?lp(m,dp):mT(m[Er])||lo(m,Er,fp)),gT(m,u,!0,!0),as&&(cp[u]=fp))),yT&&r===xr&&d&&d.name!==xr&&(!as&&TT?ST(c,"name",xr):(l=!0,p=function(){return fT(d,this)})),r)if(g={values:o(xr),keys:s?p:o(pp),entries:o(hp)},n)for(S in g)(ss||l||!(S in c))&&lo(c,S,g[S]);else hT({target:e,proto:!0,forced:ss||l},g);return(!as||n)&&c[Er]!==p&&lo(c,Er,p,{name:r}),cp[e]=p,g}});var yp=b((uk,vp)=>{"use strict";vp.exports=function(a,e){return{value:a,done:e}}});var po=b((lk,Pp)=>{"use strict";var IT=xi(),co=bn(),Tp=Xt(),Ep=Hn(),ET=Zt().f,xT=Sp(),ns=yp(),PT=et(),AT=He(),xp="Array Iterator",wT=Ep.set,kT=Ep.getterFor(xp);Pp.exports=xT(Array,"Array",function(a,e){wT(this,{type:xp,target:IT(a),index:0,kind:e})},function(){var a=kT(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ns(void 0,!0);switch(a.kind){case"keys":return ns(t,!1);case"values":return ns(e[t],!1)}return ns([t,e[t]],!1)},"values");var Ip=Tp.Arguments=Tp.Array;co("keys");co("values");co("entries");if(!PT&&AT&&Ip.name!=="values")try{ET(Ip,"name",{value:"values"})}catch(a){}});var wp=b((ck,Ap)=>{"use strict";var RT=Te(),$T=Xt(),LT=RT("iterator"),MT=Array.prototype;Ap.exports=function(a){return a!==void 0&&($T.Array===a||MT[LT]===a)}});var ho=b((dk,Rp)=>{"use strict";var CT=Tr(),kp=hr(),DT=Ei(),BT=Xt(),OT=Te(),VT=OT("iterator");Rp.exports=function(a){if(!DT(a))return kp(a,VT)||kp(a,"@@iterator")||BT[CT(a)]}});var Lp=b((pk,$p)=>{"use strict";var _T=Oe(),NT=vt(),FT=ut(),qT=pr(),UT=ho(),HT=TypeError;$p.exports=function(a,e){var t=arguments.length<2?UT(a):e;if(NT(t))return FT(_T(t,a));throw new HT(qT(a)+" is not iterable")}});var Dp=b((hk,Cp)=>{"use strict";var jT=Oe(),Mp=ut(),GT=hr();Cp.exports=function(a,e,t){var i,r;Mp(a);try{if(i=GT(a,"return"),!i){if(e==="throw")throw t;return t}i=jT(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Mp(i),t}});var us=b((fk,_p)=>{"use strict";var WT=vr(),YT=Oe(),QT=ut(),zT=pr(),KT=wp(),JT=Za(),Bp=dr(),XT=Lp(),ZT=ho(),Op=Dp(),eI=TypeError,os=function(a,e){this.stopped=a,this.result=e},Vp=os.prototype;_p.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=WT(e,i),l,c,d,p,h,m,g,S=function(P){return l&&Op(l,"normal",P),new os(!0,P)},T=function(P){return r?(QT(P),o?u(P[0],P[1],S):u(P[0],P[1])):o?u(P,S):u(P)};if(s)l=a.iterator;else if(n)l=a;else{if(c=ZT(a),!c)throw new eI(zT(a)+" is not iterable");if(KT(c)){for(d=0,p=JT(a);p>d;d++)if(h=T(a[d]),h&&Bp(Vp,h))return h;return new os(!1)}l=XT(a,c)}for(m=s?a.next:l.next;!(g=YT(m,l)).done;){try{h=T(g.value)}catch(P){Op(l,"throw",P)}if(typeof h=="object"&&h&&Bp(Vp,h))return h}return new os(!1)}});var Fp=b((mk,Np)=>{"use strict";var tI=He(),iI=Zt(),rI=br();Np.exports=function(a,e,t){tI?iI.f(a,e,rI(0,t)):a[e]=t}});var qp=b(()=>{"use strict";var aI=je(),sI=us(),nI=Fp();aI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return sI(e,function(i,r){nI(t,i,r)},{AS_ENTRIES:!0}),t}})});var Hp=b((Sk,Up)=>{"use strict";po();qp();var oI=Ga();Up.exports=oI.Object.fromEntries});var Gp=b((vk,jp)=>{"use strict";jp.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 Yp=b(()=>{"use strict";po();var uI=Gp(),lI=de(),cI=Ir(),Wp=Xt();for(ls in uI)cI(lI[ls],ls),Wp[ls]=Wp.Array;var ls});var zp=b((Ik,Qp)=>{"use strict";var dI=Hp();Yp();Qp.exports=dI});var fo=b((Ek,Kp)=>{"use strict";var pI=zp();Kp.exports=pI});var Jp=b(()=>{"use strict"});var mo=b((Ak,Xp)=>{"use strict";var Pr=de(),hI=Pi(),fI=Ii(),cs=function(a){return hI.slice(0,a.length)===a};Xp.exports=function(){return cs("Bun/")?"BUN":cs("Cloudflare-Workers")?"CLOUDFLARE":cs("Deno/")?"DENO":cs("Node.js/")?"NODE":Pr.Bun&&typeof Bun.version=="string"?"BUN":Pr.Deno&&typeof Deno.version=="object"?"DENO":fI(Pr.process)==="process"?"NODE":Pr.window&&Pr.document?"BROWSER":"REST"}()});var ds=b((wk,Zp)=>{"use strict";var mI=mo();Zp.exports=mI==="NODE"});var th=b((kk,eh)=>{"use strict";var bI=Zt();eh.exports=function(a,e,t){return bI.f(a,e,t)}});var ah=b((Rk,rh)=>{"use strict";var gI=St(),SI=th(),vI=Te(),yI=He(),ih=vI("species");rh.exports=function(a){var e=gI(a);yI&&e&&!e[ih]&&SI(e,ih,{configurable:!0,get:function(){return this}})}});var nh=b(($k,sh)=>{"use strict";var TI=dr(),II=TypeError;sh.exports=function(a,e){if(TI(e,a))return a;throw new II("Incorrect invocation")}});var go=b((Lk,oh)=>{"use strict";var EI=Ae(),xI=ce(),bo=fr(),PI=EI(Function.toString);xI(bo.inspectSource)||(bo.inspectSource=function(a){return PI(a)});oh.exports=bo.inspectSource});var hh=b((Mk,ph)=>{"use strict";var AI=Ae(),wI=Be(),uh=ce(),kI=Tr(),RI=St(),$I=go(),lh=function(){},ch=RI("Reflect","construct"),So=/^\s*(?:class|function)\b/,LI=AI(So.exec),MI=!So.test(lh),Ar=function(e){if(!uh(e))return!1;try{return ch(lh,[],e),!0}catch(t){return!1}},dh=function(e){if(!uh(e))return!1;switch(kI(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return MI||!!LI(So,$I(e))}catch(t){return!0}};dh.sham=!0;ph.exports=!ch||wI(function(){var a;return Ar(Ar.call)||!Ar(Object)||!Ar(function(){a=!0})||a})?dh:Ar});var mh=b((Ck,fh)=>{"use strict";var CI=hh(),DI=pr(),BI=TypeError;fh.exports=function(a){if(CI(a))return a;throw new BI(DI(a)+" is not a constructor")}});var vo=b((Dk,gh)=>{"use strict";var bh=ut(),OI=mh(),VI=Ei(),_I=Te(),NI=_I("species");gh.exports=function(a,e){var t=bh(a).constructor,i;return t===void 0||VI(i=bh(t)[NI])?e:OI(i)}});var vh=b((Bk,Sh)=>{"use strict";var FI=Ae();Sh.exports=FI([].slice)});var Th=b((Ok,yh)=>{"use strict";var qI=TypeError;yh.exports=function(a,e){if(a<e)throw new qI("Not enough arguments");return a}});var yo=b((Vk,Ih)=>{"use strict";var UI=Pi();Ih.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(UI)});var Ro=b((_k,Lh)=>{"use strict";var Ve=de(),HI=jn(),jI=vr(),Eh=ce(),GI=tt(),$h=Be(),xh=Jn(),WI=vh(),Ph=Ha(),YI=Th(),QI=yo(),zI=ds(),Ao=Ve.setImmediate,wo=Ve.clearImmediate,KI=Ve.process,To=Ve.Dispatch,JI=Ve.Function,Ah=Ve.MessageChannel,XI=Ve.String,Io=0,wr={},wh="onreadystatechange",kr,ti,Eo,xo;$h(function(){kr=Ve.location});var ko=function(a){if(GI(wr,a)){var e=wr[a];delete wr[a],e()}},Po=function(a){return function(){ko(a)}},kh=function(a){ko(a.data)},Rh=function(a){Ve.postMessage(XI(a),kr.protocol+"//"+kr.host)};(!Ao||!wo)&&(Ao=function(e){YI(arguments.length,1);var t=Eh(e)?e:JI(e),i=WI(arguments,1);return wr[++Io]=function(){HI(t,void 0,i)},ti(Io),Io},wo=function(e){delete wr[e]},zI?ti=function(a){KI.nextTick(Po(a))}:To&&To.now?ti=function(a){To.now(Po(a))}:Ah&&!QI?(Eo=new Ah,xo=Eo.port2,Eo.port1.onmessage=kh,ti=jI(xo.postMessage,xo)):Ve.addEventListener&&Eh(Ve.postMessage)&&!Ve.importScripts&&kr&&kr.protocol!=="file:"&&!$h(Rh)?(ti=Rh,Ve.addEventListener("message",kh,!1)):wh in Ph("script")?ti=function(a){xh.appendChild(Ph("script"))[wh]=function(){xh.removeChild(this),ko(a)}}:ti=function(a){setTimeout(Po(a),0)});Lh.exports={set:Ao,clear:wo}});var Dh=b((Nk,Ch)=>{"use strict";var Mh=de(),ZI=He(),eE=Object.getOwnPropertyDescriptor;Ch.exports=function(a){if(!ZI)return Mh[a];var e=eE(Mh,a);return e&&e.value}});var $o=b((Fk,Oh)=>{"use strict";var Bh=function(){this.head=null,this.tail=null};Bh.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}}};Oh.exports=Bh});var _h=b((qk,Vh)=>{"use strict";var tE=Pi();Vh.exports=/ipad|iphone|ipod/i.test(tE)&&typeof Pebble!="undefined"});var Fh=b((Uk,Nh)=>{"use strict";var iE=Pi();Nh.exports=/web0s(?!.*chrome)/i.test(iE)});var Yh=b((Hk,Wh)=>{"use strict";var Mi=de(),rE=Dh(),qh=vr(),Lo=Ro().set,aE=$o(),sE=yo(),nE=_h(),oE=Fh(),Mo=ds(),Uh=Mi.MutationObserver||Mi.WebKitMutationObserver,Hh=Mi.document,jh=Mi.process,ps=Mi.Promise,Bo=rE("queueMicrotask"),Li,Co,Do,hs,Gh;Bo||(Rr=new aE,$r=function(){var a,e;for(Mo&&(a=jh.domain)&&a.exit();e=Rr.get();)try{e()}catch(t){throw Rr.head&&Li(),t}a&&a.enter()},!sE&&!Mo&&!oE&&Uh&&Hh?(Co=!0,Do=Hh.createTextNode(""),new Uh($r).observe(Do,{characterData:!0}),Li=function(){Do.data=Co=!Co}):!nE&&ps&&ps.resolve?(hs=ps.resolve(void 0),hs.constructor=ps,Gh=qh(hs.then,hs),Li=function(){Gh($r)}):Mo?Li=function(){jh.nextTick($r)}:(Lo=qh(Lo,Mi),Li=function(){Lo($r)}),Bo=function(a){Rr.head||Li(),Rr.add(a)});var Rr,$r;Wh.exports=Bo});var zh=b((jk,Qh)=>{"use strict";Qh.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var fs=b((Gk,Kh)=>{"use strict";Kh.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ii=b((Wk,Jh)=>{"use strict";var uE=de();Jh.exports=uE.Promise});var Ci=b((Yk,tf)=>{"use strict";var lE=de(),Lr=ii(),cE=ce(),dE=Wn(),pE=go(),hE=Te(),Xh=mo(),fE=et(),Oo=Pn(),Zh=Lr&&Lr.prototype,mE=hE("species"),Vo=!1,ef=cE(lE.PromiseRejectionEvent),bE=dE("Promise",function(){var a=pE(Lr),e=a!==String(Lr);if(!e&&Oo===66||fE&&!(Zh.catch&&Zh.finally))return!0;if(!Oo||Oo<51||!/native code/.test(a)){var t=new Lr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[mE]=i,Vo=t.then(function(){})instanceof i,!Vo)return!0}return!e&&(Xh==="BROWSER"||Xh==="DENO")&&!ef});tf.exports={CONSTRUCTOR:bE,REJECTION_EVENT:ef,SUBCLASSING:Vo}});var Di=b((Qk,af)=>{"use strict";var rf=vt(),gE=TypeError,SE=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new gE("Bad Promise constructor");e=i,t=r}),this.resolve=rf(e),this.reject=rf(t)};af.exports.f=function(a){return new SE(a)}});var Ef=b(()=>{"use strict";var vE=je(),yE=et(),Ss=ds(),Nt=de(),_i=Oe(),sf=$i(),nf=uo(),TE=Ir(),IE=ah(),EE=vt(),gs=ce(),xE=Ue(),PE=nh(),AE=vo(),df=Ro().set,Uo=Yh(),wE=zh(),kE=fs(),RE=$o(),pf=Hn(),vs=ii(),Ho=Ci(),hf=Di(),ys="Promise",ff=Ho.CONSTRUCTOR,$E=Ho.REJECTION_EVENT,LE=Ho.SUBCLASSING,_o=pf.getterFor(ys),ME=pf.set,Bi=vs&&vs.prototype,ri=vs,ms=Bi,mf=Nt.TypeError,No=Nt.document,jo=Nt.process,Fo=hf.f,CE=Fo,DE=!!(No&&No.createEvent&&Nt.dispatchEvent),bf="unhandledrejection",BE="rejectionhandled",of=0,gf=1,OE=2,Go=1,Sf=2,bs,uf,VE,lf,vf=function(a){var e;return xE(a)&&gs(e=a.then)?e:!1},yf=function(a,e){var t=e.value,i=e.state===gf,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===Sf&&NE(e),e.rejection=Go),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new mf("Promise-chain cycle")):(l=vf(u))?_i(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Tf=function(a,e){a.notified||(a.notified=!0,Uo(function(){for(var t=a.reactions,i;i=t.get();)yf(i,a);a.notified=!1,e&&!a.rejection&&_E(a)}))},If=function(a,e,t){var i,r;DE?(i=No.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Nt.dispatchEvent(i)):i={promise:e,reason:t},!$E&&(r=Nt["on"+a])?r(i):a===bf&&wE("Unhandled promise rejection",t)},_E=function(a){_i(df,Nt,function(){var e=a.facade,t=a.value,i=cf(a),r;if(i&&(r=kE(function(){Ss?jo.emit("unhandledRejection",t,e):If(bf,e,t)}),a.rejection=Ss||cf(a)?Sf:Go,r.error))throw r.value})},cf=function(a){return a.rejection!==Go&&!a.parent},NE=function(a){_i(df,Nt,function(){var e=a.facade;Ss?jo.emit("rejectionHandled",e):If(BE,e,a.value)})},Oi=function(a,e,t){return function(i){a(e,i,t)}},Vi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=OE,Tf(a,!0))},qo=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new mf("Promise can't be resolved itself");var i=vf(e);i?Uo(function(){var r={done:!1};try{_i(i,e,Oi(qo,r,a),Oi(Vi,r,a))}catch(s){Vi(r,s,a)}}):(a.value=e,a.state=gf,Tf(a,!1))}catch(r){Vi({done:!1},r,a)}}};if(ff&&(ri=function(e){PE(this,ms),EE(e),_i(bs,this);var t=_o(this);try{e(Oi(qo,t),Oi(Vi,t))}catch(i){Vi(t,i)}},ms=ri.prototype,bs=function(e){ME(this,{type:ys,done:!1,notified:!1,parent:!1,reactions:new RE,rejection:!1,state:of,value:void 0})},bs.prototype=sf(ms,"then",function(e,t){var i=_o(this),r=Fo(AE(this,ri));return i.parent=!0,r.ok=gs(e)?e:!0,r.fail=gs(t)&&t,r.domain=Ss?jo.domain:void 0,i.state===of?i.reactions.add(r):Uo(function(){yf(r,i)}),r.promise}),uf=function(){var a=new bs,e=_o(a);this.promise=a,this.resolve=Oi(qo,e),this.reject=Oi(Vi,e)},hf.f=Fo=function(a){return a===ri||a===VE?new uf(a):CE(a)},!yE&&gs(vs)&&Bi!==Object.prototype)){lf=Bi.then,LE||sf(Bi,"then",function(e,t){var i=this;return new ri(function(r,s){_i(lf,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Bi.constructor}catch(a){}nf&&nf(Bi,ms)}vE({global:!0,constructor:!0,wrap:!0,forced:ff},{Promise:ri});TE(ri,ys,!1,!0);IE(ys)});var kf=b((Jk,wf)=>{"use strict";var FE=Te(),Pf=FE("iterator"),Af=!1;try{xf=0,Wo={next:function(){return{done:!!xf++}},return:function(){Af=!0}},Wo[Pf]=function(){return this},Array.from(Wo,function(){throw 2})}catch(a){}var xf,Wo;wf.exports=function(a,e){try{if(!e&&!Af)return!1}catch(r){return!1}var t=!1;try{var i={};i[Pf]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Yo=b((Xk,Rf)=>{"use strict";var qE=ii(),UE=kf(),HE=Ci().CONSTRUCTOR;Rf.exports=HE||!UE(function(a){qE.all(a).then(void 0,function(){})})});var $f=b(()=>{"use strict";var jE=je(),GE=Oe(),WE=vt(),YE=Di(),QE=fs(),zE=us(),KE=Yo();jE({target:"Promise",stat:!0,forced:KE},{all:function(e){var t=this,i=YE.f(t),r=i.resolve,s=i.reject,n=QE(function(){var o=WE(t.resolve),u=[],l=0,c=1;zE(e,function(d){var p=l++,h=!1;c++,GE(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var Mf=b(()=>{"use strict";var JE=je(),XE=et(),ZE=Ci().CONSTRUCTOR,zo=ii(),ex=St(),tx=ce(),ix=$i(),Lf=zo&&zo.prototype;JE({target:"Promise",proto:!0,forced:ZE,real:!0},{catch:function(a){return this.then(void 0,a)}});!XE&&tx(zo)&&(Qo=ex("Promise").prototype.catch,Lf.catch!==Qo&&ix(Lf,"catch",Qo,{unsafe:!0}));var Qo});var Cf=b(()=>{"use strict";var rx=je(),ax=Oe(),sx=vt(),nx=Di(),ox=fs(),ux=us(),lx=Yo();rx({target:"Promise",stat:!0,forced:lx},{race:function(e){var t=this,i=nx.f(t),r=i.reject,s=ox(function(){var n=sx(t.resolve);ux(e,function(o){ax(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Df=b(()=>{"use strict";var cx=je(),dx=Di(),px=Ci().CONSTRUCTOR;cx({target:"Promise",stat:!0,forced:px},{reject:function(e){var t=dx.f(this),i=t.reject;return i(e),t.promise}})});var Ko=b((oR,Bf)=>{"use strict";var hx=ut(),fx=Ue(),mx=Di();Bf.exports=function(a,e){if(hx(a),fx(e)&&e.constructor===a)return e;var t=mx.f(a),i=t.resolve;return i(e),t.promise}});var _f=b(()=>{"use strict";var bx=je(),gx=St(),Of=et(),Sx=ii(),Vf=Ci().CONSTRUCTOR,vx=Ko(),yx=gx("Promise"),Tx=Of&&!Vf;bx({target:"Promise",stat:!0,forced:Of||Vf},{resolve:function(e){return vx(Tx&&this===yx?Sx:this,e)}})});var Nf=b(()=>{"use strict";Ef();$f();Mf();Cf();Df();_f()});var Hf=b(()=>{"use strict";var Ix=je(),Ex=et(),Ts=ii(),xx=Be(),qf=St(),Uf=ce(),Px=vo(),Ff=Ko(),Ax=$i(),Xo=Ts&&Ts.prototype,wx=!!Ts&&xx(function(){Xo.finally.call({then:function(){}},function(){})});Ix({target:"Promise",proto:!0,real:!0,forced:wx},{finally:function(a){var e=Px(this,qf("Promise")),t=Uf(a);return this.then(t?function(i){return Ff(e,a()).then(function(){return i})}:a,t?function(i){return Ff(e,a()).then(function(){throw i})}:a)}});!Ex&&Uf(Ts)&&(Jo=qf("Promise").prototype.finally,Xo.finally!==Jo&&Ax(Xo,"finally",Jo,{unsafe:!0}));var Jo});var Is=b((fR,jf)=>{"use strict";var kx=St();jf.exports=kx});var Wf=b((mR,Gf)=>{"use strict";Jp();Nf();Hf();var Rx=Is();Gf.exports=Rx("Promise","finally")});var Qf=b((bR,Yf)=>{"use strict";var $x=Wf();Yf.exports=$x});var Es=b((gR,zf)=>{"use strict";var Lx=Qf();zf.exports=Lx});var sm=b(()=>{"use strict";var Nx=je(),Fx=mr(),qx=Za(),Ux=Xa(),Hx=bn();Nx({target:"Array",proto:!0},{at:function(e){var t=Fx(this),i=qx(t),r=Ux(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});Hx("at")});var om=b((m$,nm)=>{"use strict";sm();var jx=Is();nm.exports=jx("Array","at")});var lm=b((b$,um)=>{"use strict";var Gx=om();um.exports=Gx});var Cr=b((g$,cm)=>{"use strict";var Wx=lm();cm.exports=Wx});var tb=b(()=>{"use strict"});var ib=b(()=>{"use strict"});var ab=b((pD,rb)=>{"use strict";var AP=Ue(),wP=Ii(),kP=Te(),RP=kP("match");rb.exports=function(a){var e;return AP(a)&&((e=a[RP])!==void 0?!!e:wP(a)==="RegExp")}});var nb=b((hD,sb)=>{"use strict";var $P=Tr(),LP=String;sb.exports=function(a){if($P(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return LP(a)}});var ub=b((fD,ob)=>{"use strict";var MP=ut();ob.exports=function(){var a=MP(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 db=b((mD,cb)=>{"use strict";var CP=Oe(),DP=tt(),BP=dr(),OP=ub(),lb=RegExp.prototype;cb.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in lb)&&!DP(a,"flags")&&BP(lb,a)?CP(OP,a):e}});var hb=b((bD,pb)=>{"use strict";var Tu=Ae(),VP=mr(),_P=Math.floor,vu=Tu("".charAt),NP=Tu("".replace),yu=Tu("".slice),FP=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qP=/\$([$&'`]|\d{1,2})/g;pb.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=qP;return r!==void 0&&(r=VP(r),u=FP),NP(s,u,function(l,c){var d;switch(vu(c,0)){case"$":return"$";case"&":return a;case"`":return yu(e,0,t);case"'":return yu(e,n);case"<":d=r[yu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=_P(p/10);return h===0?l:h<=o?i[h-1]===void 0?vu(c,1):i[h-1]+vu(c,1):l}d=i[p-1]}return d===void 0?"":d})}});var bb=b(()=>{"use strict";var UP=je(),HP=Oe(),Eu=Ae(),fb=lr(),jP=ce(),GP=Ei(),WP=ab(),Qi=nb(),YP=hr(),QP=db(),zP=hb(),KP=Te(),JP=et(),XP=KP("replace"),ZP=TypeError,Iu=Eu("".indexOf),eA=Eu("".replace),mb=Eu("".slice),tA=Math.max;UP({target:"String",proto:!0},{replaceAll:function(e,t){var i=fb(this),r,s,n,o,u,l,c,d,p,h,m=0,g="";if(!GP(e)){if(r=WP(e),r&&(s=Qi(fb(QP(e))),!~Iu(s,"g")))throw new ZP("`.replaceAll` does not allow non-global regexes");if(n=YP(e,XP),n)return HP(n,e,i,t);if(JP&&r)return eA(Qi(i),e,t)}for(o=Qi(i),u=Qi(e),l=jP(t),l||(t=Qi(t)),c=u.length,d=tA(1,c),p=Iu(o,u);p!==-1;)h=l?Qi(t(u,p,o)):zP(u,o,p,[],void 0,t),g+=mb(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Iu(o,u,p+d);return m<o.length&&(g+=mb(o,m)),g}})});var Sb=b((vD,gb)=>{"use strict";tb();ib();bb();var iA=Is();gb.exports=iA("String","replaceAll")});var yb=b((yD,vb)=>{"use strict";var rA=Sb();vb.exports=rA});var Ib=b((TD,Tb)=>{"use strict";var aA=yb();Tb.exports=aA});var TA={};Tg(TA,{ChromecastState:()=>or,HttpConnectionType:()=>Fa,Observable:()=>mt.Observable,PlaybackState:()=>ye,Player:()=>Ra,SDK_VERSION:()=>yA,Subject:()=>mt.Subject,Subscription:()=>mt.Subscription,Surface:()=>qa,VERSION:()=>hn,ValueSubject:()=>mt.ValueSubject,VideoFormat:()=>gt,VideoQuality:()=>mt.VideoQuality});module.exports=Ig(TA);var hn="2.0.113-dev.53b63d90.0";var ye=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ye||{}),gt=(I=>(I.MPEG="MPEG",I.DASH="DASH",I.DASH_SEP="DASH_SEP",I.DASH_SEP_VK="DASH_SEP",I.DASH_WEBM="DASH_WEBM",I.DASH_WEBM_AV1="DASH_WEBM_AV1",I.DASH_STREAMS="DASH_STREAMS",I.DASH_WEBM_VK="DASH_WEBM",I.DASH_ONDEMAND="DASH_ONDEMAND",I.DASH_ONDEMAND_VK="DASH_ONDEMAND",I.DASH_LIVE="DASH_LIVE",I.DASH_LIVE_CMAF="DASH_LIVE_CMAF",I.DASH_LIVE_WEBM="DASH_LIVE_WEBM",I.HLS="HLS",I.HLS_ONDEMAND="HLS_ONDEMAND",I.HLS_JS="HLS",I.HLS_LIVE="HLS_LIVE",I.HLS_LIVE_CMAF="HLS_LIVE_CMAF",I.WEB_RTC_LIVE="WEB_RTC_LIVE",I))(gt||{});var or=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(or||{}),Fa=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Fa||{});var qa=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(qa||{});var q=require("@vkontakte/videoplayer-shared");var yl=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Ua=class{constructor(e){this.connection$=new q.ValueSubject(void 0);this.castState$=new q.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new q.Subject;this.realCastState$=new q.ValueSubject("NOT_AVAILABLE");this.subscription=new q.Subscription;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=(0,q.isNonNullable)((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},r||yl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:q.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 i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,q.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,q.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,q.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add((0,q.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.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,q.assertNever)(r.sessionState)}})).add((0,q.merge)((0,q.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,q.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,q.map)(r=>r.castState)),(0,q.observableFrom)([i.getCastState()])).pipe((0,q.filterChanged)(),(0,q.map)(Eg),(0,q.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=(0,q.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();(0,q.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,q.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(r==="CONNECTED"?(0,q.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:q.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Eg=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,q.assertNever)(a)}};var Hb=Xe(fo(),1);var Zf=Xe(Es(),1);var Zo=require("@vkontakte/videoplayer-shared");var Se=(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 i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Zo.assertNever)(t)}return a},eu=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Zo.assertNever)(e)}};var w=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var lt=require("@vkontakte/videoplayer-shared"),W=class{constructor(e){this.transitionStarted$=new lt.Subject;this.transitionEnded$=new lt.Subject;this.transitionUpdated$=new lt.Subject;this.forceChanged$=new lt.Subject;this.stateChangeStarted$=(0,lt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,lt.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,lt.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Kf=require("@vkontakte/videoplayer-shared"),Jf=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,Kf.assertNever)(a)}};var L=require("@vkontakte/videoplayer-shared");var Mx=5,Cx=5,Dx=500,Xf=7e3,Mr=class{constructor(e){this.subscription=new L.Subscription;this.loadMediaTimeoutSubscription=new L.Subscription;this.videoState=new W("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,L.assertNever)(e)}break}default:(0,L.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Jf(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new L.Subscription;this.subscription.add(e),this.subscription.add((0,L.merge)(this.videoState.stateChangeStarted$.pipe((0,L.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,L.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new L.Subject;e.add(r.pipe((0,L.debounce)(Dx)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>Mx)&&r.next(o),s=o})),e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.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<Cx&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,L.assertNever)(n)}}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,L.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,L.observableFrom)(["init"])).pipe((0,L.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),w(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&w(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];(0,L.assertNonNullable)(c);let d=(0,L.getHighestQuality)(Object.keys(c));(0,L.assertNonNullable)(d);let p=c[d];(0,L.assertNonNullable)(p),i=p,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,L.assertNonNullable)(c),i=c.url,r="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,L.assertNonNullable)(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,L.assertNonNullable)(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,L.assertNonNullable)(c),i=Se(c.url),r="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:L.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,L.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,L.isNonNullable)(o)&&(n.metadata.title=o),(0,L.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add((0,L.timeout)(Xf).subscribe(()=>s(`timeout(${Xf})`)))});(0,Zf.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var au=require("@vkontakte/videoplayer-shared");var em=require("@vkontakte/videoplayer-shared"),tm=a=>{try{a.pause(),a.playbackRate=0,(0,em.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var xs=require("@vkontakte/videoplayer-shared"),tu=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)}},iu=window.WeakMap?new WeakMap:new tu,ru=window.WeakMap?new WeakMap:new Map,Bx=(a,e=20)=>{let t=0;return(0,xs.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},we=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),i=!!t;t?(0,au.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),iu.set(t,i);let r=new xs.Subscription;return r.add(Bx(t,e)),ru.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ke=a=>{let e=ru.get(a);e==null||e.unsubscribe(),ru.delete(a);let t=iu.get(a);iu.delete(a),t?(0,au.clearVideoElement)(a):tm(a)};var M=require("@vkontakte/videoplayer-shared");var Ft=require("@vkontakte/videoplayer-shared"),Ps=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Ft.isNullable)(r),l=new Ft.Subscription;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ct=(a,e,t)=>Ps(e,()=>a.loop,i=>{(0,Ft.isNonNullable)(i)&&(a.loop=i)},{onError:t}),Re=(a,e,t,i)=>Ps(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,Ft.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ge=(a,e,t,i)=>Ps(e,()=>a.playbackRate,r=>{(0,Ft.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),qt=Ps;var Ox=a=>["__",a.language,a.label].join("|"),Vx=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},su=class a{constructor(){this.available$=new M.Subject;this.current$=new M.ValueSubject(void 0);this.error$=new M.Subject;this.subscription=new M.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:M.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(qt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{(0,M.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,M.isNonNullable)(s)&&(0,M.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,M.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(qt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{(0,M.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,M.isNonNullable)(s)&&(0,M.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,M.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(qt(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:r})),this.subscription.add(qt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,M.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,M.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,M.merge)((0,M.fromEvent)(e,"addtrack"),(0,M.fromEvent)(e,"removetrack"),(0,M.observableFrom)(["init"])).pipe((0,M.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,M.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,M.merge)((0,M.fromEvent)(e,"change"),(0,M.observableFrom)(["init"])).pipe((0,M.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,M.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,M.filterChanged)()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add((0,M.fromEvent)(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=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",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,M.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,M.isNonNullable)(t.align)&&(r.align=t.align),(0,M.isNonNullable)(t.position)&&(r.position=t.position),(0,M.isNonNullable)(t.size)&&(r.size=t.size),(0,M.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,M.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:i}=e,r=e.id?e.id:Ox(e),s=this.externalTracks.has(r),n=r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(o=this.externalTracks.get(r))==null?void 0:o.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(u=this.internalTracks.get(r))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,M.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,M.isNullable)(e)||!Vx(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,M.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,M.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},dt=su;var It=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 im=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},nu=a=>{let e=im(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},rm=a=>{let e=im(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var D=require("@vkontakte/videoplayer-shared");var _x=3,am=(a,e,t=_x)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var $e=a=>{let e=I=>(0,D.fromEvent)(a,I).pipe((0,D.mapTo)(void 0)),i=(0,D.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>(0,D.fromEvent)(a,I))).pipe((0,D.map)(I=>I.type==="ended"?a.readyState<2:a.readyState<3),(0,D.filterChanged)()),r=(0,D.merge)((0,D.fromEvent)(a,"progress"),(0,D.fromEvent)(a,"timeupdate")).pipe((0,D.map)(()=>am(a.buffered,a.currentTime))),s=D.clientChecker.isSafari?(0,D.combine)({play:e("play").pipe((0,D.once)()),playing:e("playing")}).pipe((0,D.mapTo)(void 0)):e("playing"),n=(0,D.fromEvent)(a,"volumechange").pipe((0,D.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,D.fromEvent)(a,"ratechange").pipe((0,D.map)(()=>a.playbackRate)),u=(0,D.fromEvent)(a,"error").pipe((0,D.filter)(()=>!!(a.error||a.played.length)),(0,D.map)(()=>{var E;let I=a.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:D.ErrorCategory.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=(0,D.fromEvent)(a,"timeupdate").pipe((0,D.map)(()=>a.currentTime)),c=new D.Subject,d=.3,p;l.subscribe(I=>{a.loop&&(0,D.isNonNullable)(p)&&(0,D.isNonNullable)(I)&&p>=a.duration-d&&I<=d&&c.next(p),p=I});let h=e("pause").pipe((0,D.filter)(()=>!a.error&&p!==a.duration)),m=(0,D.fromEvent)(a,"enterpictureinpicture"),g=(0,D.fromEvent)(a,"leavepictureinpicture"),S=new D.ValueSubject(rm(a));m.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let T=new D.ValueSubject(nu(a));return(0,D.fromEvent)(a,"fullscreenchange").pipe((0,D.map)(()=>nu(a))).subscribe(T),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,D.fromEvent)(a,"durationchange").pipe((0,D.map)(()=>a.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:T}};var Et=require("@vkontakte/videoplayer-shared"),Ut=a=>{switch(a){case"mobile":return Et.VideoQuality.Q_144P;case"lowest":return Et.VideoQuality.Q_240P;case"low":return Et.VideoQuality.Q_360P;case"sd":case"medium":return Et.VideoQuality.Q_480P;case"hd":case"high":return Et.VideoQuality.Q_720P;case"fullhd":case"full":return Et.VideoQuality.Q_1080P;case"quadhd":case"quad":return Et.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Et.VideoQuality.Q_2160P}};var ai=Xe(Cr(),1),O=require("@vkontakte/videoplayer-shared");var ou=!1,xt={},dm=a=>{ou=a},pm=()=>{xt={}},hm=a=>{a(xt)},Dr=(a,e)=>{var t;ou&&(xt.meta=(t=xt.meta)!=null?t:{},xt.meta[a]=e)},Ie=class{constructor(e){this.name=e}next(e){var i,r;if(!ou)return;xt.series=(i=xt.series)!=null?i:{};let t=(r=xt.series[this.name])!=null?r:[];t.push([Date.now(),e]),xt.series[this.name]=t}};var Yx=new Ie("best_bitrate"),mm=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var uu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Br=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,O.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},bm='Assertion "ABR Tracks is empty array" failed',As=(a,e,t,i)=>{var u;let r=[...e].sort(uu(1)),s=[...t].sort(uu(1)),n=s.filter(l=>(0,O.isNonNullable)(l.bitrate)&&(0,O.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,ai.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,ai.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,ai.default)(n,-1):(0,ai.default)(s,0)},fm=a=>"quality"in a,gm=(a,e,t,i)=>{let r=t&&i&&i.history[t.id]&&(0,O.now)()-i.history[t.id]<=a.trackCooldown&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!r&&i.recordSelection(t),r&&(i!=null&&i.last)){let s=i.last;i==null||i.recordSwitch(s);let n=fm(s)?"video":"audio",o=fm(s)?s.quality:s.bitrate;return e({message:`
|
|
7
7
|
[last ${n} selected] ${o}
|
|
8
|
-
`}),s}return
|
|
8
|
+
`}),s}return i==null||i.recordSwitch(t),t},Ht=(a,{container:e,throughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,abrLogger:p})=>{var ie,Z,F,ee,K;(0,O.assertNotEmptyArray)(a,bm);let h=i.usePixelRatio&&(ie=window.devicePixelRatio)!=null?ie:1,m=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*h*i.containerSizeFactor,height:e.height*h*i.containerSizeFactor},g=m&&(0,O.videoSizeToQuality)(m),S=i.considerPlaybackRate&&(0,O.isNonNullable)(o)?o:1,T=a.filter(C=>!(0,O.isInvariantQuality)(C.quality)).sort((C,k)=>(0,O.isHigher)(C.quality,k.quality)?-1:1),P=(Z=(0,ai.default)(T,-1))==null?void 0:Z.quality,I=(F=(0,ai.default)(T,0))==null?void 0:F.quality,E=(0,O.isNullable)(r)||(0,O.isNonNullable)(r.min)&&(0,O.isNonNullable)(r.max)&&(0,O.isLower)(r.max,r.min)||(0,O.isNonNullable)(r.min)&&I&&(0,O.isHigher)(r.min,I)||(0,O.isNonNullable)(r.max)&&P&&(0,O.isLower)(r.max,P),A=S*mm(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),B={},H=T.filter(C=>{if(!(g?(0,O.isLower)(C.quality,g):!0))return B[C.quality]="FitsContainer",!1;if(!((0,O.isNonNullable)(t)&&isFinite(t)&&(0,O.isNonNullable)(C.bitrate)?t-s>=C.bitrate*A:!0))return B[C.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,O.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,O.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,O.isHigher)(C.quality,u.quality))return B[C.quality]="Buffer",!1;if(!!d&&(0,O.isHigherOrEqual)(C.quality,d))return B[C.quality]="DroppedFramesLimit",!1;let he=E||((0,O.isNullable)(r.max)||(0,O.isLowerOrEqual)(C.quality,r.max))&&((0,O.isNullable)(r.min)||(0,O.isHigherOrEqual)(C.quality,r.min)),Ee=(0,O.isNonNullable)(c)&&!c?(0,O.isLowerOrEqual)(C.quality,i.backgroundVideoQualityLimit):!0;return!he||!Ee?(B[C.quality]="FitsQualityLimits",!1):!0})[0];H&&H.bitrate&&Yx.next(H.bitrate);let Q=(ee=H!=null?H:T[Math.ceil((T.length-1)/2)])!=null?ee:a[0];return Q.quality!==((K=l==null?void 0:l.last)==null?void 0:K.quality)&&p({message:`
|
|
9
9
|
[VIDEO TRACKS ABR]
|
|
10
10
|
[available video tracks]
|
|
11
|
-
${a.map(
|
|
11
|
+
${a.map(C=>`{ id: ${C.id}, quality: ${C.quality}, bitrate: ${C.bitrate} }`).join(`
|
|
12
12
|
`)}
|
|
13
13
|
|
|
14
14
|
[tuning]
|
|
15
|
-
${Object.entries(
|
|
15
|
+
${Object.entries(i!=null?i:{}).map(([C,k])=>`${C}: ${k}`).join(`
|
|
16
16
|
`)}
|
|
17
17
|
|
|
18
18
|
[limit params]
|
|
@@ -23,39 +23,39 @@
|
|
|
23
23
|
playbackRateFactor: ${S},
|
|
24
24
|
forwardBufferHealth: ${n},
|
|
25
25
|
bitrateFactor: ${A},
|
|
26
|
-
minBufferToSwitchUp: ${
|
|
26
|
+
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
27
27
|
droppedVideoMaxQualityLimit: ${d},
|
|
28
28
|
limitsAreInvalid: ${E},
|
|
29
|
-
maxQualityLimit: ${
|
|
30
|
-
minQualityLimit: ${
|
|
29
|
+
maxQualityLimit: ${r==null?void 0:r.max},
|
|
30
|
+
minQualityLimit: ${r==null?void 0:r.min},
|
|
31
31
|
|
|
32
32
|
[limited video tracks]
|
|
33
|
-
${Object.entries(
|
|
33
|
+
${Object.entries(B).map(([C,k])=>`${C}: ${k}`).join(`
|
|
34
34
|
`)||"All tracks are available"}
|
|
35
35
|
|
|
36
|
-
[best video track] ${
|
|
37
|
-
[selected video track] ${
|
|
38
|
-
`}),
|
|
36
|
+
[best video track] ${H==null?void 0:H.quality}
|
|
37
|
+
[selected video track] ${Q==null?void 0:Q.quality}
|
|
38
|
+
`}),gm(i,p,Q,l)},Sm=(a,e,t,{throughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u})=>{var m;(0,O.assertNotEmptyArray)(t,bm);let l=r.considerPlaybackRate&&(0,O.isNonNullable)(s)?s:1,c=[...t].sort(uu(-1)),d=a.bitrate;(0,O.assertNonNullable)(d);let p=l*mm(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h;return(0,O.isNonNullable)(i)&&isFinite(i)&&(h=c.find(g=>(0,O.isNonNullable)(g.bitrate)?i-d>=g.bitrate*p:!0)),h||(h=As(a,e,t,r.minVideoAudioRatio)),(h==null?void 0:h.bitrate)!==((m=o==null?void 0:o.last)==null?void 0:m.bitrate)&&u({message:`
|
|
39
39
|
[AUDIO TRACKS ABR]
|
|
40
40
|
[available audio tracks]
|
|
41
41
|
${t.map(g=>`{ id: ${g.id}, bitrate: ${g.bitrate} }`).join(`
|
|
42
42
|
`)}
|
|
43
43
|
|
|
44
44
|
[tuning]
|
|
45
|
-
${Object.entries(
|
|
45
|
+
${Object.entries(r!=null?r:{}).map(([g,S])=>`${g}: ${S}`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[limit params]
|
|
49
|
-
throughput: ${
|
|
49
|
+
throughput: ${i},
|
|
50
50
|
reserve: ${d},
|
|
51
51
|
playbackRate: ${s},
|
|
52
|
-
playbackRateFactor: ${
|
|
52
|
+
playbackRateFactor: ${l},
|
|
53
53
|
forwardBufferHealth: ${n},
|
|
54
54
|
bitrateFactor: ${p},
|
|
55
|
-
minBufferToSwitchUp: ${
|
|
55
|
+
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
56
56
|
|
|
57
57
|
[selected audio track] ${h==null?void 0:h.id}
|
|
58
|
-
`}),h&&Kf(i,u,h,o)};var be=a=>new URL(a).hostname;var V=require("@vkontakte/videoplayer-shared");var Xf=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},$e=a=>O(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!Xf(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(r){return Xf(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});var Ve=require("@vkontakte/videoplayer-shared");var ot=require("@vkontakte/videoplayer-shared");function ge(){return(0,ot.now)()}function Ko(a){return ge()-a}function Jo(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 c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Zf(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Rr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,c=0,l,d,p=!1,h="arraybuffer",m=7e3,g=2e3,S=()=>{if(u)return;(0,ot.assertNonNullable)(l);let F=Ko(l),ee;if(F<g){ee=g-F,setTimeout(S,ee);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new i,_()},T=F=>(s=F,Z),P=F=>(d=F,Z),I=()=>(h="json",Z),E=()=>{if(!u){if(--c>=0){S(),r&&r();return}u=!0,d&&d(),t&&t()}},A=F=>(p=F,Z),_=()=>{l=ge(),n=new i,n.open("get",a);let F=0,ee,K=0,M=()=>((0,ot.assertNonNullable)(l),Math.max(l,Math.max(ee||0,K||0)));if(s&&n.addEventListener("progress",k=>{let Y=ge();s.updateChunk&&k.loaded>F&&(s.updateChunk(M(),k.loaded-F),F=k.loaded,ee=Y)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;(0,ot.assertNonNullable)(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let Y=n.response.byteLength-F;Y&&s.updateChunk&&s.updateChunk(M(),Y)}n.responseType==="json"&&!Object.values(n.response).length?E():(d&&d(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),p){let k=()=>{(0,ot.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=ge(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),Z},Z={withBitrateReporting:T,withParallel:A,withJSONResponse:I,withRetryCount:F=>(c=F,Z),withRetryInterval:(F,ee)=>((0,ot.isNonNullable)(F)&&(g=F),(0,ot.isNonNullable)(ee)&&(m=ee),Z),withTimeout:F=>(o=F,Z),withFinally:P,send:_,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return Z}var xi=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 Pi=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=Rr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=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(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var ls=1e4,Xo=3;var _x=6e4,Nx=10,Fx=1,qx=500,Ai=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new xi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Jo(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=Jo(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ve.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Zf(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 Pi(Xo,ls,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,c=null,l=!1,d=()=>{let E=s&&(!l||l===this.rep);return E||t("Not running!"),E},p=(E,A,_)=>{u&&u.abort(),u=Rr(this.urlResolver.resolve(E,!1),A,_,()=>this._retryCallback()).withTimeout(ls).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Xo).withFinally(()=>{u=null}).send()},h=(E,A,_)=>{(0,Ve.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),A,_,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{let A=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${A}=>${E}`),r.playbackRate=E)},g=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let _=ge()-1e4,ae=0;for(let W=0;W<this.bufferStates.length;W++){let te=this.bufferStates[W];E=Math.min(E,te.buf),te.ts<_&&ae++}this.bufferStates.splice(0,ae),t(`update playback rate; minBuffer=${E} drop=${ae} jitter=${this.sourceJitter}`);let Q=E-Fx;this.sourceJitter>=0?Q-=this.sourceJitter/2:this.sourceJitter-=1,Q>3?m(1.15):Q>1?m(1.1):Q>.3?m(1.05):m(1)}},T=E=>{let A,_=()=>A&&A.start?A.start.length:0,ae=k=>A.start[k]/1e3,Q=k=>A.dur[k]/1e3,W=k=>A.fragIndex+k,te=(k,Y)=>({chunkIdx:W(k),startTS:ae(k),dur:Q(k),discontinuity:Y}),Z=()=>{let k=0;if(A&&A.dur){let Y=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,se=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ue=Y;this.sourceJitter>1&&(ue+=this.sourceJitter-1);let pe=A.dur.length-1;for(;pe>=0&&(ue-=A.dur[pe],!(ue<=0));--pe);k=Math.min(pe,A.dur.length-1-se),k=Math.max(k,0)}return te(k,!0)},F=k=>{let Y=_();if(!(Y<=0)){if((0,Ve.isNonNullable)(k)){for(let se=0;se<Y;se++)if(ae(se)>k)return te(se)}return Z()}},ee=k=>{let Y=_(),se=k?k.chunkIdx+1:0,ue=se-A.fragIndex;if(!(Y<=0)){if(!k||ue<0||ue-Y>Nx)return t(`Resync: offset=${ue} bChunks=${Y} chunk=`+JSON.stringify(k)),Z();if(!(ue>=Y))return te(se-A.fragIndex,!1)}},K=(k,Y,se)=>{c&&c.abort(),c=Rr(this.urlResolver.resolve(k,!0,this.lowLatency),Y,se,()=>this._retryCallback()).withTimeout(ls).withRetryCount(Xo).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(k,Y)=>{K(E,se=>{if(!d())return;A=se;let ue=!!A.lowLatency;ue!==this.lowLatency&&g(ue);let pe=0;for(let Ie=0;Ie<A.dur.length;++Ie)pe+=A.dur[Ie];pe>0&&((0,Ve.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,k(F(Y))},()=>this._handleNetworkError())},nextChunk:ee}},P=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),(0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:E=>{let{videoElement:A,logger:_}=this.params,ae=T(e.jidxUrl),Q,W,te,Z,F=0,ee,K,M,k=()=>{ee&&(clearTimeout(ee),ee=void 0);let R=Math.max(qx,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=F+R,Ce=ge(),Ne=Math.min(1e4,Ee-Ce);F=Ce;let kt=()=>{c||d()&&ae.seek(()=>{d()&&(F=ge(),Y(),k())})};Ne>0?ee=window.setTimeout(()=>{this.paused?k():kt()},Ne):kt()},Y=()=>{let R;for(;R=ae.nextChunk(Z);)Z=R,Vt(R);let Ee=ae.nextChunk(te);if(Ee){if(te&&Ee.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?k():(P(),this._initPlayerWith(e));return}Ie(Ee)}else k()},se=(R,Ee)=>{if(!d()||!this.sourceBuffer)return;let Ce,Ne,kt,or=Rt=>{window.setTimeout(()=>{d()&&se(R,Ee)},Rt)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),or(100);else{let Rt=ge(),_t=A.currentTime;!this.paused&&A.buffered.length>1&&K===_t&&Rt-M>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),K!==_t&&(K=_t,M=Rt);let ur=this._getBufferSizeSec();if(ur>30)_(`Buffered ${ur} seconds; delaying appendBuffer`),or(2e3);else try{this.sourceBuffer.appendBuffer(R),this.videoPlayStarted?(this.bufferStates.push({ts:Rt,buf:ur}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Hr){if(Hr.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),kt=this.sourceBuffer.buffered.length,kt!==0&&(Ce=this.sourceBuffer.buffered.start(0),Ne=_t,Ne-Ce>4&&this.sourceBuffer.remove(Ce,Ne-3)),or(1e3);else throw Hr}}},ue=()=>{W&&Q&&(_([`Appending chunk, sz=${W.byteLength}:`,JSON.stringify(te)]),se(W,function(){W=null,Y()}))},pe=R=>e.fragUrlTemplate.replace("%%id%%",R.chunkIdx),Ie=R=>{d()&&h(pe(R),(Ee,Ce)=>{if(d()){if(Ce/=1e3,W=Ee,te=R,n=R.startTS,Ce){let Ne=Math.min(10,R.dur/Ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ne:Ne}ue()}},()=>this._handleNetworkError())},Vt=R=>{d()&&((0,Ve.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(pe(R),!1)))},wt=R=>{d()&&(e.cachedHeader=R,se(R,()=>{Q=!0,ue()}))};s=!0,ae.seek(R=>{if(d()){if(F=ge(),!R){k();return}Z=R,!(0,Ve.isNullable)(E)||R.startTS>E?Ie(R):(te=R,Y())}},E),e.cachedHeader?wt(e.cachedHeader):p(e.headerUrl,wt,()=>this._handleNetworkError())},stop:P,getTimestampSec:()=>n},l}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,Ve.isNonNullable)(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Ve.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ve.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=ge();if(this.chunkRateEstimator.addInterval(p,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,c=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Ko(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&c(),h},notifySwitch:d=>{let p=ge();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Rr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ls).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;$e(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.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))},_x))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var oe=require("@vkontakte/videoplayer-shared"),Zo=class{constructor(){this.onDroopedVideoFramesLimit$=new oe.Subject;this.subscription=new oe.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new oe.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!(0,oe.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,oe.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,oe.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,oe.interval)(this.droppedFramesChecker.checkTime).pipe((0,oe.filter)(()=>this.playing),(0,oe.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,oe.debounce)(this.droppedFramesChecker.checkTime)),r=(0,oe.merge)(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,oe.isLower)(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ds=Zo;var ps=require("@vkontakte/videoplayer-shared"),em=require("@vkontakte/videoplayer-shared");var wi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Ux=(a,e)=>new ps.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||wi()))},C(C({},r),e));i.observe(a);let s=(0,em.fromEvent)(document,"visibilitychange").pipe((0,ps.map)(n=>!document.hidden||wi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ge=Ux;var Hx=["paused","playing","ready"],jx=["paused","playing","ready"],ki=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new j("stopped");this.representations$=new V.ValueSubject([]);this.textTracksManager=new je;this.droppedFramesManager=new ds;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new bt;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:V.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),l=(r=Dt(u.name))!=null?r:(0,V.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p=C({},u.video);if(!l)continue;let h={id:c,quality:l,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,V.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(jx.includes(e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&Hx.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Se(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(Se(this.params.source.url,u))}return;default:return(0,V.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:V.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,V.merge)(this.videoState.stateChangeStarted$.pipe((0,V.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,V.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(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.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Re(this.video);this.subscription.add(this.representations$.pipe((0,V.map)(i=>i.map(({track:s})=>s)),(0,V.filter)(i=>!!i.length),(0,V.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,V.filterChanged)(),(0,V.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,V.combine)({zeroTime:this.zeroTime$.pipe((0,V.filter)(V.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(nt(this.video,this.params.desiredState.isLooped,t)).add(ke(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(He(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ge(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&(0,V.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,V.assertNever)(i.to)}},t)).add((0,V.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,V.observableFrom)(["init"])).pipe((0,V.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),we(this.video)}createLiveDashPlayer(){let e=new Ai({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 c,l,d,p,h,m;let e=this.representations$.getValue(),t=(l=(c=this.params.desiredState.videoTrack.getTransition())==null?void 0:c.to)!=null?l: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,V.isNonNullable)(t)?t:Bt(e.map(({track:g})=>g),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let g=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,V.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,V.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(Se(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var tm=ki;var vt=(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 U=require("@vkontakte/videoplayer-shared");var hs=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}},$r=class extends hs{constructor(){super(),this.listeners||hs.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)}},Ri=class{constructor(){Object.defineProperty(this,"signal",{value:new $r,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&&(Ri.prototype[Symbol.toStringTag]="AbortController",$r.prototype[Symbol.toStringTag]="AbortSignal");function fs(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 eu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!fs({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(c,l){let d;l&&l.signal&&(d=l.signal,delete l.signal);let p=new t(c,l);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,c)=>{let l=s&&s.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(l){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(l.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{l.addEventListener("abort",()=>m(d),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([p,n(u,c)])}return n(u,c)},Request:s}}var $i=fs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),rm=$i?eu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,yt=$i?rm.fetch:window.fetch,IL=$i?rm.Request:window.Request,Tt=$i?Ri:window.AbortController,EL=$i?$r:window.AbortSignal;var mm=ze(Ti(),1);var It=()=>window.ManagedMediaSource||window.MediaSource,ms=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},im=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},am=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ut=require("@vkontakte/videoplayer-shared");var We=document.createElement("video"),Yx='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Qx='video/mp4; codecs="hev1.1.6.L93.B0"',bm='video/webm; codecs="vp09.00.10.08"',gm='video/webm; codecs="av01.0.00M.08"',zx='audio/mp4; codecs="mp4a.40.2"',Kx='audio/webm; codecs="opus"',sm,nm,Jt={mms:ms(),mse:im(),hls:!!((sm=We.canPlayType)!=null&&sm.call(We,"application/x-mpegurl")||(nm=We.canPlayType)!=null&&nm.call(We,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},om,um,Le={mp4:!!((om=We.canPlayType)!=null&&om.call(We,"video/mp4")),webm:!!((um=We.canPlayType)!=null&&um.call(We,"video/webm")),cmaf:!0},gs,cm,Ss,lm,vs,dm,ys,pm,Ts,hm,Is,fm,Me={h264:!!((cm=(gs=It())==null?void 0:gs.isTypeSupported)!=null&&cm.call(gs,Yx)),h265:!!((lm=(Ss=It())==null?void 0:Ss.isTypeSupported)!=null&&lm.call(Ss,Qx)),vp9:!!((dm=(vs=It())==null?void 0:vs.isTypeSupported)!=null&&dm.call(vs,bm)),av1:!!((pm=(ys=It())==null?void 0:ys.isTypeSupported)!=null&&pm.call(ys,gm)),aac:!!((hm=(Ts=It())==null?void 0:Ts.isTypeSupported)!=null&&hm.call(Ts,zx)),opus:!!((fm=(Is=It())==null?void 0:Is.isTypeSupported)!=null&&fm.call(Is,Kx))},Lr=(Me.h264||Me.h265)&&Me.aac,Xt,Jx=()=>O(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(z(C({},a),{video:z(C({},a.video),{contentType:gm})})),window.navigator.mediaCapabilities.decodingInfo(z(C({},a),{video:z(C({},a.video),{contentType:bm})}))]);Xt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{Jx()}catch(a){console.error(a)}var Mr=Jt.hls&&Le.mp4,Sm=()=>Object.keys(Me).filter(a=>Me[a]),vm=(a,e=!1,t=!1)=>{let r=Jt.mse||Jt.mms&&t;return a.filter(i=>{switch(i){case"DASH_SEP":return r&&Le.mp4&&Lr;case"DASH_WEBM":return r&&Le.webm&&Me.vp9&&Me.opus;case"DASH_WEBM_AV1":return r&&Le.webm&&Me.av1&&Me.opus;case"DASH_STREAMS":return r&&(Le.mp4&&Lr||Le.webm&&(Me.vp9||Me.av1)&&(Me.opus||Me.aac));case"DASH_LIVE":return Jt.mse&&Le.mp4&&Lr;case"DASH_LIVE_CMAF":return r&&Le.mp4&&Lr&&Le.cmaf;case"DASH_ONDEMAND":return r&&Le.mp4&&Lr;case"HLS":case"HLS_ONDEMAND":return Mr||e&&Jt.mse&&Le.mp4&&Lr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Mr;case"MPEG":return Le.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Jt.webrtc&&Jt.ws&&Me.h264&&(Le.mp4||Le.webm);default:return(0,ut.assertNever)(i)}})},bs=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Xt?Xt[t].smooth?[t,e]:Xt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Xt?Xt[t].powerEfficient?[t,e]:Xt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,ut.assertNever)(a)}return[e,t]},ym=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...bs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ut.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...bs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...bs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...bs(a),...i,"HLS","HLS_ONDEMAND"];default:(0,ut.assertNever)(e)}return Mr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Tm=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=ut.clientChecker.isMac&&ut.clientChecker.isSafari;if(ut.clientChecker.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,ut.assertNever)(a)}else Mr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},tu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Im=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,mm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};var Cr=require("@vkontakte/videoplayer-shared"),Em=a=>{if(!a)return{id:"EmptyResponse",category:Cr.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Cr.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Cr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Cr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Cr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Dr=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared");var Fr=ze(Ti(),1);var Xx=(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)},Zx=a=>window.clearTimeout(a),xm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ru=xm?Xx:window.requestIdleCallback,OL=xm?Zx:window.cancelIdleCallback;var lb=ze(ns(),1);var Ye=require("@vkontakte/videoplayer-shared");var eP=16,Pm=!1;try{Pm=Ye.clientChecker.isSafari&&!!Ye.clientChecker.macVersion&&Ye.clientChecker.macVersion<=eP}catch(a){console.error(a)}var iu=class{constructor(e){this.bufferFull$=new Ye.Subject;this.error$=new Ye.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:Ye.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return O(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return O(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return O(this,null,function*(){return new Promise(t=>{let r;Pm&&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:Ye.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,Ye.assertNever)(t)}}},Am=iu;var au=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var x=require("@vkontakte/videoplayer-shared");var re=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Br=class extends re{};var Li=class extends re{};var Mi=class extends re{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var Ci=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Di=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Bi=class extends re{constructor(e,t){super(e,t),this.data=this.content}};var de=class extends re{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Zt=class extends de{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,c=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}};var Oi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Vi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var _i=class extends de{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ni=class extends de{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Fi=class extends de{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var qi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends de{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Hi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends de{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Wi=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yi=class extends de{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Qi=class extends de{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var zi=class extends de{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var rP={ftyp:Mi,moov:Ci,moof:Di,mdat:Bi,sidx:Zt,trak:Oi,mdia:qi,mfhd:Gi,tkhd:Ui,traf:Wi,tfhd:Yi,tfdt:Qi,trun:zi,minf:Hi,sv3d:Vi,st3d:_i,prhd:Ni,proj:ji,equi:Fi,uuid:Li,unknown:Br},er=class a{constructor(e={}){this.options=C({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=rP[e];return r?new r(t,new a):new Br(t,new a)}};var Or=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var aP=new TextDecoder("ascii"),sP=a=>aP.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",nP=a=>{let e=new Zt(a,new er),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},oP=(a,e)=>{let r=new er().parse(a),i=new Or(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,d)},uP=(a,e)=>{let r=new er().parse(a),s=new Or(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((d,p)=>d+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},cP=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new er().parse(a),i=new Or(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},wm={validateData:sP,parseInit:cP,getIndexRange:()=>{},parseSegments:nP,parseFeedableSegmentChunk:oP,getSegmentEndTime:uP};var Et=require("@vkontakte/videoplayer-shared");var Rm=require("@vkontakte/videoplayer-shared");var km={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"}},$m=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Ki(a,t),i=r in km,s=i?km[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),c=n&255>>o,l=Ki(u),d=c*it(2,(o-1)*8)+l,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Ki=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*it(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*it(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*it(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},et=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ki(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,Rm.assertNever)(e)}},tr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=$m(r);if(!e(i))return;i.type==="master"&&tr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Lm=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=$m(a);return tr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=et(o,n):s===17026?t=et(o,n):s===17029&&(r=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Mm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],lP=[231,22612,22743,167,171,163,160,175],dP=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,c,l=!1,d=0;return tr(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let S=et(m,h);c=Ki(S)}else p!==21420&&(c=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=et(m,h):p===17545?i=et(m,h):p===21420&&c===475249515?u=et(m,h):p===374648427?tr(m,({tag:S,type:T,value:P})=>S===30321?(l=et(P,T)===1,!1):!0):s&&n&&Mm.includes(p)&&(o=!0),!o}),(0,Et.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Et.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Et.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:l,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},pP=a=>{if((0,Et.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hP=(a,e)=>{let t=!1,r=!1,i=o=>(0,Et.isNonNullable)(o.time)&&(0,Et.isNonNullable)(o.position),s=[],n;return tr(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=et(c,u));break;case 183:break;case 241:n&&(n.position=et(c,u));break;default:t&&Mm.includes(o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:l}=o,d=s[u+1];return{status:"none",time:{from:c,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},fP=a=>{let e=0,t=!1;try{tr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):lP.includes(r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Cm={validateData:Lm,parseInit:dP,getIndexRange:pP,parseSegments:hP,parseFeedableSegmentChunk:fP};var Vr=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Cm;case"mp4":return wm}}throw new ReferenceError(`Unsupported mime type ${a}`)};var pu=ze(tb(),1);var du=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var Nr=require("@vkontakte/videoplayer-shared");var rb=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var ib=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},rr=(a,e)=>{let t=a;t=(0,pu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of Object.entries(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,pu.default)(t,n,(o,u)=>(0,Nr.isNullable)(s)?o:(0,Nr.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},sb=(a,e)=>{var E,A,_,ae,Q,W,te,Z,F,ee,K,M,k,Y,se,ue,pe,Ie,Vt,wt,R,Ee,Ce,Ne,kt,or,Rt,_t,ur,Hr,Pu,Au,wu,ku,Ru,$u,Lu,Mu,Cu,Du,Bu,Ou,Vu,_u,Nu,Fu,qu,Uu,Hu,ju;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(_=(A=(E=s.querySelector("BaseURL"))==null?void 0:E.textContent)==null?void 0:A.trim())!=null?_:"",u=n.children,c=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=ib(h);else if(m){let xe=ib(m);(0,Nr.isNonNullable)(xe)&&(p=xe)}else S&&(p=parseInt(S,10));let T=0,P=(Q=(ae=s.getAttribute("profiles"))==null?void 0:ae.split(","))!=null?Q:[];for(let xe of u){let Ob=(W=xe.getAttribute("id"))!=null?W:"id"+(T++).toString(10),jr=(te=xe.getAttribute("mimeType"))!=null?te:"",_s=(Z=xe.getAttribute("codecs"))!=null?Z:"",Ns=(F=xe.getAttribute("contentType"))!=null?F:jr==null?void 0:jr.split("/")[0],Vb=(K=(ee=xe.getAttribute("profiles"))==null?void 0:ee.split(","))!=null?K:[],_b=(M=xe.getAttribute("lang"))!=null?M:void 0,Nb=(se=(Y=(k=xe.querySelector("Label"))==null?void 0:k.textContent)==null?void 0:Y.trim())!=null?se:void 0,Fb=xe.querySelectorAll("Representation"),qb=xe.querySelector("SegmentTemplate"),Ub=(pe=(ue=xe.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?pe:void 0,Gr=Ns,fe={id:Ob,language:_b,isDefault:Ub==="main",label:Nb,codecs:_s,hdr:Gr==="video"&&du(_s),mime:jr,representations:[]};for(let he of Fb){let Hb=(Ie=he.getAttribute("lang"))!=null?Ie:void 0,jb=(Vt=he.getAttribute("label"))!=null?Vt:void 0,Gb=(Ee=(R=(wt=he.querySelector("BaseURL"))==null?void 0:wt.textContent)==null?void 0:R.trim())!=null?Ee:"",Fs=new URL(Gb||o,e).toString(),cr=(Ce=he.getAttribute("mimeType"))!=null?Ce:jr,ga=(kt=(Ne=he.getAttribute("codecs"))!=null?Ne:_s)!=null?kt:"",qs;if(Ns==="text"){let Nt=he.getAttribute("id")||"",Us=Nt.includes("_auto");qs={id:Nt,isAuto:Us,kind:"text",url:Fs}}else{let Nt=(Rt=(or=he.getAttribute("contentType"))!=null?or:cr==null?void 0:cr.split("/")[0])!=null?Rt:Ns,Us=(ur=(_t=xe.getAttribute("profiles"))==null?void 0:_t.split(","))!=null?ur:[],Wb=parseInt((Hr=he.getAttribute("width"))!=null?Hr:"",10),Gu=parseInt((Pu=he.getAttribute("height"))!=null?Pu:"",10),Wu=parseInt((Au=he.getAttribute("bandwidth"))!=null?Au:"",10)/1e3,Yu=(wu=he.getAttribute("frameRate"))!=null?wu:"",Yb=(ku=he.getAttribute("quality"))!=null?ku:void 0,Qb=Yu?rb(Yu):void 0,zb=(Ru=he.getAttribute("id"))!=null?Ru:"id"+(T++).toString(10),Kb=Nt==="video"?`${Gu}p`:Nt==="audio"?`${Wu}Kbps`:ga,Jb=`${zb}@${Kb}`,Xb=[...P,...Vb,...Us],Hs,Zb=he.querySelector("SegmentBase"),Ft=($u=he.querySelector("SegmentTemplate"))!=null?$u:qb;if(Zb){let qt=(Mu=(Lu=he.querySelector("SegmentBase Initialization"))==null?void 0:Lu.getAttribute("range"))!=null?Mu:"",[Ut,Gs]=qt.split("-").map(lr=>parseInt(lr,10)),$t={from:Ut,to:Gs},Wr=(Cu=he.querySelector("SegmentBase"))==null?void 0:Cu.getAttribute("indexRange"),[Ws,Sa]=Wr?Wr.split("-").map(lr=>parseInt(lr,10)):[],Yr=Wr?{from:Ws,to:Sa}:void 0;Hs={type:"byteRange",url:Fs,initRange:$t,indexRange:Yr}}else if(Ft){let qt={representationId:(Du=he.getAttribute("id"))!=null?Du:void 0,bandwidth:(Bu=he.getAttribute("bandwidth"))!=null?Bu:void 0},Ut=parseInt((Ou=Ft.getAttribute("timescale"))!=null?Ou:"",10),Gs=(Vu=Ft.getAttribute("initialization"))!=null?Vu:"",$t=Ft.getAttribute("media"),Wr=(Nu=parseInt((_u=Ft.getAttribute("startNumber"))!=null?_u:"",10))!=null?Nu:1,Ws=rr(Gs,qt);if(!$t)throw new ReferenceError("No media attribute in SegmentTemplate");let Sa=(Fu=Ft.querySelectorAll("SegmentTimeline S"))!=null?Fu:[],Yr=[],lr=0,Ys="",Qs=0;if(Sa.length){let va=Wr,Qe=0;for(let dr of Sa){let rt=parseInt((qu=dr.getAttribute("d"))!=null?qu:"",10),Ht=parseInt((Uu=dr.getAttribute("r"))!=null?Uu:"",10)||0,ya=parseInt((Hu=dr.getAttribute("t"))!=null?Hu:"",10);Qe=Number.isFinite(ya)?ya:Qe;let zs=rt/Ut*1e3,Ks=Qe/Ut*1e3;for(let Ta=0;Ta<Ht+1;Ta++){let tg=rr($t,z(C({},qt),{segmentNumber:va.toString(10),segmentTime:(Qe+Ta*rt).toString(10)})),Qu=(Ks!=null?Ks:0)+Ta*zs,rg=Qu+zs;va++,Yr.push({time:{from:Qu,to:rg},url:tg})}Qe+=(Ht+1)*rt,lr+=(Ht+1)*zs}Qs=Qe/Ut*1e3,Ys=rr($t,z(C({},qt),{segmentNumber:va.toString(10),segmentTime:Qe.toString(10)}))}else if((0,Nr.isNonNullable)(p)){let Qe=parseInt((ju=Ft.getAttribute("duration"))!=null?ju:"",10)/Ut*1e3,dr=Math.ceil(p/Qe),rt=0;for(let Ht=1;Ht<dr;Ht++){let ya=rr($t,z(C({},qt),{segmentNumber:Ht.toString(10),segmentTime:rt.toString(10)}));Yr.push({time:{from:rt,to:rt+Qe},url:ya}),rt+=Qe}Qs=rt,Ys=rr($t,z(C({},qt),{segmentNumber:dr.toString(10),segmentTime:rt.toString(10)}))}let eg={time:{from:Qs,to:1/0},url:Ys};Hs={type:"template",baseUrl:Fs,segmentTemplateUrl:$t,initUrl:Ws,totalSegmentsDurationMs:lr,segments:Yr,nextSegmentBeyondManifest:eg,timescale:Ut}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Nt||!cr)continue;let js={video:"video",audio:"audio",text:"text"}[Nt];if(!js)continue;Gr||(Gr=js),qs={id:Jb,kind:js,segmentReference:Hs,profiles:Xb,duration:p,bitrate:Wu,mime:cr,codecs:ga,width:Wb,height:Gu,fps:Qb,quality:Yb}}fe.language||(fe.language=Hb),fe.label||(fe.label=jb),fe.mime||(fe.mime=cr),fe.codecs||(fe.codecs=ga),fe.hdr||(fe.hdr=Gr==="video"&&du(ga)),fe.representations.push(qs)}Gr&&i[Gr].push(fe)}return{dynamic:c,liveAvailabilityStartTime:d,duration:p,streams:i}};var Ji=ze(Ti(),1);var nb=require("@vkontakte/videoplayer-shared"),ob=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s})=>{var o;let n=(o=s?Dt(s):void 0)!=null?o:(0,nb.videoSizeToQuality)({width:e,height:t});return n&&{id:a,quality:n,bitrate:r,size:{width:e,height:t},fps:i}},ub=({id:a,bitrate:e})=>({id:a,bitrate:e}),Es=(a,e,t)=>{var i;let r=e.indexOf(a);return(i=(0,Ji.default)(t,Math.round(t.length*r/e.length)))!=null?i:(0,Ji.default)(t,-1)},cb=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),fu=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ji.default)(r.split("."),0),isDefault:i}),mu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ji.default)(i.split("."),0)}),xs=a=>"url"in a,ct=a=>a.type==="template",Xi=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Zi=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentSegmentLength$=new x.ValueSubject(0);this.onLastSegment$=new x.ValueSubject(!1);this.fullyBuffered$=new x.ValueSubject(!1);this.playingRepresentation$=new x.ValueSubject(void 0);this.playingRepresentationInit$=new x.ValueSubject(void 0);this.error$=new x.Subject;this.gaps=[];this.subscription=new x.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Tt;this.destroyAbortController=new Tt;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,x.abortable)(this.destroyAbortController.signal,function(e){return me(this,null,function*(){let t=this.representations.get(e);(0,x.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 Am(this.sourceBuffer),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.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,au(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let c=vt(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,c<l)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,x.assertNonNullable)(r,"No init buffer for starting representation"),(0,x.assertNonNullable)(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,x.abortable)(this.destroyAbortController.signal,function(e,t=!1){return me(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,x.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,x.isNullable)(s)||(0,x.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,x.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,x.isNonNullable)(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),yield new Xs(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,x.abortable)(this.destroyAbortController.signal,function(e){return me(this,null,function*(){var u,c;let t=(u=e==null?void 0:e.flatMap(l=>l.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let l of this.representations.keys()){let d=t.find(m=>m.id===l);d&&this.representations.set(l,d);let p=this.representations.get(l);if(!p||!ct(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(c=this.switchingToRepresentationId)!=null?c:this.downloadingRepresentationId,i=this.representations.get(r);(0,x.assertNonNullable)(i);let s=this.segments.get(r);(0,x.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,x.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Tt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var c,l;if((0,x.isNullable)(e)||(0,x.isNullable)(this.downloadingRepresentationId)||(0,x.isNullable)(this.playingRepresentationId)||(0,x.isNullable)(this.sourceBuffer)||!(0,x.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,x.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(((c=i==null?void 0:i.time.to)!=null?c:0)-((l=i==null?void 0:i.time.from)!=null?l:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=vt(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&au(this.sourceBuffer.buffered)>=this.bufferLimit){let d=vt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if(o.includes(i))d="high";else{let p=(0,Fr.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&vt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Fr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;(0,x.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!ct(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>z(C({},p),{status:"none",size:void 0})),c=(i=this.segments.get(o.id))!=null?i:[],l=(n=(s=(0,Fr.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(l)>=Math.floor(p.time.from)&&Math.floor(l)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,x.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!ct(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),c=rr(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let g=p<=r&&h>=r,S=p>r||g||m===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&p<=r+T||h<=r+T;return(d==="none"||d==="partially_ejected"&&S&&P&&this.sourceBuffer&&!(Dr(this.sourceBuffer.buffered,p)&&Dr(this.sourceBuffer.buffered,h)))&&S&&P});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=c||o<=l);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return O(this,null,function*(){ct(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return O(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,x.abortable)(o,function(){return me(this,null,function*(){let l=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!l)return;let d=new DataView(l);if(!isFinite(i.segment.time.to)){let p=t.segmentReference.timescale,h=Vr(t.mime);i.segment.time.to=h.getSegmentEndTime(d,p)}u&&i.feedingBytes&&c?yield Promise.all(c):yield this.sourceBufferTaskQueue.append(d,o),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),Xi(l)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return O(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,x.abortable)(n,function(){return me(this,null,function*(){let u=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),(0,x.fromEvent)(window,"online").pipe((0,x.once)()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Xi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(ct(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Fr.default)(e,0).byte.from,to:(0,Fr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ct(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?(c,l)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:c,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return O(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Vr(o.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(c.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,c=e.byteLength;for(let l of this.activeSegments){let{segment:d}=l,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:c;if(l.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let g=p?d.byte.from-r:0,S=p?d.byte.to-r:e.byteLength,T=g<i,P=S<=i;if(d.status==="downloading"&&T&&P){d.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+g,h),E=this.getCurrentPosition();(0,x.isNonNullable)(E)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-E,this.bufferAccumulation.accumulated.push({segmentView:I,segmentProgress:l}),this.activeSegments.delete(l));let A=({segmentView:_,segmentProgress:ae})=>this.sourceBufferTaskQueue.append(_,s).then(Q=>Q&&!s.aborted?this.onSegmentFullyAppended(ae,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(A),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||(0,x.isNullable)(E))&&(A({segmentView:I,segmentProgress:l}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&!P&&(l.loadedBytes=Math.min(h,i-g),l.loadedBytes>l.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+g+l.feedingBytes,l.loadedBytes-l.feedingBytes),E=l.loadedBytes===h?I:Vr(o.mime).parseFeedableSegmentChunk(I);E!=null&&E.byteLength&&(d.status="partially_fed",l.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,s).then(A=>{if(s.aborted)n();else if(A)l.fedBytes+=E.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return O(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let c of this.activeSegments){let{segment:l}=c;if(c.representationId!==t)continue;if(s.aborted){n();continue}let d=l.byte.from-r,p=l.byte.to-r,h=p-d+1,m=d<i,g=p<=i;if(m){if(l.status==="downloading"&&g){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(c,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(c.loadedBytes=Math.min(h,i-d),c.loadedBytes>c.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===h?S:Vr(u.mime).parseFeedableSegmentChunk(S);T!=null&&T.byteLength&&(l.status="partially_fed",c.feedingBytes+=T.byteLength,(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?(c.fedBytes+=T.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t)):n())}}}})}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",xs(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,x.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=ru(()=>(0,lb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return O(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,x.abortable)(this.destroyAbortController.signal,function(){return me(this,null,function*(){let o=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Vr(e.mime),i)).then(o=>O(this,null,function*(){if(!o)return;let{init:u,dataView:c,segments:l}=o,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d);let p=l;this.isLive&&ct(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:x.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return O(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return O(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,r):this.pruneBufferOld(e,t,r)})}pruneBufferNew(e,t,r=!1){return O(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((l,d)=>l.from-d.from);let c=[u[0]];for(let l=1;l<u.length;l++){let{from:d,to:p}=u[l],h=c[c.length-1];h.to>=d?h.to=Math.max(h.to,p):c.push(u[l])}return c},o=u=>{var l;if(s>=t)return i;i.push(C({},u.time)),i=n(i);let c=xs(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let l=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let p={time:{from:c,to:l},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let l of c)l.time.from>=e+u&&l.status==="fed"&&o(l)}return i.length?(yield Promise.all(i.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,l)=>c||l,!1):!1})}pruneBufferOld(e,t,r=!1){return O(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let i=0,s=1/0,n=-1/0,o=!1,u=c=>{var d;s=Math.min(s,c.time.from),n=Math.max(n,c.time.to);let l=xs(c)?(d=c.size)!=null?d:0:c.byte.to-c.byte.from;i+=l};for(let c of this.segments.values())for(let l of c){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||i>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(s)&&isFinite(n),!o){i=0,s=1/0,n=-1/0;for(let c of this.segments.values())for(let l of c){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||i>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(s)&&isFinite(n),!o)for(let c=0;c<this.sourceBuffer.buffered.length;c++){let l=this.sourceBuffer.buffered.start(c)*1e3,d=this.sourceBuffer.buffered.end(c)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)){s=l,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){i=0,s=1/0,n=-1/0;let c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>e+c&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){(0,x.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=ru(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:x.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,x.isNullable)(this.sourceBuffer)||(0,x.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(l=>l.from-t<=n&&l.to+t>=o),c=e.filter(l=>n>=l.from&&n<l.to-t||o>l.from+t&&o<=l.to);u||(c.length===1?i.status="partially_ejected":this.gaps.some(l=>l.from===i.time.from||l.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var ea=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var db=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 J=require("@vkontakte/videoplayer-shared");var Ps=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1}){this.lastConnectionType$=new J.ValueSubject(void 0);this.lastConnectionReused$=new J.ValueSubject(void 0);this.lastRequestFirstBytes$=new J.ValueSubject(void 0);this.abortAllController=new Tt;this.subscription=new J.Subscription;this.fetchManifest=(0,J.abortable)(this.abortAllController.signal,function(e){return me(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ea(r));let i=yield yt(r,{signal:this.abortAllController.signal}).catch(ta);return i?(t.log("success",(0,J.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,J.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,J.abortable)(this.abortAllController.signal,function(c){return me(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var F,ee;let l=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let K=new URL(l,location.href);K.searchParams.append("bytes",`${r.from}-${r.to}`),l=K.toString();break}default:(0,J.assertNever)(t)}this.requestQuic&&(l=ea(l));let h=this.abortAllController.signal,m;if(n){let K=new Tt;if(m=(0,J.merge)((0,J.fromEvent)(this.abortAllController.signal,"abort"),(0,J.fromEvent)(n,"abort")).subscribe(()=>{try{K.abort()}catch(M){ta(M)}}),this.abortAllController.signal.aborted||n.aborted)try{K.abort()}catch(M){ta(M)}h=K.signal}let g=(0,J.now)();p.log("startRequest",(0,J.flattenObject)({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:g}));let S=yield yt(l,{priority:s,headers:d,signal:h}).catch(ta),T=(0,J.now)();if(!S)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((F=this.throughputEstimator)==null||F.addRawRtt(T-g),!S.ok||!S.body){m==null||m.unsubscribe();let K=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:K}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!i&&!o){m==null||m.unsubscribe();let K=(0,J.now)(),M={requestStartedAt:g,requestEndedAt:K,duration:K-g};return p.log("endRequest",(0,J.flattenObject)(M)),p.end(),S.arrayBuffer()}let[P,I]=S.body.tee(),E=P.getReader();o&&((ee=this.throughputEstimator)==null||ee.trackStream(I,u));let A=0,_=new Uint8Array(0),ae=!1,Q=K=>{m==null||m.unsubscribe(),ae=!0,ta(K)},W=(0,J.abortable)(h,function(k){return me(this,arguments,function*({done:K,value:M}){if(A===0&&this.lastRequestFirstBytes$.next((0,J.now)()-g),h.aborted){m==null||m.unsubscribe();return}if(!K&&M){let Y=new Uint8Array(_.length+M.length);Y.set(_),Y.set(M,_.length),_=Y,A+=M.byteLength,i==null||i(new DataView(_.buffer),A),yield E==null?void 0:E.read().then(W,Q)}})}.bind(this));yield E==null?void 0:E.read().then(W,Q),m==null||m.unsubscribe();let te=(0,J.now)(),Z={failed:ae,requestStartedAt:g,requestEndedAt:te,duration:te-g};return ae?(p.error("endRequest",(0,J.flattenObject)(Z)),p.end(),null):(p.log("endRequest",(0,J.flattenObject)(Z)),p.end(),_.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t,r){return me(this,null,function*(){var T;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,c,l;e.indexRange&&(c=e.indexRange.from,l=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,i),o=Math.max(l,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(T=e.indexRange)!=null?T:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let P=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!P)return null;g=new DataView(P)}let S=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t){return me(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>z(C({},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")}onHeadersReceived(e){let{type:t,reused:r}=db(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return O(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,J.assertNever)(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ta=a=>{if(!Xi(a))throw a};var ir=(a,e,t)=>t*e+(1-t)*a,bu=(a,e)=>a.reduce((t,r)=>t+r,0)/e,pb=(a,e,t,r)=>{let i=0,s=t,n=bu(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};var ra=require("@vkontakte/videoplayer-shared");var Ot=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ra.ValueSubject(e.initial),this.debounced$=new ra.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Te(`raw_${t}`),this.smoothedSeries$=new Te(`smoothed_${t}`),this.reportedSeries$=new Te(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=it(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,ra.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var As=class extends Ot{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ir(this.slow,e,this.params.emaAlphaSlow),this.fast=ir(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ws=class extends Ot{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=bu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ir(this.emaSmoothed,e,this.params.emaAlpha);let r=pb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var ks=class extends Ot{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?ir(this.smoothed,t,this.params.emaAlpha):t}};var ar=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new As({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ws({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ks(C({initial:e,label:"liveEdgeDelay"},t))}};var gu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var fb=["timeupdate","progress","play","seeked","stalled","waiting"];var Rs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new j("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.isLive$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.timeInWaiting=0;this.isActiveLowLatency$=new v.ValueSubject(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new Tt;this.initManifest=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return me(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,function(){return me(this,null,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:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t;try{t=sb(e!=null?e:"",this.manifestUrlString)}catch(u){let c=(n=Em(e))!=null?n:{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(c)}if(!t)return null;let r=(u,c,l)=>{var d,p,h,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,c)&&((m=(h=It())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${c}; codecs="${l}"`))||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 l=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),d=new Set(l.map(({codecs:h})=>h)),p=Im(d);if(p&&(i[u]=l.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(S=>S.hdr),g=i.video.some(S=>!S.hdr);v.clientChecker.isHDR&&h&&m?i.video=i.video.filter(S=>S.hdr):g&&(i.video=i.video.filter(S=>!S.hdr))}}let s=z(C({},t),{streams:i});return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return me(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,v.fromEvent)(p,"error").pipe((0,v.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?am():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ms())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Zi("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Zi("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,v.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=qo(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add((0,v.merge)(...fb.filter(p=>p!=="waiting").map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?vt(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.filter)(p=>!!p),(0,v.tap)(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,v.filterChanged)()).subscribe(h=>gu(this.element,1))),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,v.filter)(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add((0,v.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:m})=>{if(!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,P=h-g,I=1;Math.abs(P)>S&&(I=1+Math.sign(P)*T),gu(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let T=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var E,A;return(A=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?A:T}))-T}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(g=>O(this,[g],function*({liveLoadBufferLength:h,bufferLength:m}){if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,T=qo(this.manifestUrlString,2),P=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(P,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,_=isFinite(h)?h:m,ae=this.isActiveLowLatency$.getValue(),Q=P<=this.tuning.live.activeLiveDelay&&T===0;this.isActiveLowLatency$.next(ae&&Q);let W="none";if(ae?W="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&Q?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(te=>te.proceedLowLatencyLive()),W="active_low_latency"):T!==0&&_<I?W="live_forward_buffering":_<I+A&&(W="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),W==="live_forward_buffering"||W==="live_with_target_offset"){let te=p-(I+E),Z=this.normolizeLiveOffset(Math.trunc(T+te/S)),F=Math.abs(Z-T),ee;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?ee=T:Z>0&&F>this.tuning.dashCmafLive.offsetCalculationError?ee=Z:ee=0,this.manifestUrlString=Se(this.manifestUrlString,ee,2)}W!=="none"&&W!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=(0,v.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,v.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:u,someBufferEnded:c}).pipe((0,v.filter)(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let l=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),ct(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...l)/1e3,this.audioBufferManager&&(0,v.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),i=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:i})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Ps({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=ar.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,C({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return O(this,null,function*(){var r,i,s,n;(0,v.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=Se(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive((r=this.manifest)==null?void 0:r.streams.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio))})}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...fb.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{var t,r,i;this.element&&this.element.readyState===2&&!this.element.seeking&&Dr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var n,o;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting};if(this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s=z(C({},s),{liveLastSeekOffset:this.liveLastSeekOffset});else{let u=this.element.currentTime*1e3;(n=this.videoBufferManager)==null||n.maintain(u),(o=this.audioBufferManager)==null||o.maintain(u),s=z(C({},s),{position:u})}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(r=this.audioBufferManager)==null||r.startAccumulateBuffer(),(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return O(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u,c;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Dr(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(c=this.audioBufferManager)==null||c.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,v.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,v.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return O(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;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=z(C({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,v.flattenObject)(t)))}}};var $s=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ls=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/it(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=C({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*it(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var mb=`attribute vec2 a_vertex;
|
|
58
|
+
`}),h&&gm(r,u,h,o)};var be=a=>new URL(a).hostname;var _=require("@vkontakte/videoplayer-shared");var vm=a=>{if(a instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Le=a=>V(void 0,null,function*(){let e=a.muted;try{yield a.play()}catch(t){if(!vm(t))return!1;if(e)return console.warn(t),!1;a.muted=!0;try{yield a.play()}catch(i){return vm(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});var _e=require("@vkontakte/videoplayer-shared");var pt=require("@vkontakte/videoplayer-shared");function ge(){return(0,pt.now)()}function lu(a){return ge()-a}function cu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(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 ym(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Ni(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,g=2e3,S=()=>{if(u)return;(0,pt.assertNonNullable)(c);let F=lu(c),ee;if(F<g){ee=g-F,setTimeout(S,ee);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new r,B()},T=F=>(s=F,Z),P=F=>(d=F,Z),I=()=>(h="json",Z),E=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,d&&d(),t&&t()}},A=F=>(p=F,Z),B=()=>{c=ge(),n=new r,n.open("get",a);let F=0,ee,K=0,C=()=>((0,pt.assertNonNullable)(c),Math.max(c,Math.max(ee||0,K||0)));if(s&&n.addEventListener("progress",k=>{let z=ge();s.updateChunk&&k.loaded>F&&(s.updateChunk(C(),k.loaded-F),F=k.loaded,ee=z)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;(0,pt.assertNonNullable)(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let z=n.response.byteLength-F;z&&s.updateChunk&&s.updateChunk(C(),z)}n.responseType==="json"&&!Object.values(n.response).length?E():(d&&d(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),p){let k=()=>{(0,pt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=ge(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),Z},Z={withBitrateReporting:T,withParallel:A,withJSONResponse:I,withRetryCount:F=>(l=F,Z),withRetryInterval:(F,ee)=>((0,pt.isNonNullable)(F)&&(g=F),(0,pt.isNonNullable)(ee)&&(m=ee),Z),withTimeout:F=>(o=F,Z),withFinally:P,send:B,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return Z}var Or=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Vr=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ge(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ge()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ni(t,s,()=>r("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 i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,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 ws=1e4,du=3;var zx=6e4,Kx=10,Jx=1,Xx=500,_r=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.chunkRateEstimator=new Or(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=cu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=cu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,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)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,_e.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{ym(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 Vr(du,ws,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let E=s&&(!c||c===this.rep);return E||t("Not running!"),E},p=(E,A,B)=>{u&&u.abort(),u=Ni(this.urlResolver.resolve(E,!1),A,B,()=>this._retryCallback()).withTimeout(ws).withBitrateReporting(this.bitrateSwitcher).withRetryCount(du).withFinally(()=>{u=null}).send()},h=(E,A,B)=>{(0,_e.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),A,B,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{let A=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${A}=>${E}`),i.playbackRate=E)},g=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let B=ge()-1e4,te=0;for(let Q=0;Q<this.bufferStates.length;Q++){let ie=this.bufferStates[Q];E=Math.min(E,ie.buf),ie.ts<B&&te++}this.bufferStates.splice(0,te),t(`update playback rate; minBuffer=${E} drop=${te} jitter=${this.sourceJitter}`);let H=E-Jx;this.sourceJitter>=0?H-=this.sourceJitter/2:this.sourceJitter-=1,H>3?m(1.15):H>1?m(1.1):H>.3?m(1.05):m(1)}},T=E=>{let A,B=()=>A&&A.start?A.start.length:0,te=k=>A.start[k]/1e3,H=k=>A.dur[k]/1e3,Q=k=>A.fragIndex+k,ie=(k,z)=>({chunkIdx:Q(k),startTS:te(k),dur:H(k),discontinuity:z}),Z=()=>{let k=0;if(A&&A.dur){let z=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,se=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,le=z;this.sourceJitter>1&&(le+=this.sourceJitter-1);let he=A.dur.length-1;for(;he>=0&&(le-=A.dur[he],!(le<=0));--he);k=Math.min(he,A.dur.length-1-se),k=Math.max(k,0)}return ie(k,!0)},F=k=>{let z=B();if(!(z<=0)){if((0,_e.isNonNullable)(k)){for(let se=0;se<z;se++)if(te(se)>k)return ie(se)}return Z()}},ee=k=>{let z=B(),se=k?k.chunkIdx+1:0,le=se-A.fragIndex;if(!(z<=0)){if(!k||le<0||le-z>Kx)return t(`Resync: offset=${le} bChunks=${z} chunk=`+JSON.stringify(k)),Z();if(!(le>=z))return ie(se-A.fragIndex,!1)}},K=(k,z,se)=>{l&&l.abort(),l=Ni(this.urlResolver.resolve(k,!0,this.lowLatency),z,se,()=>this._retryCallback()).withTimeout(ws).withRetryCount(du).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,z)=>{K(E,se=>{if(!d())return;A=se;let le=!!A.lowLatency;le!==this.lowLatency&&g(le);let he=0;for(let Ee=0;Ee<A.dur.length;++Ee)he+=A.dur[Ee];he>0&&((0,_e.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(he/A.dur.length)),r({name:"index",zeroTime:A.zeroTime,shiftDuration:A.shiftDuration}),this.sourceJitter=A.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,A.jitter/1e3)):1,k(F(z))},()=>this._handleNetworkError())},nextChunk:ee}},P=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,_e.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:A,logger:B}=this.params,te=T(e.jidxUrl),H,Q,ie,Z,F=0,ee,K,C,k=()=>{ee&&(clearTimeout(ee),ee=void 0);let $=Math.max(Xx,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),xe=F+$,De=ge(),Fe=Math.min(1e4,xe-De);F=De;let Dt=()=>{l||d()&&te.seek(()=>{d()&&(F=ge(),z(),k())})};Fe>0?ee=window.setTimeout(()=>{this.paused?k():Dt()},Fe):Dt()},z=()=>{let $;for(;$=te.nextChunk(Z);)Z=$,Gt($);let xe=te.nextChunk(ie);if(xe){if(ie&&xe.discontinuity){B("Detected discontinuity; restarting playback"),this.paused?k():(P(),this._initPlayerWith(e));return}Ee(xe)}else k()},se=($,xe)=>{if(!d()||!this.sourceBuffer)return;let De,Fe,Dt,fi=Bt=>{window.setTimeout(()=>{d()&&se($,xe)},Bt)};if(this.sourceBuffer.updating)B("Source buffer is updating; delaying appendBuffer"),fi(100);else{let Bt=ge(),Wt=A.currentTime;!this.paused&&A.buffered.length>1&&K===Wt&&Bt-C>500&&(B("Stall suspected; trying to fix"),this._fixupStall()),K!==Wt&&(K=Wt,C=Bt);let mi=this._getBufferSizeSec();if(mi>30)B(`Buffered ${mi} seconds; delaying appendBuffer`),fi(2e3);else try{this.sourceBuffer.appendBuffer($),this.videoPlayStarted?(this.bufferStates.push({ts:Bt,buf:mi}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),xe&&xe()}catch(Zi){if(Zi.name==="QuotaExceededError")B("QuotaExceededError; delaying appendBuffer"),Dt=this.sourceBuffer.buffered.length,Dt!==0&&(De=this.sourceBuffer.buffered.start(0),Fe=Wt,Fe-De>4&&this.sourceBuffer.remove(De,Fe-3)),fi(1e3);else throw Zi}}},le=()=>{Q&&H&&(B([`Appending chunk, sz=${Q.byteLength}:`,JSON.stringify(ie)]),se(Q,function(){Q=null,z()}))},he=$=>e.fragUrlTemplate.replace("%%id%%",$.chunkIdx),Ee=$=>{d()&&h(he($),(xe,De)=>{if(d()){if(De/=1e3,Q=xe,ie=$,n=$.startTS,De){let Fe=Math.min(10,$.dur/De);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Fe:Fe}le()}},()=>this._handleNetworkError())},Gt=$=>{d()&&((0,_e.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(he($),!1)))},Ct=$=>{d()&&(e.cachedHeader=$,se($,()=>{H=!0,le()}))};s=!0,te.seek($=>{if(d()){if(F=ge(),!$){k();return}Z=$,!(0,_e.isNullable)(E)||$.startTS>E?Ee($):(ie=$,z())}},E),e.cachedHeader?Ct(e.cachedHeader):p(e.headerUrl,Ct,()=>this._handleNetworkError())},stop:P,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,_e.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,_e.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,_e.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=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 S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&lu(n)<3e4)return;i(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,i){this.manifestRequest=Ni(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ws).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Le(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},zx))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var ue=require("@vkontakte/videoplayer-shared"),pu=class{constructor(){this.onDroopedVideoFramesLimit$=new ue.Subject;this.subscription=new ue.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ue.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,ue.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,ue.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,ue.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ue.interval)(this.droppedFramesChecker.checkTime).pipe((0,ue.filter)(()=>this.playing),(0,ue.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,ue.debounce)(this.droppedFramesChecker.checkTime)),i=(0,ue.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,ue.isLower)(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[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}},ks=pu;var Rs=require("@vkontakte/videoplayer-shared"),Tm=require("@vkontakte/videoplayer-shared");var Nr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Zx=(a,e)=>new Rs.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Nr()))},R(R({},i),e));r.observe(a);let s=(0,Tm.fromEvent)(document,"visibilitychange").pipe((0,Rs.map)(n=>!document.hidden||Nr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe}}),We=Zx;var eP=["paused","playing","ready"],tP=["paused","playing","ready"],Fr=class{constructor(e){this.subscription=new _.Subscription;this.videoState=new W("stopped");this.representations$=new _.ValueSubject([]);this.textTracksManager=new dt;this.droppedFramesManager=new ks;this.maxSeekBackTime$=new _.ValueSubject(1/0);this.zeroTime$=new _.ValueSubject(void 0);this.liveOffset=new It;this._dashCb=e=>{var t,i,r,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:_.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=(i=Ut(u.name))!=null?i:(0,_.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p=R({},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)),((r=this.videoState.getTransition())==null?void 0:r.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,_.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(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(tP.includes(e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&eP.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Se(this.params.source.url,u))}return;default:return(0,_.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:_.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};(0,_.merge)(this.videoState.stateChangeStarted$.pipe((0,_.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,_.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})}),this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(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 i=$e(this.video);this.subscription.add(this.representations$.pipe((0,_.map)(r=>r.map(({track:s})=>s)),(0,_.filter)(r=>!!r.length),(0,_.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,_.filterChanged)(),(0,_.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,_.combine)({zeroTime:this.zeroTime$.pipe((0,_.filter)(_.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ct(this.video,this.params.desiredState.isLooped,t)).add(Re(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ge(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(We(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let s=r&&(0,_.videoQualityToHeight)(r);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((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,_.assertNever)(r.to)}},t)).add((0,_.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,_.observableFrom)(["init"])).pipe((0,_.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 _r({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(),i=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,_.isNonNullable)(t)?t:Ht(e.map(({track:g})=>g),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.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(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let g=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;(0,_.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,_.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Se(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Im=Fr;var ht=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var U=require("@vkontakte/videoplayer-shared");var $s=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];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}},Fi=class extends $s{constructor(){super(),this.listeners||$s.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)}},qr=class{constructor(){Object.defineProperty(this,"signal",{value:new Fi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(qr.prototype[Symbol.toStringTag]="AbortController",Fi.prototype[Symbol.toStringTag]="AbortSignal");function Ls(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 hu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Ls({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(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 Ur=Ls({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Em=Ur?hu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Pt=Ur?Em.fetch:window.fetch,BL=Ur?Em.Request:window.Request,At=Ur?qr:window.AbortController,OL=Ur?Fi:window.AbortSignal;var Om=Xe(Cr(),1);var wt=()=>window.ManagedMediaSource||window.MediaSource,Ms=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},xm=()=>{var a,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Pm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var ft=require("@vkontakte/videoplayer-shared");var Ye=document.createElement("video"),aP='video/mp4; codecs="avc1.42000a,mp4a.40.2"',sP='video/mp4; codecs="hev1.1.6.L93.B0"',Vm='video/webm; codecs="vp09.00.10.08"',_m='video/webm; codecs="av01.0.00M.08"',nP='audio/mp4; codecs="mp4a.40.2"',oP='audio/webm; codecs="opus"',Am,wm,si={mms:Ms(),mse:xm(),hls:!!((Am=Ye.canPlayType)!=null&&Am.call(Ye,"application/x-mpegurl")||(wm=Ye.canPlayType)!=null&&wm.call(Ye,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},km,Rm,Me={mp4:!!((km=Ye.canPlayType)!=null&&km.call(Ye,"video/mp4")),webm:!!((Rm=Ye.canPlayType)!=null&&Rm.call(Ye,"video/webm")),cmaf:!0},Ds,$m,Bs,Lm,Os,Mm,Vs,Cm,_s,Dm,Ns,Bm,Ce={h264:!!(($m=(Ds=wt())==null?void 0:Ds.isTypeSupported)!=null&&$m.call(Ds,aP)),h265:!!((Lm=(Bs=wt())==null?void 0:Bs.isTypeSupported)!=null&&Lm.call(Bs,sP)),vp9:!!((Mm=(Os=wt())==null?void 0:Os.isTypeSupported)!=null&&Mm.call(Os,Vm)),av1:!!((Cm=(Vs=wt())==null?void 0:Vs.isTypeSupported)!=null&&Cm.call(Vs,_m)),aac:!!((Dm=(_s=wt())==null?void 0:_s.isTypeSupported)!=null&&Dm.call(_s,nP)),opus:!!((Bm=(Ns=wt())==null?void 0:Ns.isTypeSupported)!=null&&Bm.call(Ns,oP))},qi=(Ce.h264||Ce.h265)&&Ce.aac,ni,uP=()=>V(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(j(R({},a),{video:j(R({},a.video),{contentType:_m})})),window.navigator.mediaCapabilities.decodingInfo(j(R({},a),{video:j(R({},a.video),{contentType:Vm})}))]);ni={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{uP()}catch(a){console.error(a)}var Ui=si.hls&&Me.mp4,Nm=()=>Object.keys(Ce).filter(a=>Ce[a]),Fm=(a,e=!1,t=!1)=>{let i=si.mse||si.mms&&t;return a.filter(r=>{switch(r){case"DASH_SEP":return i&&Me.mp4&&qi;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&&qi||Me.webm&&(Ce.vp9||Ce.av1)&&(Ce.opus||Ce.aac));case"DASH_LIVE":return si.mse&&Me.mp4&&qi;case"DASH_LIVE_CMAF":return i&&Me.mp4&&qi&&Me.cmaf;case"DASH_ONDEMAND":return i&&Me.mp4&&qi;case"HLS":case"HLS_ONDEMAND":return Ui||e&&si.mse&&Me.mp4&&qi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Ui;case"MPEG":return Me.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return si.webrtc&&si.ws&&Ce.h264&&(Me.mp4||Me.webm);default:return(0,ft.assertNever)(r)}})},Cs=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 ni?ni[t].smooth?[t,e]:ni[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ni?ni[t].powerEfficient?[t,e]:ni[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,ft.assertNever)(a)}return[e,t]},qm=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Cs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ft.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Cs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Cs(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Cs(a),...r,"HLS","HLS_ONDEMAND"];default:(0,ft.assertNever)(e)}return Ui?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Um=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],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 Ui&&!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"]},fu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Hm=a=>{if(a.size!==0){if(a.size===1)return a.values().next().value.split(".").at(0);for(let e of a){let t=(0,Om.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return a.values().next().value.split(".").at(0)}};var Hi=require("@vkontakte/videoplayer-shared"),jm=a=>{if(!a)return{id:"EmptyResponse",category:Hi.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Hi.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=a.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Hi.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:Hi.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Hi.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var ji=(a,e)=>{for(let t=0;t<a.length;t++)if(a.start(t)*1e3<=e&&a.end(t)*1e3>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared");var Ki=Xe(Cr(),1);var lP=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},cP=a=>window.clearTimeout(a),Gm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",mu=Gm?lP:window.requestIdleCallback,zL=Gm?cP:window.cancelIdleCallback;var $b=Xe(Es(),1);var Qe=require("@vkontakte/videoplayer-shared");var dP=16,Wm=!1;try{Wm=Qe.clientChecker.isSafari&&!!Qe.clientChecker.macVersion&&Qe.clientChecker.macVersion<=dP}catch(a){console.error(a)}var bu=class{constructor(e){this.bufferFull$=new Qe.Subject;this.error$=new Qe.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:Qe.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return V(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return V(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return V(this,null,function*(){return new Promise(t=>{let i;Wm&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.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:Qe.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,Qe.assertNever)(t)}}},Ym=bu;var gu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var x=require("@vkontakte/videoplayer-shared");var re=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Gi=class extends re{};var Hr=class extends re{};var jr=class extends re{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Gr=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Wr=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Yr=class extends re{constructor(e,t){super(e,t),this.data=this.content}};var pe=class extends re{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var oi=class extends pe{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Qr=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zr=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Kr=class extends pe{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Jr=class extends pe{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Xr=class extends pe{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Zr=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends pe{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ta=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ia=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends pe{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var aa=class extends re{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var sa=class extends pe{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var na=class extends pe{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var oa=class extends pe{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var hP={ftyp:jr,moov:Gr,moof:Wr,mdat:Yr,sidx:oi,trak:Qr,mdia:Zr,mfhd:ra,tkhd:ea,traf:aa,tfhd:sa,tfdt:na,trun:oa,minf:ta,sv3d:zr,st3d:Kr,prhd:Jr,proj:ia,equi:Xr,uuid:Hr,unknown:Gi},ui=class a{constructor(e={}){this.options=R({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=hP[e];return i?new i(t,new a):new Gi(t,new a)}};var Wi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 mP=new TextDecoder("ascii"),bP=a=>mP.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",gP=a=>{let e=new oi(a,new ui),t=e.earliestPresentationTime/e.timescale*1e3,i=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:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},SP=(a,e)=>{let i=new ui().parse(a),r=new Wi(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.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)},vP=(a,e)=>{let i=new ui().parse(a),s=new Wi(i).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},yP=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}}},i=new ui().parse(a),r=new Wi(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Qm={validateData:bP,parseInit:yP,getIndexRange:()=>{},parseSegments:gP,parseFeedableSegmentChunk:SP,getSegmentEndTime:vP};var kt=require("@vkontakte/videoplayer-shared");var Km=require("@vkontakte/videoplayer-shared");var zm={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"}},Jm=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 i=ua(a,t),r=i in zm,s=r?zm[i].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=ua(u),d=l*ot(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:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ua=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*ot(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*ot(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*ot(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},rt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ua(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,Km.assertNever)(e)}},li=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Jm(i);if(!e(r))return;r.type==="master"&&li(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Xm=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Jm(a);return li(r.value,({tag:s,type:n,value:o})=>(s===17143?e=rt(o,n):s===17026?t=rt(o,n):s===17029&&(i=rt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Zm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],TP=[231,22612,22743,167,171,163,160,175],IP=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return li(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let S=rt(m,h);l=ua(S)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=rt(m,h):p===17545?r=rt(m,h):p===21420&&l===475249515?u=rt(m,h):p===374648427?li(m,({tag:S,type:T,value:P})=>S===30321?(c=rt(P,T)===1,!1):!0):s&&n&&Zm.includes(p)&&(o=!0),!o}),(0,kt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,kt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,kt.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},EP=a=>{if((0,kt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},xP=(a,e)=>{let t=!1,i=!1,r=o=>(0,kt.isNonNullable)(o.time)&&(0,kt.isNonNullable)(o.position),s=[],n;return li(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=rt(l,u));break;case 183:break;case 241:n&&(n.position=rt(l,u));break;default:t&&Zm.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(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}}})},PP=a=>{let e=0,t=!1;try{li(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):TP.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},eb={validateData:Xm,parseInit:IP,getIndexRange:EP,parseSegments:xP,parseFeedableSegmentChunk:PP};var Yi=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return eb;case"mp4":return Qm}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Pu=Xe(Ib(),1);var xu=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};var zi=require("@vkontakte/videoplayer-shared");var Eb=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var xb=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Rt=(a,e)=>{let t=a;t=(0,Pu.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Pu.default)(t,n,(o,u)=>(0,zi.isNullable)(s)?o:(0,zi.isNullable)(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Pb=(a,e)=>{var E,A,B,te,H,Q,ie,Z,F,ee,K,C,k,z,se,le,he,Ee,Gt,Ct,$,xe,De,Fe,Dt,fi,Bt,Wt,mi,Zi,Nu,Fu,qu,Uu,Hu,ju,Gu,Wu,Yu,Qu,zu,Ku,Ju,Xu,Zu,el,tl,il,rl,al,sl,nl,ol,ul,ll,cl,dl,pl,hl,fl;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=s.getElementsByTagName("Period")[0],o=(B=(A=(E=s.querySelector("BaseURL"))==null?void 0:E.textContent)==null?void 0:A.trim())!=null?B:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=xb(h);else if(m){let Pe=xb(m);(0,zi.isNonNullable)(Pe)&&(p=Pe)}else S&&(p=parseInt(S,10));let T=0,P=(H=(te=s.getAttribute("profiles"))==null?void 0:te.split(","))!=null?H:[];for(let Pe of u){let tg=(Q=Pe.getAttribute("id"))!=null?Q:"id"+(T++).toString(10),er=(ie=Pe.getAttribute("mimeType"))!=null?ie:"",rn=(Z=Pe.getAttribute("codecs"))!=null?Z:"",an=(F=Pe.getAttribute("contentType"))!=null?F:er==null?void 0:er.split("/")[0],ig=(K=(ee=Pe.getAttribute("profiles"))==null?void 0:ee.split(","))!=null?K:[],rg=(C=Pe.getAttribute("lang"))!=null?C:void 0,ag=(se=(z=(k=Pe.querySelector("Label"))==null?void 0:k.textContent)==null?void 0:z.trim())!=null?se:void 0,sg=Pe.querySelectorAll("Representation"),ng=Pe.querySelector("SegmentTemplate"),og=(he=(le=Pe.querySelector("Role"))==null?void 0:le.getAttribute("value"))!=null?he:void 0,tr=an,fe={id:tg,language:rg,isDefault:og==="main",label:ag,codecs:rn,hdr:tr==="video"&&xu(rn),mime:er,representations:[]};for(let ne of sg){let ug=(Ee=ne.getAttribute("lang"))!=null?Ee:void 0,lg=(Gt=ne.getAttribute("label"))!=null?Gt:void 0,cg=(xe=($=(Ct=ne.querySelector("BaseURL"))==null?void 0:Ct.textContent)==null?void 0:$.trim())!=null?xe:"",sn=new URL(cg||o,e).toString(),bi=(De=ne.getAttribute("mimeType"))!=null?De:er,$a=(Dt=(Fe=ne.getAttribute("codecs"))!=null?Fe:rn)!=null?Dt:"",nn;if(an==="text"){let Yt=ne.getAttribute("id")||"",on=Yt.includes("_auto"),Qt=ne.querySelector("SegmentTemplate");if(!Qt)continue;let ir={representationId:(fi=ne.getAttribute("id"))!=null?fi:void 0,bandwidth:(Bt=ne.getAttribute("bandwidth"))!=null?Bt:void 0},La=parseInt((Wt=ne.getAttribute("bandwidth"))!=null?Wt:"",10)/1e3,Ma=(Zi=parseInt((mi=Qt.getAttribute("startNumber"))!=null?mi:"",10))!=null?Zi:1,gi=parseInt((Nu=Qt.getAttribute("timescale"))!=null?Nu:"",10),un=(Fu=Qt.querySelectorAll("SegmentTimeline S"))!=null?Fu:[],Si=Qt.getAttribute("media");if(!Si)continue;let Ca=[],Da=0,Ba="",vi=0,rr=Ma,ve=0;for(let Ke of un){let zt=parseInt((qu=Ke.getAttribute("d"))!=null?qu:"",10),qe=parseInt((Uu=Ke.getAttribute("r"))!=null?Uu:"",10)||0,Ot=parseInt((Hu=Ke.getAttribute("t"))!=null?Hu:"",10);ve=Number.isFinite(Ot)?Ot:ve;let Kt=zt/gi*1e3,Vt=ve/gi*1e3;for(let st=0;st<qe+1;st++){let _t=Rt(Si,j(R({},ir),{segmentNumber:rr.toString(10),segmentTime:(ve+st*zt).toString(10)})),yi=(Vt!=null?Vt:0)+st*Kt,sr=yi+Kt;rr++,Ca.push({time:{from:yi,to:sr},url:_t})}ve+=(qe+1)*zt,Da+=(qe+1)*Kt}vi=ve/gi*1e3,Ba=Rt(Si,j(R({},ir),{segmentNumber:rr.toString(10),segmentTime:ve.toString(10)}));let ar={time:{from:vi,to:1/0},url:Ba},bt={type:"template",baseUrl:sn,segmentTemplateUrl:Si,initUrl:"",totalSegmentsDurationMs:Da,segments:Ca,nextSegmentBeyondManifest:ar,timescale:gi};nn={id:Yt,kind:"text",segmentReference:bt,profiles:[],duration:p,bitrate:La,mime:"",codecs:"",width:0,height:0,isAuto:on}}else{let Yt=(Gu=(ju=ne.getAttribute("contentType"))!=null?ju:bi==null?void 0:bi.split("/")[0])!=null?Gu:an,on=(Yu=(Wu=Pe.getAttribute("profiles"))==null?void 0:Wu.split(","))!=null?Yu:[],Qt=parseInt((Qu=ne.getAttribute("width"))!=null?Qu:"",10),ir=parseInt((zu=ne.getAttribute("height"))!=null?zu:"",10),La=parseInt((Ku=ne.getAttribute("bandwidth"))!=null?Ku:"",10)/1e3,Ma=(Ju=ne.getAttribute("frameRate"))!=null?Ju:"",gi=(Xu=ne.getAttribute("quality"))!=null?Xu:void 0,un=Ma?Eb(Ma):void 0,Si=(Zu=ne.getAttribute("id"))!=null?Zu:"id"+(T++).toString(10),Ca=Yt==="video"?`${ir}p`:Yt==="audio"?`${La}Kbps`:$a,Da=`${Si}@${Ca}`,Ba=[...P,...ig,...on],vi,rr=ne.querySelector("SegmentBase"),ve=(el=ne.querySelector("SegmentTemplate"))!=null?el:ng;if(rr){let bt=(il=(tl=ne.querySelector("SegmentBase Initialization"))==null?void 0:tl.getAttribute("range"))!=null?il:"",[Ke,zt]=bt.split("-").map(_t=>parseInt(_t,10)),qe={from:Ke,to:zt},Ot=(rl=ne.querySelector("SegmentBase"))==null?void 0:rl.getAttribute("indexRange"),[Kt,Vt]=Ot?Ot.split("-").map(_t=>parseInt(_t,10)):[],st=Ot?{from:Kt,to:Vt}:void 0;vi={type:"byteRange",url:sn,initRange:qe,indexRange:st}}else if(ve){let bt={representationId:(al=ne.getAttribute("id"))!=null?al:void 0,bandwidth:(sl=ne.getAttribute("bandwidth"))!=null?sl:void 0},Ke=parseInt((nl=ve.getAttribute("timescale"))!=null?nl:"",10),zt=(ol=ve.getAttribute("initialization"))!=null?ol:"",qe=ve.getAttribute("media"),Ot=(ll=parseInt((ul=ve.getAttribute("startNumber"))!=null?ul:"",10))!=null?ll:1,Kt=Rt(zt,bt);if(!qe)throw new ReferenceError("No media attribute in SegmentTemplate");let Vt=(cl=ve.querySelectorAll("SegmentTimeline S"))!=null?cl:[],st=[],_t=0,yi="",sr=0;if(Vt.length){let Oa=Ot,Je=0;for(let Ti of Vt){let nt=parseInt((dl=Ti.getAttribute("d"))!=null?dl:"",10),Jt=parseInt((pl=Ti.getAttribute("r"))!=null?pl:"",10)||0,Va=parseInt((hl=Ti.getAttribute("t"))!=null?hl:"",10);Je=Number.isFinite(Va)?Va:Je;let ln=nt/Ke*1e3,cn=Je/Ke*1e3;for(let _a=0;_a<Jt+1;_a++){let pg=Rt(qe,j(R({},bt),{segmentNumber:Oa.toString(10),segmentTime:(Je+_a*nt).toString(10)})),ml=(cn!=null?cn:0)+_a*ln,hg=ml+ln;Oa++,st.push({time:{from:ml,to:hg},url:pg})}Je+=(Jt+1)*nt,_t+=(Jt+1)*ln}sr=Je/Ke*1e3,yi=Rt(qe,j(R({},bt),{segmentNumber:Oa.toString(10),segmentTime:Je.toString(10)}))}else if((0,zi.isNonNullable)(p)){let Je=parseInt((fl=ve.getAttribute("duration"))!=null?fl:"",10)/Ke*1e3,Ti=Math.ceil(p/Je),nt=0;for(let Jt=1;Jt<Ti;Jt++){let Va=Rt(qe,j(R({},bt),{segmentNumber:Jt.toString(10),segmentTime:nt.toString(10)}));st.push({time:{from:nt,to:nt+Je},url:Va}),nt+=Je}sr=nt,yi=Rt(qe,j(R({},bt),{segmentNumber:Ti.toString(10),segmentTime:nt.toString(10)}))}let dg={time:{from:sr,to:1/0},url:yi};vi={type:"template",baseUrl:sn,segmentTemplateUrl:qe,initUrl:Kt,totalSegmentsDurationMs:_t,segments:st,nextSegmentBeyondManifest:dg,timescale:Ke}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Yt||!bi)continue;let ar={video:"video",audio:"audio",text:"text"}[Yt];if(!ar)continue;tr||(tr=ar),nn={id:Da,kind:ar,segmentReference:vi,profiles:Ba,duration:p,bitrate:La,mime:bi,codecs:$a,width:Qt,height:ir,fps:un,quality:gi}}fe.language||(fe.language=ug),fe.label||(fe.label=lg),fe.mime||(fe.mime=bi),fe.codecs||(fe.codecs=$a),fe.hdr||(fe.hdr=tr==="video"&&xu($a)),fe.representations.push(nn)}tr&&r[tr].push(fe)}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,streams:r}};var la=Xe(Cr(),1);var Ab=require("@vkontakte/videoplayer-shared"),wb=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s})=>{var o;let n=(o=s?Ut(s):void 0)!=null?o:(0,Ab.videoSizeToQuality)({width:e,height:t});return n&&{id:a,quality:n,bitrate:i,size:{width:e,height:t},fps:r}},kb=({id:a,bitrate:e})=>({id:a,bitrate:e}),Fs=(a,e,t)=>{var r;let i=e.indexOf(a);return(r=(0,la.default)(t,Math.round(t.length*i/e.length)))!=null?r:(0,la.default)(t,-1)},Rb=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),ku=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,la.default)(i.split("."),0),isDefault:r}),Ru=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,la.default)(r.split("."),0)}),qs=a=>"url"in a,ze=a=>a.type==="template",ca=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var da=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new x.ValueSubject(0);this.onLastSegment$=new x.ValueSubject(!1);this.fullyBuffered$=new x.ValueSubject(!1);this.playingRepresentation$=new x.ValueSubject(void 0);this.playingRepresentationInit$=new x.ValueSubject(void 0);this.error$=new x.Subject;this.gaps=[];this.subscription=new x.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new At;this.destroyAbortController=new At;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,x.abortable)(this.destroyAbortController.signal,function(e){return me(this,null,function*(){let t=this.representations.get(e);(0,x.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 Ym(this.sourceBuffer),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,x.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.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,gu(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let l=ht(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,n*2,l<c)}else this.pruneBufferOld(o,n)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,x.assertNonNullable)(i,"No init buffer for starting representation"),(0,x.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,x.abortable)(this.destroyAbortController.signal,function(e,t=!1){return me(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,x.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,x.isNullable)(s)||(0,x.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,x.assertNonNullable)(r,"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,x.isNonNullable)(n)&&(this.isLive||(this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),yield new pn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,x.abortable)(this.destroyAbortController.signal,function(e){return me(this,null,function*(){var u,l;let t=(u=e==null?void 0:e.flatMap(c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!ze(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,x.assertNonNullable)(r);let s=this.segments.get(i);(0,x.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,x.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,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new At,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if((0,x.isNullable)(e)||(0,x.isNullable)(this.downloadingRepresentationId)||(0,x.isNullable)(this.playingRepresentationId)||(0,x.isNullable)(this.sourceBuffer)||!(0,x.isNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,x.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=r==null?void 0:r.time.to)!=null?l:0)-((c=r==null?void 0:r.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=ht(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&gu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=ht(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{let p=(0,Ki.default)(o,0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&ht(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Ki.default)(i,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;(0,x.isNonNullable)(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?i:[];for(let o of t){if(!o||!ze(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>j(R({},p),{status:"none",size:void 0})),l=(r=this.segments.get(o.id))!=null?r:[],c=(n=(s=(0,Ki.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(p=>Math.floor(c)>=Math.floor(p.time.from)&&Math.floor(c)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(d+1);this.segments.set(o.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,x.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){this.bufferAccumulation={enabled:!1,targetBufferSizeMs:this.tuning.accumulationBufferStallSizeMs,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let i of this.representations.values()){let r=i.segmentReference;if(!ze(r))return;let s=(t=this.segments.get(i.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*r.timescale/1e3).toString(10),l=Rt(r.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 i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let g=p<=i&&h>=i,S=p>i||g||m===0&&i===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),P=this.preloadOnly&&p<=i+T||h<=i+T;return(d==="none"||d==="partially_ejected"&&S&&P&&this.sourceBuffer&&!(ji(this.sourceBuffer.buffered,p)&&ji(this.sourceBuffer.buffered,h)))&&S&&P});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+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=r;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,i="auto"){return V(this,null,function*(){ze(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return V(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,x.abortable)(o,function(){return me(this,null,function*(){let c=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,x.now)(),!c)return;let d=new DataView(c);if(!isFinite(r.segment.time.to)){let p=t.segmentReference.timescale,h=Yi(t.mime);r.segment.time.to=h.getSegmentEndTime(d,p)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),ca(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,i="auto"){return V(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,x.abortable)(n,function(){return me(this,null,function*(){let u=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,x.fromEvent)(window,"online").pipe((0,x.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,x.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ca(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(ze(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ki.default)(e,0).byte.from,to:(0,Ki.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,x.now)(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ze(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,x.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:x.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return V(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Yi(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){let o={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:l;if(c.representationId!==t||!(!p||d.byte.from>=i&&d.byte.to<i+e.byteLength))continue;if(s.aborted){n();continue}let g=p?d.byte.from-i:0,S=p?d.byte.to-i:e.byteLength,T=g<r,P=S<=r;if(d.status==="downloading"&&T&&P){d.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+g,h),E=this.getCurrentPosition();(0,x.isNonNullable)(E)&&(this.bufferAccumulation.accumulatedBufferSizeMs=d.time.to-E,this.bufferAccumulation.accumulated.push({segmentView:I,segmentProgress:c}),this.activeSegments.delete(c));let A=({segmentView:B,segmentProgress:te})=>this.sourceBufferTaskQueue.append(B,s).then(H=>H&&!s.aborted?this.onSegmentFullyAppended(te,t):n());this.bufferAccumulation.enabled&&this.bufferAccumulation.targetBufferSizeMs<this.bufferAccumulation.accumulatedBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(A),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||(0,x.isNullable)(E))&&(A({segmentView:I,segmentProgress:c}),this.resetAccumulateBufferAfterStall())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&!P&&(c.loadedBytes=Math.min(h,r-g),c.loadedBytes>c.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+g+c.feedingBytes,c.loadedBytes-c.feedingBytes),E=c.loadedBytes===h?I:Yi(o.mime).parseFeedableSegmentChunk(I);E!=null&&E.byteLength&&(d.status="partially_fed",c.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,s).then(A=>{if(s.aborted)n();else if(A)c.fedBytes+=E.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSomeByteRangesDataLoadedNew(o){return V(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-i,p=c.byte.to-i,h=p-d+1,m=d<r,g=p<=r;if(m){if(c.status==="downloading"&&g){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,r-d),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),T=l.loadedBytes===h?S:Yi(u.mime).parseFeedableSegmentChunk(S);T!=null&&T.byteLength&&(c.status="partially_fed",l.feedingBytes+=T.byteLength,(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?(l.fedBytes+=T.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):n())}}}})}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",qs(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])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,x.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[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=mu(()=>(0,$b.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return V(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,x.abortable)(this.destroyAbortController.signal,function(){return me(this,null,function*(){let o=(0,x.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Yi(e.mime),r)).then(o=>V(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&ze(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:x.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return V(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return V(this,null,function*(){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)})}pruneBufferNew(e,t,i=!1){return V(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=[],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 r;r.push(R({},u.time)),r=n(r);let l=qs(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)["none","partially_ejected"].includes(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(r.length&&i){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 r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}pruneBufferOld(e,t,i=!1){return V(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,x.isNullable)(e)||this.sourceBuffer.updating)return!1;let r=0,s=1/0,n=-1/0,o=!1,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=qs(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;r+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){r=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&i){r=0,s=1/0,n=-1/0;let l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+l&&d.status==="fed"&&u(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,x.isNullable)(e)?0:ht(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){(0,x.assertNonNullable)(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=mu(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:x.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,x.isNullable)(this.sourceBuffer)||(0,x.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.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?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var pa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Lb=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};var J=require("@vkontakte/videoplayer-shared");var Us=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1}){this.lastConnectionType$=new J.ValueSubject(void 0);this.lastConnectionReused$=new J.ValueSubject(void 0);this.lastRequestFirstBytes$=new J.ValueSubject(void 0);this.abortAllController=new At;this.subscription=new J.Subscription;this.fetchManifest=(0,J.abortable)(this.abortAllController.signal,function(e){return me(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=pa(i));let r=yield Pt(i,{signal:this.abortAllController.signal}).catch(ha);return r?(t.log("success",(0,J.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,J.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,J.abortable)(this.abortAllController.signal,function(l){return me(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var F,ee;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let K=new URL(c,location.href);K.searchParams.append("bytes",`${i.from}-${i.to}`),c=K.toString();break}default:(0,J.assertNever)(t)}this.requestQuic&&(c=pa(c));let h=this.abortAllController.signal,m;if(n){let K=new At;if(m=(0,J.merge)((0,J.fromEvent)(this.abortAllController.signal,"abort"),(0,J.fromEvent)(n,"abort")).subscribe(()=>{try{K.abort()}catch(C){ha(C)}}),this.abortAllController.signal.aborted||n.aborted)try{K.abort()}catch(C){ha(C)}h=K.signal}let g=(0,J.now)();p.log("startRequest",(0,J.flattenObject)({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g}));let S=yield Pt(c,{priority:s,headers:d,signal:h}).catch(ha),T=(0,J.now)();if(!S)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((F=this.throughputEstimator)==null||F.addRawRtt(T-g),!S.ok||!S.body){m==null||m.unsubscribe();let K=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:K}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!o){m==null||m.unsubscribe();let K=(0,J.now)(),C={requestStartedAt:g,requestEndedAt:K,duration:K-g};return p.log("endRequest",(0,J.flattenObject)(C)),p.end(),S.arrayBuffer()}let[P,I]=S.body.tee(),E=P.getReader();o&&((ee=this.throughputEstimator)==null||ee.trackStream(I,u));let A=0,B=new Uint8Array(0),te=!1,H=K=>{m==null||m.unsubscribe(),te=!0,ha(K)},Q=(0,J.abortable)(h,function(k){return me(this,arguments,function*({done:K,value:C}){if(A===0&&this.lastRequestFirstBytes$.next((0,J.now)()-g),h.aborted){m==null||m.unsubscribe();return}if(!K&&C){let z=new Uint8Array(B.length+C.length);z.set(B),z.set(C,B.length),B=z,A+=C.byteLength,r==null||r(new DataView(B.buffer),A),yield E==null?void 0:E.read().then(Q,H)}})}.bind(this));yield E==null?void 0:E.read().then(Q,H),m==null||m.unsubscribe();let ie=(0,J.now)(),Z={failed:te,requestStartedAt:g,requestEndedAt:ie,duration:ie-g};return te?(p.error("endRequest",(0,J.flattenObject)(Z)),p.end(),null):(p.log("endRequest",(0,J.flattenObject)(Z)),p.end(),B.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t,i){return me(this,null,function*(){var T;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,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,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(T=e.indexRange)!=null?T:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let P=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!P)return null;g=new DataView(P)}let S=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,J.abortable)(this.abortAllController.signal,function(e,t){return me(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>j(R({},n),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher")}onHeadersReceived(e){let{type:t,reused:i}=Lb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return V(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,J.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ha=a=>{if(!ca(a))throw a};var ci=(a,e,t)=>t*e+(1-t)*a,$u=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Mb=(a,e,t,i)=>{let r=0,s=t,n=$u(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var fa=require("@vkontakte/videoplayer-shared");var jt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new fa.ValueSubject(e.initial),this.debounced$=new fa.ValueSubject(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${t}`),this.smoothedSeries$=new Ie(`smoothed_${t}`),this.reportedSeries$=new Ie(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=ot(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,fa.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 Hs=class extends jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ci(this.slow,e,this.params.emaAlphaSlow),this.fast=ci(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var js=class extends jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=$u(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ci(this.emaSmoothed,e,this.params.emaAlpha);let i=Mb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Gs=class extends jt{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?ci(this.smoothed,t,this.params.emaAlpha):t}};var di=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Hs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new js({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Gs(R({initial:e,label:"liveEdgeDelay"},t))}};var Lu=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var Ws=require("@vkontakte/videoplayer-shared");var ma=class a{constructor(e,t){this.currentRepresentation$=new Ws.ValueSubject(null);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,Ws.isNullable)(e))for(let i of this.representations){let r=i.segmentReference.segments.find(s=>s.time.from<=e&&s.time.to>=e);if(!r||((t=this.currentSegment)==null?void 0:t.time.from)===r.time.from&&this.currentSegment.time.to===r.time.to)return;this.currentSegment=r,this.currentRepresentation$.next(j(R({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(r.url,i.segmentReference.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations=i;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&&ze(t.segmentReference))}};var oA=["timeupdate","progress","play","seeked","stalled","waiting"],uA=["timeupdate","progress","loadeddata","playing","seeked"];var Ys=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new W("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.currentLiveTextRepresentation$=new v.ValueSubject(null);this.isLive$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.isActiveLowLatency$=new v.ValueSubject(!1);this.timeInWaiting=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new At;this.initManifest=(0,v.abortable)(this.destroyController.signal,function(e,t,i){return me(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,function(){return me(this,null,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:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Pb(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=jm(e))!=null?n:{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(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=wt())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${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 r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:m})=>i(u,h,m)),d=new Set(c.map(({codecs:h})=>h)),p=Hm(d);if(p&&(r[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=r.video.some(S=>S.hdr),g=r.video.some(S=>!S.hdr);v.clientChecker.isHDR&&h&&m?r.video=r.video.filter(S=>S.hdr):g&&(r.video=r.video.filter(S=>!S.hdr))}}let s=j(R({},t),{streams:r});return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,function(e,t,i){return me(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,v.fromEvent)(p,"error").pipe((0,v.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Pm():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ms())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new da("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new da("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(ma.isSupported(this.manifest.streams.text)&&!this.tuning.dashCmafLive.lowLatency.isActive&&(this.liveTextManager=new ma(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,v.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=eu(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add((0,v.merge)(...uA.map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?ht(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.tap)(p=>{var h;p>this.tuning.dash.bufferEmptinessTolerance&&((h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,v.filterChanged)()).subscribe(h=>Lu(this.element,1))),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,v.filter)(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add((0,v.combine)({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:m})=>{if(!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,P=h-g,I=1;Math.abs(P)>S&&(I=1+Math.sign(P)*T),Lu(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let T=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var E,A;return(A=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?A:T}))-T}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(g=>V(this,[g],function*({liveLoadBufferLength:h,bufferLength:m}){if((0,v.assertNonNullable)(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,T=eu(this.manifestUrlString,2),P=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(P,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,B=isFinite(h)?h:m,te=this.isActiveLowLatency$.getValue(),H=P<=this.tuning.live.activeLiveDelay&&T===0;this.isActiveLowLatency$.next(te&&H);let Q="none";if(te?Q="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&H?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(ie=>ie.proceedLowLatencyLive()),Q="active_low_latency"):T!==0&&B<I?Q="live_forward_buffering":B<I+A&&(Q="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),Q==="live_forward_buffering"||Q==="live_with_target_offset"){let ie=p-(I+E),Z=this.normolizeLiveOffset(Math.trunc(T+ie/S)),F=Math.abs(Z-T),ee;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?ee=T:Z>0&&F>this.tuning.dashCmafLive.offsetCalculationError?ee=Z:ee=0,this.manifestUrlString=Se(this.manifestUrlString,ee,2)}Q!=="none"&&Q!=="active_low_latency"&&(p=0,this.updateLive())})))}let u=(0,v.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=(0,v.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:u,someBufferEnded:l}).pipe((0,v.filter)(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.subscription.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)}));let c=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),ze(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&(0,v.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,i,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(i=this.liveTextManager)==null||i.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:v.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 Us({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer}),this.liveEstimatedDelay=di.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,R({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.initTracerSubscription()}seekLive(e){return V(this,null,function*(){var i,r,s;(0,v.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=Se(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive(this.manifest.streams.video),yield(r=this.audioBufferManager)==null?void 0:r.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...oA.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{var t,i,r;this.element&&this.element.readyState===2&&!this.element.seeking&&ji(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var m,g,S,T,P,I,E,A,B,te;if(!this.element)return;this.timeInWaiting+=1e3;let s={timeInWaiting:this.timeInWaiting},n=(0,v.now)(),o=100,u=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0,l=(T=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?T:0,c=(I=(P=this.videoBufferManager)==null?void 0:P.getForwardBufferDuration())!=null?I:0,d=(A=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?A:0,p=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if(this.tuning.useNewProviderReinitLogic&&(p||h)||this.tuning.useNewProviderReinitLogic&&this.timeInWaiting>=2*this.tuning.dash.crashOnStallTimeout||!this.tuning.useNewProviderReinitLogic&&this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset),s=j(R({},s),{liveLastSeekOffset:this.liveLastSeekOffset});else{let H=this.element.currentTime*1e3;(B=this.videoBufferManager)==null||B.maintain(H),(te=this.audioBufferManager)==null||te.maintain(H),s=j(R({},s),{position:H})}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(s))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(i=this.audioBufferManager)==null||i.startAccumulateBuffer(),(r=this.stallWatchdogSubscription)==null||r.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(1e3).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:this.tuning.useNewProviderReinitLogic?v.ErrorCategory.NETWORK:v.ErrorCategory.FATAL,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return V(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)})}seek(e,t){var r,s,n,o,u,l;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),ji(this.element.buffered,i)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:i}))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.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,v.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return V(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.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 i=this.element.currentTime*1e3,r=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=i&&o.to+s>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r.push(1/0):r.push(o.to));if(r.length){let n=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=j(R({},t),{gapEnds:r,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,v.flattenObject)(t)))}}};var Qs=class{constructor(e,t){this.fov=e,this.orientation=t}};var zs=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/ot(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=R({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*ot(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Db=`attribute vec2 a_vertex;
|
|
59
59
|
attribute vec2 a_texel;
|
|
60
60
|
|
|
61
61
|
varying vec2 v_texel;
|
|
@@ -66,7 +66,7 @@ void main(void) {
|
|
|
66
66
|
// save texel vector to pass to fragment shader
|
|
67
67
|
v_texel = a_texel;
|
|
68
68
|
}
|
|
69
|
-
`;var
|
|
69
|
+
`;var Bb=`#ifdef GL_ES
|
|
70
70
|
precision highp float;
|
|
71
71
|
precision highp int;
|
|
72
72
|
#else
|
|
@@ -109,5 +109,5 @@ void main(void) {
|
|
|
109
109
|
// sample using new coordinates
|
|
110
110
|
gl_FragColor = texture2D(u_texture, tc);
|
|
111
111
|
}
|
|
112
|
-
`;var Ms=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 $s(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ls(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(mb,this.gl.VERTEX_SHADER),r=this.createShader(bb,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,c=e+r,l=t+i,d=e-r,p=t+i;return[s,n,o,u,c,l,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 sr=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new j("stopped");this.elementSize$=new U.ValueSubject(void 0);this.textTracksManager=new je;this.droppedFramesManager=new ds;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ei;this.audioTrackSwitchHistory=new Ei;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let c=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-c,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&w(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,U.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Ms(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=Ae(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.player=new Rs({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=Re(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:U.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,U.filter)(c=>!!c.length),(0,U.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})})),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,U.filter)(U.isNonNullable),(0,U.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,U.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(ke(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(He(this.video,t.playbackRate,r.playbackRateState$,i)),s((0,U.observeElementSize)(this.video),this.elementSize$),s(Ge(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let l=this.player.getStreams();if((0,U.assertNonNullable)(l,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of l.audio){p.push(fu(h));let m=[];for(let g of h.representations){let S=ub(g);m.push(S),this.audioTracksMap.set(S,{stream:h,representation:g})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of l.video){d.push(mu(p));let h=[];for(let m of p.representations){let g=ob(m);g&&(h.push(g),this.videoTracksMap.set(g,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of l.text)for(let h of p.representations){let m=cb(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let n=c=>e.error$.next({id:"RepresentationSwitch",category:U.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,U.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,U.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),l=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||l)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),c==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,g).catch(n)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,U.filterChanged)()).subscribe(c=>{let l=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===c);if(!l){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=l,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(mu(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,U.filterChanged)()).subscribe(c=>{let l=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===c);if(!l){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=l,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(fu(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var l,d;if(c!=null&&c.is3dVideo&&((l=this.params.tuning.spherical)!=null&&l.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(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,U.map)(({to:c})=>c==="ready"),(0,U.filterChanged)());this.subscription.add((0,U.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,U.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,U.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var _,ae,Q,W,te,Z,F,ee,K,M,k,Y,se,ue,pe,Ie,Vt,wt;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:R})=>R===i),o=t.currentVideoTrack$.getValue(),u=((W=(Q=e.videoStream.getState())!=null?Q:n&&((ae=this.videoTracksMap.get(n))==null?void 0:ae.stream))!=null?W:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let c=[...this.videoStreamsMap.keys()].find(({id:R})=>R===u.id),l=c&&this.videoStreamsMap.get(c);if(!l)return;let d=vt(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=(te=e.audioStream.getState())!=null?te:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(Z=[...this.audioStreamsMap.keys()].find(({id:R})=>R===(m==null?void 0:m.id)))!=null?Z:this.audioStreamsMap.keys().next().value,S=0;if(g){if(n&&!r)if(this.params.tuning.useSeparateAudioVideoABR){let R=cs(n,l,(F=this.audioStreamsMap.get(g))!=null?F:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(ee=R==null?void 0:R.bitrate)!=null?ee:-1/0)}else{let R=Es(n,l,(K=this.audioStreamsMap.get(g))!=null?K:[]);S=Math.max(S,(M=R==null?void 0:R.bitrate)!=null?M:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let R=cs(o,l,(k=this.audioStreamsMap.get(g))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(Y=R==null?void 0:R.bitrate)!=null?Y:-1/0)}else{let R=Es(o,l,(se=this.audioStreamsMap.get(g))!=null?se:[]);S=Math.max(S,(ue=R==null?void 0:R.bitrate)!=null?ue:-1/0)}}let T=Bt(l,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),P=r?T!=null?T:n:n!=null?n:T,I;this.params.tuning.useSeparateAudioVideoABR?I=g&&Jf(P,l,(pe=this.audioStreamsMap.get(g))!=null?pe:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):I=g&&Es(P,l,(Ie=this.audioStreamsMap.get(g))!=null?Ie:[]);let E=(Vt=this.videoTracksMap.get(P))==null?void 0:Vt.representation,A=I&&((wt=this.audioTracksMap.get(I))==null?void 0:wt.representation);if(E&&A)return[E,A];if(E&&!A&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){$e(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),we(this.video),this.tracer.end()}};var aa=class extends sr{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 nr=require("@vkontakte/videoplayer-shared");var sa=class extends sr{constructor(e){super(e),this.liveOffset=new bt}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,nr.combine)({interval:(0,nr.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:i})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(i-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add((0,nr.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,nr.map)(({liveBufferTime:i,liveAvailabilityStartTime:s})=>i&&s?i+s:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var gb=ze(ns(),1);var G=require("@vkontakte/videoplayer-shared");var tt={};var qr=(a,e)=>new G.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),na=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new j("initializing");this.textTracksManager=new je;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,G.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,G.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,G.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,G.assertNever)(e)}break;default:(0,G.assertNever)(t)}};this.video=Ae(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),we(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,gb.default)(import("hls.js").then(i=>{e||(tt.Hls=i.default,tt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,G.assertNonNullable)(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,G.assertNonNullable)(tt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=c=>{t.error$.next({id:"HlsJsProvider",category:G.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:c})},i=Re(this.video),s=(c,l)=>this.subscription.add(c.subscribe(l,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(nt(this.video,e.isLooped,r)),this.subscription.add(ke(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(He(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ge(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,G.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(qr(this.hls,tt.Events.ERROR).subscribe(c=>{var l;c.fatal&&t.error$.next({id:["HlsJsFatal",c.type,c.details].join("_"),category:G.ErrorCategory.WTF,message:`HlsJs fatal ${c.type} ${c.details}, ${(l=c.err)==null?void 0:l.message} ${c.reason}`,thrown:c.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var c;((c=this.videoState.getTransition())==null?void 0:c.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(qr(this.hls,tt.Events.MANIFEST_PARSED).pipe((0,G.map)(({levels:c})=>c.reduce((l,d)=>{var P,I;let p=d.name||d.height.toString(10),{width:h,height:m}=d,g=(I=Dt((P=d.attrs.QUALITY)!=null?P:""))!=null?I:(0,G.videoSizeToQuality)({width:h,height:m});if(!g)return l;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:T,level:d}),l.push(T),l},[]))),t.availableVideoTracks$),s(qr(this.hls,tt.Events.MANIFEST_PARSED),c=>{if(c.subtitleTracks.length>0){let l=[];for(let d of c.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;l.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(l)}}),s(qr(this.hls,tt.Events.LEVEL_LOADING).pipe((0,G.map)(({url:c})=>be(c))),t.hostname$),s(qr(this.hls,tt.Events.FRAG_CHANGED),c=>{var p,h,m,g;let{video:l,audio:d}=c.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=l==null?void 0:l.endPTS)!=null?p:0)-((h=l==null?void 0:l.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Ct(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,c=>{this.hls.nextLevel=c?-1:this.hls.currentLevel,this.hls.loadLevel=c?-1:this.hls.loadLevel},{onError:r}));let n=c=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:d})=>d===c))==null?void 0:l.track},o=qr(this.hls,tt.Events.LEVEL_SWITCHED).pipe((0,G.map)(({level:c})=>n(this.hls.levels[c])));o.pipe((0,G.filter)(G.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ct(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),c=>{var m;if((0,G.isNullable)(c))return;let l=(m=this.trackLevels.get(c.id))==null?void 0:m.level;if(!l)return;let d=this.hls.levels.indexOf(l),p=this.hls.currentLevel,h=this.hls.levels[p];!h||l.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,G.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return O(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield $e(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0)}};var Sb="X-Playback-Duration",Su=a=>O(void 0,null,function*(){var i;let e=yield yt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Sb)?parseInt(e.headers.get(Sb),10):void 0});var H=require("@vkontakte/videoplayer-shared");var yu=ze(eo(),1);var Cs=require("@vkontakte/videoplayer-shared");var eA=a=>{let e=null;if(a.QUALITY&&(e=Dt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=(0,Cs.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},tA=(a,e)=>{var s,n;let t=a.split(`
|
|
113
|
-
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],c=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!l)){if(c){let d=(0,yu.default)(c[1].split(",").map(P=>P.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=eA(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[P,I]=d.RESOLUTION.split("x").map(E=>parseInt(E,10));P&&I&&(S={width:P,height:I})}let T=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:T,bandwidth:m,size:S,fps:g})}if(l){let d=(0,yu.default)(l[1].split(",").map(g=>g.split("=")).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&i.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},rA=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),vu=0,vb=(r,...i)=>O(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield yt(a)).text();vu+=1;try{let{qualityManifests:o,textTracks:u}=tA(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(vu<=t.manifestRetryMaxCount)return yield rA((0,Cs.getExponentialDelay)(vu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),vb(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Ds=vb;var oa=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new j("stopped");this.textTracksManager=new je;this.manifests$=new H.ValueSubject([]);this.liveOffset=new bt;this.manifestStartTime$=new H.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,H.assertNever)(t)}};var t;this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:H.VideoQuality.INVARIANT,url:this.params.source.url},Ds(Se(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.maxSeekBackTime$=new H.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(l=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.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=Re(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(He(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ge(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,H.filterChanged)(),(0,H.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,H.isNonNullable)(c.to)){let d=c.to.id;this.params.desiredState.videoTrack.setState(c.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)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.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,c,l;let o=(l=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:l.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:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,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),we(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:c,min:l}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[c,"mq"],[l,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Se(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Su(n).then(c=>{var l;if(!(0,H.isNullable)(c))this.maxSeekBackTime$.next(c);else{let d=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if((0,H.isNullable)(d)||!isFinite(d))try{yt(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();Su(g).then(S=>{(0,H.isNullable)(S)||this.maxSeekBackTime$.next(S)})}})}catch(p){}}})}playIfAllowed(){$e(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};var X=require("@vkontakte/videoplayer-shared");var ua=class{constructor(e){this.subscription=new X.Subscription;this.videoState=new j("stopped");this.textTracksManager=new je;this.manifests$=new X.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":r==="ready"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,X.assertNever)(t)}};this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:X.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),Ds(Se(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:X.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,c,l,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(l=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?l:(c=t.getState())==null?void 0:c.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:X.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Re(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,X.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(He(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(0,X.isNonNullable)(c.to)){let p=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let h=this.manifests$.getValue().find(m=>m.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(be(h.url));let m=this.params.desiredState.playbackRate.getState(),g=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(m!==g){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(m),S.playbackRate=m)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.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,X.map)(o=>o.map(({id:u,quality:c,size:l,bandwidth:d,fps:p})=>({id:u,quality:c,size:l,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!X.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,X.merge)((0,X.fromEvent)(o,"addtrack"),(0,X.fromEvent)(o,"removetrack"),(0,X.fromEvent)(o,"change"),(0,X.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,X.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,X.observableFrom)(["init"])).pipe((0,X.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),we(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,X.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[c,l]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(c||""));l&&c&&i.searchParams.set(l,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){$e(this.video).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:X.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var ie=require("@vkontakte/videoplayer-shared");var ca=class{constructor(e){this.subscription=new ie.Subscription;this.videoState=new j("stopped");this.trackUrls={};this.textTracksManager=new je;this.syncPlayback=()=>{var u,c,l;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((l=(c=this.trackUrls[n.to.id])==null?void 0:c.track)==null?void 0:l.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?w(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,ie.assertNever)(e)}};this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:ie.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Re(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,ie.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(ke(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(He(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ge(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,c;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,ie.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),d=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(l!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(l),p.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,ie.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ie.observableFrom)(["init"])).pipe((0,ie.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),we(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,ie.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,ie.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ea(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(be(t))}playIfAllowed(){$e(this.video).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ie.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!(0,ie.isInvariantQuality)(d.track.quality)&&(0,ie.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,c=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,l=(o=this.trackUrls[c!=null?c:"0"])==null?void 0:o.track;if(u&&l&&(0,ie.isHigherOrEqual)(l.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!(0,ie.isInvariantQuality)(h.track.quality)&&(0,ie.isHigher)(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(c=>c.track);t=Bt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};var ne=require("@vkontakte/videoplayer-shared");var Tb=require("@vkontakte/videoplayer-shared");var yb=["stun:videostun.mycdn.me:80"],iA=1e3,aA=3,Tu=()=>null,Bs=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=Tu;this.externalStopCallback=Tu;this.externalErrorCallback=Tu;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return O(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return O(this,null,function*(){try{let e={iceServers:[{urls:yb}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return O(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return O(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Tb.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return O(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return O(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),iA)}normalizeOptions(e={}){let t={stunServerList:yb,maxRetryNumber:aA,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 j("stopped");this.maxSeekBackTime$=new ne.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,ne.assertNever)(e)}};this.subscription=new ne.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ae(e.container,e.tuning),this.liveStreamClient=new Bs(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),we(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ne.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,ne.merge)(this.videoState.stateChangeStarted$.pipe((0,ne.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ne.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Re(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Ge(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ke(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,ne.assertNever)(n.to)}},r)).add((0,ne.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ne.observableFrom)(["init"])).pipe((0,ne.debounce)(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(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,w(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:ne.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){$e(this.video).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ne.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var da=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared");var xt=require("@vkontakte/videoplayer-shared"),Ib=a=>new xt.Observable(e=>{let t=new xt.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,xt.map)(({from:c,to:l})=>`${c}-${l}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,xt.map)(({type:c})=>c!==void 0)),n=new xt.Subject,o=0,u="unknown";return t.add(r.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(c=>{o&&(window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var _e=require("@vkontakte/videoplayer-shared");var pa=null,Os=null;function Iu(){return pa||(pa=new(window.AudioContext||window.webkitAudioContext)),Os||(Os=new GainNode(pa,{gain:1}),Os.connect(pa.destination)),{audioCtx:pa,gainNode:Os}}var Eb=require("@vkontakte/videoplayer-shared");var Ur=class Ur{constructor(e,t,r,i,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.subscriptions=new _e.Subscription;this.lastAudioContextResumeId=0;!s||!this.isSupported()||i===1||this.subscriptions.add(this.provider$.pipe((0,_e.filter)(n=>!!n.type),(0,_e.once)()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){Eb.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,_e.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,_e.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,_e.once)()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:i}=Iu(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,r.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Ur.errorId} destroyed`);i.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(i)}catch(o){this.volumeMultiplierError$.next({id:Ur.errorId,category:_e.ErrorCategory.VIDEO_PIPELINE,message:(n=o==null?void 0:o.message)!=null?n:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(n=>{var o;this.volumeMultiplierError$.next({id:Ur.errorId,category:_e.ErrorCategory.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Iu();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Ur.errorId="VolumeMultiplierManager";var ha=Ur;var sA={chunkDuration:5e3,maxParallelRequests:5},fa=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject("")};this.subscription=new y.Subscription;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=vm([...Tm(this.params.tuning),...ym(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>(0,y.isNonNullable)(e.sources[u])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(u=>!i.includes(u)),...t.filter(u=>i.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new da(s);let n=[...tu(!0),...tu(!1)];this.chromecastFormatsIterator=new da(n.filter(u=>(0,y.isNonNullable)(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new ha(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy(),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 aa(z(C({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new sa(z(C({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),Mr||!this.params.tuning.useHlsJs?new ua(z(C({},n),{source:o})):new na(z(C({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new oa(z(C({},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 ca(z(C({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new tm(z(C({},n),{source:o,config:z(C({},sA),{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 yi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return z(C({},e),{url:r(e.url)})}return(0,xb.default)(Object.entries(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,r=0;return e.add((0,y.merge)(this.providerOutput.error$,Ib({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,c=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!u,d=c&&!u&&(o&&t||!l);n=z(C({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:c,tryFailover:d,canReinitProvider:l}),d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var N=require("@vkontakte/videoplayer-shared");var nA=5e3,Pb="one_video_throughput",Ab="one_video_rtt",Pt=window.navigator.connection,wb=()=>{let a=Pt==null?void 0:Pt.downlink;if((0,N.isNonNullable)(a)&&a!==10)return a*1e3},kb=()=>{let a=Pt==null?void 0:Pt.rtt;if((0,N.isNonNullable)(a)&&a!==3e3)return a},Rb=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Eu=class a{constructor(e){this.subscription=new N.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(Pb)||(e.useBrowserEstimation?wb():void 0)||nA,r=(s=(i=a.load(Ab))!=null?i:e.useBrowserEstimation?kb():void 0)!=null?s:0;if(this.throughput$=new N.ValueSubject(t),this.rtt$=new N.ValueSubject(r),this.rttAdjustedThroughput$=new N.ValueSubject(Rb(t,r,e.rttPenaltyRequestSize)),this.throughput=ar.getSmoothedValue(t,-1,e),this.rtt=ar.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=wb();u&&this.throughput.next(u);let c=kb();(0,N.isNonNullable)(c)&&this.rtt.next(c)};Pt&&"onchange"in Pt&&this.subscription.add((0,N.fromEvent)(Pt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{N.safeStorage.set(Pb,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{N.safeStorage.set(Ab,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,N.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,N.map)(({throughput:n,rtt:o})=>Rb(n,o,e.rttPenaltyRequestSize)),(0,N.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,N.now)(),i=new N.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,N.fromEvent)(e,"progress").pipe((0,N.once)()).subscribe(s=>{t=s.loaded,r=(0,N.now)()}));break;case 1:case 0:i.add((0,N.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,N.now)()}));break}i.add((0,N.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,N.now)(),u=n-t,c=o-r;this.addRawSpeed(u,c,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=(0,N.now)(),n=0,o=(0,N.now)(),u=l=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},c=p=>O(this,[p],function*({done:l,value:d}){if(l)!t&&this.addRawSpeed(i,(0,N.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=(0,N.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=d.byteLength,s=(0,N.now)()}else n+=d.byteLength;o=(0,N.now)()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,N.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,N.now)()-o,this.concurrentDownloads.size),n=0,o=(0,N.now)());yield r==null?void 0:r.read().then(c,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(c,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=N.safeStorage.get(e);if((0,N.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},$b=Eu;var ma=require("@vkontakte/videoplayer-shared");var Lb={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:7,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:5,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:ma.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ma.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},Mb=a=>{var e;return z(C({},(0,ma.fillWithDefault)(a,Lb)),{configName:[...(e=a.configName)!=null?e:[],...Lb.configName]})};var f=require("@vkontakte/videoplayer-shared");var At=require("@vkontakte/videoplayer-shared"),xu=({seekState:a,position$:e})=>(0,At.merge)(a.stateChangeEnded$.pipe((0,At.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,At.filter)(At.isNonNullable)),e.pipe((0,At.filter)(()=>a.getState().state==="none")));var Cb=require("@vkontakte/videoplayer-shared"),Db=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,Cb.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Vs=require("@vkontakte/videoplayer-shared"),Bb=(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,Vs.filter)(i=>i.length>0),(0,Vs.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var ba=class{constructor(e={configName:[]},t=f.Tracer.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new j("stopped"),seekState:new j({state:"none"}),volume:new j({volume:1,muted:!1}),videoTrack:new j(void 0),videoStream:new j(void 0),audioStream:new j(void 0),autoVideoTrackSwitching:new j(!0),autoVideoTrackLimits:new j({}),isLooped:new j(!1),playbackRate:new j(1),externalTextTracks:new j([]),internalTextTracks:new j([]),currentTextTrack:new j(void 0),textTrackCuesSettings:new j({}),cameraOrientation:new j({x:0,y:0})};this.info={playbackState$:new f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:Wf};if(this.initLogs(),this.tuning=Mb(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Pa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new $b(this.tuning.throughputEstimator),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 c=o.map(p=>JSON.stringify(p,(h,m)=>{let g=typeof m;return["number","string","boolean"].includes(g)?m:m===null?null:`<${g}>`})),l=`Player.${String(i)}`,d=`Exception calling ${l} (${c.join(", ")})`;throw this.events.fatalError$.next({id:l,category:f.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o;this.config=e;let i=e,{container:t}=i,r=Ju(i,["container"]);return this.tracer.log("initVideo",(0,f.flattenObject)(r)),this.domContainer=Db(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new fa({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;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()}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&&!wi()?(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.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.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=>C({type:"external"},t))),this}selectTextTrack(e){var t;return Bb(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",C({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let 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(z(C({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).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(e.providerOutput.availableVideoTracks$.pipe((0,f.map)(n=>n.map(({quality:o})=>o).sort((o,u)=>(0,f.isInvariantQuality)(o)?1:(0,f.isInvariantQuality)(u)?-1:(0,f.isHigher)(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.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((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:xu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return n&&Math.abs(o)<c/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(xu({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,c;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(c=n==null?void 0:n.size)==null?void 0:c.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(),c=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),d;l==="CONNECTED"?d="second_screen":u?c?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t,r=(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=Bt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),Gf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>jf(r)),this.providerContainer.current$.subscribe(({type:r})=>Ii("provider",r)),e.duration$.subscribe(r=>Ii("duration",r)),e.availableVideoTracks$.pipe((0,f.filter)(r=>!!r.length),(0,f.once)()).subscribe(r=>Ii("tracks",r)),this.events.fatalError$.subscribe(new Te("fatalError")),this.events.managedError$.subscribe(new Te("managedError")),e.position$.subscribe(new Te("position")),e.currentVideoTrack$.pipe((0,f.map)(r=>r==null?void 0:r.quality)).subscribe(new Te("quality")),this.info.currentBuffer$.subscribe(new Te("buffer")),e.isBuffering$.subscribe(new Te("isBuffering"))].forEach(r=>this.subscription.add(r)),Ii("codecs",Sm())}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=()=>O(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(i)})})});this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);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 lt=require("@vkontakte/videoplayer-shared"),oA=`@vkontakte/videoplayer-core@${Zs}`;
|
|
112
|
+
`;var Ks=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Qs(this.params.fov,this.params.orientation),this.cameraRotationManager=new zs(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Db,this.gl.VERTEX_SHADER),i=this.createShader(Bb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,p=t+r;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 pi=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new W("stopped");this.elementSize$=new U.ValueSubject(void 0);this.droppedFramesManager=new ks;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Br;this.audioTrackSwitchHistory=new Br;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(r.position-l,r.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&w(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,U.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Ks(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=we(e.container,e.tuning),this.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 Ys({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=$e(this.video),r=this.constructor.name,s=o=>{e.error$.next({id:r,category:U.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,U.filter)(l=>!!l.length),(0,U.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})})),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,U.filter)(U.isNonNullable),(0,U.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,U.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ct(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((0,U.observeElementSize)(this.video),this.elementSize$),s(We(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map;let c=this.player.getStreams();if((0,U.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(ku(h));let m=[];for(let g of h.representations){let S=kb(g);m.push(S),this.audioTracksMap.set(S,{stream:h,representation:g})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Ru(p));let h=[];for(let m of p.representations){let g=wb(m);g&&(h.push(g),this.videoTracksMap.set(g,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d),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)}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let n=l=>e.error$.next({id:"RepresentationSwitch",category:U.ErrorCategory.WTF,message:"Switching representations threw",thrown:l});this.subscription.add((0,U.merge)(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,U.fromEvent)(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(n),h){let g=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",h.id,g).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,U.filterChanged)()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Ru(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,U.filterChanged)()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(ku(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r));let o=t.playbackState.stateChangeStarted$.pipe((0,U.map)(({to:l})=>l==="ready"),(0,U.filterChanged)());this.subscription.add((0,U.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,U.merge)(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,U.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var B,te,H,Q,ie,Z,F,ee,K,C,k,z,se,le,he,Ee,Gt,Ct;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(B=e.videoTrack.getState())==null?void 0:B.id,n=[...this.videoTracksMap.keys()].find(({id:$})=>$===r),o=t.currentVideoTrack$.getValue(),u=((Q=(H=e.videoStream.getState())!=null?H:n&&((te=this.videoTracksMap.get(n))==null?void 0:te.stream))!=null?Q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:$})=>$===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ht(this.video.buffered,this.video.currentTime*1e3),p=i?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=(ie=e.audioStream.getState())!=null?ie:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(Z=[...this.audioStreamsMap.keys()].find(({id:$})=>$===(m==null?void 0:m.id)))!=null?Z:this.audioStreamsMap.keys().next().value,S=0;if(g){if(n&&!i)if(this.params.tuning.useSeparateAudioVideoABR){let $=As(n,c,(F=this.audioStreamsMap.get(g))!=null?F:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(ee=$==null?void 0:$.bitrate)!=null?ee:-1/0)}else{let $=Fs(n,c,(K=this.audioStreamsMap.get(g))!=null?K:[]);S=Math.max(S,(C=$==null?void 0:$.bitrate)!=null?C:-1/0)}if(o)if(this.params.tuning.useSeparateAudioVideoABR){let $=As(o,c,(k=this.audioStreamsMap.get(g))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);S=Math.max(S,(z=$==null?void 0:$.bitrate)!=null?z:-1/0)}else{let $=Fs(o,c,(se=this.audioStreamsMap.get(g))!=null?se:[]);S=Math.max(S,(le=$==null?void 0:$.bitrate)!=null?le:-1/0)}}let T=Ht(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),P=i?T!=null?T:n:n!=null?n:T,I;this.params.tuning.useSeparateAudioVideoABR?I=g&&Sm(P,c,(he=this.audioStreamsMap.get(g))!=null?he:[],{throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}):I=g&&Fs(P,c,(Ee=this.audioStreamsMap.get(g))!=null?Ee:[]);let E=(Gt=this.videoTracksMap.get(P))==null?void 0:Gt.representation,A=I&&((Ct=this.audioTracksMap.get(I))==null?void 0:Ct.representation);if(E&&A)return[E,A];if(E&&!A&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Le(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.player.destroy(),this.params.output.element$.next(void 0),ke(this.video),this.tracer.end()}};var ga=class extends pi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var hi=require("@vkontakte/videoplayer-shared");var Sa=class extends pi{constructor(e){super(e),this.liveOffset=new It}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,hi.combine)({interval:(0,hi.interval)(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var s;if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(r-1);n<=0&&e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add((0,hi.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,hi.map)(({liveBufferTime:r,liveAvailabilityStartTime:s})=>r&&s?r+s:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(r=>{if(r){let s=Rb(r);this.params.output.availableTextTracks$.next([s])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,r)})}};var Ob=Xe(Es(),1);var Y=require("@vkontakte/videoplayer-shared");var at={};var Ji=(a,e)=>new Y.Observable(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),va=class{constructor(e){this.subscription=new Y.Subscription;this.videoState=new W("initializing");this.textTracksManager=new dt;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,Y.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,Y.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,Y.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,Y.assertNever)(e)}break;default:(0,Y.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(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),ke(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Y.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Ob.default)(import("hls.js").then(r=>{e||(at.Hls=r.default,at.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){(0,Y.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,Y.assertNonNullable)(at.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Y.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=$e(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(ct(this.video,e.isLooped,i)),this.subscription.add(Re(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ge(this.video,e.playbackRate,r.playbackRateState$,i)),s(We(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,Y.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Ji(this.hls,at.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Y.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(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(Ji(this.hls,at.Events.MANIFEST_PARSED).pipe((0,Y.map)(({levels:l})=>l.reduce((c,d)=>{var P,I;let p=d.name||d.height.toString(10),{width:h,height:m}=d,g=(I=Ut((P=d.attrs.QUALITY)!=null?P:""))!=null?I:(0,Y.videoSizeToQuality)({width:h,height:m});if(!g)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(Ji(this.hls,at.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(Ji(this.hls,at.Events.LEVEL_LOADING).pipe((0,Y.map)(({url:l})=>be(l))),t.hostname$),s(Ji(this.hls,at.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(qt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Ji(this.hls,at.Events.LEVEL_SWITCHED).pipe((0,Y.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,Y.filter)(Y.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(qt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,Y.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:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,Y.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,Y.observableFrom)(["init"])).pipe((0,Y.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return V(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Le(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Y.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0)}};var Vb="X-Playback-Duration",Mu=a=>V(void 0,null,function*(){var r;let e=yield Pt(a),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Vb)?parseInt(e.headers.get(Vb),10):void 0});var G=require("@vkontakte/videoplayer-shared");var Du=Xe(fo(),1);var Js=require("@vkontakte/videoplayer-shared");var hA=a=>{let e=null;if(a.QUALITY&&(e=Ut(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Js.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},fA=(a,e)=>{var s,n;let t=a.split(`
|
|
113
|
+
`),i=[],r=[];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,Du.default)(l[1].split(",").map(P=>P.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=hA(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[P,I]=d.RESOLUTION.split("x").map(E=>parseInt(E,10));P&&I&&(S={width:P,height:I})}let T=new URL(t[++o],e).toString();h&&i.push({id:p,quality:h,url:T,bandwidth:m,size:S,fps:g})}if(c){let d=(0,Du.default)(c[1].split(",").map(g=>g.split("=")).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&r.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},mA=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Cu=0,_b=(i,...r)=>V(void 0,[i,...r],function*(a,e=a,t){let n=yield(yield Pt(a)).text();Cu+=1;try{let{qualityManifests:o,textTracks:u}=fA(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Cu<=t.manifestRetryMaxCount)return yield mA((0,Js.getExponentialDelay)(Cu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),_b(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Xs=_b;var ya=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new W("stopped");this.textTracksManager=new dt;this.manifests$=new G.ValueSubject([]);this.liveOffset=new It;this.manifestStartTime$=new G.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,G.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:G.VideoQuality.INVARIANT,url:this.params.source.url},Xs(Se(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:i})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:G.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:G.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),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 G.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,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:G.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=$e(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),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)),s(We(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe((0,G.filterChanged)(),(0,G.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,G.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)},i)),this.subscription.add(r.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)},i)),this.subscription.add((0,G.combine)({startTime:this.manifestStartTime$.pipe((0,G.filter)(G.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,G.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$,i));let n=(0,G.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}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,G.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&r.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Se(r.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Mu(n).then(l=>{var c;if(!(0,G.isNullable)(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if((0,G.isNullable)(d)||!isFinite(d))try{Pt(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let g=new URL(h,n).toString();Mu(g).then(S=>{(0,G.isNullable)(S)||this.maxSeekBackTime$.next(S)})}})}catch(p){}}})}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}};var X=require("@vkontakte/videoplayer-shared");var Ta=class{constructor(e){this.subscription=new X.Subscription;this.videoState=new W("stopped");this.textTracksManager=new dt;this.manifests$=new X.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?w(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,X.assertNever)(t)}};this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:X.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),Xs(Se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:X.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,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:X.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=$e(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,X.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ct(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.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,X.isNonNullable)(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(m=>m.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(be(h.url));let m=this.params.desiredState.playbackRate.getState(),g=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(m!==g){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(m),S.playbackRate=m)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,X.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$,i)),!X.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,X.merge)((0,X.fromEvent)(o,"addtrack"),(0,X.fromEvent)(o,"removetrack"),(0,X.fromEvent)(o,"change"),(0,X.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,X.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,X.observableFrom)(["init"])).pipe((0,X.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}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,X.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:X.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var ae=require("@vkontakte/videoplayer-shared");var Ia=class{constructor(e){this.subscription=new ae.Subscription;this.videoState=new W("stopped");this.trackUrls={};this.textTracksManager=new dt;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?w(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,ae.assertNever)(e)}};this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:ae.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=$e(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,ae.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ct(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)),s(We(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(t.playbackState,"paused")},i)).add(r.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,ae.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()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,ae.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ae.observableFrom)(["init"])).pipe((0,ae.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ke(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,ae.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,ae.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(){Le(this.video).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ae.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var r,s,n,o;let t,i=e;if(e&&((r=this.params.output.currentVideoTrack$.getValue())==null?void 0:r.quality)!==e){let u=(s=Object.values(this.trackUrls).find(d=>!(0,ae.isInvariantQuality)(d.track.quality)&&(0,ae.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,ae.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!(0,ae.isInvariantQuality)(h.track.quality)&&(0,ae.isHigher)(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=Ht(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};var oe=require("@vkontakte/videoplayer-shared");var Fb=require("@vkontakte/videoplayer-shared");var Nb=["stun:videostun.mycdn.me:80"],bA=1e3,gA=3,Bu=()=>null,Zs=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Bu;this.externalStopCallback=Bu;this.externalErrorCallback=Bu;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return V(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return V(this,null,function*(){try{let e={iceServers:[{urls:Nb}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return V(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return V(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Fb.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return V(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return V(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(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),bA)}normalizeOptions(e={}){let t={stunServerList:Nb,maxRetryNumber:gA,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ea=class{constructor(e){this.videoState=new W("stopped");this.maxSeekBackTime$=new oe.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return(0,oe.assertNever)(e)}};this.subscription=new oe.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=we(e.container,e.tuning),this.liveStreamClient=new Zs(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,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:oe.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,oe.merge)(this.videoState.stateChangeStarted$.pipe((0,oe.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,oe.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let r=$e(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),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(We(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Re(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,oe.assertNever)(n.to)}},i)).add((0,oe.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,oe.observableFrom)(["init"])).pipe((0,oe.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(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:oe.VideoQuality.INVARIANT}),this.video.srcObject=e,w(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:oe.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Le(this.video).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oe.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var xa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared");var $t=require("@vkontakte/videoplayer-shared"),qb=a=>new $t.Observable(e=>{let t=new $t.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,$t.map)(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,$t.map)(({type:l})=>l!==void 0)),n=new $t.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.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 Ne=require("@vkontakte/videoplayer-shared");var Pa=null,en=null;function Ou(){return Pa||(Pa=new(window.AudioContext||window.webkitAudioContext)),en||(en=new GainNode(Pa,{gain:1}),en.connect(Pa.destination)),{audioCtx:Pa,gainNode:en}}var Ub=require("@vkontakte/videoplayer-shared");var Xi=class Xi{constructor(e,t,i,r,s){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.subscriptions=new Ne.Subscription;this.lastAudioContextResumeId=0;!s||!this.isSupported()||r===1||this.subscriptions.add(this.provider$.pipe((0,Ne.filter)(n=>!!n.type),(0,Ne.once)()).subscribe(({type:n})=>this.subscribe(n)))}subscribe(e){Ub.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Ne.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Ne.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,Ne.once)()).subscribe(({video:t})=>this.initAudioContextOnce(t)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=Ou(),s=(Math.random()+1)*999999;this.lastAudioContextResumeId=s,i.resume().then(()=>{var n;if(s!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${Xi.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r)}catch(o){this.volumeMultiplierError$.next({id:Xi.errorId,category:Ne.ErrorCategory.VIDEO_PIPELINE,message:(n=o==null?void 0:o.message)!=null?n:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(n=>{var o;this.volumeMultiplierError$.next({id:Xi.errorId,category:Ne.ErrorCategory.VIDEO_PIPELINE,message:(o=n==null?void 0:n.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:n})})}destroy(){let{gainNode:e}=Ou();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};Xi.errorId="VolumeMultiplierManager";var Aa=Xi;var SA={chunkDuration:5e3,maxParallelRequests:5},wa=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject("")};this.subscription=new y.Subscription;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Fm([...Um(this.params.tuning),...qm(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>(0,y.isNonNullable)(e.sources[u])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(u=>!r.includes(u)),...t.filter(u=>r.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new xa(s);let n=[...fu(!0),...fu(!1)];this.chromecastFormatsIterator=new xa(n.filter(u=>(0,y.isNonNullable)(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Aa(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager.destroy(),this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let 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:i,desiredState:r}=this.params,s=this.providerOutput,n={container:i,source:null,desiredState:r,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 ga(j(R({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Sa(j(R({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),Ui||!this.params.tuning.useHlsJs?new Ta(j(R({},n),{source:o})):new va(j(R({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new ya(j(R({},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 Ia(j(R({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Im(j(R({},n),{source:o,config:j(R({},SA),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ea({container:i,source:o,desiredState:r,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:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new Mr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,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 i=r=>{let s=new URL(r);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 j(R({},e),{url:i(e.url)})}return(0,Hb.default)(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,i=0;return e.add((0,y.merge)(this.providerOutput.error$,qb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(r=>({id:`ProviderHangup:${r}`,category:y.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===y.ErrorCategory.NETWORK,u=r.category===y.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=j(R({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),this.params.tuning.useNewProviderReinitLogic?c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN"):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(i++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var N=require("@vkontakte/videoplayer-shared");var vA=5e3,jb="one_video_throughput",Gb="one_video_rtt",Lt=window.navigator.connection,Wb=()=>{let a=Lt==null?void 0:Lt.downlink;if((0,N.isNonNullable)(a)&&a!==10)return a*1e3},Yb=()=>{let a=Lt==null?void 0:Lt.rtt;if((0,N.isNonNullable)(a)&&a!==3e3)return a},Qb=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Vu=class a{constructor(e){this.subscription=new N.Subscription;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(jb)||(e.useBrowserEstimation?Wb():void 0)||vA,i=(s=(r=a.load(Gb))!=null?r:e.useBrowserEstimation?Yb():void 0)!=null?s:0;if(this.throughput$=new N.ValueSubject(t),this.rtt$=new N.ValueSubject(i),this.rttAdjustedThroughput$=new N.ValueSubject(Qb(t,i,e.rttPenaltyRequestSize)),this.throughput=di.getSmoothedValue(t,-1,e),this.rtt=di.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=Wb();u&&this.throughput.next(u);let l=Yb();(0,N.isNonNullable)(l)&&this.rtt.next(l)};Lt&&"onchange"in Lt&&this.subscription.add((0,N.fromEvent)(Lt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{N.safeStorage.set(jb,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{N.safeStorage.set(Gb,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,N.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,N.map)(({throughput:n,rtt:o})=>Qb(n,o,e.rttPenaltyRequestSize)),(0,N.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,N.now)(),r=new N.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,N.fromEvent)(e,"progress").pipe((0,N.once)()).subscribe(s=>{t=s.loaded,i=(0,N.now)()}));break;case 1:case 0:r.add((0,N.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,N.now)()}));break}r.add((0,N.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,N.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=(0,N.now)(),n=0,o=(0,N.now)(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>V(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(r,(0,N.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=(0,N.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=d.byteLength,s=(0,N.now)()}else n+=d.byteLength;o=(0,N.now)()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,N.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,N.now)()-o,this.concurrentDownloads.size),n=0,o=(0,N.now)());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=N.safeStorage.get(e);if((0,N.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},zb=Vu;var ka=require("@vkontakte/videoplayer-shared");var Kb={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:7,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:5,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:ka.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ka.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},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,accumulationBufferStallSizeMs:0,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,useSeparateAudioVideoABR:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,useNewProviderReinitLogic:!1,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},Jb=a=>{var e;return j(R({},(0,ka.fillWithDefault)(a,Kb)),{configName:[...(e=a.configName)!=null?e:[],...Kb.configName]})};var f=require("@vkontakte/videoplayer-shared");var Mt=require("@vkontakte/videoplayer-shared"),_u=({seekState:a,position$:e})=>(0,Mt.merge)(a.stateChangeEnded$.pipe((0,Mt.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,Mt.filter)(Mt.isNonNullable)),e.pipe((0,Mt.filter)(()=>a.getState().state==="none")));var Xb=require("@vkontakte/videoplayer-shared"),Zb=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,Xb.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var tn=require("@vkontakte/videoplayer-shared"),eg=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,tn.filter)(r=>r.length>0),(0,tn.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var Ra=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.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new W("stopped"),seekState:new W({state:"none"}),volume:new W({volume:1,muted:!1}),videoTrack:new W(void 0),videoStream:new W(void 0),audioStream:new W(void 0),autoVideoTrackSwitching:new W(!0),autoVideoTrackLimits:new W({}),isLooped:new W(!1),playbackRate:new W(1),externalTextTracks:new W([]),internalTextTracks:new W([]),currentTextTrack:new W(void 0),textTrackCuesSettings:new W({}),cameraOrientation:new W({x:0,y:0})};this.info={playbackState$:new f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:hm};if(this.initLogs(),this.tuning=Jb(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ua({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new zb(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let g=typeof m;return["number","string","boolean"].includes(g)?m:m===null?null:`<${g}>`})),c=`Player.${String(r)}`,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 s,n,o;this.config=e;let r=e,{container:t}=r,i=Sl(r,["container"]);return this.tracer.log("initVideo",(0,f.flattenObject)(i)),this.domContainer=Zb(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new wa({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;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()}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&&!Nr()?(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 i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;return e>=i&&!r&&(s=i-.1),this.tracer.log("seekTime",{duration:i,isLive:r,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.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;(0,f.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.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=>R({type:"external"},t))),this}selectTextTrack(e){var t;return eg(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",R({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.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(),i=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,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(j(R({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).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(e.providerOutput.availableVideoTracks$.pipe((0,f.map)(n=>n.map(({quality:o})=>o).sort((o,u)=>(0,f.isInvariantQuality)(o)?1:(0,f.isInvariantQuality)(u)?-1:(0,f.isHigher)(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.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((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:_u({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(_u({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 i=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),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)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t,i=(r=this.desiredState.videoTrack.getState())==null?void 0:r.quality;i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Ht(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),pm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>dm(i)),this.providerContainer.current$.subscribe(({type:i})=>Dr("provider",i)),e.duration$.subscribe(i=>Dr("duration",i)),e.availableVideoTracks$.pipe((0,f.filter)(i=>!!i.length),(0,f.once)()).subscribe(i=>Dr("tracks",i)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),e.position$.subscribe(new Ie("position")),e.currentVideoTrack$.pipe((0,f.map)(i=>i==null?void 0:i.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),e.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(i=>this.subscription.add(i)),Dr("codecs",Nm())}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:i,videoBitrate:r})=>!!i&&!!r),(0,f.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(i=>i>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)(i=>i.end>0),(0,f.filterChanged)((i,r)=>i.end===r.end&&i.start===r.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:i,liveBufferTime:r})=>!!i&&!!r),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!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)(i=>i===!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:i,rtt:r})=>!!i&&!!r),(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)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>V(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(r)})})});this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var mt=require("@vkontakte/videoplayer-shared"),yA=`@vkontakte/videoplayer-core@${hn}`;
|