@vkontakte/videoplayer-core 2.0.134-dev.ca4b9a20.0 → 2.0.134-dev.ddf0760d.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 +28 -28
- package/es2015.esm.js +27 -27
- package/es2018.cjs.js +34 -34
- package/es2018.esm.js +26 -26
- package/es2024.cjs.js +33 -33
- package/es2024.esm.js +25 -25
- package/esnext.cjs.js +33 -33
- package/esnext.esm.js +25 -25
- package/evergreen.esm.js +25 -25
- package/package.json +2 -3
- package/types/player/Player.d.ts +1 -1
- package/types/player/types.d.ts +6 -1
- package/types/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +2 -0
- package/types/providers/ProviderContainer/utils/formatsSupport.d.ts +2 -2
- package/types/utils/tuningConfig.d.ts +1 -1
- package/types/providers/HlsJsProvider/index.d.ts +0 -24
package/es2015.esm.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.134-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.134-dev.ddf0760d.0
|
|
3
|
+
* Tue, 17 Jun 2025 09:21:37 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-134/doc/
|
|
5
5
|
*/
|
|
6
|
-
var KE=Object.create;var Wl=Object.defineProperty,XE=Object.defineProperties,JE=Object.getOwnPropertyDescriptor,ZE=Object.getOwnPropertyDescriptors,ew=Object.getOwnPropertyNames,Mo=Object.getOwnPropertySymbols,tw=Object.getPrototypeOf,Yl=Object.prototype.hasOwnProperty,zh=Object.prototype.propertyIsEnumerable;var iw=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var st=Math.pow,Gh=(s,e,t)=>e in s?Wl(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,E=(s,e)=>{for(var t in e||(e={}))Yl.call(e,t)&&Gh(s,t,e[t]);if(Mo)for(var t of Mo(e))zh.call(e,t)&&Gh(s,t,e[t]);return s},B=(s,e)=>XE(s,ZE(e));var Qh=(s,e)=>{var t={};for(var i in s)Yl.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&Mo)for(var i of Mo(s))e.indexOf(i)<0&&zh.call(s,i)&&(t[i]=s[i]);return t};var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var rw=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ew(e))!Yl.call(s,r)&&r!==t&&Wl(s,r,{get:()=>e[r],enumerable:!(i=JE(e,r))||i.enumerable});return s};var j=(s,e,t)=>(t=s!=null?KE(tw(s)):{},rw(e||!s||!s.__esModule?Wl(t,"default",{value:s,enumerable:!0}):t,s));var x=(s,e,t)=>new Promise((i,r)=>{var a=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(a,n);o((t=t.apply(s,e)).next())}),tr=function(s,e){this[0]=s,this[1]=e},X=(s,e,t)=>{var i=(n,o,u,l)=>{try{var d=t[n](o),c=(o=d.value)instanceof tr,h=d.done;Promise.resolve(c?o[0]:o).then(p=>c?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>a[n]=o=>new Promise((u,l)=>i(n,o,u,l)),a={};return t=t.apply(s,e),a[iw("asyncIterator")]=()=>a,r("next"),r("throw"),r("return"),a};var xe=b((Jl,Yh)=>{"use strict";var ca=function(s){return s&&s.Math===Math&&s};Yh.exports=ca(typeof globalThis=="object"&&globalThis)||ca(typeof window=="object"&&window)||ca(typeof self=="object"&&self)||ca(typeof global=="object"&&global)||ca(typeof Jl=="object"&&Jl)||function(){return this}()||Function("return this")()});var qe=b((P_,Kh)=>{"use strict";Kh.exports=function(s){try{return!!s()}catch(e){return!0}}});var da=b((A_,Xh)=>{"use strict";var sw=qe();Xh.exports=!sw(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Zl=b((k_,tf)=>{"use strict";var aw=da(),ef=Function.prototype,Jh=ef.apply,Zh=ef.call;tf.exports=typeof Reflect=="object"&&Reflect.apply||(aw?Zh.bind(Jh):function(){return Zh.apply(Jh,arguments)})});var Ve=b((R_,af)=>{"use strict";var rf=da(),sf=Function.prototype,ec=sf.call,nw=rf&&sf.bind.bind(ec,ec);af.exports=rf?nw:function(s){return function(){return ec.apply(s,arguments)}}});var ir=b((L_,of)=>{"use strict";var nf=Ve(),ow=nf({}.toString),uw=nf("".slice);of.exports=function(s){return uw(ow(s),8,-1)}});var tc=b((M_,uf)=>{"use strict";var lw=ir(),cw=Ve();uf.exports=function(s){if(lw(s)==="Function")return cw(s)}});var Te=b(($_,lf)=>{"use strict";var ic=typeof document=="object"&&document.all;lf.exports=typeof ic=="undefined"&&ic!==void 0?function(s){return typeof s=="function"||s===ic}:function(s){return typeof s=="function"}});var It=b((B_,cf)=>{"use strict";var dw=qe();cf.exports=!dw(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var xt=b((D_,df)=>{"use strict";var pw=da(),Do=Function.prototype.call;df.exports=pw?Do.bind(Do):function(){return Do.apply(Do,arguments)}});var rc=b(ff=>{"use strict";var pf={}.propertyIsEnumerable,hf=Object.getOwnPropertyDescriptor,hw=hf&&!pf.call({1:2},1);ff.f=hw?function(e){var t=hf(this,e);return!!t&&t.enumerable}:pf});var pa=b((V_,mf)=>{"use strict";mf.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var gf=b((O_,bf)=>{"use strict";var fw=Ve(),mw=qe(),bw=ir(),sc=Object,gw=fw("".split);bf.exports=mw(function(){return!sc("z").propertyIsEnumerable(0)})?function(s){return bw(s)==="String"?gw(s,""):sc(s)}:sc});var Rr=b((__,Sf)=>{"use strict";Sf.exports=function(s){return s==null}});var Di=b((F_,vf)=>{"use strict";var Sw=Rr(),vw=TypeError;vf.exports=function(s){if(Sw(s))throw new vw("Can't call method on "+s);return s}});var rr=b((N_,yf)=>{"use strict";var yw=gf(),Tw=Di();yf.exports=function(s){return yw(Tw(s))}});var Et=b((U_,Tf)=>{"use strict";var Iw=Te();Tf.exports=function(s){return typeof s=="object"?s!==null:Iw(s)}});var Lr=b((q_,If)=>{"use strict";If.exports={}});var yi=b((j_,Ef)=>{"use strict";var ac=Lr(),nc=xe(),xw=Te(),xf=function(s){return xw(s)?s:void 0};Ef.exports=function(s,e){return arguments.length<2?xf(ac[s])||xf(nc[s]):ac[s]&&ac[s][e]||nc[s]&&nc[s][e]}});var ha=b((H_,wf)=>{"use strict";var Ew=Ve();wf.exports=Ew({}.isPrototypeOf)});var sr=b((G_,kf)=>{"use strict";var ww=xe(),Pf=ww.navigator,Af=Pf&&Pf.userAgent;kf.exports=Af?String(Af):""});var uc=b((z_,Df)=>{"use strict";var Bf=xe(),oc=sr(),Rf=Bf.process,Lf=Bf.Deno,Mf=Rf&&Rf.versions||Lf&&Lf.version,$f=Mf&&Mf.v8,Ft,Co;$f&&(Ft=$f.split("."),Co=Ft[0]>0&&Ft[0]<4?1:+(Ft[0]+Ft[1]));!Co&&oc&&(Ft=oc.match(/Edge\/(\d+)/),(!Ft||Ft[1]>=74)&&(Ft=oc.match(/Chrome\/(\d+)/),Ft&&(Co=+Ft[1])));Df.exports=Co});var lc=b((Q_,Vf)=>{"use strict";var Cf=uc(),Pw=qe(),Aw=xe(),kw=Aw.String;Vf.exports=!!Object.getOwnPropertySymbols&&!Pw(function(){var s=Symbol("symbol detection");return!kw(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Cf&&Cf<41})});var cc=b((W_,Of)=>{"use strict";var Rw=lc();Of.exports=Rw&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var dc=b((Y_,_f)=>{"use strict";var Lw=yi(),Mw=Te(),$w=ha(),Bw=cc(),Dw=Object;_f.exports=Bw?function(s){return typeof s=="symbol"}:function(s){var e=Lw("Symbol");return Mw(e)&&$w(e.prototype,Dw(s))}});var fa=b((K_,Ff)=>{"use strict";var Cw=String;Ff.exports=function(s){try{return Cw(s)}catch(e){return"Object"}}});var Kt=b((X_,Nf)=>{"use strict";var Vw=Te(),Ow=fa(),_w=TypeError;Nf.exports=function(s){if(Vw(s))return s;throw new _w(Ow(s)+" is not a function")}});var ma=b((J_,Uf)=>{"use strict";var Fw=Kt(),Nw=Rr();Uf.exports=function(s,e){var t=s[e];return Nw(t)?void 0:Fw(t)}});var jf=b((Z_,qf)=>{"use strict";var pc=xt(),hc=Te(),fc=Et(),Uw=TypeError;qf.exports=function(s,e){var t,i;if(e==="string"&&hc(t=s.toString)&&!fc(i=pc(t,s))||hc(t=s.valueOf)&&!fc(i=pc(t,s))||e!=="string"&&hc(t=s.toString)&&!fc(i=pc(t,s)))return i;throw new Uw("Can't convert object to primitive value")}});var Nt=b((eF,Hf)=>{"use strict";Hf.exports=!0});var Qf=b((tF,zf)=>{"use strict";var Gf=xe(),qw=Object.defineProperty;zf.exports=function(s,e){try{qw(Gf,s,{value:e,configurable:!0,writable:!0})}catch(t){Gf[s]=e}return e}});var ba=b((iF,Kf)=>{"use strict";var jw=Nt(),Hw=xe(),Gw=Qf(),Wf="__core-js_shared__",Yf=Kf.exports=Hw[Wf]||Gw(Wf,{});(Yf.versions||(Yf.versions=[])).push({version:"3.38.0",mode:jw?"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 mc=b((rF,Jf)=>{"use strict";var Xf=ba();Jf.exports=function(s,e){return Xf[s]||(Xf[s]=e||{})}});var Mr=b((sF,Zf)=>{"use strict";var zw=Di(),Qw=Object;Zf.exports=function(s){return Qw(zw(s))}});var Ut=b((aF,em)=>{"use strict";var Ww=Ve(),Yw=Mr(),Kw=Ww({}.hasOwnProperty);em.exports=Object.hasOwn||function(e,t){return Kw(Yw(e),t)}});var bc=b((nF,tm)=>{"use strict";var Xw=Ve(),Jw=0,Zw=Math.random(),eP=Xw(1 .toString);tm.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+eP(++Jw+Zw,36)}});var je=b((oF,rm)=>{"use strict";var tP=xe(),iP=mc(),im=Ut(),rP=bc(),sP=lc(),aP=cc(),$r=tP.Symbol,gc=iP("wks"),nP=aP?$r.for||$r:$r&&$r.withoutSetter||rP;rm.exports=function(s){return im(gc,s)||(gc[s]=sP&&im($r,s)?$r[s]:nP("Symbol."+s)),gc[s]}});var om=b((uF,nm)=>{"use strict";var oP=xt(),sm=Et(),am=dc(),uP=ma(),lP=jf(),cP=je(),dP=TypeError,pP=cP("toPrimitive");nm.exports=function(s,e){if(!sm(s)||am(s))return s;var t=uP(s,pP),i;if(t){if(e===void 0&&(e="default"),i=oP(t,s,e),!sm(i)||am(i))return i;throw new dP("Can't convert object to primitive value")}return e===void 0&&(e="number"),lP(s,e)}});var Sc=b((lF,um)=>{"use strict";var hP=om(),fP=dc();um.exports=function(s){var e=hP(s,"string");return fP(e)?e:e+""}});var Vo=b((cF,cm)=>{"use strict";var mP=xe(),lm=Et(),vc=mP.document,bP=lm(vc)&&lm(vc.createElement);cm.exports=function(s){return bP?vc.createElement(s):{}}});var yc=b((dF,dm)=>{"use strict";var gP=It(),SP=qe(),vP=Vo();dm.exports=!gP&&!SP(function(){return Object.defineProperty(vP("div"),"a",{get:function(){return 7}}).a!==7})});var fm=b(hm=>{"use strict";var yP=It(),TP=xt(),IP=rc(),xP=pa(),EP=rr(),wP=Sc(),PP=Ut(),AP=yc(),pm=Object.getOwnPropertyDescriptor;hm.f=yP?pm:function(e,t){if(e=EP(e),t=wP(t),AP)try{return pm(e,t)}catch(i){}if(PP(e,t))return xP(!TP(IP.f,e,t),e[t])}});var Tc=b((hF,mm)=>{"use strict";var kP=qe(),RP=Te(),LP=/#|\.prototype\./,ga=function(s,e){var t=$P[MP(s)];return t===DP?!0:t===BP?!1:RP(e)?kP(e):!!e},MP=ga.normalize=function(s){return String(s).replace(LP,".").toLowerCase()},$P=ga.data={},BP=ga.NATIVE="N",DP=ga.POLYFILL="P";mm.exports=ga});var Br=b((fF,gm)=>{"use strict";var bm=tc(),CP=Kt(),VP=da(),OP=bm(bm.bind);gm.exports=function(s,e){return CP(s),e===void 0?s:VP?OP(s,e):function(){return s.apply(e,arguments)}}});var Ic=b((mF,Sm)=>{"use strict";var _P=It(),FP=qe();Sm.exports=_P&&FP(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Xt=b((bF,vm)=>{"use strict";var NP=Et(),UP=String,qP=TypeError;vm.exports=function(s){if(NP(s))return s;throw new qP(UP(s)+" is not an object")}});var ar=b(Tm=>{"use strict";var jP=It(),HP=yc(),GP=Ic(),Oo=Xt(),ym=Sc(),zP=TypeError,xc=Object.defineProperty,QP=Object.getOwnPropertyDescriptor,Ec="enumerable",wc="configurable",Pc="writable";Tm.f=jP?GP?function(e,t,i){if(Oo(e),t=ym(t),Oo(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Pc in i&&!i[Pc]){var r=QP(e,t);r&&r[Pc]&&(e[t]=i.value,i={configurable:wc in i?i[wc]:r[wc],enumerable:Ec in i?i[Ec]:r[Ec],writable:!1})}return xc(e,t,i)}:xc:function(e,t,i){if(Oo(e),t=ym(t),Oo(i),HP)try{return xc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new zP("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Dr=b((SF,Im)=>{"use strict";var WP=It(),YP=ar(),KP=pa();Im.exports=WP?function(s,e,t){return YP.f(s,e,KP(1,t))}:function(s,e,t){return s[e]=t,s}});var ke=b((vF,Em)=>{"use strict";var Sa=xe(),XP=Zl(),JP=tc(),ZP=Te(),eA=fm().f,tA=Tc(),Cr=Lr(),iA=Br(),Vr=Dr(),xm=Ut();ba();var rA=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return XP(s,this,arguments)};return e.prototype=s.prototype,e};Em.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Sa:r?Sa[t]:Sa[t]&&Sa[t].prototype,o=i?Cr:Cr[t]||Vr(Cr,t,{})[t],u=o.prototype,l,d,c,h,p,f,m,g,S;for(h in e)l=tA(i?h:t+(r?".":"#")+h,s.forced),d=!l&&n&&xm(n,h),f=o[h],d&&(s.dontCallGetSet?(S=eA(n,h),m=S&&S.value):m=n[h]),p=d&&m?m:e[h],!(!l&&!a&&typeof f==typeof p)&&(s.bind&&d?g=iA(p,Sa):s.wrap&&d?g=rA(p):a&&ZP(p)?g=JP(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&Vr(g,"sham",!0),Vr(o,h,g),a&&(c=t+"Prototype",xm(Cr,c)||Vr(Cr,c,{}),Vr(Cr[c],h,p),s.real&&u&&(l||!u[h])&&Vr(u,h,p)))}});var Pm=b((yF,wm)=>{"use strict";var sA=Math.ceil,aA=Math.floor;wm.exports=Math.trunc||function(e){var t=+e;return(t>0?aA:sA)(t)}});var va=b((TF,Am)=>{"use strict";var nA=Pm();Am.exports=function(s){var e=+s;return e!==e||e===0?0:nA(e)}});var Rm=b((IF,km)=>{"use strict";var oA=va(),uA=Math.max,lA=Math.min;km.exports=function(s,e){var t=oA(s);return t<0?uA(t+e,0):lA(t,e)}});var Ac=b((xF,Lm)=>{"use strict";var cA=va(),dA=Math.min;Lm.exports=function(s){var e=cA(s);return e>0?dA(e,9007199254740991):0}});var Or=b((EF,Mm)=>{"use strict";var pA=Ac();Mm.exports=function(s){return pA(s.length)}});var kc=b((wF,Bm)=>{"use strict";var hA=rr(),fA=Rm(),mA=Or(),$m=function(s){return function(e,t,i){var r=hA(e),a=mA(r);if(a===0)return!s&&-1;var n=fA(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};Bm.exports={includes:$m(!0),indexOf:$m(!1)}});var ya=b((PF,Dm)=>{"use strict";Dm.exports=function(){}});var Cm=b(()=>{"use strict";var bA=ke(),gA=kc().includes,SA=qe(),vA=ya(),yA=SA(function(){return!Array(1).includes()});bA({target:"Array",proto:!0,forced:yA},{includes:function(e){return gA(this,e,arguments.length>1?arguments[1]:void 0)}});vA("includes")});var Ci=b((RF,Vm)=>{"use strict";var TA=yi();Vm.exports=TA});var _m=b((LF,Om)=>{"use strict";Cm();var IA=Ci();Om.exports=IA("Array","includes")});var Nm=b((MF,Fm)=>{"use strict";var xA=_m();Fm.exports=xA});var wt=b(($F,Um)=>{"use strict";var EA=Nm();Um.exports=EA});var No=b((HF,Ym)=>{"use strict";var $A=mc(),BA=bc(),Wm=$A("keys");Ym.exports=function(s){return Wm[s]||(Wm[s]=BA(s))}});var Xm=b((GF,Km)=>{"use strict";var DA=qe();Km.exports=!DA(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Uo=b((zF,Zm)=>{"use strict";var CA=Ut(),VA=Te(),OA=Mr(),_A=No(),FA=Xm(),Jm=_A("IE_PROTO"),Mc=Object,NA=Mc.prototype;Zm.exports=FA?Mc.getPrototypeOf:function(s){var e=OA(s);if(CA(e,Jm))return e[Jm];var t=e.constructor;return VA(t)&&e instanceof t?t.prototype:e instanceof Mc?NA:null}});var qo=b((QF,eb)=>{"use strict";eb.exports={}});var rb=b((WF,ib)=>{"use strict";var UA=Ve(),$c=Ut(),qA=rr(),jA=kc().indexOf,HA=qo(),tb=UA([].push);ib.exports=function(s,e){var t=qA(s),i=0,r=[],a;for(a in t)!$c(HA,a)&&$c(t,a)&&tb(r,a);for(;e.length>i;)$c(t,a=e[i++])&&(~jA(r,a)||tb(r,a));return r}});var Bc=b((YF,sb)=>{"use strict";sb.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Dc=b((KF,ab)=>{"use strict";var GA=rb(),zA=Bc();ab.exports=Object.keys||function(e){return GA(e,zA)}});var Cc=b((XF,cb)=>{"use strict";var ob=It(),QA=qe(),ub=Ve(),WA=Uo(),YA=Dc(),KA=rr(),XA=rc().f,lb=ub(XA),JA=ub([].push),ZA=ob&&QA(function(){var s=Object.create(null);return s[2]=2,!lb(s,2)}),nb=function(s){return function(e){for(var t=KA(e),i=YA(t),r=ZA&&WA(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!ob||(r?u in t:lb(t,u)))&&JA(o,s?[u,t[u]]:t[u]);return o}};cb.exports={entries:nb(!0),values:nb(!1)}});var db=b(()=>{"use strict";var ek=ke(),tk=Cc().entries;ek({target:"Object",stat:!0},{entries:function(e){return tk(e)}})});var hb=b((eN,pb)=>{"use strict";db();var ik=Lr();pb.exports=ik.Object.entries});var mb=b((tN,fb)=>{"use strict";var rk=hb();fb.exports=rk});var nr=b((iN,bb)=>{"use strict";var sk=mb();bb.exports=sk});var or=b((rN,gb)=>{"use strict";gb.exports={}});var yb=b((sN,vb)=>{"use strict";var ak=xe(),nk=Te(),Sb=ak.WeakMap;vb.exports=nk(Sb)&&/native code/.test(String(Sb))});var Fc=b((aN,xb)=>{"use strict";var ok=yb(),Ib=xe(),uk=Et(),lk=Dr(),Vc=Ut(),Oc=ba(),ck=No(),dk=qo(),Tb="Object already initialized",_c=Ib.TypeError,pk=Ib.WeakMap,jo,Ta,Ho,hk=function(s){return Ho(s)?Ta(s):jo(s,{})},fk=function(s){return function(e){var t;if(!uk(e)||(t=Ta(e)).type!==s)throw new _c("Incompatible receiver, "+s+" required");return t}};ok||Oc.state?(qt=Oc.state||(Oc.state=new pk),qt.get=qt.get,qt.has=qt.has,qt.set=qt.set,jo=function(s,e){if(qt.has(s))throw new _c(Tb);return e.facade=s,qt.set(s,e),e},Ta=function(s){return qt.get(s)||{}},Ho=function(s){return qt.has(s)}):(ur=ck("state"),dk[ur]=!0,jo=function(s,e){if(Vc(s,ur))throw new _c(Tb);return e.facade=s,lk(s,ur,e),e},Ta=function(s){return Vc(s,ur)?s[ur]:{}},Ho=function(s){return Vc(s,ur)});var qt,ur;xb.exports={set:jo,get:Ta,has:Ho,enforce:hk,getterFor:fk}});var qc=b((nN,wb)=>{"use strict";var Nc=It(),mk=Ut(),Eb=Function.prototype,bk=Nc&&Object.getOwnPropertyDescriptor,Uc=mk(Eb,"name"),gk=Uc&&function(){}.name==="something",Sk=Uc&&(!Nc||Nc&&bk(Eb,"name").configurable);wb.exports={EXISTS:Uc,PROPER:gk,CONFIGURABLE:Sk}});var Ab=b(Pb=>{"use strict";var vk=It(),yk=Ic(),Tk=ar(),Ik=Xt(),xk=rr(),Ek=Dc();Pb.f=vk&&!yk?Object.defineProperties:function(e,t){Ik(e);for(var i=xk(t),r=Ek(t),a=r.length,n=0,o;a>n;)Tk.f(e,o=r[n++],i[o]);return e}});var jc=b((uN,kb)=>{"use strict";var wk=yi();kb.exports=wk("document","documentElement")});var Qc=b((lN,Cb)=>{"use strict";var Pk=Xt(),Ak=Ab(),Rb=Bc(),kk=qo(),Rk=jc(),Lk=Vo(),Mk=No(),Lb=">",Mb="<",Gc="prototype",zc="script",Bb=Mk("IE_PROTO"),Hc=function(){},Db=function(s){return Mb+zc+Lb+s+Mb+"/"+zc+Lb},$b=function(s){s.write(Db("")),s.close();var e=s.parentWindow.Object;return s=null,e},$k=function(){var s=Lk("iframe"),e="java"+zc+":",t;return s.style.display="none",Rk.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Db("document.F=Object")),t.close(),t.F},Go,zo=function(){try{Go=new ActiveXObject("htmlfile")}catch(e){}zo=typeof document!="undefined"?document.domain&&Go?$b(Go):$k():$b(Go);for(var s=Rb.length;s--;)delete zo[Gc][Rb[s]];return zo()};kk[Bb]=!0;Cb.exports=Object.create||function(e,t){var i;return e!==null?(Hc[Gc]=Pk(e),i=new Hc,Hc[Gc]=null,i[Bb]=e):i=zo(),t===void 0?i:Ak.f(i,t)}});var _r=b((cN,Vb)=>{"use strict";var Bk=Dr();Vb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Bk(s,e,t),s}});var Xc=b((dN,Fb)=>{"use strict";var Dk=qe(),Ck=Te(),Vk=Et(),Ok=Qc(),Ob=Uo(),_k=_r(),Fk=je(),Nk=Nt(),Kc=Fk("iterator"),_b=!1,Ti,Wc,Yc;[].keys&&(Yc=[].keys(),"next"in Yc?(Wc=Ob(Ob(Yc)),Wc!==Object.prototype&&(Ti=Wc)):_b=!0);var Uk=!Vk(Ti)||Dk(function(){var s={};return Ti[Kc].call(s)!==s});Uk?Ti={}:Nk&&(Ti=Ok(Ti));Ck(Ti[Kc])||_k(Ti,Kc,function(){return this});Fb.exports={IteratorPrototype:Ti,BUGGY_SAFARI_ITERATORS:_b}});var Qo=b((pN,Ub)=>{"use strict";var qk=je(),jk=qk("toStringTag"),Nb={};Nb[jk]="z";Ub.exports=String(Nb)==="[object z]"});var Ia=b((hN,qb)=>{"use strict";var Hk=Qo(),Gk=Te(),Wo=ir(),zk=je(),Qk=zk("toStringTag"),Wk=Object,Yk=Wo(function(){return arguments}())==="Arguments",Kk=function(s,e){try{return s[e]}catch(t){}};qb.exports=Hk?Wo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Kk(e=Wk(s),Qk))=="string"?t:Yk?Wo(e):(i=Wo(e))==="Object"&&Gk(e.callee)?"Arguments":i}});var Hb=b((fN,jb)=>{"use strict";var Xk=Qo(),Jk=Ia();jb.exports=Xk?{}.toString:function(){return"[object "+Jk(this)+"]"}});var xa=b((mN,zb)=>{"use strict";var Zk=Qo(),eR=ar().f,tR=Dr(),iR=Ut(),rR=Hb(),sR=je(),Gb=sR("toStringTag");zb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(iR(r,Gb)||eR(r,Gb,{configurable:!0,value:e}),i&&!Zk&&tR(r,"toString",rR))}});var Wb=b((bN,Qb)=>{"use strict";var aR=Xc().IteratorPrototype,nR=Qc(),oR=pa(),uR=xa(),lR=or(),cR=function(){return this};Qb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=nR(aR,{next:oR(+!i,t)}),uR(s,r,!1,!0),lR[r]=cR,s}});var Kb=b((gN,Yb)=>{"use strict";var dR=Ve(),pR=Kt();Yb.exports=function(s,e,t){try{return dR(pR(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Jb=b((SN,Xb)=>{"use strict";var hR=Et();Xb.exports=function(s){return hR(s)||s===null}});var eg=b((vN,Zb)=>{"use strict";var fR=Jb(),mR=String,bR=TypeError;Zb.exports=function(s){if(fR(s))return s;throw new bR("Can't set "+mR(s)+" as a prototype")}});var Jc=b((yN,tg)=>{"use strict";var gR=Kb(),SR=Et(),vR=Di(),yR=eg();tg.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=gR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return vR(r),yR(a),SR(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var pg=b((TN,dg)=>{"use strict";var TR=ke(),IR=xt(),Yo=Nt(),lg=qc(),xR=Te(),ER=Wb(),ig=Uo(),rg=Jc(),wR=xa(),PR=Dr(),Zc=_r(),AR=je(),sg=or(),cg=Xc(),kR=lg.PROPER,RR=lg.CONFIGURABLE,ag=cg.IteratorPrototype,Ko=cg.BUGGY_SAFARI_ITERATORS,Ea=AR("iterator"),ng="keys",wa="values",og="entries",ug=function(){return this};dg.exports=function(s,e,t,i,r,a,n){ER(t,e,i);var o=function(S){if(S===r&&h)return h;if(!Ko&&S&&S in d)return d[S];switch(S){case ng:return function(){return new t(this,S)};case wa:return function(){return new t(this,S)};case og:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[Ea]||d["@@iterator"]||r&&d[r],h=!Ko&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=ig(p.call(new s)),f!==Object.prototype&&f.next&&(!Yo&&ig(f)!==ag&&(rg?rg(f,ag):xR(f[Ea])||Zc(f,Ea,ug)),wR(f,u,!0,!0),Yo&&(sg[u]=ug))),kR&&r===wa&&c&&c.name!==wa&&(!Yo&&RR?PR(d,"name",wa):(l=!0,h=function(){return IR(c,this)})),r)if(m={values:o(wa),keys:a?h:o(ng),entries:o(og)},n)for(g in m)(Ko||l||!(g in d))&&Zc(d,g,m[g]);else TR({target:e,proto:!0,forced:Ko||l},m);return(!Yo||n)&&d[Ea]!==h&&Zc(d,Ea,h,{name:r}),sg[e]=h,m}});var fg=b((IN,hg)=>{"use strict";hg.exports=function(s,e){return{value:s,done:e}}});var td=b((xN,vg)=>{"use strict";var LR=rr(),ed=ya(),mg=or(),gg=Fc(),MR=ar().f,$R=pg(),Xo=fg(),BR=Nt(),DR=It(),Sg="Array Iterator",CR=gg.set,VR=gg.getterFor(Sg);vg.exports=$R(Array,"Array",function(s,e){CR(this,{type:Sg,target:LR(s),index:0,kind:e})},function(){var s=VR(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,Xo(void 0,!0);switch(s.kind){case"keys":return Xo(t,!1);case"values":return Xo(e[t],!1)}return Xo([t,e[t]],!1)},"values");var bg=mg.Arguments=mg.Array;ed("keys");ed("values");ed("entries");if(!BR&&DR&&bg.name!=="values")try{MR(bg,"name",{value:"values"})}catch(s){}});var Tg=b((EN,yg)=>{"use strict";var OR=je(),_R=or(),FR=OR("iterator"),NR=Array.prototype;yg.exports=function(s){return s!==void 0&&(_R.Array===s||NR[FR]===s)}});var id=b((wN,xg)=>{"use strict";var UR=Ia(),Ig=ma(),qR=Rr(),jR=or(),HR=je(),GR=HR("iterator");xg.exports=function(s){if(!qR(s))return Ig(s,GR)||Ig(s,"@@iterator")||jR[UR(s)]}});var wg=b((PN,Eg)=>{"use strict";var zR=xt(),QR=Kt(),WR=Xt(),YR=fa(),KR=id(),XR=TypeError;Eg.exports=function(s,e){var t=arguments.length<2?KR(s):e;if(QR(t))return WR(zR(t,s));throw new XR(YR(s)+" is not iterable")}});var kg=b((AN,Ag)=>{"use strict";var JR=xt(),Pg=Xt(),ZR=ma();Ag.exports=function(s,e,t){var i,r;Pg(s);try{if(i=ZR(s,"return"),!i){if(e==="throw")throw t;return t}i=JR(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Pg(i),t}});var Zo=b((kN,$g)=>{"use strict";var eL=Br(),tL=xt(),iL=Xt(),rL=fa(),sL=Tg(),aL=Or(),Rg=ha(),nL=wg(),oL=id(),Lg=kg(),uL=TypeError,Jo=function(s,e){this.stopped=s,this.result=e},Mg=Jo.prototype;$g.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=eL(e,i),l,d,c,h,p,f,m,g=function(v){return l&&Lg(l,"normal",v),new Jo(!0,v)},S=function(v){return r?(iL(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(a)l=s.iterator;else if(n)l=s;else{if(d=oL(s),!d)throw new uL(rL(s)+" is not iterable");if(sL(d)){for(c=0,h=aL(s);h>c;c++)if(p=S(s[c]),p&&Rg(Mg,p))return p;return new Jo(!1)}l=nL(s,d)}for(f=a?s.next:l.next;!(m=tL(f,l)).done;){try{p=S(m.value)}catch(v){Lg(l,"throw",v)}if(typeof p=="object"&&p&&Rg(Mg,p))return p}return new Jo(!1)}});var Dg=b((RN,Bg)=>{"use strict";var lL=It(),cL=ar(),dL=pa();Bg.exports=function(s,e,t){lL?cL.f(s,e,dL(0,t)):s[e]=t}});var Cg=b(()=>{"use strict";var pL=ke(),hL=Zo(),fL=Dg();pL({target:"Object",stat:!0},{fromEntries:function(e){var t={};return hL(e,function(i,r){fL(t,i,r)},{AS_ENTRIES:!0}),t}})});var Og=b(($N,Vg)=>{"use strict";td();Cg();var mL=Lr();Vg.exports=mL.Object.fromEntries});var Fg=b((BN,_g)=>{"use strict";_g.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 Ug=b(()=>{"use strict";td();var bL=Fg(),gL=xe(),SL=xa(),Ng=or();for(eu in bL)SL(gL[eu],eu),Ng[eu]=Ng.Array;var eu});var jg=b((VN,qg)=>{"use strict";var vL=Og();Ug();qg.exports=vL});var rd=b((ON,Hg)=>{"use strict";var yL=jg();Hg.exports=yL});var Gg=b(()=>{"use strict"});var sd=b((NN,zg)=>{"use strict";var Pa=xe(),TL=sr(),IL=ir(),tu=function(s){return TL.slice(0,s.length)===s};zg.exports=function(){return tu("Bun/")?"BUN":tu("Cloudflare-Workers")?"CLOUDFLARE":tu("Deno/")?"DENO":tu("Node.js/")?"NODE":Pa.Bun&&typeof Bun.version=="string"?"BUN":Pa.Deno&&typeof Deno.version=="object"?"DENO":IL(Pa.process)==="process"?"NODE":Pa.window&&Pa.document?"BROWSER":"REST"}()});var iu=b((UN,Qg)=>{"use strict";var xL=sd();Qg.exports=xL==="NODE"});var Yg=b((qN,Wg)=>{"use strict";var EL=ar();Wg.exports=function(s,e,t){return EL.f(s,e,t)}});var Jg=b((jN,Xg)=>{"use strict";var wL=yi(),PL=Yg(),AL=je(),kL=It(),Kg=AL("species");Xg.exports=function(s){var e=wL(s);kL&&e&&!e[Kg]&&PL(e,Kg,{configurable:!0,get:function(){return this}})}});var eS=b((HN,Zg)=>{"use strict";var RL=ha(),LL=TypeError;Zg.exports=function(s,e){if(RL(e,s))return s;throw new LL("Incorrect invocation")}});var nd=b((GN,tS)=>{"use strict";var ML=Ve(),$L=Te(),ad=ba(),BL=ML(Function.toString);$L(ad.inspectSource)||(ad.inspectSource=function(s){return BL(s)});tS.exports=ad.inspectSource});var ud=b((zN,nS)=>{"use strict";var DL=Ve(),CL=qe(),iS=Te(),VL=Ia(),OL=yi(),_L=nd(),rS=function(){},sS=OL("Reflect","construct"),od=/^\s*(?:class|function)\b/,FL=DL(od.exec),NL=!od.test(rS),Aa=function(e){if(!iS(e))return!1;try{return sS(rS,[],e),!0}catch(t){return!1}},aS=function(e){if(!iS(e))return!1;switch(VL(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return NL||!!FL(od,_L(e))}catch(t){return!0}};aS.sham=!0;nS.exports=!sS||CL(function(){var s;return Aa(Aa.call)||!Aa(Object)||!Aa(function(){s=!0})||s})?aS:Aa});var uS=b((QN,oS)=>{"use strict";var UL=ud(),qL=fa(),jL=TypeError;oS.exports=function(s){if(UL(s))return s;throw new jL(qL(s)+" is not a constructor")}});var ld=b((WN,cS)=>{"use strict";var lS=Xt(),HL=uS(),GL=Rr(),zL=je(),QL=zL("species");cS.exports=function(s,e){var t=lS(s).constructor,i;return t===void 0||GL(i=lS(t)[QL])?e:HL(i)}});var pS=b((YN,dS)=>{"use strict";var WL=Ve();dS.exports=WL([].slice)});var fS=b((KN,hS)=>{"use strict";var YL=TypeError;hS.exports=function(s,e){if(s<e)throw new YL("Not enough arguments");return s}});var cd=b((XN,mS)=>{"use strict";var KL=sr();mS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(KL)});var vd=b((JN,ES)=>{"use strict";var Pt=xe(),XL=Zl(),JL=Br(),bS=Te(),ZL=Ut(),xS=qe(),gS=jc(),eM=pS(),SS=Vo(),tM=fS(),iM=cd(),rM=iu(),bd=Pt.setImmediate,gd=Pt.clearImmediate,sM=Pt.process,dd=Pt.Dispatch,aM=Pt.Function,vS=Pt.MessageChannel,nM=Pt.String,pd=0,ka={},yS="onreadystatechange",Ra,lr,hd,fd;xS(function(){Ra=Pt.location});var Sd=function(s){if(ZL(ka,s)){var e=ka[s];delete ka[s],e()}},md=function(s){return function(){Sd(s)}},TS=function(s){Sd(s.data)},IS=function(s){Pt.postMessage(nM(s),Ra.protocol+"//"+Ra.host)};(!bd||!gd)&&(bd=function(e){tM(arguments.length,1);var t=bS(e)?e:aM(e),i=eM(arguments,1);return ka[++pd]=function(){XL(t,void 0,i)},lr(pd),pd},gd=function(e){delete ka[e]},rM?lr=function(s){sM.nextTick(md(s))}:dd&&dd.now?lr=function(s){dd.now(md(s))}:vS&&!iM?(hd=new vS,fd=hd.port2,hd.port1.onmessage=TS,lr=JL(fd.postMessage,fd)):Pt.addEventListener&&bS(Pt.postMessage)&&!Pt.importScripts&&Ra&&Ra.protocol!=="file:"&&!xS(IS)?(lr=IS,Pt.addEventListener("message",TS,!1)):yS in SS("script")?lr=function(s){gS.appendChild(SS("script"))[yS]=function(){gS.removeChild(this),Sd(s)}}:lr=function(s){setTimeout(md(s),0)});ES.exports={set:bd,clear:gd}});var AS=b((ZN,PS)=>{"use strict";var wS=xe(),oM=It(),uM=Object.getOwnPropertyDescriptor;PS.exports=function(s){if(!oM)return wS[s];var e=uM(wS,s);return e&&e.value}});var yd=b((eU,RS)=>{"use strict";var kS=function(){this.head=null,this.tail=null};kS.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};RS.exports=kS});var MS=b((tU,LS)=>{"use strict";var lM=sr();LS.exports=/ipad|iphone|ipod/i.test(lM)&&typeof Pebble!="undefined"});var BS=b((iU,$S)=>{"use strict";var cM=sr();$S.exports=/web0s(?!.*chrome)/i.test(cM)});var NS=b((rU,FS)=>{"use strict";var Nr=xe(),dM=AS(),DS=Br(),Td=vd().set,pM=yd(),hM=cd(),fM=MS(),mM=BS(),Id=iu(),CS=Nr.MutationObserver||Nr.WebKitMutationObserver,VS=Nr.document,OS=Nr.process,ru=Nr.Promise,wd=dM("queueMicrotask"),Fr,xd,Ed,su,_S;wd||(La=new pM,Ma=function(){var s,e;for(Id&&(s=OS.domain)&&s.exit();e=La.get();)try{e()}catch(t){throw La.head&&Fr(),t}s&&s.enter()},!hM&&!Id&&!mM&&CS&&VS?(xd=!0,Ed=VS.createTextNode(""),new CS(Ma).observe(Ed,{characterData:!0}),Fr=function(){Ed.data=xd=!xd}):!fM&&ru&&ru.resolve?(su=ru.resolve(void 0),su.constructor=ru,_S=DS(su.then,su),Fr=function(){_S(Ma)}):Id?Fr=function(){OS.nextTick(Ma)}:(Td=DS(Td,Nr),Fr=function(){Td(Ma)}),wd=function(s){La.head||Fr(),La.add(s)});var La,Ma;FS.exports=wd});var qS=b((sU,US)=>{"use strict";US.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var au=b((aU,jS)=>{"use strict";jS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var cr=b((nU,HS)=>{"use strict";var bM=xe();HS.exports=bM.Promise});var Ur=b((oU,WS)=>{"use strict";var gM=xe(),$a=cr(),SM=Te(),vM=Tc(),yM=nd(),TM=je(),GS=sd(),IM=Nt(),Pd=uc(),zS=$a&&$a.prototype,xM=TM("species"),Ad=!1,QS=SM(gM.PromiseRejectionEvent),EM=vM("Promise",function(){var s=yM($a),e=s!==String($a);if(!e&&Pd===66||IM&&!(zS.catch&&zS.finally))return!0;if(!Pd||Pd<51||!/native code/.test(s)){var t=new $a(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[xM]=i,Ad=t.then(function(){})instanceof i,!Ad)return!0}return!e&&(GS==="BROWSER"||GS==="DENO")&&!QS});WS.exports={CONSTRUCTOR:EM,REJECTION_EVENT:QS,SUBCLASSING:Ad}});var qr=b((uU,KS)=>{"use strict";var YS=Kt(),wM=TypeError,PM=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new wM("Bad Promise constructor");e=i,t=r}),this.resolve=YS(e),this.reject=YS(t)};KS.exports.f=function(s){return new PM(s)}});var mv=b(()=>{"use strict";var AM=ke(),kM=Nt(),lu=iu(),Vi=xe(),zr=xt(),XS=_r(),JS=Jc(),RM=xa(),LM=Jg(),MM=Kt(),uu=Te(),$M=Et(),BM=eS(),DM=ld(),rv=vd().set,$d=NS(),CM=qS(),VM=au(),OM=yd(),sv=Fc(),cu=cr(),Bd=Ur(),av=qr(),du="Promise",nv=Bd.CONSTRUCTOR,_M=Bd.REJECTION_EVENT,FM=Bd.SUBCLASSING,kd=sv.getterFor(du),NM=sv.set,jr=cu&&cu.prototype,dr=cu,nu=jr,ov=Vi.TypeError,Rd=Vi.document,Dd=Vi.process,Ld=av.f,UM=Ld,qM=!!(Rd&&Rd.createEvent&&Vi.dispatchEvent),uv="unhandledrejection",jM="rejectionhandled",ZS=0,lv=1,HM=2,Cd=1,cv=2,ou,ev,GM,tv,dv=function(s){var e;return $M(s)&&uu(e=s.then)?e:!1},pv=function(s,e){var t=e.value,i=e.state===lv,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===cv&&QM(e),e.rejection=Cd),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new ov("Promise-chain cycle")):(l=dv(u))?zr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},hv=function(s,e){s.notified||(s.notified=!0,$d(function(){for(var t=s.reactions,i;i=t.get();)pv(i,s);s.notified=!1,e&&!s.rejection&&zM(s)}))},fv=function(s,e,t){var i,r;qM?(i=Rd.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Vi.dispatchEvent(i)):i={promise:e,reason:t},!_M&&(r=Vi["on"+s])?r(i):s===uv&&CM("Unhandled promise rejection",t)},zM=function(s){zr(rv,Vi,function(){var e=s.facade,t=s.value,i=iv(s),r;if(i&&(r=VM(function(){lu?Dd.emit("unhandledRejection",t,e):fv(uv,e,t)}),s.rejection=lu||iv(s)?cv:Cd,r.error))throw r.value})},iv=function(s){return s.rejection!==Cd&&!s.parent},QM=function(s){zr(rv,Vi,function(){var e=s.facade;lu?Dd.emit("rejectionHandled",e):fv(jM,e,s.value)})},Hr=function(s,e,t){return function(i){s(e,i,t)}},Gr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=HM,hv(s,!0))},Md=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new ov("Promise can't be resolved itself");var i=dv(e);i?$d(function(){var r={done:!1};try{zr(i,e,Hr(Md,r,s),Hr(Gr,r,s))}catch(a){Gr(r,a,s)}}):(s.value=e,s.state=lv,hv(s,!1))}catch(r){Gr({done:!1},r,s)}}};if(nv&&(dr=function(e){BM(this,nu),MM(e),zr(ou,this);var t=kd(this);try{e(Hr(Md,t),Hr(Gr,t))}catch(i){Gr(t,i)}},nu=dr.prototype,ou=function(e){NM(this,{type:du,done:!1,notified:!1,parent:!1,reactions:new OM,rejection:!1,state:ZS,value:void 0})},ou.prototype=XS(nu,"then",function(e,t){var i=kd(this),r=Ld(DM(this,dr));return i.parent=!0,r.ok=uu(e)?e:!0,r.fail=uu(t)&&t,r.domain=lu?Dd.domain:void 0,i.state===ZS?i.reactions.add(r):$d(function(){pv(r,i)}),r.promise}),ev=function(){var s=new ou,e=kd(s);this.promise=s,this.resolve=Hr(Md,e),this.reject=Hr(Gr,e)},av.f=Ld=function(s){return s===dr||s===GM?new ev(s):UM(s)},!kM&&uu(cu)&&jr!==Object.prototype)){tv=jr.then,FM||XS(jr,"then",function(e,t){var i=this;return new dr(function(r,a){zr(tv,i,r,a)}).then(e,t)},{unsafe:!0});try{delete jr.constructor}catch(s){}JS&&JS(jr,nu)}AM({global:!0,constructor:!0,wrap:!0,forced:nv},{Promise:dr});RM(dr,du,!1,!0);LM(du)});var yv=b((dU,vv)=>{"use strict";var WM=je(),gv=WM("iterator"),Sv=!1;try{bv=0,Vd={next:function(){return{done:!!bv++}},return:function(){Sv=!0}},Vd[gv]=function(){return this},Array.from(Vd,function(){throw 2})}catch(s){}var bv,Vd;vv.exports=function(s,e){try{if(!e&&!Sv)return!1}catch(r){return!1}var t=!1;try{var i={};i[gv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Od=b((pU,Tv)=>{"use strict";var YM=cr(),KM=yv(),XM=Ur().CONSTRUCTOR;Tv.exports=XM||!KM(function(s){YM.all(s).then(void 0,function(){})})});var Iv=b(()=>{"use strict";var JM=ke(),ZM=xt(),e$=Kt(),t$=qr(),i$=au(),r$=Zo(),s$=Od();JM({target:"Promise",stat:!0,forced:s$},{all:function(e){var t=this,i=t$.f(t),r=i.resolve,a=i.reject,n=i$(function(){var o=e$(t.resolve),u=[],l=0,d=1;r$(e,function(c){var h=l++,p=!1;d++,ZM(o,t,c).then(function(f){p||(p=!0,u[h]=f,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),i.promise}})});var Ev=b(()=>{"use strict";var a$=ke(),n$=Nt(),o$=Ur().CONSTRUCTOR,Fd=cr(),u$=yi(),l$=Te(),c$=_r(),xv=Fd&&Fd.prototype;a$({target:"Promise",proto:!0,forced:o$,real:!0},{catch:function(s){return this.then(void 0,s)}});!n$&&l$(Fd)&&(_d=u$("Promise").prototype.catch,xv.catch!==_d&&c$(xv,"catch",_d,{unsafe:!0}));var _d});var wv=b(()=>{"use strict";var d$=ke(),p$=xt(),h$=Kt(),f$=qr(),m$=au(),b$=Zo(),g$=Od();d$({target:"Promise",stat:!0,forced:g$},{race:function(e){var t=this,i=f$.f(t),r=i.reject,a=m$(function(){var n=h$(t.resolve);b$(e,function(o){p$(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var Pv=b(()=>{"use strict";var S$=ke(),v$=qr(),y$=Ur().CONSTRUCTOR;S$({target:"Promise",stat:!0,forced:y$},{reject:function(e){var t=v$.f(this),i=t.reject;return i(e),t.promise}})});var Nd=b((TU,Av)=>{"use strict";var T$=Xt(),I$=Et(),x$=qr();Av.exports=function(s,e){if(T$(s),I$(e)&&e.constructor===s)return e;var t=x$.f(s),i=t.resolve;return i(e),t.promise}});var Lv=b(()=>{"use strict";var E$=ke(),w$=yi(),kv=Nt(),P$=cr(),Rv=Ur().CONSTRUCTOR,A$=Nd(),k$=w$("Promise"),R$=kv&&!Rv;E$({target:"Promise",stat:!0,forced:kv||Rv},{resolve:function(e){return A$(R$&&this===k$?P$:this,e)}})});var Mv=b(()=>{"use strict";mv();Iv();Ev();wv();Pv();Lv()});var Cv=b(()=>{"use strict";var L$=ke(),M$=Nt(),pu=cr(),$$=qe(),Bv=yi(),Dv=Te(),B$=ld(),$v=Nd(),D$=_r(),qd=pu&&pu.prototype,C$=!!pu&&$$(function(){qd.finally.call({then:function(){}},function(){})});L$({target:"Promise",proto:!0,real:!0,forced:C$},{finally:function(s){var e=B$(this,Bv("Promise")),t=Dv(s);return this.then(t?function(i){return $v(e,s()).then(function(){return i})}:s,t?function(i){return $v(e,s()).then(function(){throw i})}:s)}});!M$&&Dv(pu)&&(Ud=Bv("Promise").prototype.finally,qd.finally!==Ud&&D$(qd,"finally",Ud,{unsafe:!0}));var Ud});var Ov=b((kU,Vv)=>{"use strict";Gg();Mv();Cv();var V$=Ci();Vv.exports=V$("Promise","finally")});var Fv=b((RU,_v)=>{"use strict";var O$=Ov();_v.exports=O$});var Ba=b((LU,Nv)=>{"use strict";var _$=Fv();Nv.exports=_$});var Zv=b(()=>{"use strict";var J$=ke(),Z$=Cc().values;J$({target:"Object",stat:!0},{values:function(e){return Z$(e)}})});var ty=b((f1,ey)=>{"use strict";Zv();var eB=Lr();ey.exports=eB.Object.values});var ry=b((m1,iy)=>{"use strict";var tB=ty();iy.exports=tB});var fr=b((b1,sy)=>{"use strict";var iB=ry();sy.exports=iB});var Ty=b(()=>{"use strict";var wB=ke(),PB=Mr(),AB=Or(),kB=va(),RB=ya();wB({target:"Array",proto:!0},{at:function(e){var t=PB(this),i=AB(t),r=kB(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});RB("at")});var xy=b((kq,Iy)=>{"use strict";Ty();var LB=Ci();Iy.exports=LB("Array","at")});var wy=b((Rq,Ey)=>{"use strict";var MB=xy();Ey.exports=MB});var jt=b((Lq,Py)=>{"use strict";var $B=wy();Py.exports=$B});var dp=b((SH,aT)=>{"use strict";var pD=ir();aT.exports=Array.isArray||function(e){return pD(e)==="Array"}});var oT=b((vH,nT)=>{"use strict";var hD=TypeError,fD=9007199254740991;nT.exports=function(s){if(s>fD)throw hD("Maximum allowed index exceeded");return s}});var cT=b((yH,lT)=>{"use strict";var mD=dp(),bD=Or(),gD=oT(),SD=Br(),uT=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?SD(n,o):!1,c,h;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&mD(c)?(h=bD(c),u=uT(s,e,c,h,u,a-1)-1):(gD(u+1),s[u]=c),u++),l++;return u};lT.exports=uT});var fT=b((TH,hT)=>{"use strict";var dT=dp(),vD=ud(),yD=Et(),TD=je(),ID=TD("species"),pT=Array;hT.exports=function(s){var e;return dT(s)&&(e=s.constructor,vD(e)&&(e===pT||dT(e.prototype))?e=void 0:yD(e)&&(e=e[ID],e===null&&(e=void 0))),e===void 0?pT:e}});var bT=b((IH,mT)=>{"use strict";var xD=fT();mT.exports=function(s,e){return new(xD(s))(e===0?0:e)}});var gT=b(()=>{"use strict";var ED=ke(),wD=cT(),PD=Kt(),AD=Mr(),kD=Or(),RD=bT();ED({target:"Array",proto:!0},{flatMap:function(e){var t=AD(this),i=kD(t),r;return PD(e),r=RD(t,0),r.length=wD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var ST=b(()=>{"use strict";var LD=ya();LD("flatMap")});var yT=b((AH,vT)=>{"use strict";gT();ST();var MD=Ci();vT.exports=MD("Array","flatMap")});var IT=b((kH,TT)=>{"use strict";var $D=yT();TT.exports=$D});var Ya=b((RH,xT)=>{"use strict";var BD=IT();xT.exports=BD});var Ka=b((LH,ET)=>{"use strict";var DD=Ia(),CD=String;ET.exports=function(s){if(DD(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return CD(s)}});var pp=b((MH,wT)=>{"use strict";wT.exports=`
|
|
7
|
-
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var kT=b(($H,AT)=>{"use strict";var VD=Ve(),OD=Di(),_D=Ka(),fp=pp(),PT=VD("".replace),FD=RegExp("^["+fp+"]+"),ND=RegExp("(^|[^"+fp+"])["+fp+"]+$"),hp=function(s){return function(e){var t=_D(OD(e));return s&1&&(t=PT(t,FD,"")),s&2&&(t=PT(t,ND,"$1")),t}};AT.exports={start:hp(1),end:hp(2),trim:hp(3)}});var $T=b((BH,MT)=>{"use strict";var UD=qc().PROPER,qD=qe(),RT=pp(),LT="\u200B\x85\u180E";MT.exports=function(s){return qD(function(){return!!RT[s]()||LT[s]()!==LT||UD&&RT[s].name!==s})}});var mp=b((DH,BT)=>{"use strict";var jD=kT().start,HD=$T();BT.exports=HD("trimStart")?function(){return jD(this)}:"".trimStart});var CT=b(()=>{"use strict";var GD=ke(),DT=mp();GD({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==DT},{trimLeft:DT})});var OT=b(()=>{"use strict";CT();var zD=ke(),VT=mp();zD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==VT},{trimStart:VT})});var FT=b((FH,_T)=>{"use strict";OT();var QD=Ci();_T.exports=QD("String","trimLeft")});var UT=b((NH,NT)=>{"use strict";var WD=FT();NT.exports=WD});var jT=b((UH,qT)=>{"use strict";var YD=UT();qT.exports=YD});var sI=b(()=>{"use strict"});var aI=b(()=>{"use strict"});var oI=b((EG,nI)=>{"use strict";var S0=Et(),v0=ir(),y0=je(),T0=y0("match");nI.exports=function(s){var e;return S0(s)&&((e=s[T0])!==void 0?!!e:v0(s)==="RegExp")}});var lI=b((wG,uI)=>{"use strict";var I0=Xt();uI.exports=function(){var s=I0(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var pI=b((PG,dI)=>{"use strict";var x0=xt(),E0=Ut(),w0=ha(),P0=lI(),cI=RegExp.prototype;dI.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in cI)&&!E0(s,"flags")&&w0(cI,s)?x0(P0,s):e}});var fI=b((AG,hI)=>{"use strict";var Tp=Ve(),A0=Mr(),k0=Math.floor,vp=Tp("".charAt),R0=Tp("".replace),yp=Tp("".slice),L0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,M0=/\$([$&'`]|\d{1,2})/g;hI.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=M0;return r!==void 0&&(r=A0(r),u=L0),R0(a,u,function(l,d){var c;switch(vp(d,0)){case"$":return"$";case"&":return s;case"`":return yp(e,0,t);case"'":return yp(e,n);case"<":c=r[yp(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var p=k0(h/10);return p===0?l:p<=o?i[p-1]===void 0?vp(d,1):i[p-1]+vp(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var gI=b(()=>{"use strict";var $0=ke(),B0=xt(),xp=Ve(),mI=Di(),D0=Te(),C0=Rr(),V0=oI(),ns=Ka(),O0=ma(),_0=pI(),F0=fI(),N0=je(),U0=Nt(),q0=N0("replace"),j0=TypeError,Ip=xp("".indexOf),H0=xp("".replace),bI=xp("".slice),G0=Math.max;$0({target:"String",proto:!0},{replaceAll:function(e,t){var i=mI(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!C0(e)){if(r=V0(e),r&&(a=ns(mI(_0(e))),!~Ip(a,"g")))throw new j0("`.replaceAll` does not allow non-global regexes");if(n=O0(e,q0),n)return B0(n,e,i,t);if(U0&&r)return H0(ns(i),e,t)}for(o=ns(i),u=ns(e),l=D0(t),l||(t=ns(t)),d=u.length,c=G0(1,d),h=Ip(o,u);h!==-1;)p=l?ns(t(u,h,o)):F0(u,o,h,[],void 0,t),m+=bI(o,f,h)+p,f=h+d,h=h+c>o.length?-1:Ip(o,u,h+c);return f<o.length&&(m+=bI(o,f)),m}})});var vI=b((LG,SI)=>{"use strict";sI();aI();gI();var z0=Ci();SI.exports=z0("String","replaceAll")});var TI=b((MG,yI)=>{"use strict";var Q0=vI();yI.exports=Q0});var Ep=b(($G,II)=>{"use strict";var W0=TI();II.exports=W0});var EI=b((BG,xI)=>{"use strict";var Y0=va(),K0=Ka(),X0=Di(),J0=RangeError;xI.exports=function(e){var t=K0(X0(this)),i="",r=Y0(e);if(r<0||r===1/0)throw new J0("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var RI=b((DG,kI)=>{"use strict";var AI=Ve(),Z0=Ac(),wI=Ka(),eC=EI(),tC=Di(),iC=AI(eC),rC=AI("".slice),sC=Math.ceil,PI=function(s){return function(e,t,i){var r=wI(tC(e)),a=Z0(t),n=r.length,o=i===void 0?" ":wI(i),u,l;return a<=n||o===""?r:(u=a-n,l=iC(o,sC(u/o.length)),l.length>u&&(l=rC(l,0,u)),s?r+l:l+r)}};kI.exports={start:PI(!1),end:PI(!0)}});var MI=b((CG,LI)=>{"use strict";var aC=sr();LI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(aC)});var $I=b(()=>{"use strict";var nC=ke(),oC=RI().start,uC=MI();nC({target:"String",proto:!0,forced:uC},{padStart:function(e){return oC(this,e,arguments.length>1?arguments[1]:void 0)}})});var DI=b((_G,BI)=>{"use strict";$I();var lC=Ci();BI.exports=lC("String","padStart")});var VI=b((FG,CI)=>{"use strict";var cC=DI();CI.exports=cC});var wp=b((NG,OI)=>{"use strict";var dC=VI();OI.exports=dC});var Wh="2.0.134-dev.ca4b9a20.0";var ct=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ct||{}),vi=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(vi||{});var $o=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))($o||{}),Kl=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Kl||{});var Xl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Xl||{}),Bo=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Bo||{});var YE=j(wt(),1);import{assertNever as Qm,assertNonNullable as wA,isNonNullable as _o,ValueSubject as Rc,Subject as PA,Subscription as AA,merge as kA,observableFrom as RA,fromEvent as jm,map as Hm,tap as Gm,filterChanged as LA,isNullable as Lc,ErrorCategory as zm}from"@vkontakte/videoplayer-shared/es2015";var qm=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Fo=class{constructor(e){this.connection$=new Rc(void 0);this.castState$=new Rc("NOT_AVAILABLE");this.errorEvent$=new PA;this.realCastState$=new Rc("NOT_AVAILABLE");this.subscription=new AA;this.isDestroyed=!1;var a;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=_o((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||qm("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:zm.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,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){_o(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Lc(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Lc(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(jm(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,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=(a=i.getCurrentSession())==null?void 0:a.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 Qm(r.sessionState)}})).add(kA(jm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Gm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Hm(r=>r.castState)),RA([i.getCastState()])).pipe(LA(),Hm(MA),Gm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=_o(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();wA(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Lc(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?_o(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(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:zm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},MA=s=>{switch(s){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 Qm(s)}};var Oh=j(wt(),1),LE=j(nr(),1),ME=j(rd(),1);var Kv=j(Ba(),1);import{assertNever as Uv}from"@vkontakte/videoplayer-shared/es2015";var Ie=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Uv(t)}return s},Oi=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:Uv(e)}};var L=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as F$,Subject as hu,merge as qv}from"@vkontakte/videoplayer-shared/es2015";var Q=class{constructor(e){this.transitionStarted$=new hu;this.transitionEnded$=new hu;this.transitionUpdated$=new hu;this.forceChanged$=new hu;this.stateChangeStarted$=qv(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=qv(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||F$(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as N$}from"@vkontakte/videoplayer-shared/es2015";var jv=s=>{switch(s){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 N$(s)}};import{assertNever as Qr,assertNonNullable as pr,debounce as Hv,ErrorCategory as Gv,fromEvent as hr,isNonNullable as zv,map as Qv,merge as Wv,observableFrom as U$,Subject as q$,Subscription as jd,timeout as j$,getHighestQuality as H$}from"@vkontakte/videoplayer-shared/es2015";var G$=5,z$=5,Q$=500,Yv=7e3,Da=class{constructor(e){this.subscription=new jd;this.loadMediaTimeoutSubscription=new jd;this.videoState=new Q("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Qr(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:Qr(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:Qr(e)}break}default:Qr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(jv(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 jd;this.subscription.add(e),this.subscription.add(Wv(this.videoState.stateChangeStarted$.pipe(Qv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Qv(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new q$;e.add(r.pipe(Hv(Q$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(hr(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-a)>G$)&&r.next(o),a=o})),e.add(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=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()&&a.duration-a.currentTime<z$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),L(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:Qr(n)}}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Wv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,U$(["init"])).pipe(Hv(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"),L(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),L(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"),L(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"),L(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"&&L(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a: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,a;switch(e){case"MPEG":{let d=t[e];pr(d);let c=H$(Object.keys(d));pr(c);let h=d[c];pr(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];pr(d),i=d.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];pr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];pr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];pr(d),i=Ie(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Gv.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Qr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return zv(o)&&(n.metadata.title=o),zv(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,a)=>{this.loadMediaTimeoutSubscription.add(j$(Yv).subscribe(()=>a(`timeout(${Yv})`)))});(0,Kv.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 a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Gv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var lp=j(wt(),1);import{clearVideoElement as Jv}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as W$}from"@vkontakte/videoplayer-shared/es2015";var Xv=s=>{try{s.pause(),s.playbackRate=0,W$(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as Y$,Subscription as K$}from"@vkontakte/videoplayer-shared/es2015";var Hd=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)}},Gd=window.WeakMap?new WeakMap:new Hd,zd=window.WeakMap?new WeakMap:new Map,X$=(s,e=20)=>{let t=0;return Y$(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},He=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Jv(i):(i=document.createElement("video"),s.appendChild(i)),Gd.set(i,r);let a=new K$;return a.add(X$(i,e)),zd.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ge=s=>{let e=zd.get(s);e==null||e.unsubscribe(),zd.delete(s);let t=Gd.get(s);Gd.delete(s),t?Jv(s):Xv(s)};var Wd=j(fr(),1);import{assertNonNullable as Ca,isNonNullable as Zt,isNullable as aB,fromEvent as Wr,merge as ay,observableFrom as ny,filterChanged as oy,map as Va,Subject as uy,Subscription as nB,ValueSubject as oB,ErrorCategory as uB}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Qd,isNullable as rB,Subscription as sB}from"@vkontakte/videoplayer-shared/es2015";var fu=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=rB(r),l=new sB;return r&&l.add(r.subscribe(d=>{let c=s.getState();i(d,c)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),l},Lt=(s,e,t)=>fu(e,()=>s.loop,i=>{Qd(i)&&(s.loop=i)},{onError:t}),ze=(s,e,t,i)=>fu(e,()=>({muted:s.muted,volume:s.volume}),r=>{Qd(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),dt=(s,e,t,i)=>fu(e,()=>s.playbackRate,r=>{Qd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),_i=fu;var lB=s=>["__",s.language,s.label].join("|"),cB=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Yd=class s{constructor(e){this.available$=new uy;this.current$=new oB(void 0);this.error$=new uy;this.subscription=new nB;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:uB.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(_i(t.internalTextTracks,()=>(0,Wd.default)(this.internalTracks),a=>{Zt(a)&&this.setInternal(a)},{equal:(a,n)=>Zt(a)&&Zt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Va(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(_i(t.externalTextTracks,()=>(0,Wd.default)(this.externalTracks),a=>{Zt(a)&&this.setExternal(a)},{equal:(a,n)=>Zt(a)&&Zt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Va(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(_i(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(_i(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Ca(this.video);let{textTracks:e}=this.video;this.subscription.add(Wr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(ay(Wr(e,"addtrack"),Wr(e,"removetrack"),ny(["init"])).pipe(Va(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),oy((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(ay(Wr(e,"change"),ny(["init"])).pipe(Va(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Va(i=>i&&this.htmlTextTrackToITextTrack(i).id),oy()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(Wr(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,d,c,h,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((h=(c=o.target)==null?void 0:c.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Wr(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;Zt(t.align)&&(r.align=t.align),Zt(t.position)&&(r.position=t.position),Zt(t.size)&&(r.size=t.size),Zt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ca(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:lB(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Ca(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(aB(e)||!cB(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){Ca(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):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){Ca(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)}},pt=Yd;var mr=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 ly=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Kd=s=>{let e=ly(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},cy=s=>{let e=ly(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as at,map as ei,merge as Tu,filterChanged as Sy,isNonNullable as vy,Subject as vB,filter as Jd,mapTo as Zd,combine as yB,once as TB,throttle as IB,ErrorCategory as xB,ValueSubject as yy,Subscription as EB}from"@vkontakte/videoplayer-shared/es2015";var dB=3,dy=(s,e,t=dB)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var mu=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isFirefox(){return this.current==="Firefox"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var py=j(wt(),1);var Oa=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var bu=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,py.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Oa()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return x(this,null,function*(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var gu=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var At=()=>window.ManagedMediaSource||window.MediaSource,Yr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},hy=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},Su=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var pB=document.createElement("video"),hB='video/mp4; codecs="avc1.42000a,mp4a.40.2"',fB='video/mp4; codecs="hev1.1.6.L93.B0"',fy='video/webm; codecs="vp09.00.10.08"',my='video/webm; codecs="av01.0.00M.08"',mB='audio/mp4; codecs="mp4a.40.2"',bB='audio/webm; codecs="opus"',by,gB=()=>x(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(B(E({},s),{video:B(E({},s.video),{contentType:my})})),window.navigator.mediaCapabilities.decodingInfo(B(E({},s),{video:B(E({},s.video),{contentType:fy})}))]);by={DASH_WEBM_AV1:e,DASH_WEBM:t}});gB().catch(s=>{console.log(pB),console.error(s)});var vu=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return by}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,d,c,h,p,f,m,g,S,v,y,T;this._video=document.createElement("video");try{this._protocols={mms:Yr(),mse:hy(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(a=this._video).canPlayType)!=null&&n.call(a,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let I=!!((d=(l=At())==null?void 0:l.isTypeSupported)!=null&&d.call(l,hB)),k=!!((h=(c=At())==null?void 0:c.isTypeSupported)!=null&&h.call(c,fB)),C=!!((f=(p=At())==null?void 0:p.isTypeSupported)!=null&&f.call(p,mB));this._codecs={h264:I,h265:k,vp9:!!((g=(m=At())==null?void 0:m.isTypeSupported)!=null&&g.call(m,fy)),av1:!!((v=(S=At())==null?void 0:S.isTypeSupported)!=null&&v.call(S,my)),aac:C,opus:!!((T=(y=At())==null?void 0:y.isTypeSupported)!=null&&T.call(y,bB)),mpeg:(I||k)&&C},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(I){console.error(I)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var gy="audio/mpeg",yu=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,gy))},this._codecs={mp3:!!((r=(i=At())==null?void 0:i.isTypeSupported)!=null&&r.call(i,gy))}}catch(a){console.error(a)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as SB}from"@vkontakte/videoplayer-shared/es2015";var Xd=class{constructor(){this.isInited$=new SB(!1);this._displayChecker=new gu,this._deviceChecker=new bu(this._displayChecker),this._browserChecker=new mu,this._videoChecker=new vu(this._deviceChecker,this._browserChecker),this._audioChecker=new yu,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return x(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},G=new Xd;var Qe=s=>{let e=w=>at(s,w).pipe(Zd(void 0)),t=new EB,i=()=>t.unsubscribe(),r=Tu(at(s,"progress"),at(s,"timeupdate")).pipe(ei(()=>dy(s.buffered,s.currentTime))),a=G.browser.isSafari?yB({play:e("play").pipe(TB()),playing:e("playing")}).pipe(Zd(void 0)):e("playing"),n=at(s,"volumechange").pipe(ei(()=>({muted:s.muted,volume:s.volume}))),o=at(s,"ratechange").pipe(ei(()=>s.playbackRate)),u=at(s,"error").pipe(Jd(()=>!!(s.error||s.played.length)),ei(()=>{var F;let w=s.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:xB.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(F=s.error)!=null?F:void 0}})),l=at(s,"timeupdate").pipe(ei(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new vB,h=.3,p;t.add(Tu(...d.map(w=>at(s,w))).subscribe(w=>{let F=s.currentTime;s.loop&&vy(p)&&vy(F)&&p>=s.duration-h&&F<=h&&c.next(p),p=F}));let f=e("pause").pipe(Jd(()=>!s.error&&p!==s.duration)),m=at(s,"enterpictureinpicture"),g=at(s,"leavepictureinpicture"),S=new yy(cy(s));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new yy(Kd(s)),y=at(s,"fullscreenchange");t.add(y.pipe(ei(()=>Kd(s))).subscribe(v));let T=.1,I=1e3,k=at(s,"timeupdate").pipe(ei(w=>s.duration-s.currentTime<T),Sy()),C=Tu(k.pipe(Jd(w=>!s.loop&&w)),at(s,"ended")).pipe(IB(I),Zd(void 0)),D=Tu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>at(s,w)),k.pipe(ei(w=>({type:w?"ended":"unknown"})))).pipe(ei(w=>G.browser.isFirefox&&w.type==="ended"?s.readyState<2:s.readyState<3),Sy());return{playing$:a,pause$:f,canplay$:e("canplay"),ended$:C,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$:at(s,"durationchange").pipe(ei(()=>s.duration)),isBuffering$:D,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Fi}from"@vkontakte/videoplayer-shared/es2015";var ti=s=>{switch(s){case"mobile":return Fi.Q_144P;case"lowest":return Fi.Q_240P;case"low":return Fi.Q_360P;case"sd":case"medium":return Fi.Q_480P;case"hd":case"high":return Fi.Q_720P;case"fullhd":case"full":return Fi.Q_1080P;case"quadhd":case"quad":return Fi.Q_1440P;case"ultrahd":case"ultra":return Fi.Q_2160P}};var ot=j(jt(),1),ip=j(wt(),1),br=j(nr(),1);import{isNonNullable as ne,isNullable as Pu,now as Vy,isHigher as Au,isHigherOrEqual as Xr,isInvariantQuality as ku,isLowerOrEqual as Jr,videoSizeToQuality as Oy,assertNotEmptyArray as Ru,assertNonNullable as _y}from"@vkontakte/videoplayer-shared/es2015";var ep=!1,Ii={},Ay=s=>{ep=s},ky=()=>{Ii={}},Ry=s=>{s(Ii)},_a=(s,e)=>{var t;ep&&(Ii.meta=(t=Ii.meta)!=null?t:{},Ii.meta[s]=e)},nt=class{constructor(e){this.name=e}next(e){var i,r;if(!ep)return;Ii.series=(i=Ii.series)!=null?i:{};let t=(r=Ii.series[this.name])!=null?r:[];t.push([Date.now(),e]),Ii.series[this.name]=t}};import{isHigher as BB,isHigherOrEqual as Vq,isLower as Ly,isLowerOrEqual as Oq,isNonNullable as Iu,isNullable as DB,videoHeightToQuality as xu}from"@vkontakte/videoplayer-shared/es2015";function tp(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Eu(s,e,t){return!!s&&tp(s,e,t)==="high_quality"}function Kr(s,e,t){return DB(s)||Iu(s.min)&&Iu(s.max)&&Ly(s.max,s.min)||Iu(s.min)&&e&&BB(s.min,e)||Iu(s.max)&&t&&Ly(s.max,t)}function My({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Kr({max:s!=null&&s.max?xu(s.max):void 0,min:s!=null&&s.min?xu(s.min):void 0},e?xu(e):void 0,t?xu(t):void 0)}var Fy=new nt("best_bitrate"),Lu=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Zr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Ni=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Vy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Mu='Assertion "ABR Tracks is empty array" failed',wu=new WeakMap,$y=new WeakMap,By=new WeakMap,Fa=(s,e,t,i)=>{var u;let r=[...e].sort(Zr(1)),a=[...t].sort(Zr(1)),n=a.filter(l=>ne(l.bitrate)&&ne(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,ot.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,ot.default)(a,-1);return o&&(0,ip.default)(n,o)?o:n.length?(0,ot.default)(n,-1):(0,ot.default)(a,0)},Na=(s,e,t,i)=>{var u;let r=wu.get(e);r||(r=[...e].sort(Zr(1)),wu.set(e,r));let a=wu.get(t);a||(a=[...t].sort(Zr(1)),wu.set(t,a));let n=By.get(s);n||(n=a.filter(l=>ne(l.bitrate)&&ne(s.bitrate)?s.bitrate/l.bitrate>i:!0),By.set(s,n));let o=(u=(0,ot.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,ot.default)(a,-1);return o&&(0,ip.default)(n,o)?o:n.length?(0,ot.default)(n,-1):(0,ot.default)(a,0)},Dy=s=>"quality"in s,$u=(s,e,t,i)=>{var n;let r=ne((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&ne(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&Vy()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Dy(o)?"video":"audio",l=Dy(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var qE=Object.create;var ql=Object.defineProperty,jE=Object.defineProperties,HE=Object.getOwnPropertyDescriptor,zE=Object.getOwnPropertyDescriptors,QE=Object.getOwnPropertyNames,wo=Object.getOwnPropertySymbols,GE=Object.getPrototypeOf,jl=Object.prototype.hasOwnProperty,Uh=Object.prototype.propertyIsEnumerable;var WE=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var Ze=Math.pow,Nh=(s,e,t)=>e in s?ql(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,x=(s,e)=>{for(var t in e||(e={}))jl.call(e,t)&&Nh(s,t,e[t]);if(wo)for(var t of wo(e))Uh.call(e,t)&&Nh(s,t,e[t]);return s},B=(s,e)=>jE(s,zE(e));var qh=(s,e)=>{var t={};for(var i in s)jl.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&wo)for(var i of wo(s))e.indexOf(i)<0&&Uh.call(s,i)&&(t[i]=s[i]);return t};var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var YE=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of QE(e))!jl.call(s,r)&&r!==t&&ql(s,r,{get:()=>e[r],enumerable:!(i=HE(e,r))||i.enumerable});return s};var H=(s,e,t)=>(t=s!=null?qE(GE(s)):{},YE(e||!s||!s.__esModule?ql(t,"default",{value:s,enumerable:!0}):t,s));var E=(s,e,t)=>new Promise((i,r)=>{var a=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(a,n);o((t=t.apply(s,e)).next())}),Zi=function(s,e){this[0]=s,this[1]=e},X=(s,e,t)=>{var i=(n,o,u,l)=>{try{var d=t[n](o),c=(o=d.value)instanceof Zi,h=d.done;Promise.resolve(c?o[0]:o).then(p=>c?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>a[n]=o=>new Promise((u,l)=>i(n,o,u,l)),a={};return t=t.apply(s,e),a[WE("asyncIterator")]=()=>a,r("next"),r("throw"),r("return"),a};var xe=b((Ql,Hh)=>{"use strict";var na=function(s){return s&&s.Math===Math&&s};Hh.exports=na(typeof globalThis=="object"&&globalThis)||na(typeof window=="object"&&window)||na(typeof self=="object"&&self)||na(typeof global=="object"&&global)||na(typeof Ql=="object"&&Ql)||function(){return this}()||Function("return this")()});var Ue=b((l_,zh)=>{"use strict";zh.exports=function(s){try{return!!s()}catch(e){return!0}}});var oa=b((c_,Qh)=>{"use strict";var KE=Ue();Qh.exports=!KE(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Gl=b((d_,Kh)=>{"use strict";var XE=oa(),Yh=Function.prototype,Gh=Yh.apply,Wh=Yh.call;Kh.exports=typeof Reflect=="object"&&Reflect.apply||(XE?Wh.bind(Gh):function(){return Wh.apply(Gh,arguments)})});var Ce=b((p_,Zh)=>{"use strict";var Xh=oa(),Jh=Function.prototype,Wl=Jh.call,JE=Xh&&Jh.bind.bind(Wl,Wl);Zh.exports=Xh?JE:function(s){return function(){return Wl.apply(s,arguments)}}});var er=b((h_,tf)=>{"use strict";var ef=Ce(),ZE=ef({}.toString),ew=ef("".slice);tf.exports=function(s){return ew(ZE(s),8,-1)}});var Yl=b((f_,rf)=>{"use strict";var tw=er(),iw=Ce();rf.exports=function(s){if(tw(s)==="Function")return iw(s)}});var Te=b((m_,sf)=>{"use strict";var Kl=typeof document=="object"&&document.all;sf.exports=typeof Kl=="undefined"&&Kl!==void 0?function(s){return typeof s=="function"||s===Kl}:function(s){return typeof s=="function"}});var vt=b((b_,af)=>{"use strict";var rw=Ue();af.exports=!rw(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var yt=b((g_,nf)=>{"use strict";var sw=oa(),ko=Function.prototype.call;nf.exports=sw?ko.bind(ko):function(){return ko.apply(ko,arguments)}});var Xl=b(lf=>{"use strict";var of={}.propertyIsEnumerable,uf=Object.getOwnPropertyDescriptor,aw=uf&&!of.call({1:2},1);lf.f=aw?function(e){var t=uf(this,e);return!!t&&t.enumerable}:of});var ua=b((v_,cf)=>{"use strict";cf.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var pf=b((y_,df)=>{"use strict";var nw=Ce(),ow=Ue(),uw=er(),Jl=Object,lw=nw("".split);df.exports=ow(function(){return!Jl("z").propertyIsEnumerable(0)})?function(s){return uw(s)==="String"?lw(s,""):Jl(s)}:Jl});var Pr=b((T_,hf)=>{"use strict";hf.exports=function(s){return s==null}});var Bi=b((I_,ff)=>{"use strict";var cw=Pr(),dw=TypeError;ff.exports=function(s){if(cw(s))throw new dw("Can't call method on "+s);return s}});var tr=b((x_,mf)=>{"use strict";var pw=pf(),hw=Bi();mf.exports=function(s){return pw(hw(s))}});var Tt=b((E_,bf)=>{"use strict";var fw=Te();bf.exports=function(s){return typeof s=="object"?s!==null:fw(s)}});var kr=b((w_,gf)=>{"use strict";gf.exports={}});var gi=b((A_,vf)=>{"use strict";var Zl=kr(),ec=xe(),mw=Te(),Sf=function(s){return mw(s)?s:void 0};vf.exports=function(s,e){return arguments.length<2?Sf(Zl[s])||Sf(ec[s]):Zl[s]&&Zl[s][e]||ec[s]&&ec[s][e]}});var la=b((P_,yf)=>{"use strict";var bw=Ce();yf.exports=bw({}.isPrototypeOf)});var ir=b((k_,xf)=>{"use strict";var gw=xe(),Tf=gw.navigator,If=Tf&&Tf.userAgent;xf.exports=If?String(If):""});var ic=b((R_,Rf)=>{"use strict";var kf=xe(),tc=ir(),Ef=kf.process,wf=kf.Deno,Af=Ef&&Ef.versions||wf&&wf.version,Pf=Af&&Af.v8,_t,Ro;Pf&&(_t=Pf.split("."),Ro=_t[0]>0&&_t[0]<4?1:+(_t[0]+_t[1]));!Ro&&tc&&(_t=tc.match(/Edge\/(\d+)/),(!_t||_t[1]>=74)&&(_t=tc.match(/Chrome\/(\d+)/),_t&&(Ro=+_t[1])));Rf.exports=Ro});var rc=b((M_,Lf)=>{"use strict";var Mf=ic(),Sw=Ue(),vw=xe(),yw=vw.String;Lf.exports=!!Object.getOwnPropertySymbols&&!Sw(function(){var s=Symbol("symbol detection");return!yw(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Mf&&Mf<41})});var sc=b((L_,Bf)=>{"use strict";var Tw=rc();Bf.exports=Tw&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ac=b((B_,$f)=>{"use strict";var Iw=gi(),xw=Te(),Ew=la(),ww=sc(),Aw=Object;$f.exports=ww?function(s){return typeof s=="symbol"}:function(s){var e=Iw("Symbol");return xw(e)&&Ew(e.prototype,Aw(s))}});var ca=b(($_,Df)=>{"use strict";var Pw=String;Df.exports=function(s){try{return Pw(s)}catch(e){return"Object"}}});var Wt=b((D_,Cf)=>{"use strict";var kw=Te(),Rw=ca(),Mw=TypeError;Cf.exports=function(s){if(kw(s))return s;throw new Mw(Rw(s)+" is not a function")}});var da=b((C_,Vf)=>{"use strict";var Lw=Wt(),Bw=Pr();Vf.exports=function(s,e){var t=s[e];return Bw(t)?void 0:Lw(t)}});var _f=b((V_,Of)=>{"use strict";var nc=yt(),oc=Te(),uc=Tt(),$w=TypeError;Of.exports=function(s,e){var t,i;if(e==="string"&&oc(t=s.toString)&&!uc(i=nc(t,s))||oc(t=s.valueOf)&&!uc(i=nc(t,s))||e!=="string"&&oc(t=s.toString)&&!uc(i=nc(t,s)))return i;throw new $w("Can't convert object to primitive value")}});var Ft=b((O_,Ff)=>{"use strict";Ff.exports=!0});var qf=b((__,Uf)=>{"use strict";var Nf=xe(),Dw=Object.defineProperty;Uf.exports=function(s,e){try{Dw(Nf,s,{value:e,configurable:!0,writable:!0})}catch(t){Nf[s]=e}return e}});var pa=b((F_,zf)=>{"use strict";var Cw=Ft(),Vw=xe(),Ow=qf(),jf="__core-js_shared__",Hf=zf.exports=Vw[jf]||Ow(jf,{});(Hf.versions||(Hf.versions=[])).push({version:"3.38.0",mode:Cw?"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 lc=b((N_,Gf)=>{"use strict";var Qf=pa();Gf.exports=function(s,e){return Qf[s]||(Qf[s]=e||{})}});var Rr=b((U_,Wf)=>{"use strict";var _w=Bi(),Fw=Object;Wf.exports=function(s){return Fw(_w(s))}});var Nt=b((q_,Yf)=>{"use strict";var Nw=Ce(),Uw=Rr(),qw=Nw({}.hasOwnProperty);Yf.exports=Object.hasOwn||function(e,t){return qw(Uw(e),t)}});var cc=b((j_,Kf)=>{"use strict";var jw=Ce(),Hw=0,zw=Math.random(),Qw=jw(1 .toString);Kf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Qw(++Hw+zw,36)}});var qe=b((H_,Jf)=>{"use strict";var Gw=xe(),Ww=lc(),Xf=Nt(),Yw=cc(),Kw=rc(),Xw=sc(),Mr=Gw.Symbol,dc=Ww("wks"),Jw=Xw?Mr.for||Mr:Mr&&Mr.withoutSetter||Yw;Jf.exports=function(s){return Xf(dc,s)||(dc[s]=Kw&&Xf(Mr,s)?Mr[s]:Jw("Symbol."+s)),dc[s]}});var im=b((z_,tm)=>{"use strict";var Zw=yt(),Zf=Tt(),em=ac(),eA=da(),tA=_f(),iA=qe(),rA=TypeError,sA=iA("toPrimitive");tm.exports=function(s,e){if(!Zf(s)||em(s))return s;var t=eA(s,sA),i;if(t){if(e===void 0&&(e="default"),i=Zw(t,s,e),!Zf(i)||em(i))return i;throw new rA("Can't convert object to primitive value")}return e===void 0&&(e="number"),tA(s,e)}});var pc=b((Q_,rm)=>{"use strict";var aA=im(),nA=ac();rm.exports=function(s){var e=aA(s,"string");return nA(e)?e:e+""}});var Mo=b((G_,am)=>{"use strict";var oA=xe(),sm=Tt(),hc=oA.document,uA=sm(hc)&&sm(hc.createElement);am.exports=function(s){return uA?hc.createElement(s):{}}});var fc=b((W_,nm)=>{"use strict";var lA=vt(),cA=Ue(),dA=Mo();nm.exports=!lA&&!cA(function(){return Object.defineProperty(dA("div"),"a",{get:function(){return 7}}).a!==7})});var lm=b(um=>{"use strict";var pA=vt(),hA=yt(),fA=Xl(),mA=ua(),bA=tr(),gA=pc(),SA=Nt(),vA=fc(),om=Object.getOwnPropertyDescriptor;um.f=pA?om:function(e,t){if(e=bA(e),t=gA(t),vA)try{return om(e,t)}catch(i){}if(SA(e,t))return mA(!hA(fA.f,e,t),e[t])}});var mc=b((K_,cm)=>{"use strict";var yA=Ue(),TA=Te(),IA=/#|\.prototype\./,ha=function(s,e){var t=EA[xA(s)];return t===AA?!0:t===wA?!1:TA(e)?yA(e):!!e},xA=ha.normalize=function(s){return String(s).replace(IA,".").toLowerCase()},EA=ha.data={},wA=ha.NATIVE="N",AA=ha.POLYFILL="P";cm.exports=ha});var Lr=b((X_,pm)=>{"use strict";var dm=Yl(),PA=Wt(),kA=oa(),RA=dm(dm.bind);pm.exports=function(s,e){return PA(s),e===void 0?s:kA?RA(s,e):function(){return s.apply(e,arguments)}}});var bc=b((J_,hm)=>{"use strict";var MA=vt(),LA=Ue();hm.exports=MA&&LA(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Yt=b((Z_,fm)=>{"use strict";var BA=Tt(),$A=String,DA=TypeError;fm.exports=function(s){if(BA(s))return s;throw new DA($A(s)+" is not an object")}});var rr=b(bm=>{"use strict";var CA=vt(),VA=fc(),OA=bc(),Lo=Yt(),mm=pc(),_A=TypeError,gc=Object.defineProperty,FA=Object.getOwnPropertyDescriptor,Sc="enumerable",vc="configurable",yc="writable";bm.f=CA?OA?function(e,t,i){if(Lo(e),t=mm(t),Lo(i),typeof e=="function"&&t==="prototype"&&"value"in i&&yc in i&&!i[yc]){var r=FA(e,t);r&&r[yc]&&(e[t]=i.value,i={configurable:vc in i?i[vc]:r[vc],enumerable:Sc in i?i[Sc]:r[Sc],writable:!1})}return gc(e,t,i)}:gc:function(e,t,i){if(Lo(e),t=mm(t),Lo(i),VA)try{return gc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new _A("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Br=b((tF,gm)=>{"use strict";var NA=vt(),UA=rr(),qA=ua();gm.exports=NA?function(s,e,t){return UA.f(s,e,qA(1,t))}:function(s,e,t){return s[e]=t,s}});var ke=b((iF,vm)=>{"use strict";var fa=xe(),jA=Gl(),HA=Yl(),zA=Te(),QA=lm().f,GA=mc(),$r=kr(),WA=Lr(),Dr=Br(),Sm=Nt();pa();var YA=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return jA(s,this,arguments)};return e.prototype=s.prototype,e};vm.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?fa:r?fa[t]:fa[t]&&fa[t].prototype,o=i?$r:$r[t]||Dr($r,t,{})[t],u=o.prototype,l,d,c,h,p,f,m,g,S;for(h in e)l=GA(i?h:t+(r?".":"#")+h,s.forced),d=!l&&n&&Sm(n,h),f=o[h],d&&(s.dontCallGetSet?(S=QA(n,h),m=S&&S.value):m=n[h]),p=d&&m?m:e[h],!(!l&&!a&&typeof f==typeof p)&&(s.bind&&d?g=WA(p,fa):s.wrap&&d?g=YA(p):a&&zA(p)?g=HA(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&Dr(g,"sham",!0),Dr(o,h,g),a&&(c=t+"Prototype",Sm($r,c)||Dr($r,c,{}),Dr($r[c],h,p),s.real&&u&&(l||!u[h])&&Dr(u,h,p)))}});var Tm=b((rF,ym)=>{"use strict";var KA=Math.ceil,XA=Math.floor;ym.exports=Math.trunc||function(e){var t=+e;return(t>0?XA:KA)(t)}});var ma=b((sF,Im)=>{"use strict";var JA=Tm();Im.exports=function(s){var e=+s;return e!==e||e===0?0:JA(e)}});var Em=b((aF,xm)=>{"use strict";var ZA=ma(),eP=Math.max,tP=Math.min;xm.exports=function(s,e){var t=ZA(s);return t<0?eP(t+e,0):tP(t,e)}});var Tc=b((nF,wm)=>{"use strict";var iP=ma(),rP=Math.min;wm.exports=function(s){var e=iP(s);return e>0?rP(e,9007199254740991):0}});var Cr=b((oF,Am)=>{"use strict";var sP=Tc();Am.exports=function(s){return sP(s.length)}});var Ic=b((uF,km)=>{"use strict";var aP=tr(),nP=Em(),oP=Cr(),Pm=function(s){return function(e,t,i){var r=aP(e),a=oP(r);if(a===0)return!s&&-1;var n=nP(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};km.exports={includes:Pm(!0),indexOf:Pm(!1)}});var ba=b((lF,Rm)=>{"use strict";Rm.exports=function(){}});var Mm=b(()=>{"use strict";var uP=ke(),lP=Ic().includes,cP=Ue(),dP=ba(),pP=cP(function(){return!Array(1).includes()});uP({target:"Array",proto:!0,forced:pP},{includes:function(e){return lP(this,e,arguments.length>1?arguments[1]:void 0)}});dP("includes")});var $i=b((pF,Lm)=>{"use strict";var hP=gi();Lm.exports=hP});var $m=b((hF,Bm)=>{"use strict";Mm();var fP=$i();Bm.exports=fP("Array","includes")});var Cm=b((fF,Dm)=>{"use strict";var mP=$m();Dm.exports=mP});var It=b((mF,Vm)=>{"use strict";var bP=Cm();Vm.exports=bP});var Do=b((PF,Hm)=>{"use strict";var EP=lc(),wP=cc(),jm=EP("keys");Hm.exports=function(s){return jm[s]||(jm[s]=wP(s))}});var Qm=b((kF,zm)=>{"use strict";var AP=Ue();zm.exports=!AP(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Co=b((RF,Wm)=>{"use strict";var PP=Nt(),kP=Te(),RP=Rr(),MP=Do(),LP=Qm(),Gm=MP("IE_PROTO"),wc=Object,BP=wc.prototype;Wm.exports=LP?wc.getPrototypeOf:function(s){var e=RP(s);if(PP(e,Gm))return e[Gm];var t=e.constructor;return kP(t)&&e instanceof t?t.prototype:e instanceof wc?BP:null}});var Vo=b((MF,Ym)=>{"use strict";Ym.exports={}});var Jm=b((LF,Xm)=>{"use strict";var $P=Ce(),Ac=Nt(),DP=tr(),CP=Ic().indexOf,VP=Vo(),Km=$P([].push);Xm.exports=function(s,e){var t=DP(s),i=0,r=[],a;for(a in t)!Ac(VP,a)&&Ac(t,a)&&Km(r,a);for(;e.length>i;)Ac(t,a=e[i++])&&(~CP(r,a)||Km(r,a));return r}});var Pc=b((BF,Zm)=>{"use strict";Zm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var kc=b(($F,eb)=>{"use strict";var OP=Jm(),_P=Pc();eb.exports=Object.keys||function(e){return OP(e,_P)}});var Rc=b((DF,ab)=>{"use strict";var ib=vt(),FP=Ue(),rb=Ce(),NP=Co(),UP=kc(),qP=tr(),jP=Xl().f,sb=rb(jP),HP=rb([].push),zP=ib&&FP(function(){var s=Object.create(null);return s[2]=2,!sb(s,2)}),tb=function(s){return function(e){for(var t=qP(e),i=UP(t),r=zP&&NP(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!ib||(r?u in t:sb(t,u)))&&HP(o,s?[u,t[u]]:t[u]);return o}};ab.exports={entries:tb(!0),values:tb(!1)}});var nb=b(()=>{"use strict";var QP=ke(),GP=Rc().entries;QP({target:"Object",stat:!0},{entries:function(e){return GP(e)}})});var ub=b((OF,ob)=>{"use strict";nb();var WP=kr();ob.exports=WP.Object.entries});var cb=b((_F,lb)=>{"use strict";var YP=ub();lb.exports=YP});var sr=b((FF,db)=>{"use strict";var KP=cb();db.exports=KP});var ar=b((NF,pb)=>{"use strict";pb.exports={}});var mb=b((UF,fb)=>{"use strict";var XP=xe(),JP=Te(),hb=XP.WeakMap;fb.exports=JP(hb)&&/native code/.test(String(hb))});var $c=b((qF,Sb)=>{"use strict";var ZP=mb(),gb=xe(),ek=Tt(),tk=Br(),Mc=Nt(),Lc=pa(),ik=Do(),rk=Vo(),bb="Object already initialized",Bc=gb.TypeError,sk=gb.WeakMap,Oo,ga,_o,ak=function(s){return _o(s)?ga(s):Oo(s,{})},nk=function(s){return function(e){var t;if(!ek(e)||(t=ga(e)).type!==s)throw new Bc("Incompatible receiver, "+s+" required");return t}};ZP||Lc.state?(Ut=Lc.state||(Lc.state=new sk),Ut.get=Ut.get,Ut.has=Ut.has,Ut.set=Ut.set,Oo=function(s,e){if(Ut.has(s))throw new Bc(bb);return e.facade=s,Ut.set(s,e),e},ga=function(s){return Ut.get(s)||{}},_o=function(s){return Ut.has(s)}):(nr=ik("state"),rk[nr]=!0,Oo=function(s,e){if(Mc(s,nr))throw new Bc(bb);return e.facade=s,tk(s,nr,e),e},ga=function(s){return Mc(s,nr)?s[nr]:{}},_o=function(s){return Mc(s,nr)});var Ut,nr;Sb.exports={set:Oo,get:ga,has:_o,enforce:ak,getterFor:nk}});var Vc=b((jF,yb)=>{"use strict";var Dc=vt(),ok=Nt(),vb=Function.prototype,uk=Dc&&Object.getOwnPropertyDescriptor,Cc=ok(vb,"name"),lk=Cc&&function(){}.name==="something",ck=Cc&&(!Dc||Dc&&uk(vb,"name").configurable);yb.exports={EXISTS:Cc,PROPER:lk,CONFIGURABLE:ck}});var Ib=b(Tb=>{"use strict";var dk=vt(),pk=bc(),hk=rr(),fk=Yt(),mk=tr(),bk=kc();Tb.f=dk&&!pk?Object.defineProperties:function(e,t){fk(e);for(var i=mk(t),r=bk(t),a=r.length,n=0,o;a>n;)hk.f(e,o=r[n++],i[o]);return e}});var Oc=b((zF,xb)=>{"use strict";var gk=gi();xb.exports=gk("document","documentElement")});var Uc=b((QF,Mb)=>{"use strict";var Sk=Yt(),vk=Ib(),Eb=Pc(),yk=Vo(),Tk=Oc(),Ik=Mo(),xk=Do(),wb=">",Ab="<",Fc="prototype",Nc="script",kb=xk("IE_PROTO"),_c=function(){},Rb=function(s){return Ab+Nc+wb+s+Ab+"/"+Nc+wb},Pb=function(s){s.write(Rb("")),s.close();var e=s.parentWindow.Object;return s=null,e},Ek=function(){var s=Ik("iframe"),e="java"+Nc+":",t;return s.style.display="none",Tk.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Rb("document.F=Object")),t.close(),t.F},Fo,No=function(){try{Fo=new ActiveXObject("htmlfile")}catch(e){}No=typeof document!="undefined"?document.domain&&Fo?Pb(Fo):Ek():Pb(Fo);for(var s=Eb.length;s--;)delete No[Fc][Eb[s]];return No()};yk[kb]=!0;Mb.exports=Object.create||function(e,t){var i;return e!==null?(_c[Fc]=Sk(e),i=new _c,_c[Fc]=null,i[kb]=e):i=No(),t===void 0?i:vk.f(i,t)}});var Vr=b((GF,Lb)=>{"use strict";var wk=Br();Lb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:wk(s,e,t),s}});var zc=b((WF,Db)=>{"use strict";var Ak=Ue(),Pk=Te(),kk=Tt(),Rk=Uc(),Bb=Co(),Mk=Vr(),Lk=qe(),Bk=Ft(),Hc=Lk("iterator"),$b=!1,Si,qc,jc;[].keys&&(jc=[].keys(),"next"in jc?(qc=Bb(Bb(jc)),qc!==Object.prototype&&(Si=qc)):$b=!0);var $k=!kk(Si)||Ak(function(){var s={};return Si[Hc].call(s)!==s});$k?Si={}:Bk&&(Si=Rk(Si));Pk(Si[Hc])||Mk(Si,Hc,function(){return this});Db.exports={IteratorPrototype:Si,BUGGY_SAFARI_ITERATORS:$b}});var Uo=b((YF,Vb)=>{"use strict";var Dk=qe(),Ck=Dk("toStringTag"),Cb={};Cb[Ck]="z";Vb.exports=String(Cb)==="[object z]"});var Sa=b((KF,Ob)=>{"use strict";var Vk=Uo(),Ok=Te(),qo=er(),_k=qe(),Fk=_k("toStringTag"),Nk=Object,Uk=qo(function(){return arguments}())==="Arguments",qk=function(s,e){try{return s[e]}catch(t){}};Ob.exports=Vk?qo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=qk(e=Nk(s),Fk))=="string"?t:Uk?qo(e):(i=qo(e))==="Object"&&Ok(e.callee)?"Arguments":i}});var Fb=b((XF,_b)=>{"use strict";var jk=Uo(),Hk=Sa();_b.exports=jk?{}.toString:function(){return"[object "+Hk(this)+"]"}});var va=b((JF,Ub)=>{"use strict";var zk=Uo(),Qk=rr().f,Gk=Br(),Wk=Nt(),Yk=Fb(),Kk=qe(),Nb=Kk("toStringTag");Ub.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(Wk(r,Nb)||Qk(r,Nb,{configurable:!0,value:e}),i&&!zk&&Gk(r,"toString",Yk))}});var jb=b((ZF,qb)=>{"use strict";var Xk=zc().IteratorPrototype,Jk=Uc(),Zk=ua(),eR=va(),tR=ar(),iR=function(){return this};qb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Jk(Xk,{next:Zk(+!i,t)}),eR(s,r,!1,!0),tR[r]=iR,s}});var zb=b((eN,Hb)=>{"use strict";var rR=Ce(),sR=Wt();Hb.exports=function(s,e,t){try{return rR(sR(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Gb=b((tN,Qb)=>{"use strict";var aR=Tt();Qb.exports=function(s){return aR(s)||s===null}});var Yb=b((iN,Wb)=>{"use strict";var nR=Gb(),oR=String,uR=TypeError;Wb.exports=function(s){if(nR(s))return s;throw new uR("Can't set "+oR(s)+" as a prototype")}});var Qc=b((rN,Kb)=>{"use strict";var lR=zb(),cR=Tt(),dR=Bi(),pR=Yb();Kb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=lR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return dR(r),pR(a),cR(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var og=b((sN,ng)=>{"use strict";var hR=ke(),fR=yt(),jo=Ft(),sg=Vc(),mR=Te(),bR=jb(),Xb=Co(),Jb=Qc(),gR=va(),SR=Br(),Gc=Vr(),vR=qe(),Zb=ar(),ag=zc(),yR=sg.PROPER,TR=sg.CONFIGURABLE,eg=ag.IteratorPrototype,Ho=ag.BUGGY_SAFARI_ITERATORS,ya=vR("iterator"),tg="keys",Ta="values",ig="entries",rg=function(){return this};ng.exports=function(s,e,t,i,r,a,n){bR(t,e,i);var o=function(S){if(S===r&&h)return h;if(!Ho&&S&&S in d)return d[S];switch(S){case tg:return function(){return new t(this,S)};case Ta:return function(){return new t(this,S)};case ig:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[ya]||d["@@iterator"]||r&&d[r],h=!Ho&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=Xb(p.call(new s)),f!==Object.prototype&&f.next&&(!jo&&Xb(f)!==eg&&(Jb?Jb(f,eg):mR(f[ya])||Gc(f,ya,rg)),gR(f,u,!0,!0),jo&&(Zb[u]=rg))),yR&&r===Ta&&c&&c.name!==Ta&&(!jo&&TR?SR(d,"name",Ta):(l=!0,h=function(){return fR(c,this)})),r)if(m={values:o(Ta),keys:a?h:o(tg),entries:o(ig)},n)for(g in m)(Ho||l||!(g in d))&&Gc(d,g,m[g]);else hR({target:e,proto:!0,forced:Ho||l},m);return(!jo||n)&&d[ya]!==h&&Gc(d,ya,h,{name:r}),Zb[e]=h,m}});var lg=b((aN,ug)=>{"use strict";ug.exports=function(s,e){return{value:s,done:e}}});var Yc=b((nN,fg)=>{"use strict";var IR=tr(),Wc=ba(),cg=ar(),pg=$c(),xR=rr().f,ER=og(),zo=lg(),wR=Ft(),AR=vt(),hg="Array Iterator",PR=pg.set,kR=pg.getterFor(hg);fg.exports=ER(Array,"Array",function(s,e){PR(this,{type:hg,target:IR(s),index:0,kind:e})},function(){var s=kR(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,zo(void 0,!0);switch(s.kind){case"keys":return zo(t,!1);case"values":return zo(e[t],!1)}return zo([t,e[t]],!1)},"values");var dg=cg.Arguments=cg.Array;Wc("keys");Wc("values");Wc("entries");if(!wR&&AR&&dg.name!=="values")try{xR(dg,"name",{value:"values"})}catch(s){}});var bg=b((oN,mg)=>{"use strict";var RR=qe(),MR=ar(),LR=RR("iterator"),BR=Array.prototype;mg.exports=function(s){return s!==void 0&&(MR.Array===s||BR[LR]===s)}});var Kc=b((uN,Sg)=>{"use strict";var $R=Sa(),gg=da(),DR=Pr(),CR=ar(),VR=qe(),OR=VR("iterator");Sg.exports=function(s){if(!DR(s))return gg(s,OR)||gg(s,"@@iterator")||CR[$R(s)]}});var yg=b((lN,vg)=>{"use strict";var _R=yt(),FR=Wt(),NR=Yt(),UR=ca(),qR=Kc(),jR=TypeError;vg.exports=function(s,e){var t=arguments.length<2?qR(s):e;if(FR(t))return NR(_R(t,s));throw new jR(UR(s)+" is not iterable")}});var xg=b((cN,Ig)=>{"use strict";var HR=yt(),Tg=Yt(),zR=da();Ig.exports=function(s,e,t){var i,r;Tg(s);try{if(i=zR(s,"return"),!i){if(e==="throw")throw t;return t}i=HR(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Tg(i),t}});var Go=b((dN,Pg)=>{"use strict";var QR=Lr(),GR=yt(),WR=Yt(),YR=ca(),KR=bg(),XR=Cr(),Eg=la(),JR=yg(),ZR=Kc(),wg=xg(),eM=TypeError,Qo=function(s,e){this.stopped=s,this.result=e},Ag=Qo.prototype;Pg.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=QR(e,i),l,d,c,h,p,f,m,g=function(v){return l&&wg(l,"normal",v),new Qo(!0,v)},S=function(v){return r?(WR(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(a)l=s.iterator;else if(n)l=s;else{if(d=ZR(s),!d)throw new eM(YR(s)+" is not iterable");if(KR(d)){for(c=0,h=XR(s);h>c;c++)if(p=S(s[c]),p&&Eg(Ag,p))return p;return new Qo(!1)}l=JR(s,d)}for(f=a?s.next:l.next;!(m=GR(f,l)).done;){try{p=S(m.value)}catch(v){wg(l,"throw",v)}if(typeof p=="object"&&p&&Eg(Ag,p))return p}return new Qo(!1)}});var Rg=b((pN,kg)=>{"use strict";var tM=vt(),iM=rr(),rM=ua();kg.exports=function(s,e,t){tM?iM.f(s,e,rM(0,t)):s[e]=t}});var Mg=b(()=>{"use strict";var sM=ke(),aM=Go(),nM=Rg();sM({target:"Object",stat:!0},{fromEntries:function(e){var t={};return aM(e,function(i,r){nM(t,i,r)},{AS_ENTRIES:!0}),t}})});var Bg=b((mN,Lg)=>{"use strict";Yc();Mg();var oM=kr();Lg.exports=oM.Object.fromEntries});var Dg=b((bN,$g)=>{"use strict";$g.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 Vg=b(()=>{"use strict";Yc();var uM=Dg(),lM=xe(),cM=va(),Cg=ar();for(Wo in uM)cM(lM[Wo],Wo),Cg[Wo]=Cg.Array;var Wo});var _g=b((vN,Og)=>{"use strict";var dM=Bg();Vg();Og.exports=dM});var Xc=b((yN,Fg)=>{"use strict";var pM=_g();Fg.exports=pM});var Ng=b(()=>{"use strict"});var Jc=b((xN,Ug)=>{"use strict";var Ia=xe(),hM=ir(),fM=er(),Yo=function(s){return hM.slice(0,s.length)===s};Ug.exports=function(){return Yo("Bun/")?"BUN":Yo("Cloudflare-Workers")?"CLOUDFLARE":Yo("Deno/")?"DENO":Yo("Node.js/")?"NODE":Ia.Bun&&typeof Bun.version=="string"?"BUN":Ia.Deno&&typeof Deno.version=="object"?"DENO":fM(Ia.process)==="process"?"NODE":Ia.window&&Ia.document?"BROWSER":"REST"}()});var Ko=b((EN,qg)=>{"use strict";var mM=Jc();qg.exports=mM==="NODE"});var Hg=b((wN,jg)=>{"use strict";var bM=rr();jg.exports=function(s,e,t){return bM.f(s,e,t)}});var Gg=b((AN,Qg)=>{"use strict";var gM=gi(),SM=Hg(),vM=qe(),yM=vt(),zg=vM("species");Qg.exports=function(s){var e=gM(s);yM&&e&&!e[zg]&&SM(e,zg,{configurable:!0,get:function(){return this}})}});var Yg=b((PN,Wg)=>{"use strict";var TM=la(),IM=TypeError;Wg.exports=function(s,e){if(TM(e,s))return s;throw new IM("Incorrect invocation")}});var ed=b((kN,Kg)=>{"use strict";var xM=Ce(),EM=Te(),Zc=pa(),wM=xM(Function.toString);EM(Zc.inspectSource)||(Zc.inspectSource=function(s){return wM(s)});Kg.exports=Zc.inspectSource});var id=b((RN,tS)=>{"use strict";var AM=Ce(),PM=Ue(),Xg=Te(),kM=Sa(),RM=gi(),MM=ed(),Jg=function(){},Zg=RM("Reflect","construct"),td=/^\s*(?:class|function)\b/,LM=AM(td.exec),BM=!td.test(Jg),xa=function(e){if(!Xg(e))return!1;try{return Zg(Jg,[],e),!0}catch(t){return!1}},eS=function(e){if(!Xg(e))return!1;switch(kM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return BM||!!LM(td,MM(e))}catch(t){return!0}};eS.sham=!0;tS.exports=!Zg||PM(function(){var s;return xa(xa.call)||!xa(Object)||!xa(function(){s=!0})||s})?eS:xa});var rS=b((MN,iS)=>{"use strict";var $M=id(),DM=ca(),CM=TypeError;iS.exports=function(s){if($M(s))return s;throw new CM(DM(s)+" is not a constructor")}});var rd=b((LN,aS)=>{"use strict";var sS=Yt(),VM=rS(),OM=Pr(),_M=qe(),FM=_M("species");aS.exports=function(s,e){var t=sS(s).constructor,i;return t===void 0||OM(i=sS(t)[FM])?e:VM(i)}});var oS=b((BN,nS)=>{"use strict";var NM=Ce();nS.exports=NM([].slice)});var lS=b(($N,uS)=>{"use strict";var UM=TypeError;uS.exports=function(s,e){if(s<e)throw new UM("Not enough arguments");return s}});var sd=b((DN,cS)=>{"use strict";var qM=ir();cS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(qM)});var hd=b((CN,vS)=>{"use strict";var xt=xe(),jM=Gl(),HM=Lr(),dS=Te(),zM=Nt(),SS=Ue(),pS=Oc(),QM=oS(),hS=Mo(),GM=lS(),WM=sd(),YM=Ko(),cd=xt.setImmediate,dd=xt.clearImmediate,KM=xt.process,ad=xt.Dispatch,XM=xt.Function,fS=xt.MessageChannel,JM=xt.String,nd=0,Ea={},mS="onreadystatechange",wa,or,od,ud;SS(function(){wa=xt.location});var pd=function(s){if(zM(Ea,s)){var e=Ea[s];delete Ea[s],e()}},ld=function(s){return function(){pd(s)}},bS=function(s){pd(s.data)},gS=function(s){xt.postMessage(JM(s),wa.protocol+"//"+wa.host)};(!cd||!dd)&&(cd=function(e){GM(arguments.length,1);var t=dS(e)?e:XM(e),i=QM(arguments,1);return Ea[++nd]=function(){jM(t,void 0,i)},or(nd),nd},dd=function(e){delete Ea[e]},YM?or=function(s){KM.nextTick(ld(s))}:ad&&ad.now?or=function(s){ad.now(ld(s))}:fS&&!WM?(od=new fS,ud=od.port2,od.port1.onmessage=bS,or=HM(ud.postMessage,ud)):xt.addEventListener&&dS(xt.postMessage)&&!xt.importScripts&&wa&&wa.protocol!=="file:"&&!SS(gS)?(or=gS,xt.addEventListener("message",bS,!1)):mS in hS("script")?or=function(s){pS.appendChild(hS("script"))[mS]=function(){pS.removeChild(this),pd(s)}}:or=function(s){setTimeout(ld(s),0)});vS.exports={set:cd,clear:dd}});var IS=b((VN,TS)=>{"use strict";var yS=xe(),ZM=vt(),eL=Object.getOwnPropertyDescriptor;TS.exports=function(s){if(!ZM)return yS[s];var e=eL(yS,s);return e&&e.value}});var fd=b((ON,ES)=>{"use strict";var xS=function(){this.head=null,this.tail=null};xS.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};ES.exports=xS});var AS=b((_N,wS)=>{"use strict";var tL=ir();wS.exports=/ipad|iphone|ipod/i.test(tL)&&typeof Pebble!="undefined"});var kS=b((FN,PS)=>{"use strict";var iL=ir();PS.exports=/web0s(?!.*chrome)/i.test(iL)});var CS=b((NN,DS)=>{"use strict";var _r=xe(),rL=IS(),RS=Lr(),md=hd().set,sL=fd(),aL=sd(),nL=AS(),oL=kS(),bd=Ko(),MS=_r.MutationObserver||_r.WebKitMutationObserver,LS=_r.document,BS=_r.process,Xo=_r.Promise,vd=rL("queueMicrotask"),Or,gd,Sd,Jo,$S;vd||(Aa=new sL,Pa=function(){var s,e;for(bd&&(s=BS.domain)&&s.exit();e=Aa.get();)try{e()}catch(t){throw Aa.head&&Or(),t}s&&s.enter()},!aL&&!bd&&!oL&&MS&&LS?(gd=!0,Sd=LS.createTextNode(""),new MS(Pa).observe(Sd,{characterData:!0}),Or=function(){Sd.data=gd=!gd}):!nL&&Xo&&Xo.resolve?(Jo=Xo.resolve(void 0),Jo.constructor=Xo,$S=RS(Jo.then,Jo),Or=function(){$S(Pa)}):bd?Or=function(){BS.nextTick(Pa)}:(md=RS(md,_r),Or=function(){md(Pa)}),vd=function(s){Aa.head||Or(),Aa.add(s)});var Aa,Pa;DS.exports=vd});var OS=b((UN,VS)=>{"use strict";VS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Zo=b((qN,_S)=>{"use strict";_S.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var ur=b((jN,FS)=>{"use strict";var uL=xe();FS.exports=uL.Promise});var Fr=b((HN,jS)=>{"use strict";var lL=xe(),ka=ur(),cL=Te(),dL=mc(),pL=ed(),hL=qe(),NS=Jc(),fL=Ft(),yd=ic(),US=ka&&ka.prototype,mL=hL("species"),Td=!1,qS=cL(lL.PromiseRejectionEvent),bL=dL("Promise",function(){var s=pL(ka),e=s!==String(ka);if(!e&&yd===66||fL&&!(US.catch&&US.finally))return!0;if(!yd||yd<51||!/native code/.test(s)){var t=new ka(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[mL]=i,Td=t.then(function(){})instanceof i,!Td)return!0}return!e&&(NS==="BROWSER"||NS==="DENO")&&!qS});jS.exports={CONSTRUCTOR:bL,REJECTION_EVENT:qS,SUBCLASSING:Td}});var Nr=b((zN,zS)=>{"use strict";var HS=Wt(),gL=TypeError,SL=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new gL("Bad Promise constructor");e=i,t=r}),this.resolve=HS(e),this.reject=HS(t)};zS.exports.f=function(s){return new SL(s)}});var cv=b(()=>{"use strict";var vL=ke(),yL=Ft(),ru=Ko(),Di=xe(),Hr=yt(),QS=Vr(),GS=Qc(),TL=va(),IL=Gg(),xL=Wt(),iu=Te(),EL=Tt(),wL=Yg(),AL=rd(),JS=hd().set,Ad=CS(),PL=OS(),kL=Zo(),RL=fd(),ZS=$c(),su=ur(),Pd=Fr(),ev=Nr(),au="Promise",tv=Pd.CONSTRUCTOR,ML=Pd.REJECTION_EVENT,LL=Pd.SUBCLASSING,Id=ZS.getterFor(au),BL=ZS.set,Ur=su&&su.prototype,lr=su,eu=Ur,iv=Di.TypeError,xd=Di.document,kd=Di.process,Ed=ev.f,$L=Ed,DL=!!(xd&&xd.createEvent&&Di.dispatchEvent),rv="unhandledrejection",CL="rejectionhandled",WS=0,sv=1,VL=2,Rd=1,av=2,tu,YS,OL,KS,nv=function(s){var e;return EL(s)&&iu(e=s.then)?e:!1},ov=function(s,e){var t=e.value,i=e.state===sv,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===av&&FL(e),e.rejection=Rd),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new iv("Promise-chain cycle")):(l=nv(u))?Hr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},uv=function(s,e){s.notified||(s.notified=!0,Ad(function(){for(var t=s.reactions,i;i=t.get();)ov(i,s);s.notified=!1,e&&!s.rejection&&_L(s)}))},lv=function(s,e,t){var i,r;DL?(i=xd.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Di.dispatchEvent(i)):i={promise:e,reason:t},!ML&&(r=Di["on"+s])?r(i):s===rv&&PL("Unhandled promise rejection",t)},_L=function(s){Hr(JS,Di,function(){var e=s.facade,t=s.value,i=XS(s),r;if(i&&(r=kL(function(){ru?kd.emit("unhandledRejection",t,e):lv(rv,e,t)}),s.rejection=ru||XS(s)?av:Rd,r.error))throw r.value})},XS=function(s){return s.rejection!==Rd&&!s.parent},FL=function(s){Hr(JS,Di,function(){var e=s.facade;ru?kd.emit("rejectionHandled",e):lv(CL,e,s.value)})},qr=function(s,e,t){return function(i){s(e,i,t)}},jr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=VL,uv(s,!0))},wd=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new iv("Promise can't be resolved itself");var i=nv(e);i?Ad(function(){var r={done:!1};try{Hr(i,e,qr(wd,r,s),qr(jr,r,s))}catch(a){jr(r,a,s)}}):(s.value=e,s.state=sv,uv(s,!1))}catch(r){jr({done:!1},r,s)}}};if(tv&&(lr=function(e){wL(this,eu),xL(e),Hr(tu,this);var t=Id(this);try{e(qr(wd,t),qr(jr,t))}catch(i){jr(t,i)}},eu=lr.prototype,tu=function(e){BL(this,{type:au,done:!1,notified:!1,parent:!1,reactions:new RL,rejection:!1,state:WS,value:void 0})},tu.prototype=QS(eu,"then",function(e,t){var i=Id(this),r=Ed(AL(this,lr));return i.parent=!0,r.ok=iu(e)?e:!0,r.fail=iu(t)&&t,r.domain=ru?kd.domain:void 0,i.state===WS?i.reactions.add(r):Ad(function(){ov(r,i)}),r.promise}),YS=function(){var s=new tu,e=Id(s);this.promise=s,this.resolve=qr(wd,e),this.reject=qr(jr,e)},ev.f=Ed=function(s){return s===lr||s===OL?new YS(s):$L(s)},!yL&&iu(su)&&Ur!==Object.prototype)){KS=Ur.then,LL||QS(Ur,"then",function(e,t){var i=this;return new lr(function(r,a){Hr(KS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Ur.constructor}catch(s){}GS&&GS(Ur,eu)}vL({global:!0,constructor:!0,wrap:!0,forced:tv},{Promise:lr});TL(lr,au,!1,!0);IL(au)});var mv=b((WN,fv)=>{"use strict";var NL=qe(),pv=NL("iterator"),hv=!1;try{dv=0,Md={next:function(){return{done:!!dv++}},return:function(){hv=!0}},Md[pv]=function(){return this},Array.from(Md,function(){throw 2})}catch(s){}var dv,Md;fv.exports=function(s,e){try{if(!e&&!hv)return!1}catch(r){return!1}var t=!1;try{var i={};i[pv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Ld=b((YN,bv)=>{"use strict";var UL=ur(),qL=mv(),jL=Fr().CONSTRUCTOR;bv.exports=jL||!qL(function(s){UL.all(s).then(void 0,function(){})})});var gv=b(()=>{"use strict";var HL=ke(),zL=yt(),QL=Wt(),GL=Nr(),WL=Zo(),YL=Go(),KL=Ld();HL({target:"Promise",stat:!0,forced:KL},{all:function(e){var t=this,i=GL.f(t),r=i.resolve,a=i.reject,n=WL(function(){var o=QL(t.resolve),u=[],l=0,d=1;YL(e,function(c){var h=l++,p=!1;d++,zL(o,t,c).then(function(f){p||(p=!0,u[h]=f,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),i.promise}})});var vv=b(()=>{"use strict";var XL=ke(),JL=Ft(),ZL=Fr().CONSTRUCTOR,$d=ur(),eB=gi(),tB=Te(),iB=Vr(),Sv=$d&&$d.prototype;XL({target:"Promise",proto:!0,forced:ZL,real:!0},{catch:function(s){return this.then(void 0,s)}});!JL&&tB($d)&&(Bd=eB("Promise").prototype.catch,Sv.catch!==Bd&&iB(Sv,"catch",Bd,{unsafe:!0}));var Bd});var yv=b(()=>{"use strict";var rB=ke(),sB=yt(),aB=Wt(),nB=Nr(),oB=Zo(),uB=Go(),lB=Ld();rB({target:"Promise",stat:!0,forced:lB},{race:function(e){var t=this,i=nB.f(t),r=i.reject,a=oB(function(){var n=aB(t.resolve);uB(e,function(o){sB(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var Tv=b(()=>{"use strict";var cB=ke(),dB=Nr(),pB=Fr().CONSTRUCTOR;cB({target:"Promise",stat:!0,forced:pB},{reject:function(e){var t=dB.f(this),i=t.reject;return i(e),t.promise}})});var Dd=b((sU,Iv)=>{"use strict";var hB=Yt(),fB=Tt(),mB=Nr();Iv.exports=function(s,e){if(hB(s),fB(e)&&e.constructor===s)return e;var t=mB.f(s),i=t.resolve;return i(e),t.promise}});var wv=b(()=>{"use strict";var bB=ke(),gB=gi(),xv=Ft(),SB=ur(),Ev=Fr().CONSTRUCTOR,vB=Dd(),yB=gB("Promise"),TB=xv&&!Ev;bB({target:"Promise",stat:!0,forced:xv||Ev},{resolve:function(e){return vB(TB&&this===yB?SB:this,e)}})});var Av=b(()=>{"use strict";cv();gv();vv();yv();Tv();wv()});var Mv=b(()=>{"use strict";var IB=ke(),xB=Ft(),nu=ur(),EB=Ue(),kv=gi(),Rv=Te(),wB=rd(),Pv=Dd(),AB=Vr(),Vd=nu&&nu.prototype,PB=!!nu&&EB(function(){Vd.finally.call({then:function(){}},function(){})});IB({target:"Promise",proto:!0,real:!0,forced:PB},{finally:function(s){var e=wB(this,kv("Promise")),t=Rv(s);return this.then(t?function(i){return Pv(e,s()).then(function(){return i})}:s,t?function(i){return Pv(e,s()).then(function(){throw i})}:s)}});!xB&&Rv(nu)&&(Cd=kv("Promise").prototype.finally,Vd.finally!==Cd&&AB(Vd,"finally",Cd,{unsafe:!0}));var Cd});var Bv=b((dU,Lv)=>{"use strict";Ng();Av();Mv();var kB=$i();Lv.exports=kB("Promise","finally")});var Dv=b((pU,$v)=>{"use strict";var RB=Bv();$v.exports=RB});var ou=b((hU,Cv)=>{"use strict";var MB=Dv();Cv.exports=MB});var Wv=b(()=>{"use strict";var HB=ke(),zB=Rc().values;HB({target:"Object",stat:!0},{values:function(e){return zB(e)}})});var Kv=b((XU,Yv)=>{"use strict";Wv();var QB=kr();Yv.exports=QB.Object.values});var Jv=b((JU,Xv)=>{"use strict";var GB=Kv();Xv.exports=GB});var pr=b((ZU,Zv)=>{"use strict";var WB=Jv();Zv.exports=WB});var by=b(()=>{"use strict";var g$=ke(),S$=Rr(),v$=Cr(),y$=ma(),T$=ba();g$({target:"Array",proto:!0},{at:function(e){var t=S$(this),i=v$(t),r=y$(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});T$("at")});var Sy=b((d1,gy)=>{"use strict";by();var I$=$i();gy.exports=I$("Array","at")});var yy=b((p1,vy)=>{"use strict";var x$=Sy();vy.exports=x$});var qt=b((h1,Ty)=>{"use strict";var E$=yy();Ty.exports=E$});var ap=b((iH,eT)=>{"use strict";var s0=er();eT.exports=Array.isArray||function(e){return s0(e)==="Array"}});var iT=b((rH,tT)=>{"use strict";var a0=TypeError,n0=9007199254740991;tT.exports=function(s){if(s>n0)throw a0("Maximum allowed index exceeded");return s}});var aT=b((sH,sT)=>{"use strict";var o0=ap(),u0=Cr(),l0=iT(),c0=Lr(),rT=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?c0(n,o):!1,c,h;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&o0(c)?(h=u0(c),u=rT(s,e,c,h,u,a-1)-1):(l0(u+1),s[u]=c),u++),l++;return u};sT.exports=rT});var lT=b((aH,uT)=>{"use strict";var nT=ap(),d0=id(),p0=Tt(),h0=qe(),f0=h0("species"),oT=Array;uT.exports=function(s){var e;return nT(s)&&(e=s.constructor,d0(e)&&(e===oT||nT(e.prototype))?e=void 0:p0(e)&&(e=e[f0],e===null&&(e=void 0))),e===void 0?oT:e}});var dT=b((nH,cT)=>{"use strict";var m0=lT();cT.exports=function(s,e){return new(m0(s))(e===0?0:e)}});var pT=b(()=>{"use strict";var b0=ke(),g0=aT(),S0=Wt(),v0=Rr(),y0=Cr(),T0=dT();b0({target:"Array",proto:!0},{flatMap:function(e){var t=v0(this),i=y0(t),r;return S0(e),r=T0(t,0),r.length=g0(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var hT=b(()=>{"use strict";var I0=ba();I0("flatMap")});var mT=b((dH,fT)=>{"use strict";pT();hT();var x0=$i();fT.exports=x0("Array","flatMap")});var gT=b((pH,bT)=>{"use strict";var E0=mT();bT.exports=E0});var za=b((hH,ST)=>{"use strict";var w0=gT();ST.exports=w0});var Qa=b((fH,vT)=>{"use strict";var A0=Sa(),P0=String;vT.exports=function(s){if(A0(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return P0(s)}});var np=b((mH,yT)=>{"use strict";yT.exports=`
|
|
7
|
+
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var xT=b((bH,IT)=>{"use strict";var k0=Ce(),R0=Bi(),M0=Qa(),up=np(),TT=k0("".replace),L0=RegExp("^["+up+"]+"),B0=RegExp("(^|[^"+up+"])["+up+"]+$"),op=function(s){return function(e){var t=M0(R0(e));return s&1&&(t=TT(t,L0,"")),s&2&&(t=TT(t,B0,"$1")),t}};IT.exports={start:op(1),end:op(2),trim:op(3)}});var PT=b((gH,AT)=>{"use strict";var $0=Vc().PROPER,D0=Ue(),ET=np(),wT="\u200B\x85\u180E";AT.exports=function(s){return D0(function(){return!!ET[s]()||wT[s]()!==wT||$0&&ET[s].name!==s})}});var lp=b((SH,kT)=>{"use strict";var C0=xT().start,V0=PT();kT.exports=V0("trimStart")?function(){return C0(this)}:"".trimStart});var MT=b(()=>{"use strict";var O0=ke(),RT=lp();O0({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==RT},{trimLeft:RT})});var BT=b(()=>{"use strict";MT();var _0=ke(),LT=lp();_0({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==LT},{trimStart:LT})});var DT=b((xH,$T)=>{"use strict";BT();var F0=$i();$T.exports=F0("String","trimLeft")});var VT=b((EH,CT)=>{"use strict";var N0=DT();CT.exports=N0});var _T=b((wH,OT)=>{"use strict";var U0=VT();OT.exports=U0});var ZT=b(()=>{"use strict"});var eI=b(()=>{"use strict"});var iI=b((uz,tI)=>{"use strict";var cD=Tt(),dD=er(),pD=qe(),hD=pD("match");tI.exports=function(s){var e;return cD(s)&&((e=s[hD])!==void 0?!!e:dD(s)==="RegExp")}});var sI=b((lz,rI)=>{"use strict";var fD=Yt();rI.exports=function(){var s=fD(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var oI=b((cz,nI)=>{"use strict";var mD=yt(),bD=Nt(),gD=la(),SD=sI(),aI=RegExp.prototype;nI.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in aI)&&!bD(s,"flags")&&gD(aI,s)?mD(SD,s):e}});var lI=b((dz,uI)=>{"use strict";var mp=Ce(),vD=Rr(),yD=Math.floor,hp=mp("".charAt),TD=mp("".replace),fp=mp("".slice),ID=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,xD=/\$([$&'`]|\d{1,2})/g;uI.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=xD;return r!==void 0&&(r=vD(r),u=ID),TD(a,u,function(l,d){var c;switch(hp(d,0)){case"$":return"$";case"&":return s;case"`":return fp(e,0,t);case"'":return fp(e,n);case"<":c=r[fp(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var p=yD(h/10);return p===0?l:p<=o?i[p-1]===void 0?hp(d,1):i[p-1]+hp(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var pI=b(()=>{"use strict";var ED=ke(),wD=yt(),gp=Ce(),cI=Bi(),AD=Te(),PD=Pr(),kD=iI(),ss=Qa(),RD=da(),MD=oI(),LD=lI(),BD=qe(),$D=Ft(),DD=BD("replace"),CD=TypeError,bp=gp("".indexOf),VD=gp("".replace),dI=gp("".slice),OD=Math.max;ED({target:"String",proto:!0},{replaceAll:function(e,t){var i=cI(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!PD(e)){if(r=kD(e),r&&(a=ss(cI(MD(e))),!~bp(a,"g")))throw new CD("`.replaceAll` does not allow non-global regexes");if(n=RD(e,DD),n)return wD(n,e,i,t);if($D&&r)return VD(ss(i),e,t)}for(o=ss(i),u=ss(e),l=AD(t),l||(t=ss(t)),d=u.length,c=OD(1,d),h=bp(o,u);h!==-1;)p=l?ss(t(u,h,o)):LD(u,o,h,[],void 0,t),m+=dI(o,f,h)+p,f=h+d,h=h+c>o.length?-1:bp(o,u,h+c);return f<o.length&&(m+=dI(o,f)),m}})});var fI=b((fz,hI)=>{"use strict";ZT();eI();pI();var _D=$i();hI.exports=_D("String","replaceAll")});var bI=b((mz,mI)=>{"use strict";var FD=fI();mI.exports=FD});var Sp=b((bz,gI)=>{"use strict";var ND=bI();gI.exports=ND});var vI=b((gz,SI)=>{"use strict";var UD=ma(),qD=Qa(),jD=Bi(),HD=RangeError;SI.exports=function(e){var t=qD(jD(this)),i="",r=UD(e);if(r<0||r===1/0)throw new HD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var EI=b((Sz,xI)=>{"use strict";var II=Ce(),zD=Tc(),yI=Qa(),QD=vI(),GD=Bi(),WD=II(QD),YD=II("".slice),KD=Math.ceil,TI=function(s){return function(e,t,i){var r=yI(GD(e)),a=zD(t),n=r.length,o=i===void 0?" ":yI(i),u,l;return a<=n||o===""?r:(u=a-n,l=WD(o,KD(u/o.length)),l.length>u&&(l=YD(l,0,u)),s?r+l:l+r)}};xI.exports={start:TI(!1),end:TI(!0)}});var AI=b((vz,wI)=>{"use strict";var XD=ir();wI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(XD)});var PI=b(()=>{"use strict";var JD=ke(),ZD=EI().start,eC=AI();JD({target:"String",proto:!0,forced:eC},{padStart:function(e){return ZD(this,e,arguments.length>1?arguments[1]:void 0)}})});var RI=b((Iz,kI)=>{"use strict";PI();var tC=$i();kI.exports=tC("String","padStart")});var LI=b((xz,MI)=>{"use strict";var iC=RI();MI.exports=iC});var vp=b((Ez,BI)=>{"use strict";var rC=LI();BI.exports=rC});var jh="2.0.134-dev.ddf0760d.0";var at=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(at||{}),bi=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(bi||{});var Ao=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ao||{}),Hl=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Hl||{});var zl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(zl||{}),Po=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Po||{});var UE=H(It(),1);import{assertNever as qm,assertNonNullable as gP,isNonNullable as Bo,ValueSubject as xc,Subject as SP,Subscription as vP,merge as yP,observableFrom as TP,fromEvent as _m,map as Fm,tap as Nm,filterChanged as IP,isNullable as Ec,ErrorCategory as Um}from"@vkontakte/videoplayer-shared/es2015";var Om=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var $o=class{constructor(e){this.connection$=new xc(void 0);this.castState$=new xc("NOT_AVAILABLE");this.errorEvent$=new SP;this.realCastState$=new xc("NOT_AVAILABLE");this.subscription=new vP;this.isDestroyed=!1;var a;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=Bo((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Om("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Um.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,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Bo(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ec(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ec(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(_m(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,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=(a=i.getCurrentSession())==null?void 0:a.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 qm(r.sessionState)}})).add(yP(_m(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Nm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Fm(r=>r.castState)),TP([i.getCastState()])).pipe(IP(),Fm(xP),Nm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=Bo(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();gP(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Ec(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Bo(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(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:Um.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},xP=s=>{switch(s){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 qm(s)}};var Bh=H(It(),1),IE=H(sr(),1),xE=H(Xc(),1);var zv=H(ou(),1);import{assertNever as Vv}from"@vkontakte/videoplayer-shared/es2015";var Ie=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Vv(t)}return s},Ci=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:Vv(e)}};var D=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as LB,Subject as uu,merge as Ov}from"@vkontakte/videoplayer-shared/es2015";var Y=class{constructor(e){this.transitionStarted$=new uu;this.transitionEnded$=new uu;this.transitionUpdated$=new uu;this.forceChanged$=new uu;this.stateChangeStarted$=Ov(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Ov(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||LB(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as BB}from"@vkontakte/videoplayer-shared/es2015";var _v=s=>{switch(s){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 BB(s)}};import{assertNever as zr,assertNonNullable as cr,debounce as Fv,ErrorCategory as Nv,fromEvent as dr,isNonNullable as Uv,map as qv,merge as jv,observableFrom as $B,Subject as DB,Subscription as Od,timeout as CB,getHighestQuality as VB}from"@vkontakte/videoplayer-shared/es2015";var OB=5,_B=5,FB=500,Hv=7e3,Ra=class{constructor(e){this.subscription=new Od;this.loadMediaTimeoutSubscription=new Od;this.videoState=new Y("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:zr(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:zr(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:zr(e)}break}default:zr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_v(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 Od;this.subscription.add(e),this.subscription.add(jv(this.videoState.stateChangeStarted$.pipe(qv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(qv(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new DB;e.add(r.pipe(Fv(FB)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(dr(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-a)>OB)&&r.next(o),a=o})),e.add(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=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()&&a.duration-a.currentTime<_B&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),D(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:zr(n)}}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=jv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$B(["init"])).pipe(Fv(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"),D(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),D(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"),D(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"),D(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"&&D(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a: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,a;switch(e){case"MPEG":{let d=t[e];cr(d);let c=VB(Object.keys(d));cr(c);let h=d[c];cr(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];cr(d),i=d.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];cr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];cr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];cr(d),i=Ie(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Nv.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return zr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Uv(o)&&(n.metadata.title=o),Uv(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,a)=>{this.loadMediaTimeoutSubscription.add(CB(Hv).subscribe(()=>a(`timeout(${Hv})`)))});(0,zv.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 a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Nv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var rp=H(It(),1);import{clearVideoElement as Gv}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as NB}from"@vkontakte/videoplayer-shared/es2015";var Qv=s=>{try{s.pause(),s.playbackRate=0,NB(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as UB,Subscription as qB}from"@vkontakte/videoplayer-shared/es2015";var _d=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)}},Fd=window.WeakMap?new WeakMap:new _d,Nd=window.WeakMap?new WeakMap:new Map,jB=(s,e=20)=>{let t=0;return UB(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},nt=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Gv(i):(i=document.createElement("video"),s.appendChild(i)),Fd.set(i,r);let a=new qB;return a.add(jB(i,e)),Nd.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},ot=s=>{let e=Nd.get(s);e==null||e.unsubscribe(),Nd.delete(s);let t=Fd.get(s);Fd.delete(s),t?Gv(s):Qv(s)};var qd=H(pr(),1);import{assertNonNullable as La,isNonNullable as Xt,isNullable as XB,fromEvent as Qr,merge as ey,observableFrom as ty,filterChanged as iy,map as Ba,Subject as ry,Subscription as JB,ValueSubject as ZB,ErrorCategory as e$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Ud,isNullable as YB,Subscription as KB}from"@vkontakte/videoplayer-shared/es2015";var lu=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=YB(r),l=new KB;return r&&l.add(r.subscribe(d=>{let c=s.getState();i(d,c)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),l},Kt=(s,e,t)=>lu(e,()=>s.loop,i=>{Ud(i)&&(s.loop=i)},{onError:t}),ut=(s,e,t,i)=>lu(e,()=>({muted:s.muted,volume:s.volume}),r=>{Ud(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Pt=(s,e,t,i)=>lu(e,()=>s.playbackRate,r=>{Ud(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Ma=lu;var t$=s=>["__",s.language,s.label].join("|"),i$=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},jd=class s{constructor(e){this.available$=new ry;this.current$=new ZB(void 0);this.error$=new ry;this.subscription=new JB;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:e$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ma(t.internalTextTracks,()=>(0,qd.default)(this.internalTracks),a=>{Xt(a)&&this.setInternal(a)},{equal:(a,n)=>Xt(a)&&Xt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ba(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ma(t.externalTextTracks,()=>(0,qd.default)(this.externalTracks),a=>{Xt(a)&&this.setExternal(a)},{equal:(a,n)=>Xt(a)&&Xt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ba(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ma(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Ma(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){La(this.video);let{textTracks:e}=this.video;this.subscription.add(Qr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(ey(Qr(e,"addtrack"),Qr(e,"removetrack"),ty(["init"])).pipe(Ba(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),iy((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(ey(Qr(e,"change"),ty(["init"])).pipe(Ba(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ba(i=>i&&this.htmlTextTrackToITextTrack(i).id),iy()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(Qr(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,d,c,h,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((h=(c=o.target)==null?void 0:c.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Qr(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;Xt(t.align)&&(r.align=t.align),Xt(t.position)&&(r.position=t.position),Xt(t.size)&&(r.size=t.size),Xt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){La(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:t$(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){La(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(XB(e)||!i$(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){La(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):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){La(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)}},kt=jd;var hr=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 sy=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Hd=s=>{let e=sy(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},ay=s=>{let e=sy(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as et,map as Jt,merge as bu,filterChanged as hy,isNonNullable as fy,Subject as d$,filter as Qd,mapTo as Gd,combine as p$,once as h$,throttle as f$,ErrorCategory as m$,ValueSubject as my,Subscription as b$}from"@vkontakte/videoplayer-shared/es2015";var r$=3,ny=(s,e,t=r$)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var cu=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isFirefox(){return this.current==="Firefox"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var oy=H(It(),1);var $a=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var du=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,oy.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=$a()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return E(this,null,function*(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var pu=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var Et=()=>window.ManagedMediaSource||window.MediaSource,Gr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},uy=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},hu=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var s$=document.createElement("video"),a$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',n$='video/mp4; codecs="hev1.1.6.L93.B0"',ly='video/webm; codecs="vp09.00.10.08"',cy='video/webm; codecs="av01.0.00M.08"',o$='audio/mp4; codecs="mp4a.40.2"',u$='audio/webm; codecs="opus"',dy,l$=()=>E(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(B(x({},s),{video:B(x({},s.video),{contentType:cy})})),window.navigator.mediaCapabilities.decodingInfo(B(x({},s),{video:B(x({},s.video),{contentType:ly})}))]);dy={DASH_WEBM_AV1:e,DASH_WEBM:t}});l$().catch(s=>{console.log(s$),console.error(s)});var fu=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return dy}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,d,c,h,p,f,m,g,S,v,y,T;this._video=document.createElement("video");try{this._protocols={mms:Gr(),mse:uy(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(a=this._video).canPlayType)!=null&&n.call(a,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let I=!!((d=(l=Et())==null?void 0:l.isTypeSupported)!=null&&d.call(l,a$)),k=!!((h=(c=Et())==null?void 0:c.isTypeSupported)!=null&&h.call(c,n$)),C=!!((f=(p=Et())==null?void 0:p.isTypeSupported)!=null&&f.call(p,o$));this._codecs={h264:I,h265:k,vp9:!!((g=(m=Et())==null?void 0:m.isTypeSupported)!=null&&g.call(m,ly)),av1:!!((v=(S=Et())==null?void 0:S.isTypeSupported)!=null&&v.call(S,cy)),aac:C,opus:!!((T=(y=Et())==null?void 0:y.isTypeSupported)!=null&&T.call(y,u$)),mpeg:(I||k)&&C},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(I){console.error(I)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var py="audio/mpeg",mu=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,py))},this._codecs={mp3:!!((r=(i=Et())==null?void 0:i.isTypeSupported)!=null&&r.call(i,py))}}catch(a){console.error(a)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as c$}from"@vkontakte/videoplayer-shared/es2015";var zd=class{constructor(){this.isInited$=new c$(!1);this._displayChecker=new pu,this._deviceChecker=new du(this._displayChecker),this._browserChecker=new cu,this._videoChecker=new fu(this._deviceChecker,this._browserChecker),this._audioChecker=new mu,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return E(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},Q=new zd;var lt=s=>{let e=w=>et(s,w).pipe(Gd(void 0)),t=new b$,i=()=>t.unsubscribe(),r=bu(et(s,"progress"),et(s,"timeupdate")).pipe(Jt(()=>ny(s.buffered,s.currentTime))),a=Q.browser.isSafari?p$({play:e("play").pipe(h$()),playing:e("playing")}).pipe(Gd(void 0)):e("playing"),n=et(s,"volumechange").pipe(Jt(()=>({muted:s.muted,volume:s.volume}))),o=et(s,"ratechange").pipe(Jt(()=>s.playbackRate)),u=et(s,"error").pipe(Qd(()=>!!(s.error||s.played.length)),Jt(()=>{var F;let w=s.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:m$.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(F=s.error)!=null?F:void 0}})),l=et(s,"timeupdate").pipe(Jt(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new d$,h=.3,p;t.add(bu(...d.map(w=>et(s,w))).subscribe(w=>{let F=s.currentTime;s.loop&&fy(p)&&fy(F)&&p>=s.duration-h&&F<=h&&c.next(p),p=F}));let f=e("pause").pipe(Qd(()=>!s.error&&p!==s.duration)),m=et(s,"enterpictureinpicture"),g=et(s,"leavepictureinpicture"),S=new my(ay(s));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new my(Hd(s)),y=et(s,"fullscreenchange");t.add(y.pipe(Jt(()=>Hd(s))).subscribe(v));let T=.1,I=1e3,k=et(s,"timeupdate").pipe(Jt(w=>s.duration-s.currentTime<T),hy()),C=bu(k.pipe(Qd(w=>!s.loop&&w)),et(s,"ended")).pipe(f$(I),Gd(void 0)),$=bu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>et(s,w)),k.pipe(Jt(w=>({type:w?"ended":"unknown"})))).pipe(Jt(w=>Q.browser.isFirefox&&w.type==="ended"?s.readyState<2:s.readyState<3),hy());return{playing$:a,pause$:f,canplay$:e("canplay"),ended$:C,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$:et(s,"durationchange").pipe(Jt(()=>s.duration)),isBuffering$:$,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Vi}from"@vkontakte/videoplayer-shared/es2015";var Oi=s=>{switch(s){case"mobile":return Vi.Q_144P;case"lowest":return Vi.Q_240P;case"low":return Vi.Q_360P;case"sd":case"medium":return Vi.Q_480P;case"hd":case"high":return Vi.Q_720P;case"fullhd":case"full":return Vi.Q_1080P;case"quadhd":case"quad":return Vi.Q_1440P;case"ultrahd":case"ultra":return Vi.Q_2160P}};var it=H(qt(),1),Kd=H(It(),1),fr=H(sr(),1);import{isNonNullable as ne,isNullable as Tu,now as Ly,isHigher as Iu,isHigherOrEqual as Yr,isInvariantQuality as xu,isLowerOrEqual as Kr,videoSizeToQuality as By,assertNotEmptyArray as Eu,assertNonNullable as $y}from"@vkontakte/videoplayer-shared/es2015";var Wd=!1,yi={},Iy=s=>{Wd=s},xy=()=>{yi={}},Ey=s=>{s(yi)},Da=(s,e)=>{var t;Wd&&(yi.meta=(t=yi.meta)!=null?t:{},yi.meta[s]=e)},tt=class{constructor(e){this.name=e}next(e){var i,r;if(!Wd)return;yi.series=(i=yi.series)!=null?i:{};let t=(r=yi.series[this.name])!=null?r:[];t.push([Date.now(),e]),yi.series[this.name]=t}};import{isHigher as w$,isHigherOrEqual as v1,isLower as wy,isLowerOrEqual as y1,isNonNullable as gu,isNullable as A$,videoHeightToQuality as Su}from"@vkontakte/videoplayer-shared/es2015";function Yd(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function vu(s,e,t){return!!s&&Yd(s,e,t)==="high_quality"}function Wr(s,e,t){return A$(s)||gu(s.min)&&gu(s.max)&&wy(s.max,s.min)||gu(s.min)&&e&&w$(s.min,e)||gu(s.max)&&t&&wy(s.max,t)}function Ay({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Wr({max:s!=null&&s.max?Su(s.max):void 0,min:s!=null&&s.min?Su(s.min):void 0},e?Su(e):void 0,t?Su(t):void 0)}var Dy=new tt("best_bitrate"),wu=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Xr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),_i=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ly()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Au='Assertion "ABR Tracks is empty array" failed',yu=new WeakMap,Py=new WeakMap,ky=new WeakMap,Ca=(s,e,t,i)=>{var u;let r=[...e].sort(Xr(1)),a=[...t].sort(Xr(1)),n=a.filter(l=>ne(l.bitrate)&&ne(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,it.default)(a,-1);return o&&(0,Kd.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},Va=(s,e,t,i)=>{var u;let r=yu.get(e);r||(r=[...e].sort(Xr(1)),yu.set(e,r));let a=yu.get(t);a||(a=[...t].sort(Xr(1)),yu.set(t,a));let n=ky.get(s);n||(n=a.filter(l=>ne(l.bitrate)&&ne(s.bitrate)?s.bitrate/l.bitrate>i:!0),ky.set(s,n));let o=(u=(0,it.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,it.default)(a,-1);return o&&(0,Kd.default)(n,o)?o:n.length?(0,it.default)(n,-1):(0,it.default)(a,0)},Ry=s=>"quality"in s,Pu=(s,e,t,i)=>{var n;let r=ne((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&ne(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&Ly()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Ry(o)?"video":"audio",l=Ry(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
|
-
`}),o}return i==null||i.recordSwitch(t),t},
|
|
9
|
+
`}),o}return i==null||i.recordSwitch(t),t},P$=(s,e)=>Math.log(e)/Math.log(s),Cy=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&Q.display.pixelRatio){let a=Q.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,d=P$(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return vu(t,s.highQualityLimit,s.trafficSavingLimit)&&(r*=2),{containerSizeLimit:s.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},My=new WeakMap,Zt=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:f,panelSize:m})=>{var j,N,K,P,L;Eu(s,Au);let{containerSizeFactor:g,containerSizeLimit:S}=Cy({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&ne(o)?o:1,y=My.get(s);y||(y=s.filter(R=>!xu(R.quality)).sort((R,A)=>Iu(R.quality,A.quality)?-1:1),My.set(s,y));let T=(j=(0,it.default)(y,-1))==null?void 0:j.quality,I=(N=(0,it.default)(y,0))==null?void 0:N.quality,k=Wr(r,I,T),C=v*wu(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),V={},$=null;for(let R of y){let A=!0;if(S)if(R.size)A=R.size.width<=S.width&&R.size.height<=S.height;else{let Ne=S&&By(S);A=Ne?Kr(R.quality,Ne):!0}if(!A){V[R.quality]="FitsContainer";continue}let O=p||t,de=ne(O)&&isFinite(O)&&ne(R.bitrate)?O-a>=R.bitrate*C:!0,Fe=vu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===R.quality;if(!de&&!Fe){V[R.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&ne(i.minBufferToSwitchUp)&&u&&!xu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Iu(R.quality,u.quality)){V[R.quality]="Buffer";continue}if(!!c&&Yr(R.quality,c)&&!Fe){V[R.quality]="DroppedFramesLimit";continue}if(!!h&&Yr(R.quality,h)&&!Fe){V[R.quality]="StallsLimit";continue}let we=k||(Tu(r==null?void 0:r.max)||Kr(R.quality,r.max))&&(Tu(r==null?void 0:r.min)||Yr(R.quality,r.min)),Ae=ne(d)&&!d?Kr(R.quality,i.backgroundVideoQualityLimit):!0;if(!we||!Ae){V[R.quality]="FitsQualityLimits";continue}$||($=R)}$&&$.bitrate&&Dy.next($.bitrate);let w=(K=$!=null?$:(0,it.default)(y,-1))!=null?K:s[0],F=l==null?void 0:l.last,M=Pu(i,f,w,l);return ne(l)&&M.quality!==(F==null?void 0:F.quality)&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${s.map(R=>{var
|
|
12
|
+
${s.map(R=>{var A,O;return`{ id: ${R.id}, quality: ${R.quality}, bitrate: ${R.bitrate}, size: ${(A=R.size)==null?void 0:A.width}:${(O=R.size)==null?void 0:O.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,fr.default)(i!=null?i:{}).map(([R,A])=>`${R}: ${A}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
20
|
containerSizeFactor: ${g},
|
|
21
|
-
containerSizeLimit: ${(
|
|
21
|
+
containerSizeLimit: ${(P=S==null?void 0:S.width)!=null?P:0} x ${(L=S==null?void 0:S.height)!=null?L:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${p},
|
|
24
24
|
reserve: ${a},
|
|
@@ -34,24 +34,24 @@ var KE=Object.create;var Wl=Object.defineProperty,XE=Object.defineProperties,JE=
|
|
|
34
34
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,fr.default)(V).map(([R,A])=>`${R}: ${A}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
40
|
+
[best video track] ${$==null?void 0:$.quality}
|
|
41
41
|
[selected video track] ${M==null?void 0:M.quality}
|
|
42
|
-
`}),M},
|
|
42
|
+
`}),M},ku=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:f,panelSize:m})=>{var N,K,P,L,R;Eu(s,Au);let{containerSizeFactor:g,containerSizeLimit:S}=Cy({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&ne(o)?o:1,y=s.filter(A=>!xu(A.quality)).sort((A,O)=>Iu(A.quality,O.quality)?-1:1),T=(N=(0,it.default)(y,-1))==null?void 0:N.quality,I=(K=(0,it.default)(y,0))==null?void 0:K.quality,k=Wr(r,I,T),C=v*wu(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),V={},w=y.filter(A=>{let O=!0;if(S)if(A.size)O=A.size.width<=S.width&&A.size.height<=S.height;else{let At=S&&By(S);O=At?Kr(A.quality,At):!0}if(!O)return V[A.quality]="FitsContainer",!1;let de=p||t,Fe=ne(de)&&isFinite(de)&&ne(A.bitrate)?de-a>=A.bitrate*C:!0,ue=vu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===A.quality;if(!Fe&&!ue)return V[A.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&ne(i.minBufferToSwitchUp)&&u&&!xu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Iu(A.quality,u.quality))return V[A.quality]="Buffer",!1;if(!!c&&Yr(A.quality,c)&&!ue)return V[A.quality]="DroppedFramesLimit",!1;if(!!h&&Yr(A.quality,h)&&!ue)return V[A.quality]="StallsLimit",!1;let Ae=k||(Tu(r==null?void 0:r.max)||Kr(A.quality,r.max))&&(Tu(r==null?void 0:r.min)||Yr(A.quality,r.min)),Ne=ne(d)&&!d?Kr(A.quality,i.backgroundVideoQualityLimit):!0;return!Ae||!Ne?(V[A.quality]="FitsQualityLimits",!1):!0})[0];w&&w.bitrate&&Dy.next(w.bitrate);let F=(P=w!=null?w:(0,it.default)(y,-1))!=null?P:s[0],M=l==null?void 0:l.last,j=Pu(i,f,F,l);return ne(l)&&j.quality!==(M==null?void 0:M.quality)&&f({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
|
-
${s.map(
|
|
45
|
+
${s.map(A=>{var O,de;return`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate}, size: ${(O=A.size)==null?void 0:O.width}:${(de=A.size)==null?void 0:de.height} }`}).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,fr.default)(i!=null?i:{}).map(([A,O])=>`${A}: ${O}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
53
|
containerSizeFactor: ${g},
|
|
54
|
-
containerSizeLimit: ${(
|
|
54
|
+
containerSizeLimit: ${(L=S==null?void 0:S.width)!=null?L:0} x ${(R=S==null?void 0:S.height)!=null?R:0},
|
|
55
55
|
estimatedThroughput: ${t},
|
|
56
56
|
stallsPredictedThroughput: ${p},
|
|
57
57
|
reserve: ${a},
|
|
@@ -67,19 +67,19 @@ var KE=Object.create;var Wl=Object.defineProperty,XE=Object.defineProperties,JE=
|
|
|
67
67
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
68
68
|
|
|
69
69
|
[limited video tracks]
|
|
70
|
-
${(0,
|
|
70
|
+
${(0,fr.default)(V).map(([A,O])=>`${A}: ${O}`).join(`
|
|
71
71
|
`)||"All tracks are available"}
|
|
72
72
|
|
|
73
73
|
[best video track] ${w==null?void 0:w.quality}
|
|
74
|
-
[selected video track] ${
|
|
75
|
-
`}),
|
|
74
|
+
[selected video track] ${j==null?void 0:j.quality}
|
|
75
|
+
`}),j},Ru=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Eu(t,Au);let d=r.considerPlaybackRate&&ne(a)?a:1,c=[...t].sort(Xr(-1)),h=s.bitrate;$y(h);let p=d*wu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Ca(s,e,t,r.minVideoAudioRatio),g=l||i;ne(g)&&isFinite(g)&&(f=c.find(y=>ne(y.bitrate)&&ne(m==null?void 0:m.bitrate)?g-h>=y.bitrate*p&&y.bitrate>=m.bitrate:!1)),f||(f=m);let S=o==null?void 0:o.last,v=f&&Pu(r,u,f,o);return ne(o)&&(v==null?void 0:v.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
78
|
${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
|
|
79
79
|
`)}
|
|
80
80
|
|
|
81
81
|
[tuning]
|
|
82
|
-
${(0,
|
|
82
|
+
${(0,fr.default)(r!=null?r:{}).map(([y,T])=>`${y}: ${T}`).join(`
|
|
83
83
|
`)}
|
|
84
84
|
|
|
85
85
|
[limit params]
|
|
@@ -93,14 +93,14 @@ var KE=Object.create;var Wl=Object.defineProperty,XE=Object.defineProperties,JE=
|
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
95
|
[selected audio track] ${v==null?void 0:v.id}
|
|
96
|
-
`}),v},
|
|
96
|
+
`}),v},Mu=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Eu(t,Au);let d=r.considerPlaybackRate&&ne(a)?a:1,c=Py.get(t);c||(c=[...t].sort(Xr(-1)),Py.set(t,c));let h=s.bitrate;$y(h);let p=d*wu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Va(s,e,t,r.minVideoAudioRatio),g=l||i;ne(g)&&isFinite(g)&&(f=c.find(y=>ne(y.bitrate)&&ne(m==null?void 0:m.bitrate)?g-h>=y.bitrate*p&&y.bitrate>=m.bitrate:!1)),f||(f=m);let S=o==null?void 0:o.last,v=f&&Pu(r,u,f,o);return ne(o)&&(v==null?void 0:v.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
99
|
${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
|
|
100
100
|
`)}
|
|
101
101
|
|
|
102
102
|
[tuning]
|
|
103
|
-
${(0,
|
|
103
|
+
${(0,fr.default)(r!=null?r:{}).map(([y,T])=>`${y}: ${T}`).join(`
|
|
104
104
|
`)}
|
|
105
105
|
|
|
106
106
|
[limit params]
|
|
@@ -114,14 +114,14 @@ var KE=Object.create;var Wl=Object.defineProperty,XE=Object.defineProperties,JE=
|
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
116
|
[selected audio track] ${v==null?void 0:v.id}
|
|
117
|
-
`}),v};var Re=s=>new URL(s).hostname;import{assertNever as Xy,assertNonNullable as Jy,combine as iD,debounce as rD,ErrorCategory as Zy,filter as eT,filterChanged as sD,isNonNullable as op,map as Fu,merge as tT,observableFrom as aD,once as nD,Subscription as oD,ValueSubject as up,videoQualityToHeight as iT,videoSizeToQuality as uD}from"@vkontakte/videoplayer-shared/es2015";var Qy=j(jt(),1);var qy=j(wt(),1);var Uy=s=>{if(s instanceof DOMException&&(0,qy.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},We=(s,e)=>x(void 0,null,function*(){let t=s.muted;try{yield s.play()}catch(i){if(!Uy(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{yield s.play()}catch(r){return Uy(r)&&(s.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as Ou,isNullable as _B,assertNonNullable as ja}from"@vkontakte/videoplayer-shared/es2015";var Hy=j(fr(),1);import{isNonNullable as jy,assertNonNullable as Vu,now as VB}from"@vkontakte/videoplayer-shared/es2015";function Oe(){return VB()}function rp(s){return Oe()-s}function sp(s){let e=s.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 Gy(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function es(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,d,c,h=!1,p="arraybuffer",f=7e3,m=2e3,g=()=>{if(u)return;Vu(d);let M=rp(d),H;if(M<m){H=m-M,setTimeout(g,H);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,k()},S=M=>(a=M,F),v=M=>(c=M,F),y=()=>(p="json",F),T=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},I=M=>(h=M,F),k=()=>{d=Oe(),n=new r,n.open("get",s);let M=0,H,N=0,K=()=>(Vu(d),Math.max(d,Math.max(H||0,N||0)));if(a&&n.addEventListener("progress",A=>{let $=Oe();a.updateChunk&&A.loaded>M&&(a.updateChunk(K(),A.loaded-M),M=A.loaded,H=$)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;Vu(n);let A=n.status;if(A>=200&&A<300){let{response:$,responseType:R}=n,P=$==null?void 0:$.byteLength;if(typeof P=="number"&&a){let O=P-M;O&&a.updateChunk&&a.updateChunk(K(),O)}R==="json"&&(!$||!(0,Hy.default)($).length)?T():(c&&c(),e($))}else T()}),n.addEventListener("error",()=>{T()}),h){let A=()=>{Vu(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(N=Oe(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=p,n.send(),F},F={withBitrateReporting:S,withParallel:I,withJSONResponse:y,withRetryCount:M=>(l=M,F),withRetryInterval:(M,H)=>(jy(M)&&(m=M),jy(H)&&(f=H),F),withTimeout:M=>(o=M,F),withFinally:v,send:k,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return F}var Ua=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var zy=j(fr(),1);var qa=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Oe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Oe()-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=es(t,a,()=>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=Oe()}_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=Oe();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(){(0,zy.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._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)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as FB}from"@vkontakte/videoplayer-shared/es2015";var _u=1e4,ap=3;var NB=6e4,UB=10,qB=1,jB=500,Ha=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new FB,this.chunkRateEstimator=new Ua(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=sp(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=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=sp(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&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(G.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!My({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Qy.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ou(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Gy(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new qa(ap,_u,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let T=a&&(!d||d===this.rep);return T||t("Not running!"),T},h=(T,I,k)=>{u&&u.abort(),u=es(this.urlResolver.resolve(T,!1),I,k,()=>this._retryCallback()).withTimeout(_u).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ap).withFinally(()=>{u=null}).send()},p=(T,I,k)=>{ja(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),I,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=T=>{let I=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${I}=>${T}`),i.playbackRate=T)},m=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let k=Oe()-1e4,C=0;for(let D=0;D<this.bufferStates.length;D++){let w=this.bufferStates[D];T=Math.min(T,w.buf),w.ts<k&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${T} drop=${C} jitter=${this.sourceJitter}`);let V=T-qB;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?f(1.15):V>1?f(1.1):V>.3?f(1.05):f(1)}},S=T=>{let I,k=()=>I&&I.start?I.start.length:0,C=A=>I.start[A]/1e3,V=A=>I.dur[A]/1e3,D=A=>I.fragIndex+A,w=(A,$)=>({chunkIdx:D(A),startTS:C(A),dur:V(A),discontinuity:$}),F=()=>{let A=0;if(I&&I.dur){let $=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,R=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,P=$;this.sourceJitter>1&&(P+=this.sourceJitter-1);let O=I.dur.length-1;for(;O>=0&&(P-=I.dur[O],!(P<=0));--O);A=Math.min(O,I.dur.length-1-R),A=Math.max(A,0)}return w(A,!0)},M=A=>{let $=k();if(!($<=0)){if(Ou(A)){for(let R=0;R<$;R++)if(C(R)>A)return w(R)}return F()}},H=A=>{let $=k(),R=A?A.chunkIdx+1:0,P=R-I.fragIndex;if(!($<=0)){if(!A||P<0||P-$>UB)return t(`Resync: offset=${P} bChunks=${$} chunk=`+JSON.stringify(A)),F();if(!(P>=$))return w(R-I.fragIndex,!1)}},N=(A,$,R)=>{l&&l.abort(),l=es(this.urlResolver.resolve(A,!0,this.lowLatency),$,R,()=>this._retryCallback()).withTimeout(_u).withRetryCount(ap).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,$)=>{N(T,R=>{if(!c())return;I=R;let P=!!I.lowLatency;P!==this.lowLatency&&m(P);let O=0;for(let de=0;de<I.dur.length;++de)O+=I.dur[de];O>0&&(ja(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(O/I.dur.length)),r({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,A(M($))},()=>this._handleNetworkError())},nextChunk:H}},v=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),ja(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:T=>{let{videoElement:I,logger:k}=this.params,C=S(e.jidxUrl),V,D,w,F,M=0,H,N,K,A=()=>{H&&(clearTimeout(H),H=void 0);let ee=Math.max(jB,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=M+ee,we=Oe(),Pe=Math.min(1e4,Ee-we);M=we;let Ue=()=>{l||c()&&C.seek(()=>{c()&&(M=Oe(),$(),A())})};Pe>0?H=window.setTimeout(()=>{this.paused?A():Ue()},Pe):Ue()},$=()=>{let ee;for(;ee=C.nextChunk(F);)F=ee,Ne(ee);let Ee=C.nextChunk(w);if(Ee){if(w&&Ee.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?A():(v(),this._initPlayerWith(e));return}de(Ee)}else A()},R=(ee,Ee)=>{if(!c()||!this.sourceBuffer)return;let we,Pe,Ue,Rt=$t=>{window.setTimeout(()=>{c()&&R(ee,Ee)},$t)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),Rt(100);else{let $t=Oe(),Yt=I.currentTime;!this.paused&&I.buffered.length>1&&N===Yt&&$t-K>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),N!==Yt&&(N=Yt,K=$t);let ai=this._getBufferSizeSec();if(ai>30)k(`Buffered ${ai} seconds; delaying appendBuffer`),Rt(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:$t,buf:ai}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Bi){if(Bi.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),Ue=this.sourceBuffer.buffered.length,Ue!==0&&(we=this.sourceBuffer.buffered.start(0),Pe=Yt,Pe-we>4&&this.sourceBuffer.remove(we,Pe-3)),Rt(1e3);else throw Bi}}},P=()=>{D&&V&&(k([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(w)]),R(D,function(){D=null,$()}))},O=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),de=ee=>{c()&&p(O(ee),(Ee,we)=>{if(c()){if(we/=1e3,D=Ee,w=ee,n=ee.startTS,we){let Pe=Math.min(10,ee.dur/we);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}P()}},()=>this._handleNetworkError())},Ne=ee=>{c()&&(ja(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(O(ee),!1)))},ue=ee=>{c()&&(e.cachedHeader=ee,R(ee,()=>{V=!0,P()}))};a=!0,C.seek(ee=>{if(c()){if(M=Oe(),!ee){A();return}F=ee,!_B(T)||ee.startTS>T?de(ee):(w=ee,$())}},T),e.cachedHeader?ue(e.cachedHeader):h(e.headerUrl,ue,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Ou(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,ja(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ou(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),f=c/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(h,p)=>{let f=Oe();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&rp(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{let p=a.updateChunk(c,h);return p&&l(),p},notifySwitch:c=>{let h=Oe();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=es(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(_u).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;We(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var d,c;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,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=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},NB))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ky=j(nr(),1);import{debounce as HB,filter as Wy,fromEvent as GB,interval as zB,isHigher as QB,isInvariantQuality as WB,isLower as YB,merge as KB,Subject as Yy,Subscription as XB}from"@vkontakte/videoplayer-shared/es2015";var np=class{constructor(){this.onDroopedVideoFramesLimit$=new Yy;this.subscription=new XB;this.playing=!1;this.tracks=[];this.forceChecker$=new Yy;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&&!WB(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,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&QB(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(GB(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=zB(this.droppedFramesChecker.checkTime).pipe(Wy(()=>this.playing),Wy(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(HB(this.droppedFramesChecker.checkTime)),i=KB(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=(0,Ky.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>YB(a,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}},ts=np;import{map as JB,Observable as ZB}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as eD}from"@vkontakte/videoplayer-shared/es2015";var Ga=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var tD=(s,e)=>new ZB(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ga()))},E(E({},i),e));r.observe(s);let a=eD(document,"visibilitychange").pipe(JB(n=>!document.hidden||Ga())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),ht=tD;var lD=["paused","playing","ready"],cD=["paused","playing","ready"],za=class{constructor(e){this.subscription=new oD;this.videoState=new Q("stopped");this.representations$=new up([]);this.droppedFramesManager=new ts;this.maxSeekBackTime$=new up(1/0);this.zeroTime$=new up(void 0);this.liveOffset=new mr;this._dashCb=e=>{var t,i,r,a;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:Zy.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),d=(i=ti(u.name))!=null?i:uD(u.video),c=u.bitrate/1e3,h=E({},u.video);if(!d)continue;let p={id:l,quality:d,bitrate:c,size:h};o.push({track:p,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=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),op(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(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,lp.default)(cD,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,lp.default)(lD,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ie(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(Ie(this.params.source.url,u))}return;default:return Xy(e)}};this.textTracksManager=new pt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Zy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(tT(this.videoState.stateChangeStarted$.pipe(Fu(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Fu(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=He(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Re(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=Qe(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Fu(r=>r.map(({track:a})=>a)),eT(r=>!!r.length),nD()).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(sD(),Fu(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(iD({zeroTime:this.zeroTime$.pipe(eT(op)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Lt(this.video,this.params.desiredState.isLooped,t)).add(ze(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(dt(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(ht(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&iT(r),min:a&&iT(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;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":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.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 Xy(r.to)}},t)).add(tT(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,aD(["init"])).pipe(rD(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ge(this.video)}createLiveDashPlayer(){let e=new Ha({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,d,c,h,p,f;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(h=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&op(t)?t:ii(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let m=(f=e.find(({track:g})=>g.id===a))==null?void 0:f.representation;Jy(m,"Representations missing"),this.dash.startPlay(m,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Jy(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ie(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var rT=za;var bx=j(wt(),1);var _e=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as zC,assertNonNullable as QC,debounce as WC,ErrorCategory as hx,filter as Yp,filterChanged as dl,fromEvent as YC,isNonNullable as fx,map as Kp,merge as pl,observableFrom as Xp,once as mx,Subscription as KC}from"@vkontakte/videoplayer-shared/es2015";var Nu=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,a=i.length;r<a;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,a=i.length;r<a;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}},is=class extends Nu{constructor(){super(),this.listeners||Nu.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)}},Qa=class{constructor(){Object.defineProperty(this,"signal",{value:new is,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&&(Qa.prototype[Symbol.toStringTag]="AbortController",is.prototype[Symbol.toStringTag]="AbortSignal");function Uu(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function cp(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Uu({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let h=new t(l,d);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let h=new Promise((p,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:a}}var dD=()=>"fetch"in window,Wa=dD()&&Uu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),sT=Wa?cp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Mt=Wa?sT.fetch:window.fetch,mH=Wa?sT.Request:window.Request,le=Wa?Qa:window.AbortController,bH=Wa?is:window.AbortSignal;var jp=j(Ya(),1);var HT=j(jT(),1);import{ErrorCategory as Xa}from"@vkontakte/videoplayer-shared/es2015";var qu=s=>{if(!s)return{id:"EmptyResponse",category:Xa.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Xa.NETWORK,message:`UV Error ${s}`};let e=(0,HT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Xa.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Xa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Xa.PARSER,message:"Response is valid XML, but parser failed"}};var Ye=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as Np,assertNonNullable as hs,combine as fs,ErrorCategory as Gt,filter as rl,filterChanged as Mn,flattenObject as $n,fromEvent as ki,getTraceSubscriptionMethod as kC,interval as Up,isNonNullable as Bn,isNullable as ox,map as ms,merge as yr,now as qp,Subject as sl,Subscription as ux,tap as RC,throttle as LC,ValueSubject as ge}from"@vkontakte/videoplayer-shared/es2015";var Gu=j(wt(),1),ls=j(jt(),1),zu=j(Ya(),1);var KD=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},XD=s=>window.clearTimeout(s),GT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),zT=!GT(window.requestIdleCallback)||!GT(window.cancelIdleCallback),rs=zT?KD:window.requestIdleCallback,ri=zT?XD:window.cancelIdleCallback;var XI=j(Ba(),1);import{assertNever as JD,ErrorCategory as QT,Subject as WT}from"@vkontakte/videoplayer-shared/es2015";var ZD=18,YT=!1;try{YT=G.browser.isSafari&&!!G.browser.safariVersion&&G.browser.safariVersion<=ZD}catch(s){console.error(s)}var bp=class{constructor(e){this.bufferFull$=new WT;this.error$=new WT;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:QT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return x(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 x(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return x(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};YT&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,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)&&!this.abortRequested)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(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:QT.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:JD(t)}}},KT=bp;var ss=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as qi,assertNonNullable as ft,ErrorCategory as wi,fromEvent as Dp,getExponentialDelay as Cp,isNonNullable as us,isNullable as Ke,now as Hu,once as bC,Subject as gC,Subscription as SC,ValueSubject as vr}from"@vkontakte/videoplayer-shared/es2015";var te=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}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 as=class extends te{};var Ja=class extends te{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Za=class extends te{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 en=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pe=class extends te{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var tn=class extends pe{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var rn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sn=class extends te{constructor(e,t){super(e,t),this.data=this.content}};var gr=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(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var an=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var nn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var on=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 un=class extends pe{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ln=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 cn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var dn=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 pn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fn=class extends pe{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var mn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var bn=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 gn=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 Sn=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 vn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var yn=class extends pe{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Tn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var t0={ftyp:Za,moov:en,mvhd:tn,moof:rn,mdat:sn,sidx:gr,trak:an,mdia:cn,mfhd:fn,tkhd:dn,traf:mn,tfhd:bn,tfdt:gn,trun:Sn,minf:pn,sv3d:nn,st3d:on,prhd:un,proj:hn,equi:ln,uuid:Ja,stbl:vn,stsd:yn,avc1:Tn,unknown:as},xi=class s{constructor(e={}){this.options=E({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,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=t0[e];return i?new i(t,new s):new as(t,new s)}};var Ui=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(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 r0=new TextDecoder("ascii"),s0=s=>r0.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",a0=s=>{let e=new gr(s,new xi),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},n0=(s,e)=>{let i=new xi().parse(s),r=new Ui(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},o0=s=>{let t=new xi().parse(s),i=new Ui(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},u0=s=>{var r;let t=new xi().parse(s);return(r=new Ui(t).find("sidx"))==null?void 0:r.timescale},l0=(s,e)=>{let i=new xi().parse(s),a=new Ui(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},c0=s=>{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 xi().parse(s),r=new Ui(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},XT={validateData:s0,parseInit:c0,getIndexRange:()=>{},parseSegments:a0,parseFeedableSegmentChunk:n0,getChunkEndTime:l0,getServerLatencyTimestamps:o0,getTimescaleFromIndex:u0};var xn=j(wt(),1);import{assertNonNullable as Sp,isNonNullable as tI,isNullable as p0}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as d0}from"@vkontakte/videoplayer-shared/es2015";var JT={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"}},ZT=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=In(s,t),r=i in JT,a=r?JT[i].type:"binary",n=s.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(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=In(u),c=l*st(2,(o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},In=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*st(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*st(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*st(2,32)+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ht=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return In(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:d0(e)}},Sr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=ZT(i);if(!e(r))return;r.type==="master"&&Sr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},eI=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=ZT(s);return Sr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Ht(o,n):a===17026?t=Ht(o,n):a===17029&&(i=Ht(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var iI=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],h0=[231,22612,22743,167,171,163,160,175],f0=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return Sr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=Ht(f,p);l=In(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=Ht(f,p):h===17545?r=Ht(f,p):h===21420&&l===475249515?u=Ht(f,p):h===374648427?Sr(f,({tag:g,type:S,value:v})=>g===30321?(d=Ht(v,S)===1,!1):!0):a&&n&&(0,xn.default)(iI,h)&&(o=!0),!o}),Sp(e,"Failed to parse webm Segment start"),Sp(t,"Failed to parse webm Segment end"),Sp(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:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},m0=s=>{if(p0(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},b0=(s,e)=>{let t=!1,i=!1,r=o=>tI(o.time)&&tI(o.position),a=[],n;return Sr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Ht(l,u));break;case 183:break;case 241:n&&(n.position=Ht(l,u));break;default:t&&(0,xn.default)(iI,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},g0=s=>{let e=0,t=!1;try{Sr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,xn.default)(h0,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,xn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},rI={validateData:eI,parseInit:f0,getIndexRange:m0,parseSegments:b0,parseFeedableSegmentChunk:g0};var En=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return rI;case"mp4":return XT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Mp=j(Ep(),1),zI=j(nr(),1),QI=j(wp(),1),WI=j(jt(),1),$p=j(fr(),1);var _I=j(wt(),1),os=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,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[a,n]=r.toUpperCase(),o=a+n;return(0,_I.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as fC,isNullable as HI}from"@vkontakte/videoplayer-shared/es2015";var ju=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var FI=s=>{var e;try{let t=pC(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function pC(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
117
|
+
`}),v};var je=s=>new URL(s).hostname;import{assertNever as Qy,assertNonNullable as Gy,combine as W$,debounce as Y$,ErrorCategory as Wy,filter as Yy,filterChanged as K$,isNonNullable as tp,map as Du,merge as Ky,observableFrom as X$,once as J$,Subscription as Z$,ValueSubject as ip,videoQualityToHeight as Xy,videoSizeToQuality as e0}from"@vkontakte/videoplayer-shared/es2015";var qy=H(qt(),1);var Oy=H(It(),1);var Vy=s=>{if(s instanceof DOMException&&(0,Oy.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},ct=(s,e)=>E(void 0,null,function*(){let t=s.muted;try{yield s.play()}catch(i){if(!Vy(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{yield s.play()}catch(r){return Vy(r)&&(s.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as Bu,isNullable as M$,assertNonNullable as Fa}from"@vkontakte/videoplayer-shared/es2015";var Fy=H(pr(),1);import{isNonNullable as _y,assertNonNullable as Lu,now as k$}from"@vkontakte/videoplayer-shared/es2015";function Ve(){return k$()}function Xd(s){return Ve()-s}function Jd(s){let e=s.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 Ny(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Jr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,d,c,h=!1,p="arraybuffer",f=7e3,m=2e3,g=()=>{if(u)return;Lu(d);let M=Xd(d),j;if(M<m){j=m-M,setTimeout(g,j);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,k()},S=M=>(a=M,F),v=M=>(c=M,F),y=()=>(p="json",F),T=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},I=M=>(h=M,F),k=()=>{d=Ve(),n=new r,n.open("get",s);let M=0,j,N=0,K=()=>(Lu(d),Math.max(d,Math.max(j||0,N||0)));if(a&&n.addEventListener("progress",P=>{let L=Ve();a.updateChunk&&P.loaded>M&&(a.updateChunk(K(),P.loaded-M),M=P.loaded,j=L)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;Lu(n);let P=n.status;if(P>=200&&P<300){let{response:L,responseType:R}=n,A=L==null?void 0:L.byteLength;if(typeof A=="number"&&a){let O=A-M;O&&a.updateChunk&&a.updateChunk(K(),O)}R==="json"&&(!L||!(0,Fy.default)(L).length)?T():(c&&c(),e(L))}else T()}),n.addEventListener("error",()=>{T()}),h){let P=()=>{Lu(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(N=Ve(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=p,n.send(),F},F={withBitrateReporting:S,withParallel:I,withJSONResponse:y,withRetryCount:M=>(l=M,F),withRetryInterval:(M,j)=>(_y(M)&&(m=M),_y(j)&&(f=j),F),withTimeout:M=>(o=M,F),withFinally:v,send:k,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return F}var Oa=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Uy=H(pr(),1);var _a=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Ve(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Ve()-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=Jr(t,a,()=>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=Ve()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=Ve();if(Object.keys(this.activeRequests).length>=e)return!1;let 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(){(0,Uy.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._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)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as L$}from"@vkontakte/videoplayer-shared/es2015";var $u=1e4,Zd=3;var B$=6e4,$$=10,D$=1,C$=500,Na=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new L$,this.chunkRateEstimator=new Oa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Jd(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=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(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",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=Jd(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,a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(a=e.error)==null?void 0:a.message}`),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&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(Q.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Ay({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,qy.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Bu(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Ny(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new _a(Zd,$u,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let T=a&&(!d||d===this.rep);return T||t("Not running!"),T},h=(T,I,k)=>{u&&u.abort(),u=Jr(this.urlResolver.resolve(T,!1),I,k,()=>this._retryCallback()).withTimeout($u).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Zd).withFinally(()=>{u=null}).send()},p=(T,I,k)=>{Fa(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),I,k,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=T=>{let I=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${I}=>${T}`),i.playbackRate=T)},m=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let k=Ve()-1e4,C=0;for(let $=0;$<this.bufferStates.length;$++){let w=this.bufferStates[$];T=Math.min(T,w.buf),w.ts<k&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${T} drop=${C} jitter=${this.sourceJitter}`);let V=T-D$;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?f(1.15):V>1?f(1.1):V>.3?f(1.05):f(1)}},S=T=>{let I,k=()=>I&&I.start?I.start.length:0,C=P=>I.start[P]/1e3,V=P=>I.dur[P]/1e3,$=P=>I.fragIndex+P,w=(P,L)=>({chunkIdx:$(P),startTS:C(P),dur:V(P),discontinuity:L}),F=()=>{let P=0;if(I&&I.dur){let L=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,R=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,A=L;this.sourceJitter>1&&(A+=this.sourceJitter-1);let O=I.dur.length-1;for(;O>=0&&(A-=I.dur[O],!(A<=0));--O);P=Math.min(O,I.dur.length-1-R),P=Math.max(P,0)}return w(P,!0)},M=P=>{let L=k();if(!(L<=0)){if(Bu(P)){for(let R=0;R<L;R++)if(C(R)>P)return w(R)}return F()}},j=P=>{let L=k(),R=P?P.chunkIdx+1:0,A=R-I.fragIndex;if(!(L<=0)){if(!P||A<0||A-L>$$)return t(`Resync: offset=${A} bChunks=${L} chunk=`+JSON.stringify(P)),F();if(!(A>=L))return w(R-I.fragIndex,!1)}},N=(P,L,R)=>{l&&l.abort(),l=Jr(this.urlResolver.resolve(P,!0,this.lowLatency),L,R,()=>this._retryCallback()).withTimeout($u).withRetryCount(Zd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(P,L)=>{N(T,R=>{if(!c())return;I=R;let A=!!I.lowLatency;A!==this.lowLatency&&m(A);let O=0;for(let de=0;de<I.dur.length;++de)O+=I.dur[de];O>0&&(Fa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(O/I.dur.length)),r({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,P(M(L))},()=>this._handleNetworkError())},nextChunk:j}},v=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Fa(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:T=>{let{videoElement:I,logger:k}=this.params,C=S(e.jidxUrl),V,$,w,F,M=0,j,N,K,P=()=>{j&&(clearTimeout(j),j=void 0);let ee=Math.max(C$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=M+ee,we=Ve(),Ae=Math.min(1e4,Ee-we);M=we;let Ne=()=>{l||c()&&C.seek(()=>{c()&&(M=Ve(),L(),P())})};Ae>0?j=window.setTimeout(()=>{this.paused?P():Ne()},Ae):Ne()},L=()=>{let ee;for(;ee=C.nextChunk(F);)F=ee,Fe(ee);let Ee=C.nextChunk(w);if(Ee){if(w&&Ee.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?P():(v(),this._initPlayerWith(e));return}de(Ee)}else P()},R=(ee,Ee)=>{if(!c()||!this.sourceBuffer)return;let we,Ae,Ne,At=Lt=>{window.setTimeout(()=>{c()&&R(ee,Ee)},Lt)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),At(100);else{let Lt=Ve(),Gt=I.currentTime;!this.paused&&I.buffered.length>1&&N===Gt&&Lt-K>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),N!==Gt&&(N=Gt,K=Lt);let ii=this._getBufferSizeSec();if(ii>30)k(`Buffered ${ii} seconds; delaying appendBuffer`),At(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:Lt,buf:ii}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Li){if(Li.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),Ne=this.sourceBuffer.buffered.length,Ne!==0&&(we=this.sourceBuffer.buffered.start(0),Ae=Gt,Ae-we>4&&this.sourceBuffer.remove(we,Ae-3)),At(1e3);else throw Li}}},A=()=>{$&&V&&(k([`Appending chunk, sz=${$.byteLength}:`,JSON.stringify(w)]),R($,function(){$=null,L()}))},O=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),de=ee=>{c()&&p(O(ee),(Ee,we)=>{if(c()){if(we/=1e3,$=Ee,w=ee,n=ee.startTS,we){let Ae=Math.min(10,ee.dur/we);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ae:Ae}A()}},()=>this._handleNetworkError())},Fe=ee=>{c()&&(Fa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(O(ee),!1)))},ue=ee=>{c()&&(e.cachedHeader=ee,R(ee,()=>{V=!0,A()}))};a=!0,C.seek(ee=>{if(c()){if(M=Ve(),!ee){P();return}F=ee,!M$(T)||ee.startTS>T?de(ee):(w=ee,L())}},T),e.cachedHeader?ue(e.cachedHeader):h(e.headerUrl,ue,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Bu(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,Fa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Bu(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),f=c/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(h,p)=>{let f=Ve();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Xd(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{let p=a.updateChunk(c,h);return p&&l(),p},notifySwitch:c=>{let h=Ve();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Jr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout($u).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;ct(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var d,c;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,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=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},B$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var zy=H(sr(),1);import{debounce as V$,filter as jy,fromEvent as O$,interval as _$,isHigher as F$,isInvariantQuality as N$,isLower as U$,merge as q$,Subject as Hy,Subscription as j$}from"@vkontakte/videoplayer-shared/es2015";var ep=class{constructor(){this.onDroopedVideoFramesLimit$=new Hy;this.subscription=new j$;this.playing=!1;this.tracks=[];this.forceChecker$=new Hy;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&&!N$(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,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&F$(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(O$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=_$(this.droppedFramesChecker.checkTime).pipe(jy(()=>this.playing),jy(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(V$(this.droppedFramesChecker.checkTime)),i=q$(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=(0,zy.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>U$(a,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}},Zr=ep;import{map as H$,Observable as z$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as Q$}from"@vkontakte/videoplayer-shared/es2015";var Ua=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var G$=(s,e)=>new z$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ua()))},x(x({},i),e));r.observe(s);let a=Q$(document,"visibilitychange").pipe(H$(n=>!document.hidden||Ua())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),Rt=G$;var t0=["paused","playing","ready"],i0=["paused","playing","ready"],qa=class{constructor(e){this.subscription=new Z$;this.videoState=new Y("stopped");this.representations$=new ip([]);this.droppedFramesManager=new Zr;this.maxSeekBackTime$=new ip(1/0);this.zeroTime$=new ip(void 0);this.liveOffset=new hr;this._dashCb=e=>{var t,i,r,a;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:Wy.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),d=(i=Oi(u.name))!=null?i:e0(u.video),c=u.bitrate/1e3,h=x({},u.video);if(!d)continue;let p={id:l,quality:d,bitrate:c,size:h};o.push({track:p,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=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),tp(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(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,rp.default)(i0,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,rp.default)(t0,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ie(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(Ie(this.params.source.url,u))}return;default:return Qy(e)}};this.textTracksManager=new kt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Wy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Ky(this.videoState.stateChangeStarted$.pipe(Du(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Du(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=nt(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(je(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=lt(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Du(r=>r.map(({track:a})=>a)),Yy(r=>!!r.length),J$()).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(K$(),Du(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(W$({zeroTime:this.zeroTime$.pipe(Yy(tp)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Kt(this.video,this.params.desiredState.isLooped,t)).add(ut(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Pt(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(Rt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&Xy(r),min:a&&Xy(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;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":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.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 Qy(r.to)}},t)).add(Ky(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,X$(["init"])).pipe(Y$(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),ot(this.video)}createLiveDashPlayer(){let e=new Na({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,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,d,c,h,p,f;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(h=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&tp(t)?t:Zt(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let m=(f=e.find(({track:g})=>g.id===a))==null?void 0:f.representation;Gy(m,"Representations missing"),this.dash.startPlay(m,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Gy(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ie(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Jy=qa;var dx=H(It(),1);var Oe=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as _C,assertNonNullable as FC,debounce as NC,ErrorCategory as ux,filter as jp,filterChanged as ol,fromEvent as UC,isNonNullable as lx,map as Hp,merge as ul,observableFrom as zp,once as cx,Subscription as qC}from"@vkontakte/videoplayer-shared/es2015";var Cu=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,a=i.length;r<a;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,a=i.length;r<a;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}},es=class extends Cu{constructor(){super(),this.listeners||Cu.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)}},ja=class{constructor(){Object.defineProperty(this,"signal",{value:new es,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&&(ja.prototype[Symbol.toStringTag]="AbortController",es.prototype[Symbol.toStringTag]="AbortSignal");function Vu(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function sp(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Vu({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let h=new t(l,d);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let h=new Promise((p,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:a}}var r0=()=>"fetch"in window,Ha=r0()&&Vu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Zy=Ha?sp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Mt=Ha?Zy.fetch:window.fetch,Zj=Ha?Zy.Request:window.Request,le=Ha?ja:window.AbortController,eH=Ha?es:window.AbortSignal;var Op=H(za(),1);var FT=H(_T(),1);import{ErrorCategory as Ga}from"@vkontakte/videoplayer-shared/es2015";var Ou=s=>{if(!s)return{id:"EmptyResponse",category:Ga.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Ga.NETWORK,message:`UV Error ${s}`};let e=(0,FT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ga.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ga.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ga.PARSER,message:"Response is valid XML, but parser failed"}};var He=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as Dp,assertNonNullable as cs,combine as ds,ErrorCategory as Ht,filter as Zu,filterChanged as Pn,flattenObject as kn,fromEvent as Ai,getTraceSubscriptionMethod as yC,interval as Cp,isNonNullable as Rn,isNullable as ix,map as ps,merge as Sr,now as Vp,Subject as el,Subscription as rx,tap as TC,throttle as IC,ValueSubject as ge}from"@vkontakte/videoplayer-shared/es2015";var Nu=H(It(),1),os=H(qt(),1),Uu=H(za(),1);var q0=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},j0=s=>window.clearTimeout(s),NT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),UT=!NT(window.requestIdleCallback)||!NT(window.cancelIdleCallback),ts=UT?q0:window.requestIdleCallback,ei=UT?j0:window.cancelIdleCallback;var QI=H(ou(),1);import{assertNever as H0,ErrorCategory as qT,Subject as jT}from"@vkontakte/videoplayer-shared/es2015";var z0=18,HT=!1;try{HT=Q.browser.isSafari&&!!Q.browser.safariVersion&&Q.browser.safariVersion<=z0}catch(s){console.error(s)}var cp=class{constructor(e){this.bufferFull$=new jT;this.error$=new jT;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:qT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return E(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 E(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return E(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};HT&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,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)&&!this.abortRequested)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(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:qT.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:H0(t)}}},zT=cp;var is=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as Ni,assertNonNullable as dt,ErrorCategory as xi,fromEvent as kp,getExponentialDelay as Rp,isNonNullable as ns,isNullable as ze,now as Fu,once as uC,Subject as lC,Subscription as cC,ValueSubject as gr}from"@vkontakte/videoplayer-shared/es2015";var te=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}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 rs=class extends te{};var Wa=class extends te{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Ya=class extends te{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 Ka=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pe=class extends te{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Xa=class extends pe{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Ja=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=class extends te{constructor(e,t){super(e,t),this.data=this.content}};var mr=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(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var en=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var tn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rn=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 sn=class extends pe{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var an=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 nn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var on=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 un=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ln=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cn=class extends pe{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var dn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pn=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 hn=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 fn=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 mn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var bn=class extends pe{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var gn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var G0={ftyp:Ya,moov:Ka,mvhd:Xa,moof:Ja,mdat:Za,sidx:mr,trak:en,mdia:nn,mfhd:cn,tkhd:on,traf:dn,tfhd:pn,tfdt:hn,trun:fn,minf:un,sv3d:tn,st3d:rn,prhd:sn,proj:ln,equi:an,uuid:Wa,stbl:mn,stsd:bn,avc1:gn,unknown:rs},Ti=class s{constructor(e={}){this.options=x({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,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=G0[e];return i?new i(t,new s):new rs(t,new s)}};var Fi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(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 Y0=new TextDecoder("ascii"),K0=s=>Y0.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",X0=s=>{let e=new mr(s,new Ti),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},J0=(s,e)=>{let i=new Ti().parse(s),r=new Fi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},Z0=s=>{let t=new Ti().parse(s),i=new Fi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},eD=s=>{var r;let t=new Ti().parse(s);return(r=new Fi(t).find("sidx"))==null?void 0:r.timescale},tD=(s,e)=>{let i=new Ti().parse(s),a=new Fi(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},iD=s=>{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 Ti().parse(s),r=new Fi(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},QT={validateData:K0,parseInit:iD,getIndexRange:()=>{},parseSegments:X0,parseFeedableSegmentChunk:J0,getChunkEndTime:tD,getServerLatencyTimestamps:Z0,getTimescaleFromIndex:eD};var vn=H(It(),1);import{assertNonNullable as pp,isNonNullable as KT,isNullable as sD}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as rD}from"@vkontakte/videoplayer-shared/es2015";var GT={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"}},WT=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Sn(s,t),r=i in GT,a=r?GT[i].type:"binary",n=s.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(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=Sn(u),c=l*Ze(2,(o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},Sn=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Ze(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Ze(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Ze(2,32)+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},jt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Sn(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:rD(e)}},br=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=WT(i);if(!e(r))return;r.type==="master"&&br(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},YT=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=WT(s);return br(r.value,({tag:a,type:n,value:o})=>(a===17143?e=jt(o,n):a===17026?t=jt(o,n):a===17029&&(i=jt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var XT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],aD=[231,22612,22743,167,171,163,160,175],nD=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return br(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=jt(f,p);l=Sn(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=jt(f,p):h===17545?r=jt(f,p):h===21420&&l===475249515?u=jt(f,p):h===374648427?br(f,({tag:g,type:S,value:v})=>g===30321?(d=jt(v,S)===1,!1):!0):a&&n&&(0,vn.default)(XT,h)&&(o=!0),!o}),pp(e,"Failed to parse webm Segment start"),pp(t,"Failed to parse webm Segment end"),pp(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:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},oD=s=>{if(sD(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},uD=(s,e)=>{let t=!1,i=!1,r=o=>KT(o.time)&&KT(o.position),a=[],n;return br(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=jt(l,u));break;case 183:break;case 241:n&&(n.position=jt(l,u));break;default:t&&(0,vn.default)(XT,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},lD=s=>{let e=0,t=!1;try{br(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,vn.default)(aD,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,vn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},JT={validateData:YT,parseInit:nD,getIndexRange:oD,parseSegments:uD,parseFeedableSegmentChunk:lD};var yn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return JT;case"mp4":return QT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var wp=H(Sp(),1),UI=H(sr(),1),qI=H(vp(),1),jI=H(qt(),1),Ap=H(pr(),1);var $I=H(It(),1),as=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,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[a,n]=r.toUpperCase(),o=a+n;return(0,$I.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as nC,isNullable as FI}from"@vkontakte/videoplayer-shared/es2015";var _u=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var DI=s=>{var e;try{let t=sC(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function sC(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
118
118
|
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
119
119
|
(-(?<script>[a-z]{4}))?
|
|
120
120
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
121
121
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
122
122
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
123
123
|
(?:-(?<privateuse>(?:${e})))?
|
|
124
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Ap=j(jt(),1);import{videoSizeToQuality as hC}from"@vkontakte/videoplayer-shared/es2015";var NI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?ti(a):void 0)!=null?u:hC({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},UI=({id:s,bitrate:e})=>({id:s,bitrate:e}),qI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),jI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),kp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Ap.default)(i.split("."),0),isDefault:r}),Rp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Ap.default)(r.split("."),0)}),Lp=s=>"url"in s,ut=s=>s.type==="template",wn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var GI=s=>{if(!(s!=null&&s.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(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={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 a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Ei=(s,e)=>{let t=s;t=(0,Mp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,zI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Mp.default)(t,n,(o,u)=>HI(a)?o:HI(u)?a:(0,QI.default)(a,parseInt(u,10),"0"))}return t},YI=(s,e)=>{var D,w,F,M,H,N,K,A,$,R,P,O,de,Ne,ue,ee,Ee,we,Pe,Ue,Rt,$t,Yt,ai,Bi,Ps,As,ks,Rs,Ls,Ms,$s,Bs,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,Gs,zs,Qs,Ws,Ys,Ks,Xs,Js,Zs,ea,ta,ia,ra,sa,aa,na,oa;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(fe=>{var q,Je;return(Je=(q=fe.textContent)==null?void 0:q.trim())!=null?Je:""}),o=(D=(0,WI.default)(n,0))!=null?D:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],T=y.reduce((fe,q)=>B(E({},fe),{[q.id]:q.children}),{}),I=y.reduce((fe,q)=>B(E({},fe),{[q.id]:q.getAttribute("duration")}),{});v?S=GI(v):(0,$p.default)(I).filter(fe=>fe).length&&!u?S=(0,$p.default)(I).reduce((fe,q)=>{var Je;return fe+((Je=GI(q))!=null?Je:0)},0):m&&(S=parseInt(m,10));let k=0,C=(F=(w=a.getAttribute("profiles"))==null?void 0:w.split(","))!=null?F:[];for(let fe of y.map(q=>q.id))for(let q of T[fe]){let Je=(M=q.getAttribute("id"))!=null?M:"id"+(k++).toString(10),Bt=(H=q.getAttribute("mimeType"))!=null?H:"",Ki=(N=q.getAttribute("codecs"))!=null?N:"",Xi=(K=q.getAttribute("contentType"))!=null?K:Bt==null?void 0:Bt.split("/")[0],Ul=($=(A=q.getAttribute("profiles"))==null?void 0:A.split(","))!=null?$:[],ua=(P=FI((R=q.getAttribute("lang"))!=null?R:""))!=null?P:{},ni=(Ne=(de=(O=q.querySelector("Label"))==null?void 0:O.textContent)==null?void 0:de.trim())!=null?Ne:void 0,ql=q.querySelectorAll("Representation"),jl=q.querySelector("SegmentTemplate"),Hl=(ee=(ue=q.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?ee:void 0,bt=Xi,W={id:Je,language:ua.language,isDefault:Hl==="main",label:ni,codecs:Ki,hdr:bt==="video"&&os(Ki),mime:Bt,representations:[]};for(let U of ql){let Le=(Ee=U.getAttribute("lang"))!=null?Ee:void 0,Dt=(Pe=(we=ni!=null?ni:q.getAttribute("label"))!=null?we:U.getAttribute("label"))!=null?Pe:void 0,oi=($t=(Rt=(Ue=U.querySelector("BaseURL"))==null?void 0:Ue.textContent)==null?void 0:Rt.trim())!=null?$t:"",Ze=new URL(oi||o,e).toString(),Me=(Yt=U.getAttribute("mimeType"))!=null?Yt:Bt,ui=(Bi=(ai=U.getAttribute("codecs"))!=null?ai:Ki)!=null?Bi:"",li;if(Xi==="text"){let $e=U.getAttribute("id")||"",ci=((Ps=ua.privateuse)==null?void 0:Ps.includes("x-auto"))||$e.includes("_auto"),et=U.querySelector("SegmentTemplate");if(et){let Ct={representationId:(As=U.getAttribute("id"))!=null?As:void 0,bandwidth:(ks=U.getAttribute("bandwidth"))!=null?ks:void 0},di=parseInt((Rs=U.getAttribute("bandwidth"))!=null?Rs:"",10)/1e3,pi=(Ms=parseInt((Ls=et.getAttribute("startNumber"))!=null?Ls:"",10))!=null?Ms:1,gt=parseInt(($s=et.getAttribute("timescale"))!=null?$s:"",10),Ji=(Bs=et.querySelectorAll("SegmentTimeline S"))!=null?Bs:[],St=et.getAttribute("media");if(!St)continue;let hi=[],fi=0,mi="",vt=0,Vt=pi,se=0;for(let me of Ji){let tt=parseInt((Ds=me.getAttribute("d"))!=null?Ds:"",10),ce=parseInt((Cs=me.getAttribute("r"))!=null?Cs:"",10)||0,Be=parseInt((Vs=me.getAttribute("t"))!=null?Vs:"",10);se=Number.isFinite(Be)?Be:se;let it=tt/gt*1e3,De=se/gt*1e3;for(let ve=0;ve<ce+1;ve++){let Ce=Ei(St,B(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:(se+ve*tt).toString(10)})),yt=(De!=null?De:0)+ve*it,_t=yt+it;Vt++,hi.push({time:{from:yt,to:_t},url:Ce})}se+=(ce+1)*tt,fi+=(ce+1)*it}vt=se/gt*1e3,mi=Ei(St,B(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:se.toString(10)}));let Ot={time:{from:vt,to:1/0},url:mi},Ae={type:"template",baseUrl:Ze,segmentTemplateUrl:St,initUrl:"",totalSegmentsDurationMs:fi,segments:hi,nextSegmentBeyondManifest:Ot,timescale:gt};li={id:$e,kind:"text",segmentReference:Ae,profiles:[],duration:S,bitrate:di,mime:"",codecs:"",width:0,height:0,isAuto:ci}}else li={id:$e,isAuto:ci,kind:"text",url:Ze}}else{let $e=(_s=(Os=U.getAttribute("contentType"))!=null?Os:Me==null?void 0:Me.split("/")[0])!=null?_s:Xi,ci=(Ns=(Fs=q.getAttribute("profiles"))==null?void 0:Fs.split(","))!=null?Ns:[],et=parseInt((Us=U.getAttribute("width"))!=null?Us:"",10),Ct=parseInt((qs=U.getAttribute("height"))!=null?qs:"",10),di=parseInt((js=U.getAttribute("bandwidth"))!=null?js:"",10)/1e3,pi=(Hs=U.getAttribute("frameRate"))!=null?Hs:"",gt=(Gs=U.getAttribute("quality"))!=null?Gs:void 0,Ji=pi?ju(pi):void 0,St=(zs=U.getAttribute("id"))!=null?zs:"id"+(k++).toString(10),hi=$e==="video"?`${Ct}p`:$e==="audio"?`${di}Kbps`:ui,fi=`${St}@${hi}`,mi=[...C,...Ul,...ci],vt,Vt=U.querySelector("SegmentBase"),se=(Qs=U.querySelector("SegmentTemplate"))!=null?Qs:jl;if(Vt){let Ae=(Ys=(Ws=U.querySelector("SegmentBase Initialization"))==null?void 0:Ws.getAttribute("range"))!=null?Ys:"",[me,tt]=Ae.split("-").map(Ce=>parseInt(Ce,10)),ce={from:me,to:tt},Be=(Ks=U.querySelector("SegmentBase"))==null?void 0:Ks.getAttribute("indexRange"),[it,De]=Be?Be.split("-").map(Ce=>parseInt(Ce,10)):[],ve=Be?{from:it,to:De}:void 0;vt={type:"byteRange",url:Ze,initRange:ce,indexRange:ve}}else if(se){let Ae={representationId:(Xs=U.getAttribute("id"))!=null?Xs:void 0,bandwidth:(Js=U.getAttribute("bandwidth"))!=null?Js:void 0},me=parseInt((Zs=se.getAttribute("timescale"))!=null?Zs:"",10),tt=(ea=se.getAttribute("initialization"))!=null?ea:"",ce=se.getAttribute("media"),Be=(ia=parseInt((ta=se.getAttribute("startNumber"))!=null?ta:"",10))!=null?ia:1,it=Ei(tt,Ae);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let De=(ra=se.querySelectorAll("SegmentTimeline S"))!=null?ra:[],ve=[],Ce=0,yt="",_t=0;if(De.length){let bi=Be,be=0;for(let Tt of De){let ye=parseInt((sa=Tt.getAttribute("d"))!=null?sa:"",10),rt=parseInt((aa=Tt.getAttribute("r"))!=null?aa:"",10)||0,gi=parseInt((na=Tt.getAttribute("t"))!=null?na:"",10);be=Number.isFinite(gi)?gi:be;let Zi=ye/me*1e3,er=be/me*1e3;for(let Si=0;Si<rt+1;Si++){let zl=Ei(ce,B(E({},Ae),{segmentNumber:bi.toString(10),segmentTime:(be+Si*ye).toString(10)})),la=(er!=null?er:0)+Si*Zi,Ql=la+Zi;bi++,ve.push({time:{from:la,to:Ql},url:zl})}be+=(rt+1)*ye,Ce+=(rt+1)*Zi}_t=be/me*1e3,yt=Ei(ce,B(E({},Ae),{segmentNumber:bi.toString(10),segmentTime:be.toString(10)}))}else if(fC(S)){let be=parseInt((oa=se.getAttribute("duration"))!=null?oa:"",10)/me*1e3,Tt=Math.ceil(S/be),ye=0;for(let rt=1;rt<Tt;rt++){let gi=Ei(ce,B(E({},Ae),{segmentNumber:rt.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:gi}),ye+=be}_t=ye,yt=Ei(ce,B(E({},Ae),{segmentNumber:Tt.toString(10),segmentTime:ye.toString(10)}))}let Gl={time:{from:_t,to:1/0},url:yt};vt={type:"template",baseUrl:Ze,segmentTemplateUrl:ce,initUrl:it,totalSegmentsDurationMs:Ce,segments:ve,nextSegmentBeyondManifest:Gl,timescale:me}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!$e||!Me)continue;let Ot={video:"video",audio:"audio",text:"text"}[$e];if(!Ot)continue;bt||(bt=Ot),li={id:fi,kind:Ot,segmentReference:vt,profiles:mi,duration:S,bitrate:di,mime:Me,codecs:ui,width:et,height:Ct,fps:Ji,quality:gt}}W.language||(W.language=Le),W.label||(W.label=Dt),W.mime||(W.mime=Me),W.codecs||(W.codecs=ui),W.hdr||(W.hdr=bt==="video"&&os(ui)),W.representations.push(li)}if(bt){let U=r[bt].find(Le=>Le.id===W.id);if(U&&W.representations.every(Le=>ut(Le.segmentReference)))for(let Le of U.representations){let Dt=W.representations.find(Me=>Me.id===Le.id),oi=Dt==null?void 0:Dt.segmentReference,Ze=Le.segmentReference;Ze.segments.push(...oi.segments),Ze.nextSegmentBeyondManifest=oi.nextSegmentBeyondManifest}else r[bt].push(W)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as KI}from"@vkontakte/videoplayer-shared/es2015";var z=(s,e)=>KI(s)&&KI(e)&&s.readyState==="open"&&mC(s,e);function mC(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var Pn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new vr(0);this.currentLowLatencySegmentLength$=new vr(0);this.currentSegmentLength$=new vr(0);this.onLastSegment$=new vr(!1);this.fullyBuffered$=new vr(!1);this.playingRepresentation$=new vr(void 0);this.playingRepresentationInit$=new vr(void 0);this.error$=new gC;this.gaps=[];this.subscription=new SC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new le;this.switchAbortController=new le;this.destroyAbortController=new le;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=qi(this.destroyAbortController.signal,function(e){return X(this,null,function*(){let t=this.representations.get(e);ft(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new KT(this.sourceBuffer),this.subscription.add(Dp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:wi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:wi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Dp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:wi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!z(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ss(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),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),a=this.parsedInitData.get(t.id);ft(i,"No init buffer for starting representation"),ft(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))})}.bind(this));this.switchTo=qi(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ft(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ke(a)||Ke(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ft(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();us(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new tr(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=qi(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ft(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ke(a)||Ke(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ft(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();us(n)&&(this.isLive||(this.bufferLimit=1/0,yield new tr(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=qi(this.destroyAbortController.signal,function(e){return X(this,null,function*(){var u,l;let t=(u=(0,zu.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!ut(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);ft(r);let a=this.segments.get(i);ft(a,"No segments for starting representation");let n=this.initData.get(i);if(ft(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],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}switchToWithPreviousAbort(e,t=!1){!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,qi(this.switchAbortController.signal,function(i,r=!1){return X(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);ft(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ke(o)||Ke(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),ft(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();us(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!Ke(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return x(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new le,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(Ke(e)||Ke(this.downloadingRepresentationId)||Ke(this.playingRepresentationId)||Ke(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||us(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(ft(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);us(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&ss(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Gu.default)(u,r))d="high";else{let c=(0,ls.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ls.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;us(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,zu.default)(e==null?void 0:e.streams[this.kind],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,a,n;let t=(i=(0,zu.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!ut(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>B(E({},p),{status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,ls.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ft(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!ut(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),d=Ei(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a: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&&ri&&ri(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ri&&ri(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:h,to:p}},f)=>{let m=h<=i&&p>=i,g=h>i||m||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+S||p<=i+S;return(c==="none"||c==="partially_ejected"&&g&&v&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(Ye(this.sourceBuffer.buffered,h)&&Ye(this.sourceBuffer.buffered,p)))&&g&&v});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,i="auto"){return x(this,null,function*(){ut(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return x(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:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield qi(o,function(){return X(this,null,function*(){let d=Cp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Hu(),!d)return;let c=new DataView(d),h=En(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),wn(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())ut(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return x(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:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield qi(n,function(){return X(this,null,function*(){let u=Cp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Dp(window,"online").pipe(bC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Hu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),wn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ut(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ls.default)(e,0).byte.from,to:(0,ls.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>x(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=Hu(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:wi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!ut(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Hu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:wi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Gu.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return x(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=En(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return x(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:d}=l;if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let c=d.byte.from-i,h=d.byte.to-i,p=h-c+1,f=c<r,m=h<=r;if(!f)continue;let g=En(u.mime);if(d.status==="downloading"&&m){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(S,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===p?S:g.parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(d.status="partially_fed",l.feedingBytes+=v.byteLength,(yield this.sourceBufferTaskQueue.append(v,a))&&!a.aborted?(l.fedBytes+=v.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!(Ke(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer))){!this.isLive&&G.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ye(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ye(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:wi.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Lp(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=rs(()=>(0,XI.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return x(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?qi(this.destroyAbortController.signal,function(){return X(this,null,function*(){let o=Cp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,En(e.mime),r)).then(o=>x(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&ut(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:wi.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return x(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 x(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ke(e))return!1;let r=[],a=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:h}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,h):l.push(u[d])}return l},o=u=>{var d;if(a>=t)return r;r.push(E({},u.time)),r=n(r);let l=Lp(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let h of this.segments.values())for(let p of h)(0,Gu.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let h={time:{from:l,to:d},url:"",status:"none"};o(h)}}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 d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1})}abortBuffer(){return x(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ke(e)?0:_e(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)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)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*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(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)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=rs(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:wi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ke(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||Ke(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),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:wi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ji=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Qu=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as An,assertNever as JI,fromEvent as ZI,merge as vC,now as kn,Subscription as yC,Subject as ex,ValueSubject as Vp,flattenObject as cs,ErrorCategory as Rn}from"@vkontakte/videoplayer-shared/es2015";var Wu=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var ds=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Vp(void 0);this.lastConnectionReused$=new Vp(void 0);this.lastRequestFirstBytes$=new Vp(void 0);this.recoverableError$=new ex;this.error$=new ex;this.abortAllController=new le;this.subscription=new yC;this.fetchManifest=An(this.abortAllController.signal,function(e){return X(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ji(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Wu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Yu);return r?(t.log("success",cs({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",cs({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=An(this.abortAllController.signal,function(l){return X(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var M,H;let d=e,c=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let N=new URL(d,location.href);N.searchParams.append("bytes",`${i.from}-${i.to}`),d=N.toString();break}default:JI(t)}this.requestQuic&&(d=ji(d));let p=this.abortAllController.signal,f;if(n){let N=new le;if(f=vC(ZI(this.abortAllController.signal,"abort"),ZI(n,"abort")).subscribe(()=>{try{N.abort()}catch(K){Yu(K)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(K){Yu(K)}p=N.signal}let m=kn();h.log("startRequest",cs({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(d,{priority:a,headers:c,signal:p}),S=kn();if(!g)return h.error("error",{message:"No response in request"}),h.end(),f==null||f.unsubscribe(),null;if((M=this.throughputEstimator)==null||M.addRawRtt(S-m),!g.ok||!g.body){f==null||f.unsubscribe();let N=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:N}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){f==null||f.unsubscribe();let N=kn(),K={requestStartedAt:m,requestEndedAt:N,duration:N-m};return h.log("endRequest",cs(K)),h.end(),g.arrayBuffer()}let[v,y]=g.body.tee(),T=v.getReader();o&&((H=this.throughputEstimator)==null||H.trackStream(y,u));let I=0,k=new Uint8Array(0),C=!1,V=N=>{f==null||f.unsubscribe(),C=!0,Yu(N)},D=An(p,function(A){return X(this,arguments,function*({done:N,value:K}){if(I===0&&this.lastRequestFirstBytes$.next(kn()-m),p.aborted){f==null||f.unsubscribe();return}if(!N&&K){let $=new Uint8Array(k.length+K.length);$.set(k),$.set(K,k.length),k=$,I+=K.byteLength,r==null||r(new DataView(k.buffer),I),yield T==null?void 0:T.read().then(D,V)}})}.bind(this));yield T==null?void 0:T.read().then(D,V),f==null||f.unsubscribe();let w=kn(),F={failed:C,requestStartedAt:m,requestEndedAt:w,duration:w-m};return C?(h.error("endRequest",cs(F)),h.end(),null):(h.log("endRequest",cs(F)),h.end(),k.buffer)})}.bind(this));this.fetchByteRangeRepresentation=An(this.abortAllController.signal,function(e,t,i){return X(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}})}.bind(this));this.fetchTemplateRepresentation=An(this.abortAllController.signal,function(e,t){return X(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=>B(E({},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"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Qu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return x(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:JI(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return x(this,null,function*(){let i=yield Mt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Rn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Rn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Rn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Rn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Rn.FATAL})}})}},Yu=s=>{if(!wn(s))throw s};var Pi=(s,e,t)=>t*e+(1-t)*s,Op=(s,e)=>s.reduce((t,i)=>t+i,0)/e,tx=(s,e,t,i)=>{let r=0,a=t,n=Op(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};import{isNullable as TC,ValueSubject as ix}from"@vkontakte/videoplayer-shared/es2015";var Hi=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 ix(e.initial),this.debounced$=new ix(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new nt(`raw_${t}`),this.smoothedSeries$=new nt(`smoothed_${t}`),this.reportedSeries$=new nt(`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+=st(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=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>a||this.smoothed<n)&&(TC(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 Ku=class extends Hi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Pi(this.slow,e,this.params.emaAlphaSlow),this.fast=Pi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Xu=class extends Hi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Op(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Pi(this.emaSmoothed,e,this.params.emaAlpha);let i=tx(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ju=class extends Hi{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?Pi(this.smoothed,t,this.params.emaAlpha):t}};var Ai=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ku({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Xu({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Ju(E({initial:e,label:"liveEdgeDelay"},t))}};var ps=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as IC,ValueSubject as xC}from"@vkontakte/videoplayer-shared/es2015";var Ln=class s{constructor(e,t){this.currentRepresentation$=new xC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!IC(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(B(E({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ut(t.segmentReference))}};var el=j(jt(),1);import{assertNever as tl}from"@vkontakte/videoplayer-shared/es2015";var rx=(s,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:a,codecs:n,nativeHlsSupported:o}=G.video,u=(n.h264||n.h265)&&n.aac,l=a.mse&&(!i||!!window.MediaStreamTrack)||a.mms&&t;return s.filter(d=>{switch(d){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return a.webrtc&&a.ws&&n.h264&&(r.mp4||r.webm);default:return tl(d)}})},Zu=s=>{let{webmDecodingInfo:e}=G.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:tl(s)}return[t,i]},sx=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Zu(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(G.device.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",...Zu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Zu(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Zu(s),...r,"HLS","HLS_ONDEMAND"];default:tl(e)}return G.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},ax=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=G.device.isMac&&G.browser.isSafari;if(G.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:tl(s)}else G.video.nativeHlsSupported&&!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=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},_p=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],il=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,el.default)(t.value.split("."),0)}for(let t of s){let i=(0,el.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,el.default)(e.value.split("."),0)};var MC=["timeupdate","progress","play","seeked","stalled","waiting"],$C=["timeupdate","progress","loadeddata","playing","seeked"];var al=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new ux;this.representationSubscription=new ux;this.state$=new Q("none");this.currentVideoRepresentation$=new ge(void 0);this.currentVideoRepresentationInit$=new ge(void 0);this.currentAudioRepresentation$=new ge(void 0);this.currentVideoSegmentLength$=new ge(0);this.currentAudioSegmentLength$=new ge(0);this.error$=new sl;this.lastConnectionType$=new ge(void 0);this.lastConnectionReused$=new ge(void 0);this.lastRequestFirstBytes$=new ge(void 0);this.currentLiveTextRepresentation$=new ge(null);this.isLive$=new ge(!1);this.isActiveLive$=new ge(!1);this.isLowLatency$=new ge(!1);this.liveDuration$=new ge(0);this.liveSeekableDuration$=new ge(0);this.liveAvailabilityStartTime$=new ge(0);this.liveStreamStatus$=new ge(void 0);this.bufferLength$=new ge(0);this.liveLatency$=new ge(void 0);this.liveLoadBufferLength$=new ge(0);this.livePositionFromPlayer$=new ge(0);this.currentStallDuration$=new ge(0);this.videoLastDataObtainedTimestamp$=new ge(0);this.fetcherRecoverableError$=new sl;this.fetcherError$=new sl;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new sl;this.gapWatchdogActive=!1;this.destroyController=new le;this.initManifest=Np(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ie(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:Gt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Np(this.destroyController.signal,function(){return X(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:Gt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=YI(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=qu(e))!=null?n:{id:"ManifestParsing",category:Gt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=At())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=il(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);G.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a=B(E({},t),{streams:r});return this.tracer.log("updateManifestEnd",$n(a)),a})}.bind(this));this.initRepresentations=Np(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",$n({initialVideo:e,initialAudio:t,sourceHls:i})),hs(this.manifest),hs(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(ki(p,"error").pipe(rl(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Gt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?Su():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Yr())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.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new Pn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Bn(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new Pn("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ln.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ln(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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(yr(...$C.map(p=>ki(this.element,p))).pipe(ms(p=>this.element?_e(this.element.buffered,this.element.currentTime*1e3):0),Mn(),RC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(yr(ki(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Mn()).subscribe(f=>this.liveStreamEndTimestamp=qp())),this.subscription.add(ki(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Up(1e3).subscribe(f=>{let m=Oi(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ki(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(fs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ms(({isActiveLive:f,isLowLatency:m})=>f&&m),Mn()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ps(this.element,1)})),this.representationSubscription.add(fs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(rl(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(fs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(rl(({isLive:f})=>f),Mn((f,m)=>m.bufferLength<f.bufferLength),ms(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Oi(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(fs({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=f-S;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(T)>v&&(I=1+Math.sign(T)*y),ps(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var I,k;return(k=(I=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?k:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(fs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(LC(1e3)).subscribe(g=>x(this,[g],function*({liveLoadBufferLength:f,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=Oi(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,C=isFinite(f)?f:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),D=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(D);let w="none";if(V?w="active_low_latency":this.isLowLatency$.getValue()&&D?(this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),w="active_low_latency"):v!==0&&C<T?w="live_forward_buffering":C<T+k&&(w="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let F=p-(T+I),M=this.normolizeLiveOffset(Math.trunc(v+F/S)),H=Math.abs(M-v),N=0;!f||H<=this.tuning.dashCmafLive.offsetCalculationError?N=v:M>0&&H>this.tuning.dashCmafLive.offsetCalculationError&&(N=M),this.manifestUrlString=Ie(this.manifestUrlString,N,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,yield this.updateLive())}),f=>{this.error$.next({id:"updateLive",category:Gt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=yr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ms(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=yr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ms(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=fs({allBuffersFull:l,someBufferEnded:d}).pipe(Mn(),ms(({allBuffersFull:p,someBufferEnded:f})=>p&&f),rl(p=>p));if(this.representationSubscription.add(yr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Gt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(yr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category:Gt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,jp.default)((0,jp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),ut(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Bn(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,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Up(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Gt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ds({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ai.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return x(this,null,function*(){var r,a,n;hs(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?qp()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ie(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){hs(this.element),this.state$.setState("running"),this.subscription.add(yr(...MC.map(e=>ki(this.element,e)),ki(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Gt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ki(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ki(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ye(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,m,g,S,v,y,T,I,k,C;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=qp(),n=100,o=(m=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(y=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?y:0,d=(I=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?I:0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let V=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(V).catch(D=>{this.error$.next({id:"stallIntervalCallback",category:Gt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:D})}),r.liveLastOffset=V}else{let V=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(V),(C=this.audioBufferManager)==null||C.maintain(V),r.position=V}this.tracer.log("stallIntervalCallback",$n(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Up(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Gt.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return x(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return x(this,null,function*(){var r,a,n,o,u;hs(this.element),hs(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=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ye(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(ox(this.element)||ox(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",$n({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Bn(this.element)&&Bn(this.source)&&Bn(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),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.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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=kC(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return x(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=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i=B(E({},i),{gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",$n(i)))}}};var nl=class{constructor(e,t){this.fov=e,this.orientation=t}};var ol=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/st(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,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:a,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=E({},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*st(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 cx=`attribute vec2 a_vertex;
|
|
124
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Tp=H(qt(),1);import{videoSizeToQuality as aC}from"@vkontakte/videoplayer-shared/es2015";var CI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Oi(a):void 0)!=null?u:aC({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},VI=({id:s,bitrate:e})=>({id:s,bitrate:e}),OI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),_I=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ip=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Tp.default)(i.split("."),0),isDefault:r}),xp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Tp.default)(r.split("."),0)}),Ep=s=>"url"in s,rt=s=>s.type==="template",Tn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var NI=s=>{if(!(s!=null&&s.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(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={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 a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Ii=(s,e)=>{let t=s;t=(0,wp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,UI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,wp.default)(t,n,(o,u)=>FI(a)?o:FI(u)?a:(0,qI.default)(a,parseInt(u,10),"0"))}return t},HI=(s,e)=>{var $,w,F,M,j,N,K,P,L,R,A,O,de,Fe,ue,ee,Ee,we,Ae,Ne,At,Lt,Gt,ii,Li,Is,xs,Es,ws,As,Ps,ks,Rs,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks,Xs,Js,Zs,ea,ta,ia,ra;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(fe=>{var q,Ge;return(Ge=(q=fe.textContent)==null?void 0:q.trim())!=null?Ge:""}),o=($=(0,jI.default)(n,0))!=null?$:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],T=y.reduce((fe,q)=>B(x({},fe),{[q.id]:q.children}),{}),I=y.reduce((fe,q)=>B(x({},fe),{[q.id]:q.getAttribute("duration")}),{});v?S=NI(v):(0,Ap.default)(I).filter(fe=>fe).length&&!u?S=(0,Ap.default)(I).reduce((fe,q)=>{var Ge;return fe+((Ge=NI(q))!=null?Ge:0)},0):m&&(S=parseInt(m,10));let k=0,C=(F=(w=a.getAttribute("profiles"))==null?void 0:w.split(","))!=null?F:[];for(let fe of y.map(q=>q.id))for(let q of T[fe]){let Ge=(M=q.getAttribute("id"))!=null?M:"id"+(k++).toString(10),Bt=(j=q.getAttribute("mimeType"))!=null?j:"",Wi=(N=q.getAttribute("codecs"))!=null?N:"",Yi=(K=q.getAttribute("contentType"))!=null?K:Bt==null?void 0:Bt.split("/")[0],Cl=(L=(P=q.getAttribute("profiles"))==null?void 0:P.split(","))!=null?L:[],sa=(A=DI((R=q.getAttribute("lang"))!=null?R:""))!=null?A:{},ri=(Fe=(de=(O=q.querySelector("Label"))==null?void 0:O.textContent)==null?void 0:de.trim())!=null?Fe:void 0,Vl=q.querySelectorAll("Representation"),Ol=q.querySelector("SegmentTemplate"),_l=(ee=(ue=q.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?ee:void 0,ht=Yi,G={id:Ge,language:sa.language,isDefault:_l==="main",label:ri,codecs:Wi,hdr:ht==="video"&&as(Wi),mime:Bt,representations:[]};for(let U of Vl){let Re=(Ee=U.getAttribute("lang"))!=null?Ee:void 0,$t=(Ae=(we=ri!=null?ri:q.getAttribute("label"))!=null?we:U.getAttribute("label"))!=null?Ae:void 0,si=(Lt=(At=(Ne=U.querySelector("BaseURL"))==null?void 0:Ne.textContent)==null?void 0:At.trim())!=null?Lt:"",We=new URL(si||o,e).toString(),Me=(Gt=U.getAttribute("mimeType"))!=null?Gt:Bt,ai=(Li=(ii=U.getAttribute("codecs"))!=null?ii:Wi)!=null?Li:"",ni;if(Yi==="text"){let Le=U.getAttribute("id")||"",oi=((Is=sa.privateuse)==null?void 0:Is.includes("x-auto"))||Le.includes("_auto"),Ye=U.querySelector("SegmentTemplate");if(Ye){let Dt={representationId:(xs=U.getAttribute("id"))!=null?xs:void 0,bandwidth:(Es=U.getAttribute("bandwidth"))!=null?Es:void 0},ui=parseInt((ws=U.getAttribute("bandwidth"))!=null?ws:"",10)/1e3,li=(Ps=parseInt((As=Ye.getAttribute("startNumber"))!=null?As:"",10))!=null?Ps:1,ft=parseInt((ks=Ye.getAttribute("timescale"))!=null?ks:"",10),Ki=(Rs=Ye.querySelectorAll("SegmentTimeline S"))!=null?Rs:[],mt=Ye.getAttribute("media");if(!mt)continue;let ci=[],di=0,pi="",bt=0,Ct=li,se=0;for(let me of Ki){let Ke=parseInt((Ms=me.getAttribute("d"))!=null?Ms:"",10),ce=parseInt((Ls=me.getAttribute("r"))!=null?Ls:"",10)||0,Be=parseInt((Bs=me.getAttribute("t"))!=null?Bs:"",10);se=Number.isFinite(Be)?Be:se;let Xe=Ke/ft*1e3,$e=se/ft*1e3;for(let ve=0;ve<ce+1;ve++){let De=Ii(mt,B(x({},Dt),{segmentNumber:Ct.toString(10),segmentTime:(se+ve*Ke).toString(10)})),gt=($e!=null?$e:0)+ve*Xe,Ot=gt+Xe;Ct++,ci.push({time:{from:gt,to:Ot},url:De})}se+=(ce+1)*Ke,di+=(ce+1)*Xe}bt=se/ft*1e3,pi=Ii(mt,B(x({},Dt),{segmentNumber:Ct.toString(10),segmentTime:se.toString(10)}));let Vt={time:{from:bt,to:1/0},url:pi},Pe={type:"template",baseUrl:We,segmentTemplateUrl:mt,initUrl:"",totalSegmentsDurationMs:di,segments:ci,nextSegmentBeyondManifest:Vt,timescale:ft};ni={id:Le,kind:"text",segmentReference:Pe,profiles:[],duration:S,bitrate:ui,mime:"",codecs:"",width:0,height:0,isAuto:oi}}else ni={id:Le,isAuto:oi,kind:"text",url:We}}else{let Le=(Ds=($s=U.getAttribute("contentType"))!=null?$s:Me==null?void 0:Me.split("/")[0])!=null?Ds:Yi,oi=(Vs=(Cs=q.getAttribute("profiles"))==null?void 0:Cs.split(","))!=null?Vs:[],Ye=parseInt((Os=U.getAttribute("width"))!=null?Os:"",10),Dt=parseInt((_s=U.getAttribute("height"))!=null?_s:"",10),ui=parseInt((Fs=U.getAttribute("bandwidth"))!=null?Fs:"",10)/1e3,li=(Ns=U.getAttribute("frameRate"))!=null?Ns:"",ft=(Us=U.getAttribute("quality"))!=null?Us:void 0,Ki=li?_u(li):void 0,mt=(qs=U.getAttribute("id"))!=null?qs:"id"+(k++).toString(10),ci=Le==="video"?`${Dt}p`:Le==="audio"?`${ui}Kbps`:ai,di=`${mt}@${ci}`,pi=[...C,...Cl,...oi],bt,Ct=U.querySelector("SegmentBase"),se=(js=U.querySelector("SegmentTemplate"))!=null?js:Ol;if(Ct){let Pe=(zs=(Hs=U.querySelector("SegmentBase Initialization"))==null?void 0:Hs.getAttribute("range"))!=null?zs:"",[me,Ke]=Pe.split("-").map(De=>parseInt(De,10)),ce={from:me,to:Ke},Be=(Qs=U.querySelector("SegmentBase"))==null?void 0:Qs.getAttribute("indexRange"),[Xe,$e]=Be?Be.split("-").map(De=>parseInt(De,10)):[],ve=Be?{from:Xe,to:$e}:void 0;bt={type:"byteRange",url:We,initRange:ce,indexRange:ve}}else if(se){let Pe={representationId:(Gs=U.getAttribute("id"))!=null?Gs:void 0,bandwidth:(Ws=U.getAttribute("bandwidth"))!=null?Ws:void 0},me=parseInt((Ys=se.getAttribute("timescale"))!=null?Ys:"",10),Ke=(Ks=se.getAttribute("initialization"))!=null?Ks:"",ce=se.getAttribute("media"),Be=(Js=parseInt((Xs=se.getAttribute("startNumber"))!=null?Xs:"",10))!=null?Js:1,Xe=Ii(Ke,Pe);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let $e=(Zs=se.querySelectorAll("SegmentTimeline S"))!=null?Zs:[],ve=[],De=0,gt="",Ot=0;if($e.length){let hi=Be,be=0;for(let St of $e){let ye=parseInt((ea=St.getAttribute("d"))!=null?ea:"",10),Je=parseInt((ta=St.getAttribute("r"))!=null?ta:"",10)||0,fi=parseInt((ia=St.getAttribute("t"))!=null?ia:"",10);be=Number.isFinite(fi)?fi:be;let Xi=ye/me*1e3,Ji=be/me*1e3;for(let mi=0;mi<Je+1;mi++){let Nl=Ii(ce,B(x({},Pe),{segmentNumber:hi.toString(10),segmentTime:(be+mi*ye).toString(10)})),aa=(Ji!=null?Ji:0)+mi*Xi,Ul=aa+Xi;hi++,ve.push({time:{from:aa,to:Ul},url:Nl})}be+=(Je+1)*ye,De+=(Je+1)*Xi}Ot=be/me*1e3,gt=Ii(ce,B(x({},Pe),{segmentNumber:hi.toString(10),segmentTime:be.toString(10)}))}else if(nC(S)){let be=parseInt((ra=se.getAttribute("duration"))!=null?ra:"",10)/me*1e3,St=Math.ceil(S/be),ye=0;for(let Je=1;Je<St;Je++){let fi=Ii(ce,B(x({},Pe),{segmentNumber:Je.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:fi}),ye+=be}Ot=ye,gt=Ii(ce,B(x({},Pe),{segmentNumber:St.toString(10),segmentTime:ye.toString(10)}))}let Fl={time:{from:Ot,to:1/0},url:gt};bt={type:"template",baseUrl:We,segmentTemplateUrl:ce,initUrl:Xe,totalSegmentsDurationMs:De,segments:ve,nextSegmentBeyondManifest:Fl,timescale:me}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Le||!Me)continue;let Vt={video:"video",audio:"audio",text:"text"}[Le];if(!Vt)continue;ht||(ht=Vt),ni={id:di,kind:Vt,segmentReference:bt,profiles:pi,duration:S,bitrate:ui,mime:Me,codecs:ai,width:Ye,height:Dt,fps:Ki,quality:ft}}G.language||(G.language=Re),G.label||(G.label=$t),G.mime||(G.mime=Me),G.codecs||(G.codecs=ai),G.hdr||(G.hdr=ht==="video"&&as(ai)),G.representations.push(ni)}if(ht){let U=r[ht].find(Re=>Re.id===G.id);if(U&&G.representations.every(Re=>rt(Re.segmentReference)))for(let Re of U.representations){let $t=G.representations.find(Me=>Me.id===Re.id),si=$t==null?void 0:$t.segmentReference,We=Re.segmentReference;We.segments.push(...si.segments),We.nextSegmentBeyondManifest=si.nextSegmentBeyondManifest}else r[ht].push(G)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as zI}from"@vkontakte/videoplayer-shared/es2015";var z=(s,e)=>zI(s)&&zI(e)&&s.readyState==="open"&&oC(s,e);function oC(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var In=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new gr(0);this.currentLowLatencySegmentLength$=new gr(0);this.currentSegmentLength$=new gr(0);this.onLastSegment$=new gr(!1);this.fullyBuffered$=new gr(!1);this.playingRepresentation$=new gr(void 0);this.playingRepresentationInit$=new gr(void 0);this.error$=new lC;this.gaps=[];this.subscription=new cC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new le;this.switchAbortController=new le;this.destroyAbortController=new le;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Ni(this.destroyAbortController.signal,function(e){return X(this,null,function*(){let t=this.representations.get(e);dt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new zT(this.sourceBuffer),this.subscription.add(kp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:xi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:xi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(kp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:xi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!z(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,is(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),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),a=this.parsedInitData.get(t.id);dt(i,"No init buffer for starting representation"),dt(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))})}.bind(this));this.switchTo=Ni(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);dt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ze(a)||ze(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),dt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ns(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Zi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Ni(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);dt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ze(a)||ze(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),dt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ns(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Zi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Ni(this.destroyAbortController.signal,function(e){return X(this,null,function*(){var u,l;let t=(u=(0,Uu.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!rt(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);dt(r);let a=this.segments.get(i);dt(a,"No segments for starting representation");let n=this.initData.get(i);if(dt(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],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}switchToWithPreviousAbort(e,t=!1){!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,Ni(this.switchAbortController.signal,function(i,r=!1){return X(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);dt(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ze(o)||ze(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),dt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ns(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!ze(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return E(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new le,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(ze(e)||ze(this.downloadingRepresentationId)||ze(this.playingRepresentationId)||ze(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||ns(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(dt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ns(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&is(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Nu.default)(u,r))d="high";else{let c=(0,os.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,os.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;ns(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Uu.default)(e==null?void 0:e.streams[this.kind],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,a,n;let t=(i=(0,Uu.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!rt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>B(x({},p),{status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,os.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;dt(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!rt(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),d=Ii(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a: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&&ei&&ei(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ei&&ei(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:h,to:p}},f)=>{let m=h<=i&&p>=i,g=h>i||m||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+S||p<=i+S;return(c==="none"||c==="partially_ejected"&&g&&v&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(He(this.sourceBuffer.buffered,h)&&He(this.sourceBuffer.buffered,p)))&&g&&v});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,i="auto"){return E(this,null,function*(){rt(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return E(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:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Ni(o,function(){return X(this,null,function*(){let d=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Fu(),!d)return;let c=new DataView(d),h=yn(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Tn(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())rt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return E(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:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Ni(n,function(){return X(this,null,function*(){let u=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),kp(window,"online").pipe(uC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Fu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Tn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,os.default)(e,0).byte.from,to:(0,os.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>E(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=Fu(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:xi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!rt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Fu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:xi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Nu.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return E(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=yn(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return E(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:d}=l;if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let c=d.byte.from-i,h=d.byte.to-i,p=h-c+1,f=c<r,m=h<=r;if(!f)continue;let g=yn(u.mime);if(d.status==="downloading"&&m){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(S,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===p?S:g.parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(d.status="partially_fed",l.feedingBytes+=v.byteLength,(yield this.sourceBufferTaskQueue.append(v,a))&&!a.aborted?(l.fedBytes+=v.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!(ze(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer))){!this.isLive&&Q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(He(this.sourceBuffer.buffered,e.segment.time.from,100)&&He(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:xi.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ep(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=ts(()=>(0,QI.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return E(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Ni(this.destroyAbortController.signal,function(){return X(this,null,function*(){let o=Rp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,yn(e.mime),r)).then(o=>E(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&rt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:xi.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return E(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 E(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ze(e))return!1;let r=[],a=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:h}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,h):l.push(u[d])}return l},o=u=>{var d;if(a>=t)return r;r.push(x({},u.time)),r=n(r);let l=Ep(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let h of this.segments.values())for(let p of h)(0,Nu.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let h={time:{from:l,to:d},url:"",status:"none"};o(h)}}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 d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1})}abortBuffer(){return E(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ze(e)?0:Oe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)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)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*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(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)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=ts(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:xi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ze(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||ze(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),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:xi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ui=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var qu=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as xn,assertNever as GI,fromEvent as WI,merge as dC,now as En,Subscription as pC,Subject as YI,ValueSubject as Mp,flattenObject as us,ErrorCategory as wn}from"@vkontakte/videoplayer-shared/es2015";var ju=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var zu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Mp(void 0);this.lastConnectionReused$=new Mp(void 0);this.lastRequestFirstBytes$=new Mp(void 0);this.recoverableError$=new YI;this.error$=new YI;this.abortAllController=new le;this.subscription=new pC;this.fetchManifest=xn(this.abortAllController.signal,function(e){return X(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ui(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ju(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Hu);return r?(t.log("success",us({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",us({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=xn(this.abortAllController.signal,function(l){return X(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var M,j;let d=e,c=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let N=new URL(d,location.href);N.searchParams.append("bytes",`${i.from}-${i.to}`),d=N.toString();break}default:GI(t)}this.requestQuic&&(d=Ui(d));let p=this.abortAllController.signal,f;if(n){let N=new le;if(f=dC(WI(this.abortAllController.signal,"abort"),WI(n,"abort")).subscribe(()=>{try{N.abort()}catch(K){Hu(K)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(K){Hu(K)}p=N.signal}let m=En();h.log("startRequest",us({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(d,{priority:a,headers:c,signal:p}),S=En();if(!g)return h.error("error",{message:"No response in request"}),h.end(),f==null||f.unsubscribe(),null;if((M=this.throughputEstimator)==null||M.addRawRtt(S-m),!g.ok||!g.body){f==null||f.unsubscribe();let N=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:N}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){f==null||f.unsubscribe();let N=En(),K={requestStartedAt:m,requestEndedAt:N,duration:N-m};return h.log("endRequest",us(K)),h.end(),g.arrayBuffer()}let[v,y]=g.body.tee(),T=v.getReader();o&&((j=this.throughputEstimator)==null||j.trackStream(y,u));let I=0,k=new Uint8Array(0),C=!1,V=N=>{f==null||f.unsubscribe(),C=!0,Hu(N)},$=xn(p,function(P){return X(this,arguments,function*({done:N,value:K}){if(I===0&&this.lastRequestFirstBytes$.next(En()-m),p.aborted){f==null||f.unsubscribe();return}if(!N&&K){let L=new Uint8Array(k.length+K.length);L.set(k),L.set(K,k.length),k=L,I+=K.byteLength,r==null||r(new DataView(k.buffer),I),yield T==null?void 0:T.read().then($,V)}})}.bind(this));yield T==null?void 0:T.read().then($,V),f==null||f.unsubscribe();let w=En(),F={failed:C,requestStartedAt:m,requestEndedAt:w,duration:w-m};return C?(h.error("endRequest",us(F)),h.end(),null):(h.log("endRequest",us(F)),h.end(),k.buffer)})}.bind(this));this.fetchByteRangeRepresentation=xn(this.abortAllController.signal,function(e,t,i){return X(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}})}.bind(this));this.fetchTemplateRepresentation=xn(this.abortAllController.signal,function(e,t){return X(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=>B(x({},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"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=qu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return E(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:GI(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return E(this,null,function*(){let i=yield Mt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:wn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:wn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:wn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:wn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:wn.FATAL})}})}},Hu=s=>{if(!Tn(s))throw s};var Ei=(s,e,t)=>t*e+(1-t)*s,Lp=(s,e)=>s.reduce((t,i)=>t+i,0)/e,KI=(s,e,t,i)=>{let r=0,a=t,n=Lp(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};import{isNullable as hC,ValueSubject as XI}from"@vkontakte/videoplayer-shared/es2015";var qi=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 XI(e.initial),this.debounced$=new XI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new tt(`raw_${t}`),this.smoothedSeries$=new tt(`smoothed_${t}`),this.reportedSeries$=new tt(`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+=Ze(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=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>a||this.smoothed<n)&&(hC(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 Qu=class extends qi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ei(this.slow,e,this.params.emaAlphaSlow),this.fast=Ei(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Gu=class extends qi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Lp(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ei(this.emaSmoothed,e,this.params.emaAlpha);let i=KI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Wu=class extends qi{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?Ei(this.smoothed,t,this.params.emaAlpha):t}};var wi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Qu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Gu({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Wu(x({initial:e,label:"liveEdgeDelay"},t))}};var ls=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as fC,ValueSubject as mC}from"@vkontakte/videoplayer-shared/es2015";var An=class s{constructor(e,t){this.currentRepresentation$=new mC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!fC(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(B(x({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var Ku=H(qt(),1);import{assertNever as Xu}from"@vkontakte/videoplayer-shared/es2015";var JI=(s,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:a,nativeHlsSupported:n}=Q.video,o=(a.h264||a.h265)&&a.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return s.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&a.vp9&&a.opus;case"DASH_WEBM_AV1":return u&&i.webm&&a.av1&&a.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(a.vp9||a.av1)&&(a.opus||a.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&a.h264&&(i.mp4||i.webm);default:return Xu(l)}})},Yu=s=>{let{webmDecodingInfo:e}=Q.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Xu(s)}return[t,i]},ZI=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Yu(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Q.device.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",...Yu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Yu(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Yu(s),...r,"HLS","HLS_ONDEMAND"];default:Xu(e)}return Q.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},ex=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=Q.device.isMac&&Q.browser.isSafari;if(Q.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:Xu(s)}else Q.video.nativeHlsSupported&&!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=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Bp=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ju=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Ku.default)(t.value.split("."),0)}for(let t of s){let i=(0,Ku.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Ku.default)(e.value.split("."),0)};var xC=["timeupdate","progress","play","seeked","stalled","waiting"],EC=["timeupdate","progress","loadeddata","playing","seeked"];var tl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new rx;this.representationSubscription=new rx;this.state$=new Y("none");this.currentVideoRepresentation$=new ge(void 0);this.currentVideoRepresentationInit$=new ge(void 0);this.currentAudioRepresentation$=new ge(void 0);this.currentVideoSegmentLength$=new ge(0);this.currentAudioSegmentLength$=new ge(0);this.error$=new el;this.lastConnectionType$=new ge(void 0);this.lastConnectionReused$=new ge(void 0);this.lastRequestFirstBytes$=new ge(void 0);this.currentLiveTextRepresentation$=new ge(null);this.isLive$=new ge(!1);this.isActiveLive$=new ge(!1);this.isLowLatency$=new ge(!1);this.liveDuration$=new ge(0);this.liveSeekableDuration$=new ge(0);this.liveAvailabilityStartTime$=new ge(0);this.liveStreamStatus$=new ge(void 0);this.bufferLength$=new ge(0);this.liveLatency$=new ge(void 0);this.liveLoadBufferLength$=new ge(0);this.livePositionFromPlayer$=new ge(0);this.currentStallDuration$=new ge(0);this.videoLastDataObtainedTimestamp$=new ge(0);this.fetcherRecoverableError$=new el;this.fetcherError$=new el;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new el;this.gapWatchdogActive=!1;this.destroyController=new le;this.initManifest=Dp(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ie(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:Ht.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Dp(this.destroyController.signal,function(){return X(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:Ht.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=HI(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Ou(e))!=null?n:{id:"ManifestParsing",category:Ht.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=Et())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=Ju(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);Q.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a=B(x({},t),{streams:r});return this.tracer.log("updateManifestEnd",kn(a)),a})}.bind(this));this.initRepresentations=Dp(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",kn({initialVideo:e,initialAudio:t,sourceHls:i})),cs(this.manifest),cs(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Ai(p,"error").pipe(Zu(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Ht.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?hu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Gr())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.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new In("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Rn(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new In("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}An.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new An(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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Sr(...EC.map(p=>Ai(this.element,p))).pipe(ps(p=>this.element?Oe(this.element.buffered,this.element.currentTime*1e3):0),Pn(),TC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Sr(Ai(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Pn()).subscribe(f=>this.liveStreamEndTimestamp=Vp())),this.subscription.add(Ai(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Cp(1e3).subscribe(f=>{let m=Ci(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ai(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(ds({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ps(({isActiveLive:f,isLowLatency:m})=>f&&m),Pn()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add(ds({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Zu(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(ds({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Zu(({isLive:f})=>f),Pn((f,m)=>m.bufferLength<f.bufferLength),ps(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Ci(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ds({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=f-S;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(T)>v&&(I=1+Math.sign(T)*y),ls(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var I,k;return(k=(I=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?k:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(ds({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(IC(1e3)).subscribe(g=>E(this,[g],function*({liveLoadBufferLength:f,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=Ci(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,C=isFinite(f)?f:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(V?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),w="active_low_latency"):v!==0&&C<T?w="live_forward_buffering":C<T+k&&(w="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let F=p-(T+I),M=this.normolizeLiveOffset(Math.trunc(v+F/S)),j=Math.abs(M-v),N=0;!f||j<=this.tuning.dashCmafLive.offsetCalculationError?N=v:M>0&&j>this.tuning.dashCmafLive.offsetCalculationError&&(N=M),this.manifestUrlString=Ie(this.manifestUrlString,N,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,yield this.updateLive())}),f=>{this.error$.next({id:"updateLive",category:Ht.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=Sr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ps(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Sr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ps(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=ds({allBuffersFull:l,someBufferEnded:d}).pipe(Pn(),ps(({allBuffersFull:p,someBufferEnded:f})=>p&&f),Zu(p=>p));if(this.representationSubscription.add(Sr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Ht.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(Sr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category:Ht.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,Op.default)((0,Op.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),rt(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Rn(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,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Cp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Ht.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new zu({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=wi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,x({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return E(this,null,function*(){var r,a,n;cs(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Vp()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ie(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){cs(this.element),this.state$.setState("running"),this.subscription.add(Sr(...xC.map(e=>Ai(this.element,e)),Ai(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ht.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ai(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ai(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&He(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,m,g,S,v,y,T,I,k,C;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=Vp(),n=100,o=(m=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(y=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?y:0,d=(I=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?I:0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let V=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(V).catch($=>{this.error$.next({id:"stallIntervalCallback",category:Ht.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:$})}),r.liveLastOffset=V}else{let V=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(V),(C=this.audioBufferManager)==null||C.maintain(V),r.position=V}this.tracer.log("stallIntervalCallback",kn(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Cp(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Ht.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return E(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return E(this,null,function*(){var r,a,n,o,u;cs(this.element),cs(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=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),He(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(ix(this.element)||ix(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",kn({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Rn(this.element)&&Rn(this.source)&&Rn(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),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.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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=yC(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return E(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=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i=B(x({},i),{gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",kn(i)))}}};var il=class{constructor(e,t){this.fov=e,this.orientation=t}};var rl=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/Ze(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,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:a,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=x({},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*Ze(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 ax=`attribute vec2 a_vertex;
|
|
125
125
|
attribute vec2 a_texel;
|
|
126
126
|
|
|
127
127
|
varying vec2 v_texel;
|
|
@@ -132,7 +132,7 @@ void main(void) {
|
|
|
132
132
|
// save texel vector to pass to fragment shader
|
|
133
133
|
v_texel = a_texel;
|
|
134
134
|
}
|
|
135
|
-
`;var
|
|
135
|
+
`;var nx=`#ifdef GL_ES
|
|
136
136
|
precision highp float;
|
|
137
137
|
precision highp int;
|
|
138
138
|
#else
|
|
@@ -175,13 +175,13 @@ void main(void) {
|
|
|
175
175
|
// sample using new coordinates
|
|
176
176
|
gl_FragColor = texture2D(u_texture, tc);
|
|
177
177
|
}
|
|
178
|
-
`;var bs=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 nl(this.params.fov,this.params.orientation),this.cameraRotationManager=new ol(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(cx,this.gl.VERTEX_SHADER),i=this.createShader(dx,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,h=t+r;return[a,n,o,u,l,d,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as CC,now as Dn,once as VC,Subscription as OC,ValueSubject as Hp,isNonNullable as _C,safeStorage as Gp,filterChanged as FC}from"@vkontakte/videoplayer-shared/es2015";var ul="stalls_manager_metrics",zp="stalls_manager_abr_params",px="stalls_manager_default_tuning_abr_params",Qp=class{constructor(){this.isSeeked$=new Hp(!1);this.isBuffering$=new Hp(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new OC;this.severeStallOccurred$=new Hp(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(zp):{};return E(E({},this.abrParams),e)}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Dn(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Dn()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}=E({},this.getStoredData(px)),{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}=E({},this.abrParams);this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(zp),this.setStoredData(px,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(ul,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;if(this.tuning.useTotalStallsDurationPerTvt){let r=t.reduce((o,u)=>o+u.tvt,0),n=t.reduce((o,u)=>o+u.stallsDuration,0)/r;e.push(this.calculateOptimalAbrParams(n))}if(this.tuning.useAverageStallsDurationPerTvt){let r=t.reduce((a,n)=>a+n.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(r))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed));let i={bitrateFactorAtEmptyBuffer:Math.max(...e.map(r=>r.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(r=>r.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(r=>r.containerSizeFactor))};this.setStoredData(ul,[]),this.setStoredData(zp,i)}calculateOptimalAbrParams(e){let{targetStallsDurationPerTvt:t,deviationStallsDurationPerTvt:i,criticalStallsDurationPerTvt:r,abrAdjustingSpeed:a}=this.tuning,n=this.abrTuningParams;return e<t-i?n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer-a,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer-a,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor+a,this.abrParams.maxContainerSizeFactor)}:e>t+i&&(n={bitrateFactorAtEmptyBuffer:Math.min(n.bitrateFactorAtEmptyBuffer+a,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(n.bitrateFactorAtFullBuffer+a,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(n.containerSizeFactor-a,this.abrParams.minContainerSizeFactor)}),e>r&&(n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor,this.abrParams.containerSizeFactor)}),n}getStoredData(e,t="{}"){var i;return JSON.parse((i=Gp.get(e))!=null?i:t)}setStoredData(e,t){Gp.set(e,JSON.stringify(t))}removeStoredData(e){Gp.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(ul,"[]"),r=t/e,a=i.length?Pi(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(ul,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(VC()).subscribe(t=>this.providerStartWatchingTimestamp=Dn())),this.subscription.add(this.currentStallDuration$.pipe(FC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(CC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=Dn(),c=r&&this.currentStallsCount>=r,h=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,_C(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Dn()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},ll=Qp;import{combine as NC,map as UC,observeElementSize as qC,Subscription as jC,ValueSubject as Wp,noop as HC}from"@vkontakte/videoplayer-shared/es2015";var cl=class{constructor(){this.subscription=new jC;this.pipSize$=new Wp(void 0);this.videoSize$=new Wp(void 0);this.elementSize$=new Wp(void 0);this.pictureInPictureWindowRemoveEventListener=HC}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(qC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(NC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(UC(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Tr=class{constructor(e){this.subscription=new KC;this.videoState=new Q("stopped");this.droppedFramesManager=new ts;this.stallsManager=new ll;this.elementSizeManager=new cl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ni;this.audioTrackSwitchHistory=new Ni;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(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"),L(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&L(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return zC(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new bs(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:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new pt(e.source.url),this.params=e,this.video=He(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(Re(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 al({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=Qe(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:hx.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Yp(l=>!!l.length),mx()).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})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Kp(l=>l.to.state!=="none"),dl());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Yp(fx),mx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Kp(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Lt(this.video,t.isLooped,r)),this.subscription.add(ze(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(dt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(ht(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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,this.textTracksMap=new Map;let d=this.player.getStreams();if(QC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(kp(p));let f=[];for(let m of p.representations){let g=UI(m);f.push(g),this.audioTracksMap.set(g,{stream:p,representation:m})}this.audioStreamsMap.set(p,f)}this.params.output.availableAudioStreams$.next(h)}let c=[];for(let h of d.video){c.push(Rp(h));let p=[];for(let f of h.representations){let m=NI(B(E({},f),{streamId:h.id}));m&&(p.push(m),this.videoTracksMap.set(m,{stream:h,representation:f}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(c);for(let h of d.text)for(let p of h.representations){let f=qI(h,p);this.textTracksMap.set(f,{stream:h,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(pl(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,YC(this.video,"progress")).pipe(Yp(()=>this.videoTracksMap.size>0)).subscribe(()=>x(this,null,function*(){let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,bx.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[h,p]=c,f=[...this.videoTracksMap.keys()].find(g=>{var S;return((S=this.videoTracksMap.get(g))==null?void 0:S.representation.id)===h.id});fx(f)&&(this.stallsManager.lastVideoTrackSelected=f);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")yield this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",p.id,g)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(dl()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(Rp(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(dl()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(kp(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Kp(({to:l})=>l==="ready"),dl());this.subscription.add(pl(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Xp(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(pl(o,this.player.state$.stateChangeEnded$,Xp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=pl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Xp(["init"])).pipe(WC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var w,F,M,H,N,K,A,$,R,P,O,de,Ne;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Na:Fa,t=this.params.tuning.useNewAutoSelectVideoTrack?Cu:Du,i=this.params.tuning.useNewAutoSelectVideoTrack?ii:Bu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(w=r.videoTrack.getState())==null?void 0:w.id,l=[...this.videoTracksMap.keys()].find(({id:ue})=>ue===o),d=a.currentVideoTrack$.getValue(),c=((H=(M=r.videoStream.getState())!=null?M:l&&((F=this.videoTracksMap.get(l))==null?void 0:F.stream))!=null?H:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let h=[...this.videoStreamsMap.keys()].find(({id:ue})=>ue===c.id),p=h&&this.videoStreamsMap.get(h);if(!p)return;let f=_e(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(f/Math.min(m,g||1/0),1),v=(N=r.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(K=[...this.audioStreamsMap.keys()].find(({id:ue})=>ue===(v==null?void 0:v.id)))!=null?K:this.audioStreamsMap.keys().next().value,T=0;if(y){if(l&&!n){let ue=e(l,p,(A=this.audioStreamsMap.get(y))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,($=ue==null?void 0:ue.bitrate)!=null?$:-1/0)}if(d){let ue=e(d,p,(R=this.audioStreamsMap.get(y))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(P=ue==null?void 0:ue.bitrate)!=null?P:-1/0)}}let I=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current:d,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),k=n?I!=null?I:l:l!=null?l:I,C=y&&t(k,p,(O=this.audioStreamsMap.get(y))!=null?O:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),V=(de=this.videoTracksMap.get(k))==null?void 0:de.representation,D=C&&((Ne=this.audioTracksMap.get(C))==null?void 0:Ne.representation);if(V&&D)return[V,D];if(V&&!D&&this.audioTracksMap.size===0)return[V,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hx.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ge(this.video),this.tracer.end()}};var Cn=class extends Tr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Jp,merge as gx,filter as Sx,filterChanged as XC,isNullable as Zp,map as vx,ValueSubject as eh,isNonNullable as JC}from"@vkontakte/videoplayer-shared/es2015";var Vn=class extends Tr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new eh(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(vx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Jp({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(vx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Sx(o=>JC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Jp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:gx(i.playbackRateState$,new eh(1))}).pipe(Sx(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||Zp(l)||(e=o-l)})).add(Jp({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:gx(i.playbackRateState$,new eh(1))}).pipe(XC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||Zp(o)||Zp(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=jI(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as HV,assertNonNullable as GV,debounce as zV,ErrorCategory as Jx,filter as Th,filterChanged as El,fromEvent as QV,isNonNullable as Zx,map as Ih,merge as wl,observableFrom as xh,once as eE,Subscription as WV}from"@vkontakte/videoplayer-shared/es2015";var vh=j(Ya(),1);import{abortable as mh,assertNonNullable as Ts,combine as Is,ErrorCategory as Qt,filter as yl,filterChanged as bo,flattenObject as go,fromEvent as si,getTraceSubscriptionMethod as DV,interval as bh,isNonNullable as So,isNullable as Kx,map as xs,merge as Ar,now as gh,Subject as Tl,Subscription as Sh,tap as CV,throttle as Xx,ValueSubject as Se}from"@vkontakte/videoplayer-shared/es2015";var bl=j(wt(),1),vs=j(jt(),1),gl=j(Ya(),1);var Gx=j(Ba(),1);import{assertNever as ZC,ErrorCategory as yx,Subject as Tx}from"@vkontakte/videoplayer-shared/es2015";var eV=18,Ix=!1;try{Ix=G.browser.isSafari&&!!G.browser.safariVersion&&G.browser.safariVersion<=eV}catch(s){console.error(s)}var th=class{constructor(e){this.bufferFull$=new Tx;this.error$=new Tx;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:yx.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return x(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 x(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return x(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};Ix&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,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)&&!this.abortRequested)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(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:yx.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:ZC(t)}}},xx=th;import{abortable as zi,assertNonNullable as mt,ErrorCategory as wr,fromEvent as Hx,getExponentialDelay as ph,isNonNullable as Ss,isNullable as Xe,now as ml,once as wV,Subject as PV,Subscription as AV,ValueSubject as Pr}from"@vkontakte/videoplayer-shared/es2015";var ie=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}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 gs=class extends ie{};var On=class extends ie{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var _n=class extends ie{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 Fn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var he=class extends ie{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Nn=class extends he{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Un=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qn=class extends ie{constructor(e,t){super(e,t),this.data=this.content}};var Ir=class extends he{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(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var jn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gn=class extends he{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 zn=class extends he{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Qn=class extends he{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Wn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Yn=class extends he{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 Kn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Jn=class extends he{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var eo=class extends he{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 to=class extends he{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 io=class extends he{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 ro=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var so=class extends he{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var ao=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var iV={ftyp:_n,moov:Fn,mvhd:Nn,moof:Un,mdat:qn,sidx:Ir,trak:jn,mdia:Wn,mfhd:Jn,tkhd:Yn,traf:Zn,tfhd:eo,tfdt:to,trun:io,minf:Kn,sv3d:Hn,st3d:Gn,prhd:zn,proj:Xn,equi:Qn,uuid:On,stbl:ro,stsd:so,avc1:ao,unknown:gs},Ri=class s{constructor(e={}){this.options=E({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,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=iV[e];return i?new i(t,new s):new gs(t,new s)}};var Gi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(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 sV=new TextDecoder("ascii"),aV=s=>sV.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",nV=s=>{let e=new Ir(s,new Ri),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},oV=(s,e)=>{let i=new Ri().parse(s),r=new Gi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},uV=s=>{let t=new Ri().parse(s),i=new Gi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},lV=s=>{var r;let t=new Ri().parse(s);return(r=new Gi(t).find("sidx"))==null?void 0:r.timescale},cV=(s,e)=>{let i=new Ri().parse(s),a=new Gi(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},dV=s=>{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 Ri().parse(s),r=new Gi(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},Ex={validateData:aV,parseInit:dV,getIndexRange:()=>{},parseSegments:nV,parseFeedableSegmentChunk:oV,getChunkEndTime:cV,getServerLatencyTimestamps:uV,getTimescaleFromIndex:lV};var oo=j(wt(),1);import{assertNonNullable as rh,isNonNullable as kx,isNullable as hV}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as pV}from"@vkontakte/videoplayer-shared/es2015";var wx={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"}},Px=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=no(s,t),r=i in wx,a=r?wx[i].type:"binary",n=s.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(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=no(u),c=l*st(2,(o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},no=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*st(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*st(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*st(2,32)+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},zt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return no(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:pV(e)}},xr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Px(i);if(!e(r))return;r.type==="master"&&xr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Ax=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Px(s);return xr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=zt(o,n):a===17026?t=zt(o,n):a===17029&&(i=zt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Rx=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],fV=[231,22612,22743,167,171,163,160,175],mV=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return xr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=zt(f,p);l=no(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=zt(f,p):h===17545?r=zt(f,p):h===21420&&l===475249515?u=zt(f,p):h===374648427?xr(f,({tag:g,type:S,value:v})=>g===30321?(d=zt(v,S)===1,!1):!0):a&&n&&(0,oo.default)(Rx,h)&&(o=!0),!o}),rh(e,"Failed to parse webm Segment start"),rh(t,"Failed to parse webm Segment end"),rh(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:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},bV=s=>{if(hV(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},gV=(s,e)=>{let t=!1,i=!1,r=o=>kx(o.time)&&kx(o.position),a=[],n;return xr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=zt(l,u));break;case 183:break;case 241:n&&(n.position=zt(l,u));break;default:t&&(0,oo.default)(Rx,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},SV=s=>{let e=0,t=!1;try{xr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,oo.default)(fV,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,oo.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Lx={validateData:Ax,parseInit:mV,getIndexRange:bV,parseSegments:gV,parseFeedableSegmentChunk:SV};var uo=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Lx;case"mp4":return Ex}}throw new ReferenceError(`Unsupported mime type ${s}`)};var lh=j(Ep(),1),Nx=j(nr(),1),Ux=j(wp(),1),qx=j(jt(),1),ch=j(fr(),1);import{isNonNullable as IV,isNullable as _x}from"@vkontakte/videoplayer-shared/es2015";var Mx=s=>{var e;try{let t=vV(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function vV(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
178
|
+
`;var hs=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 il(this.params.fov,this.params.orientation),this.cameraRotationManager=new rl(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(ax,this.gl.VERTEX_SHADER),i=this.createShader(nx,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,h=t+r;return[a,n,o,u,l,d,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as PC,now as Mn,once as kC,Subscription as RC,ValueSubject as _p,isNonNullable as MC,safeStorage as Fp,filterChanged as LC}from"@vkontakte/videoplayer-shared/es2015";var sl="stalls_manager_metrics",Np="stalls_manager_abr_params",ox="stalls_manager_default_tuning_abr_params",Up=class{constructor(){this.isSeeked$=new _p(!1);this.isBuffering$=new _p(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new RC;this.severeStallOccurred$=new _p(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(Np):{};return x(x({},this.abrParams),e)}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Mn(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Mn()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}=x({},this.getStoredData(ox)),{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}=x({},this.abrParams);this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(Np),this.setStoredData(ox,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(sl,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;if(this.tuning.useTotalStallsDurationPerTvt){let r=t.reduce((o,u)=>o+u.tvt,0),n=t.reduce((o,u)=>o+u.stallsDuration,0)/r;e.push(this.calculateOptimalAbrParams(n))}if(this.tuning.useAverageStallsDurationPerTvt){let r=t.reduce((a,n)=>a+n.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(r))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed));let i={bitrateFactorAtEmptyBuffer:Math.max(...e.map(r=>r.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(r=>r.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(r=>r.containerSizeFactor))};this.setStoredData(sl,[]),this.setStoredData(Np,i)}calculateOptimalAbrParams(e){let{targetStallsDurationPerTvt:t,deviationStallsDurationPerTvt:i,criticalStallsDurationPerTvt:r,abrAdjustingSpeed:a}=this.tuning,n=this.abrTuningParams;return e<t-i?n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer-a,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer-a,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor+a,this.abrParams.maxContainerSizeFactor)}:e>t+i&&(n={bitrateFactorAtEmptyBuffer:Math.min(n.bitrateFactorAtEmptyBuffer+a,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(n.bitrateFactorAtFullBuffer+a,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(n.containerSizeFactor-a,this.abrParams.minContainerSizeFactor)}),e>r&&(n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor,this.abrParams.containerSizeFactor)}),n}getStoredData(e,t="{}"){var i;return JSON.parse((i=Fp.get(e))!=null?i:t)}setStoredData(e,t){Fp.set(e,JSON.stringify(t))}removeStoredData(e){Fp.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(sl,"[]"),r=t/e,a=i.length?Ei(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(sl,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(kC()).subscribe(t=>this.providerStartWatchingTimestamp=Mn())),this.subscription.add(this.currentStallDuration$.pipe(LC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(PC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=Mn(),c=r&&this.currentStallsCount>=r,h=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,MC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Mn()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},al=Up;import{combine as BC,map as $C,observeElementSize as DC,Subscription as CC,ValueSubject as qp,noop as VC}from"@vkontakte/videoplayer-shared/es2015";var nl=class{constructor(){this.subscription=new CC;this.pipSize$=new qp(void 0);this.videoSize$=new qp(void 0);this.elementSize$=new qp(void 0);this.pictureInPictureWindowRemoveEventListener=VC}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(DC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(BC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe($C(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var vr=class{constructor(e){this.subscription=new qC;this.videoState=new Y("stopped");this.droppedFramesManager=new Zr;this.stallsManager=new al;this.elementSizeManager=new nl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new _i;this.audioTrackSwitchHistory=new _i;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),D(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"),D(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&D(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;default:return _C(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new hs(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:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new kt(e.source.url),this.params=e,this.video=nt(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(je(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 tl({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=lt(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:ux.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(jp(l=>!!l.length),cx()).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})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Hp(l=>l.to.state!=="none"),ol());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(jp(lx),cx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Hp(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Kt(this.video,t.isLooped,r)),this.subscription.add(ut(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Rt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),D(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),D(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,this.textTracksMap=new Map;let d=this.player.getStreams();if(FC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(Ip(p));let f=[];for(let m of p.representations){let g=VI(m);f.push(g),this.audioTracksMap.set(g,{stream:p,representation:m})}this.audioStreamsMap.set(p,f)}this.params.output.availableAudioStreams$.next(h)}let c=[];for(let h of d.video){c.push(xp(h));let p=[];for(let f of h.representations){let m=CI(B(x({},f),{streamId:h.id}));m&&(p.push(m),this.videoTracksMap.set(m,{stream:h,representation:f}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(c);for(let h of d.text)for(let p of h.representations){let f=OI(h,p);this.textTracksMap.set(f,{stream:h,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(ul(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,UC(this.video,"progress")).pipe(jp(()=>this.videoTracksMap.size>0)).subscribe(()=>E(this,null,function*(){let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,dx.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[h,p]=c,f=[...this.videoTracksMap.keys()].find(g=>{var S;return((S=this.videoTracksMap.get(g))==null?void 0:S.representation.id)===h.id});lx(f)&&(this.stallsManager.lastVideoTrackSelected=f);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")yield this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",p.id,g)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ol()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(xp(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ol()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Ip(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Hp(({to:l})=>l==="ready"),ol());this.subscription.add(ul(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,zp(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(ul(o,this.player.state$.stateChangeEnded$,zp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ul(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,zp(["init"])).pipe(NC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var w,F,M,j,N,K,P,L,R,A,O,de,Fe;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Va:Ca,t=this.params.tuning.useNewAutoSelectVideoTrack?Mu:Ru,i=this.params.tuning.useNewAutoSelectVideoTrack?Zt:ku,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(w=r.videoTrack.getState())==null?void 0:w.id,l=[...this.videoTracksMap.keys()].find(({id:ue})=>ue===o),d=a.currentVideoTrack$.getValue(),c=((j=(M=r.videoStream.getState())!=null?M:l&&((F=this.videoTracksMap.get(l))==null?void 0:F.stream))!=null?j:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let h=[...this.videoStreamsMap.keys()].find(({id:ue})=>ue===c.id),p=h&&this.videoStreamsMap.get(h);if(!p)return;let f=Oe(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(f/Math.min(m,g||1/0),1),v=(N=r.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(K=[...this.audioStreamsMap.keys()].find(({id:ue})=>ue===(v==null?void 0:v.id)))!=null?K:this.audioStreamsMap.keys().next().value,T=0;if(y){if(l&&!n){let ue=e(l,p,(P=this.audioStreamsMap.get(y))!=null?P:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(L=ue==null?void 0:ue.bitrate)!=null?L:-1/0)}if(d){let ue=e(d,p,(R=this.audioStreamsMap.get(y))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(A=ue==null?void 0:ue.bitrate)!=null?A:-1/0)}}let I=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current:d,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),k=n?I!=null?I:l:l!=null?l:I,C=y&&t(k,p,(O=this.audioStreamsMap.get(y))!=null?O:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),V=(de=this.videoTracksMap.get(k))==null?void 0:de.representation,$=C&&((Fe=this.audioTracksMap.get(C))==null?void 0:Fe.representation);if(V&&$)return[V,$];if(V&&!$&&this.audioTracksMap.size===0)return[V,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ux.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),ot(this.video),this.tracer.end()}};var Ln=class extends vr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Qp,merge as px,filter as hx,filterChanged as jC,isNullable as Gp,map as fx,ValueSubject as Wp,isNonNullable as HC}from"@vkontakte/videoplayer-shared/es2015";var Bn=class extends vr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new Wp(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(fx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Qp({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(fx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(hx(o=>HC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Qp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:px(i.playbackRateState$,new Wp(1))}).pipe(hx(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||Gp(l)||(e=o-l)})).add(Qp({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:px(i.playbackRateState$,new Wp(1))}).pipe(jC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||Gp(o)||Gp(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=_I(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as VV,assertNonNullable as OV,debounce as _V,ErrorCategory as Qx,filter as bh,filterChanged as yl,fromEvent as FV,isNonNullable as Gx,map as gh,merge as Tl,observableFrom as Sh,once as Wx,Subscription as NV}from"@vkontakte/videoplayer-shared/es2015";var fh=H(za(),1);import{abortable as ch,assertNonNullable as Ss,combine as vs,ErrorCategory as Qt,filter as bl,filterChanged as po,flattenObject as ho,fromEvent as ti,getTraceSubscriptionMethod as AV,interval as dh,isNonNullable as fo,isNullable as Hx,map as ys,merge as wr,now as ph,Subject as gl,Subscription as hh,tap as PV,throttle as zx,ValueSubject as Se}from"@vkontakte/videoplayer-shared/es2015";var pl=H(It(),1),bs=H(qt(),1),hl=H(za(),1);var Fx=H(ou(),1);import{assertNever as zC,ErrorCategory as mx,Subject as bx}from"@vkontakte/videoplayer-shared/es2015";var QC=18,gx=!1;try{gx=Q.browser.isSafari&&!!Q.browser.safariVersion&&Q.browser.safariVersion<=QC}catch(s){console.error(s)}var Yp=class{constructor(e){this.bufferFull$=new bx;this.error$=new bx;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:mx.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return E(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 E(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return E(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};gx&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,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)&&!this.abortRequested)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(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:mx.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:zC(t)}}},Sx=Yp;import{abortable as Hi,assertNonNullable as pt,ErrorCategory as xr,fromEvent as nh,getExponentialDelay as oh,isNonNullable as ms,isNullable as Qe,now as dl,once as gV,Subject as SV,Subscription as vV,ValueSubject as Er}from"@vkontakte/videoplayer-shared/es2015";var ie=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}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 fs=class extends ie{};var $n=class extends ie{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Dn=class extends ie{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 Cn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var he=class extends ie{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Vn=class extends he{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var On=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _n=class extends ie{constructor(e,t){super(e,t),this.data=this.content}};var yr=class extends he{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(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Fn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Nn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Un=class extends he{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 qn=class extends he{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var jn=class extends he{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Hn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zn=class extends he{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 Qn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wn=class extends he{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Yn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Kn=class extends he{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 Xn=class extends he{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 Jn=class extends he{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 Zn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var eo=class extends he{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var to=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var WC={ftyp:Dn,moov:Cn,mvhd:Vn,moof:On,mdat:_n,sidx:yr,trak:Fn,mdia:Hn,mfhd:Wn,tkhd:zn,traf:Yn,tfhd:Kn,tfdt:Xn,trun:Jn,minf:Qn,sv3d:Nn,st3d:Un,prhd:qn,proj:Gn,equi:jn,uuid:$n,stbl:Zn,stsd:eo,avc1:to,unknown:fs},Pi=class s{constructor(e={}){this.options=x({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=WC[e];return i?new i(t,new s):new fs(t,new s)}};var ji=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(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 KC=new TextDecoder("ascii"),XC=s=>KC.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",JC=s=>{let e=new yr(s,new Pi),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},ZC=(s,e)=>{let i=new Pi().parse(s),r=new ji(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},eV=s=>{let t=new Pi().parse(s),i=new ji(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},tV=s=>{var r;let t=new Pi().parse(s);return(r=new ji(t).find("sidx"))==null?void 0:r.timescale},iV=(s,e)=>{let i=new Pi().parse(s),a=new ji(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},rV=s=>{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 Pi().parse(s),r=new ji(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},vx={validateData:XC,parseInit:rV,getIndexRange:()=>{},parseSegments:JC,parseFeedableSegmentChunk:ZC,getChunkEndTime:iV,getServerLatencyTimestamps:eV,getTimescaleFromIndex:tV};var ro=H(It(),1);import{assertNonNullable as Xp,isNonNullable as xx,isNullable as aV}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as sV}from"@vkontakte/videoplayer-shared/es2015";var yx={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"}},Tx=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=io(s,t),r=i in yx,a=r?yx[i].type:"binary",n=s.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(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=io(u),c=l*Ze(2,(o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},io=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Ze(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Ze(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Ze(2,32)+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},zt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return io(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:sV(e)}},Tr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=Tx(i);if(!e(r))return;r.type==="master"&&Tr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Ix=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Tx(s);return Tr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=zt(o,n):a===17026?t=zt(o,n):a===17029&&(i=zt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Ex=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],nV=[231,22612,22743,167,171,163,160,175],oV=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return Tr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=zt(f,p);l=io(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=zt(f,p):h===17545?r=zt(f,p):h===21420&&l===475249515?u=zt(f,p):h===374648427?Tr(f,({tag:g,type:S,value:v})=>g===30321?(d=zt(v,S)===1,!1):!0):a&&n&&(0,ro.default)(Ex,h)&&(o=!0),!o}),Xp(e,"Failed to parse webm Segment start"),Xp(t,"Failed to parse webm Segment end"),Xp(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:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},uV=s=>{if(aV(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lV=(s,e)=>{let t=!1,i=!1,r=o=>xx(o.time)&&xx(o.position),a=[],n;return Tr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=zt(l,u));break;case 183:break;case 241:n&&(n.position=zt(l,u));break;default:t&&(0,ro.default)(Ex,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},cV=s=>{let e=0,t=!1;try{Tr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ro.default)(nV,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,ro.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},wx={validateData:Ix,parseInit:oV,getIndexRange:uV,parseSegments:lV,parseFeedableSegmentChunk:cV};var so=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return wx;case"mp4":return vx}}throw new ReferenceError(`Unsupported mime type ${s}`)};var rh=H(Sp(),1),Cx=H(sr(),1),Vx=H(vp(),1),Ox=H(qt(),1),sh=H(pr(),1);import{isNonNullable as fV,isNullable as $x}from"@vkontakte/videoplayer-shared/es2015";var Ax=s=>{var e;try{let t=dV(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function dV(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
179
179
|
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
180
180
|
(-(?<script>[a-z]{4}))?
|
|
181
181
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
182
182
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
183
183
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
184
184
|
(?:-(?<privateuse>(?:${e})))?
|
|
185
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var ah=j(jt(),1);import{videoSizeToQuality as yV,throttleFn as TV}from"@vkontakte/videoplayer-shared/es2015";var $x=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?ti(a):void 0)!=null?u:yV({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Bx=({id:s,bitrate:e})=>({id:s,bitrate:e}),Dx=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Cx=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),nh=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,ah.default)(i.split("."),0),isDefault:r}),oh=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,ah.default)(r.split("."),0)}),uh=s=>"url"in s,lt=s=>s.type==="template",lo=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Vx=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},Er=(s,e)=>{for(let t of s)if(e(t))return t;return null},Ox=s=>{let e=!1,t=TV(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var Fx=s=>{if(!(s!=null&&s.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(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={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 a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Li=(s,e)=>{let t=s;t=(0,lh.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Nx.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,lh.default)(t,n,(o,u)=>_x(a)?o:_x(u)?a:(0,Ux.default)(a,parseInt(u,10),"0"))}return t},jx=(s,e)=>{var D,w,F,M,H,N,K,A,$,R,P,O,de,Ne,ue,ee,Ee,we,Pe,Ue,Rt,$t,Yt,ai,Bi,Ps,As,ks,Rs,Ls,Ms,$s,Bs,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,Gs,zs,Qs,Ws,Ys,Ks,Xs,Js,Zs,ea,ta,ia,ra,sa,aa,na,oa;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(fe=>{var q,Je;return(Je=(q=fe.textContent)==null?void 0:q.trim())!=null?Je:""}),o=(D=(0,qx.default)(n,0))!=null?D:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],T=y.reduce((fe,q)=>B(E({},fe),{[q.id]:q.children}),{}),I=y.reduce((fe,q)=>B(E({},fe),{[q.id]:q.getAttribute("duration")}),{});v?S=Fx(v):(0,ch.default)(I).filter(fe=>fe).length&&!u?S=(0,ch.default)(I).reduce((fe,q)=>{var Je;return fe+((Je=Fx(q))!=null?Je:0)},0):m&&(S=parseInt(m,10));let k=0,C=(F=(w=a.getAttribute("profiles"))==null?void 0:w.split(","))!=null?F:[];for(let fe of y.map(q=>q.id))for(let q of T[fe]){let Je=(M=q.getAttribute("id"))!=null?M:"id"+(k++).toString(10),Bt=(H=q.getAttribute("mimeType"))!=null?H:"",Ki=(N=q.getAttribute("codecs"))!=null?N:"",Xi=(K=q.getAttribute("contentType"))!=null?K:Bt==null?void 0:Bt.split("/")[0],Ul=($=(A=q.getAttribute("profiles"))==null?void 0:A.split(","))!=null?$:[],ua=(P=Mx((R=q.getAttribute("lang"))!=null?R:""))!=null?P:{},ni=(Ne=(de=(O=q.querySelector("Label"))==null?void 0:O.textContent)==null?void 0:de.trim())!=null?Ne:void 0,ql=q.querySelectorAll("Representation"),jl=q.querySelector("SegmentTemplate"),Hl=(ee=(ue=q.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?ee:void 0,bt=Xi,W={id:Je,language:ua.language,isDefault:Hl==="main",label:ni,codecs:Ki,hdr:bt==="video"&&os(Ki),mime:Bt,representations:[]};for(let U of ql){let Le=(Ee=U.getAttribute("lang"))!=null?Ee:void 0,Dt=(Pe=(we=ni!=null?ni:q.getAttribute("label"))!=null?we:U.getAttribute("label"))!=null?Pe:void 0,oi=($t=(Rt=(Ue=U.querySelector("BaseURL"))==null?void 0:Ue.textContent)==null?void 0:Rt.trim())!=null?$t:"",Ze=new URL(oi||o,e).toString(),Me=(Yt=U.getAttribute("mimeType"))!=null?Yt:Bt,ui=(Bi=(ai=U.getAttribute("codecs"))!=null?ai:Ki)!=null?Bi:"",li;if(Xi==="text"){let $e=U.getAttribute("id")||"",ci=((Ps=ua.privateuse)==null?void 0:Ps.includes("x-auto"))||$e.includes("_auto"),et=U.querySelector("SegmentTemplate");if(et){let Ct={representationId:(As=U.getAttribute("id"))!=null?As:void 0,bandwidth:(ks=U.getAttribute("bandwidth"))!=null?ks:void 0},di=parseInt((Rs=U.getAttribute("bandwidth"))!=null?Rs:"",10)/1e3,pi=(Ms=parseInt((Ls=et.getAttribute("startNumber"))!=null?Ls:"",10))!=null?Ms:1,gt=parseInt(($s=et.getAttribute("timescale"))!=null?$s:"",10),Ji=(Bs=et.querySelectorAll("SegmentTimeline S"))!=null?Bs:[],St=et.getAttribute("media");if(!St)continue;let hi=[],fi=0,mi="",vt=0,Vt=pi,se=0;for(let me of Ji){let tt=parseInt((Ds=me.getAttribute("d"))!=null?Ds:"",10),ce=parseInt((Cs=me.getAttribute("r"))!=null?Cs:"",10)||0,Be=parseInt((Vs=me.getAttribute("t"))!=null?Vs:"",10);se=Number.isFinite(Be)?Be:se;let it=tt/gt*1e3,De=se/gt*1e3;for(let ve=0;ve<ce+1;ve++){let Ce=Li(St,B(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:(se+ve*tt).toString(10)})),yt=(De!=null?De:0)+ve*it,_t=yt+it;Vt++,hi.push({time:{from:yt,to:_t},url:Ce})}se+=(ce+1)*tt,fi+=(ce+1)*it}vt=se/gt*1e3,mi=Li(St,B(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:se.toString(10)}));let Ot={time:{from:vt,to:1/0},url:mi},Ae={type:"template",baseUrl:Ze,segmentTemplateUrl:St,initUrl:"",totalSegmentsDurationMs:fi,segments:hi,nextSegmentBeyondManifest:Ot,timescale:gt};li={id:$e,kind:"text",segmentReference:Ae,profiles:[],duration:S,bitrate:di,mime:"",codecs:"",width:0,height:0,isAuto:ci}}else li={id:$e,isAuto:ci,kind:"text",url:Ze}}else{let $e=(_s=(Os=U.getAttribute("contentType"))!=null?Os:Me==null?void 0:Me.split("/")[0])!=null?_s:Xi,ci=(Ns=(Fs=q.getAttribute("profiles"))==null?void 0:Fs.split(","))!=null?Ns:[],et=parseInt((Us=U.getAttribute("width"))!=null?Us:"",10),Ct=parseInt((qs=U.getAttribute("height"))!=null?qs:"",10),di=parseInt((js=U.getAttribute("bandwidth"))!=null?js:"",10)/1e3,pi=(Hs=U.getAttribute("frameRate"))!=null?Hs:"",gt=(Gs=U.getAttribute("quality"))!=null?Gs:void 0,Ji=pi?ju(pi):void 0,St=(zs=U.getAttribute("id"))!=null?zs:"id"+(k++).toString(10),hi=$e==="video"?`${Ct}p`:$e==="audio"?`${di}Kbps`:ui,fi=`${St}@${hi}`,mi=[...C,...Ul,...ci],vt,Vt=U.querySelector("SegmentBase"),se=(Qs=U.querySelector("SegmentTemplate"))!=null?Qs:jl;if(Vt){let Ae=(Ys=(Ws=U.querySelector("SegmentBase Initialization"))==null?void 0:Ws.getAttribute("range"))!=null?Ys:"",[me,tt]=Ae.split("-").map(Ce=>parseInt(Ce,10)),ce={from:me,to:tt},Be=(Ks=U.querySelector("SegmentBase"))==null?void 0:Ks.getAttribute("indexRange"),[it,De]=Be?Be.split("-").map(Ce=>parseInt(Ce,10)):[],ve=Be?{from:it,to:De}:void 0;vt={type:"byteRange",url:Ze,initRange:ce,indexRange:ve}}else if(se){let Ae={representationId:(Xs=U.getAttribute("id"))!=null?Xs:void 0,bandwidth:(Js=U.getAttribute("bandwidth"))!=null?Js:void 0},me=parseInt((Zs=se.getAttribute("timescale"))!=null?Zs:"",10),tt=(ea=se.getAttribute("initialization"))!=null?ea:"",ce=se.getAttribute("media"),Be=(ia=parseInt((ta=se.getAttribute("startNumber"))!=null?ta:"",10))!=null?ia:1,it=Li(tt,Ae);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let De=(ra=se.querySelectorAll("SegmentTimeline S"))!=null?ra:[],ve=[],Ce=0,yt="",_t=0;if(De.length){let bi=Be,be=0;for(let Tt of De){let ye=parseInt((sa=Tt.getAttribute("d"))!=null?sa:"",10),rt=parseInt((aa=Tt.getAttribute("r"))!=null?aa:"",10)||0,gi=parseInt((na=Tt.getAttribute("t"))!=null?na:"",10);be=Number.isFinite(gi)?gi:be;let Zi=ye/me*1e3,er=be/me*1e3;for(let Si=0;Si<rt+1;Si++){let zl=Li(ce,B(E({},Ae),{segmentNumber:bi.toString(10),segmentTime:(be+Si*ye).toString(10)})),la=(er!=null?er:0)+Si*Zi,Ql=la+Zi;bi++,ve.push({time:{from:la,to:Ql},url:zl})}be+=(rt+1)*ye,Ce+=(rt+1)*Zi}_t=be/me*1e3,yt=Li(ce,B(E({},Ae),{segmentNumber:bi.toString(10),segmentTime:be.toString(10)}))}else if(IV(S)){let be=parseInt((oa=se.getAttribute("duration"))!=null?oa:"",10)/me*1e3,Tt=Math.ceil(S/be),ye=0;for(let rt=1;rt<Tt;rt++){let gi=Li(ce,B(E({},Ae),{segmentNumber:rt.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:gi}),ye+=be}_t=ye,yt=Li(ce,B(E({},Ae),{segmentNumber:Tt.toString(10),segmentTime:ye.toString(10)}))}let Gl={time:{from:_t,to:1/0},url:yt};vt={type:"template",baseUrl:Ze,segmentTemplateUrl:ce,initUrl:it,totalSegmentsDurationMs:Ce,segments:ve,nextSegmentBeyondManifest:Gl,timescale:me}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!$e||!Me)continue;let Ot={video:"video",audio:"audio",text:"text"}[$e];if(!Ot)continue;bt||(bt=Ot),li={id:fi,kind:Ot,segmentReference:vt,profiles:mi,duration:S,bitrate:di,mime:Me,codecs:ui,width:et,height:Ct,fps:Ji,quality:gt}}W.language||(W.language=Le),W.label||(W.label=Dt),W.mime||(W.mime=Me),W.codecs||(W.codecs=ui),W.hdr||(W.hdr=bt==="video"&&os(ui)),W.representations.push(li)}if(bt){let U=r[bt].find(Le=>Le.id===W.id);if(U&&W.representations.every(Le=>lt(Le.segmentReference)))for(let Le of U.representations){let Dt=W.representations.find(Me=>Me.id===Le.id),oi=Dt==null?void 0:Dt.segmentReference,Ze=Le.segmentReference;Ze.segments.push(...oi.segments),Ze.nextSegmentBeyondManifest=oi.nextSegmentBeyondManifest}else r[bt].push(W)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{fromEvent as xV,Subscription as EV}from"@vkontakte/videoplayer-shared/es2015";var hl=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var fl=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new EV;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(xV(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!z(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=hl(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var co=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Pr(0);this.currentLowLatencySegmentLength$=new Pr(0);this.currentSegmentLength$=new Pr(0);this.onLastSegment$=new Pr(!1);this.fullyBuffered$=new Pr(!1);this.playingRepresentation$=new Pr(void 0);this.playingRepresentationInit$=new Pr(void 0);this.error$=new PV;this.gaps=[];this.subscription=new AV;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new le;this.switchAbortController=new le;this.destroyAbortController=new le;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=zi(this.destroyAbortController.signal,function(e){return X(this,null,function*(){let t=this.representations.get(e);mt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new xx(this.sourceBuffer),this.sourceBufferBufferedDiff=new fl(this.mediaSource,this.sourceBuffer),this.subscription.add(Hx(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:wr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!z(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ss(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=_e(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),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),a=this.parsedInitData.get(t.id);mt(i,"No init buffer for starting representation"),mt(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))})}.bind(this));this.switchTo=zi(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);mt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Xe(a)||Xe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),mt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Ss(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new tr(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=zi(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);mt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Xe(a)||Xe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),mt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Ss(n)&&(this.isLive||(this.bufferLimit=1/0,yield new tr(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=zi(this.destroyAbortController.signal,function(e){return X(this,null,function*(){var u,l;let t=(u=(0,gl.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!lt(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);mt(r);let a=this.segments.get(i);mt(a,"No segments for starting representation");let n=this.initData.get(i);if(mt(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],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}switchToWithPreviousAbort(e,t=!1){!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,zi(this.switchAbortController.signal,function(i,r=!1){return X(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);mt(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Xe(o)||Xe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),mt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Ss(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!Xe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return x(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new le,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(Xe(e)||Xe(this.downloadingRepresentationId)||Xe(this.playingRepresentationId)||Xe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||Ss(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(mt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);Ss(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=_e(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&ss(this.sourceBuffer.buffered)>=this.bufferLimit){let d=_e(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,bl.default)(u,r))d="high";else{let c=(0,vs.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&_e(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,vs.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-_e(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;Ss(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,gl.default)(e==null?void 0:e.streams[this.kind],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,a,n;let t=(i=(0,gl.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!lt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>B(E({},p),{status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,vs.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;mt(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!lt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.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=Li(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a: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,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&ri&&ri(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ri&&ri(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:h,to:p}},f)=>{let m=h<=i&&p>=i,g=h>i||m||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+S||p<=i+S;return(c==="none"||c==="partially_ejected"&&g&&v&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(Ye(this.sourceBuffer.buffered,h)&&Ye(this.sourceBuffer.buffered,p)))&&g&&v});if(r===-1)return null;if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,i="auto"){return x(this,null,function*(){lt(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return x(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:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield zi(o,function(){return X(this,null,function*(){let d=ph(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=ml(),!d)return;let c=new DataView(d),h=uo(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),lo(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())lt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return x(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:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield zi(n,function(){return X(this,null,function*(){let u=ph(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Hx(window,"online").pipe(wV()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=ml(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),lo(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(lt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,vs.default)(e,0).byte.from,to:(0,vs.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>x(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=ml(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:wr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!lt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=ml();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:wr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,bl.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return x(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=uo(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return x(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let{segment:d}=l,c=d.byte.from-i,h=d.byte.to-i,p=h-c+1,f=c<r,m=h<=r;if(f){if(d.status==="downloading"&&m){d.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(g,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?g:uo(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(d.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,a))&&!a.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}}})}onSegmentFullyAppended(e,t){if(!(Xe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer))){!this.isLive&&G.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ye(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ye(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:wr.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",uh(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&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,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=rs(()=>(0,Gx.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return x(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?zi(this.destroyAbortController.signal,function(){return X(this,null,function*(){let o=ph(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,uo(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&<(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:wr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return x(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 x(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Xe(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push(E({},o.time));let u=uh(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let h of c)(0,bl.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=Vx(r),(yield Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1})}abortBuffer(){return x(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Xe(e)?0:_e(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||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=rs(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:wr.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Xe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||Xe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=hl(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],h=e[d+1];u||(u=c-t<=n&&h+t>=o),(n>=c&&n<h-t||o>c+t&&o<=h)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:wr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as po,assertNever as zx,fromEvent as Qx,merge as kV,now as ho,Subject as Wx,ValueSubject as hh,flattenObject as ys,ErrorCategory as fo,SubscriptionRemovable as RV}from"@vkontakte/videoplayer-shared/es2015";var vl=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new hh(void 0);this.lastConnectionReused$=new hh(void 0);this.lastRequestFirstBytes$=new hh(void 0);this.recoverableError$=new Wx;this.error$=new Wx;this.abortAllController=new le;this.subscription=new RV;this.fetchManifest=po(this.abortAllController.signal,function(e){return X(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ji(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Wu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Sl);return r?(t.log("success",ys({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ys({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=po(this.abortAllController.signal,function(l){return X(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var H,N,K;let d=e,c=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let A=new URL(d,location.href);A.searchParams.append("bytes",`${i.from}-${i.to}`),d=A.toString();break}default:zx(t)}this.requestQuic&&(d=ji(d));let p=this.abortAllController.signal,f;if(n){let A=new le;if(f=kV(Qx(this.abortAllController.signal,"abort"),Qx(n,"abort")).subscribe(()=>{try{A.abort()}catch($){Sl($)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch($){Sl($)}p=A.signal}let m=ho();h.log("startRequest",ys({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(d,{priority:a,headers:c,signal:p}),S=ho();if(!g)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(f),null;if((H=this.throughputEstimator)==null||H.addRawRtt(S-m),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);let A=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:A}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let A=ho(),$={requestStartedAt:m,requestEndedAt:A,duration:A-m};return h.log("endRequest",ys($)),h.end(),g.arrayBuffer()}let v=g.body;if(o){let A;[v,A]=g.body.tee(),(N=this.throughputEstimator)==null||N.trackStream(A,u)}let y=v.getReader(),T,I=parseInt((K=g.headers.get("content-length"))!=null?K:"",10);Number.isFinite(I)&&(T=I),!T&&i&&(T=i.to-i.from+1);let k=0,C=T?new Uint8Array(T):new Uint8Array(0),V=!1,D=A=>{this.unsubscribeAbortSubscription(f),V=!0,Sl(A)},w=po(p,function(R){return X(this,arguments,function*({done:A,value:$}){if(k===0&&this.lastRequestFirstBytes$.next(ho()-m),p.aborted){this.unsubscribeAbortSubscription(f);return}if(!A&&$){if(T)C.set($,k),k+=$.byteLength;else{let P=new Uint8Array(C.length+$.length);P.set(C),P.set($,C.length),C=P,k+=$.byteLength}r==null||r(new DataView(C.buffer),k),yield y==null?void 0:y.read().then(w,D)}})}.bind(this));yield y==null?void 0:y.read().then(w,D),this.unsubscribeAbortSubscription(f);let F=ho(),M={failed:V,requestStartedAt:m,requestEndedAt:F,duration:F-m};return V?(h.error("endRequest",ys(M)),h.end(),null):(h.log("endRequest",ys(M)),h.end(),C.buffer)})}.bind(this));this.fetchByteRangeRepresentation=po(this.abortAllController.signal,function(e,t,i){return X(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}})}.bind(this));this.fetchTemplateRepresentation=po(this.abortAllController.signal,function(e,t){return X(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=>B(E({},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"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Qu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return x(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:zx(r)}})}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}doFetch(e,t){return x(this,null,function*(){let i=yield Mt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:fo.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:fo.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:fo.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:fo.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:fo.FATAL})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Sl=s=>{if(!lo(s))throw s};import{isNullable as LV,ValueSubject as MV}from"@vkontakte/videoplayer-shared/es2015";var mo=class s{constructor(e,t){this.currentRepresentation$=new MV(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!LV(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(B(E({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&<(t.segmentReference))}};var VV=["progress","play","seeked","stalled","waiting"],OV=["timeupdate","progress","loadeddata","playing","seeked"];var Il=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Sh;this.representationSubscription=new Sh;this.state$=new Q("none");this.currentVideoRepresentation$=new Se(void 0);this.currentVideoRepresentationInit$=new Se(void 0);this.currentAudioRepresentation$=new Se(void 0);this.currentVideoSegmentLength$=new Se(0);this.currentAudioSegmentLength$=new Se(0);this.error$=new Tl;this.lastConnectionType$=new Se(void 0);this.lastConnectionReused$=new Se(void 0);this.lastRequestFirstBytes$=new Se(void 0);this.currentLiveTextRepresentation$=new Se(null);this.isLive$=new Se(!1);this.isActiveLive$=new Se(!1);this.isLowLatency$=new Se(!1);this.liveDuration$=new Se(0);this.liveSeekableDuration$=new Se(0);this.liveAvailabilityStartTime$=new Se(0);this.liveStreamStatus$=new Se(void 0);this.bufferLength$=new Se(0);this.liveLatency$=new Se(void 0);this.liveLoadBufferLength$=new Se(0);this.livePositionFromPlayer$=new Se(0);this.currentStallDuration$=new Se(0);this.videoLastDataObtainedTimestamp$=new Se(0);this.fetcherRecoverableError$=new Tl;this.fetcherError$=new Tl;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Tl;this.gapWatchdogActive=!1;this.destroyController=new le;this.initManifest=mh(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ie(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:Qt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=mh(this.destroyController.signal,function(){return X(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:Qt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=jx(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=qu(e))!=null?n:{id:"ManifestParsing",category:Qt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=At())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=il(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);G.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a=B(E({},t),{streams:r});return this.tracer.log("updateManifestEnd",go(a)),a})}.bind(this));this.initRepresentations=mh(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",go({initialVideo:e,initialAudio:t,sourceHls:i})),Ts(this.manifest),Ts(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Sh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(si(p,"error").pipe(yl(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Qt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?Su():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Yr())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.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new co("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],So(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new co("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}mo.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new mo(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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ar(...OV.map(p=>si(this.element,p))).pipe(xs(p=>this.element?_e(this.element.buffered,this.element.currentTime*1e3):0),bo(),CV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ar(si(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(bo()).subscribe(f=>this.liveStreamEndTimestamp=gh())),this.subscription.add(si(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=bh(1e3).subscribe(f=>{let m=Oi(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(si(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(Is({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(xs(({isActiveLive:f,isLowLatency:m})=>f&&m),bo()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ps(this.element,1)})),this.representationSubscription.add(Is({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(yl(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(Is({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(yl(({isLive:f})=>f),bo((f,m)=>m.bufferLength<f.bufferLength),xs(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Oi(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Is({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=f-S;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(T)>v&&(I=1+Math.sign(T)*y),ps(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var I,k;return(k=(I=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?k:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Is({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Xx(1e3)).subscribe(g=>x(this,[g],function*({liveLoadBufferLength:f,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=Oi(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,C=isFinite(f)?f:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),D=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(D);let w="none";if(V?w="active_low_latency":this.isLowLatency$.getValue()&&D?(this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),w="active_low_latency"):v!==0&&C<T?w="live_forward_buffering":C<T+k&&(w="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let F=p-(T+I),M=this.normolizeLiveOffset(Math.trunc(v+F/S)),H=Math.abs(M-v),N=0;!f||H<=this.tuning.dashCmafLive.offsetCalculationError?N=v:M>0&&H>this.tuning.dashCmafLive.offsetCalculationError&&(N=M),this.manifestUrlString=Ie(this.manifestUrlString,N,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,yield this.updateLive())}),f=>{this.error$.next({id:"updateLive",category:Qt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=Ar(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(xs(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Ar(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(xs(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=Is({allBuffersFull:l,someBufferEnded:d}).pipe(bo(),xs(({allBuffersFull:p,someBufferEnded:f})=>p&&f),yl(p=>p));if(this.representationSubscription.add(Ar(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Qt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(Ar(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category:Qt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,vh.default)((0,vh.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),lt(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&So(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,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=bh(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Qt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name);let t=e.tuning.dash.useOldFetherInNewDashProvider?ds:vl;this.fetcher=new t({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ai.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return x(this,null,function*(){var r,a,n;Ts(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?gh()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ie(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){Ts(this.element),this.state$.setState("running");let e=si(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(Xx(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Ar(...VV.map(t=>si(this.element,t)),si(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Qt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(si(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(si(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ye(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var f,m,g,S,v,y,T,I,k,C,V;if(!this.element||((f=this.source)==null?void 0:f.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let a={timeInWaiting:r},n=gh(),o=100,u=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(v=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?v:0,d=(T=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?T:0,c=(k=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?k:0,h=d<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let D=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(D).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:Qt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),a.liveLastOffset=D}else{let D=this.element.currentTime*1e3;(C=this.videoBufferManager)==null||C.maintain(D),(V=this.audioBufferManager)==null||V.maintain(D),a.position=D}this.tracer.log("stallIntervalCallback",go(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=bh(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:Qt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return x(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return x(this,null,function*(){var r,a,n,o,u;Ts(this.element),Ts(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=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ye(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(Kx(this.element)||Kx(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",go({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;So(this.element)&&So(this.source)&&So(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),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.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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=DV(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return x(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.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",go({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as _V,map as FV,observeElementSize as NV,Subscription as UV,ValueSubject as yh,noop as qV}from"@vkontakte/videoplayer-shared/es2015";var xl=class{constructor(){this.subscription=new UV;this.pipSize$=new yh(void 0);this.videoSize$=new yh(void 0);this.elementSize$=new yh(void 0);this.pictureInPictureWindowRemoveEventListener=qV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(NV(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(_V({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(FV(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var kr=class{constructor(e){this.subscription=new WV;this.videoState=new Q("stopped");this.droppedFramesManager=new ts;this.stallsManager=new ll;this.elementSizeManager=new xl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ni;this.audioTrackSwitchHistory=new Ni;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(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"),L(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&L(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return HV(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new bs(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:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new pt(e.source.url),this.params=e,this.video=He(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(Re(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 Il({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=Qe(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:Jx.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Th(c=>!!c.length),eE()).subscribe(c=>{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:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Ih(c=>c.to.state!=="none"),El());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Th(Zx),eE()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Ih(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Lt(this.video,t.isLooped,r)),this.subscription.add(ze(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(dt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(ht(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),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 h=this.player.getStreams();if(GV(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let m of h.audio){f.push(nh(m));let g=[];for(let S of m.representations){let v=Bx(S);g.push(v),this.audioTracksMap.set(v,{stream:m,representation:S})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(f)}let p=[];for(let f of h.video){p.push(oh(f));let m=[];for(let g of f.representations){let S=$x(B(E({},g),{streamId:f.id}));S&&(m.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,m)}this.params.output.availableVideoStreams$.next(p);for(let f of h.text)for(let m of f.representations){let g=Dx(f,m);this.textTracksMap.set(g,{stream:f,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&Ox(o)||null;this.subscription.add(wl(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,QV(this.video,"progress")).pipe(Th(()=>this.videoTracksMap.size>0)).subscribe(()=>x(this,null,function*(){let c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||h||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:f}=this.selectedRepresentations;if(!p)return;let m=Er(this.videoTracksMap.keys(),S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===p.id});Zx(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")yield this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),f){let S=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",f.id,S)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(El()).subscribe(c=>{let h=Er(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(oh(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(El()).subscribe(c=>{let h=Er(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(nh(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var h,p;if(c!=null&&c.is3dVideo&&((h=this.params.tuning.spherical)!=null&&h.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(Ih(({to:c})=>c==="ready"),El());this.subscription.add(wl(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,xh(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(wl(l,this.player.state$.stateChangeEnded$,xh(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=wl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xh(["init"])).pipe(zV(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var V,D,w,F,M,H,N,K,A,$,R,P;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Na:Fa,t=this.params.tuning.useNewAutoSelectVideoTrack?Cu:Du,i=this.params.tuning.useNewAutoSelectVideoTrack?ii:Bu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(V=r.videoTrack.getState())==null?void 0:V.id,u=Er(this.videoTracksMap.keys(),O=>O.id===o),l=a.currentVideoTrack$.getValue(),d=((F=(w=r.videoStream.getState())!=null?w:u&&((D=this.videoTracksMap.get(u))==null?void 0:D.stream))!=null?F:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Er(this.videoStreamsMap.keys(),O=>O.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=_e(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(f,m||1/0),1),S=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(S==null?void 0:S.id)&&Er(this.audioStreamsMap.keys(),O=>O.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(v){if(u&&!n){let O=e(u,h,(H=this.audioStreamsMap.get(v))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(N=O==null?void 0:O.bitrate)!=null?N:-1/0)}if(l){let O=e(l,h,(K=this.audioStreamsMap.get(v))!=null?K:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(A=O==null?void 0:O.bitrate)!=null?A:-1/0)}}let T=u;(n||!T)&&(T=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let I=v&&t(T,h,($=this.audioStreamsMap.get(v))!=null?$:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),k=(R=this.videoTracksMap.get(T))==null?void 0:R.representation,C=I&&((P=this.audioTracksMap.get(I))==null?void 0:P.representation);k&&C?(this.selectedRepresentations.video=k,this.selectedRepresentations.audio=C):k&&!C&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=k,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Jx.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Ge(this.video),this.tracer.end()}};var vo=class extends kr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Eh,merge as tE,filter as iE,filterChanged as YV,isNullable as wh,map as rE,ValueSubject as Ph,isNonNullable as KV}from"@vkontakte/videoplayer-shared/es2015";var yo=class extends kr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new Ph(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(rE(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Eh({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(rE(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(iE(o=>KV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Eh({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:tE(i.playbackRateState$,new Ph(1))}).pipe(iE(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||wh(l)||(e=o-l)})).add(Eh({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:tE(i.playbackRateState$,new Ph(1))}).pipe(YV((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||wh(o)||wh(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Cx(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var aE=j(Ba(),1);import{assertNever as To,assertNonNullable as sE,debounce as XV,ErrorCategory as Pl,filter as JV,isNonNullable as ZV,isNullable as eO,map as Al,merge as tO,Observable as iO,observableFrom as rO,Subscription as sO,videoSizeToQuality as aO}from"@vkontakte/videoplayer-shared/es2015";var Wt={};var Es=(s,e)=>new iO(t=>{let i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)}),Io=class{constructor(e){this.subscription=new sO;this.videoState=new Q("initializing");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:To(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:To(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:To(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:To(e)}break;default:To(t)}};this.textTracksManager=new pt(e.source.url),this.video=He(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(Re(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),Ge(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Pl.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,aE.default)(import("hls.js").then(r=>{e||(Wt.Hls=r.default,Wt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){sE(Wt.Hls,"hls.js not loaded"),this.hls=new Wt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){sE(Wt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Pl.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Qe(this.video);this.subscription.add(()=>r.destroy());let a=(l,d)=>this.subscription.add(l.subscribe(d,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.loadedMetadata$,t.loadedMetadataEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Lt(this.video,e.isLooped,i)),this.subscription.add(ze(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(dt(this.video,e.playbackRate,r.playbackRateState$,i)),a(ht(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(Al(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Es(this.hls,Wt.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Pl.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)==null?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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)),a(Es(this.hls,Wt.Events.MANIFEST_PARSED).pipe(Al(({levels:l})=>l.reduce((d,c)=>{var v,y;let h=c.name||c.height.toString(10),{width:p,height:f}=c,m=(y=ti((v=c.attrs.QUALITY)!=null?v:""))!=null?y:aO({width:p,height:f});if(!m)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,S={id:h.toString(),quality:m,bitrate:c.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:S,level:c}),d.push(S),d},[]))),t.availableVideoTracks$),a(Es(this.hls,Wt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let h=c.name,p=c.attrs.URI||"",f=c.lang;d.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),a(Es(this.hls,Wt.Events.LEVEL_LOADING).pipe(Al(({url:l})=>Re(l))),t.hostname$),a(Es(this.hls,Wt.Events.FRAG_CHANGED),l=>{var h,p,f,m;let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=d==null?void 0:d.endPTS)!=null?h:0)-((p=d==null?void 0:d.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=c==null?void 0:c.endPTS)!=null?f:0)-((m=c==null?void 0:c.startPTS)!=null?m:0))*1e3)}),this.subscription.add(_i(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 d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))==null?void 0:d.track},o=Es(this.hls,Wt.Events.LEVEL_SWITCHED).pipe(Al(({level:l})=>n(this.hls.levels[l])));o.pipe(JV(ZV)).subscribe(t.currentVideoTrack$,i),this.subscription.add(_i(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(eO(l))return;let d=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!d)return;let c=this.hls.levels.indexOf(d),h=this.hls.currentLevel,p=this.hls.levels[h];!p||d.bitrate>p.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=tO(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,rO(["init"])).pipe(XV(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 x(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pl.DOM,thrown:t})))||(this.videoState.setState("paused"),L(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"),L(this.params.desiredState.playbackState,"stopped",!0)}};var nE="X-Playback-Duration",Ah=s=>x(void 0,null,function*(){var r;let e=yield Mt(s),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(nE)?parseInt(e.headers.get(nE),10):void 0});import{assertNever as bO,combine as gO,debounce as SO,ErrorCategory as Ll,filter as vO,filterChanged as yO,isNonNullable as lE,isNullable as Ml,map as cE,merge as TO,observableFrom as IO,Subscription as xO,ValueSubject as Lh,VideoQuality as EO}from"@vkontakte/videoplayer-shared/es2015";var Rh=j(rd(),1);import{videoSizeToQuality as nO,getExponentialDelay as oO}from"@vkontakte/videoplayer-shared/es2015";var uO=s=>{let e=null;if(s.QUALITY&&(e=ti(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=nO({width:t,height:i})}return e!=null?e:null},lO=(s,e)=>{var a,n;let t=s.split(`
|
|
186
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,
|
|
187
|
-
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:l}),a=a+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(dO(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([B(E({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return x(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new le;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return x(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:mO.WTF,thrown:t,message:e})}};var xo=class{constructor(e){this.subscription=new xO;this.videoState=new Q("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Lh([]);this.liveOffset=new mr;this.manifestStartTime$=new Lh(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),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"),L(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(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),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&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),L(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"&&L(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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(L(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return bO(t)}};var i;this.params=e,this.video=He(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:EO.INVARIANT,url:this.params.source.url};let t=(r,a)=>kl(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Rl(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new pt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Ll.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Ll.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(Re(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Lh((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Ll.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Qe(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ze(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(dt(this.video,t.playbackRate,r.playbackRateState$,i)),a(ht(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(yO(),cE(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&lE(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Re(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(gO({startTime:this.manifestStartTime$.pipe(vO(lE)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(cE(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=TO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,IO(["init"])).pipe(SO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Ge(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Ml(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:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[d,"mq"],[c,"lq"]]){let f=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,f)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ie(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Ah(n).then(d=>{var c;if(!Ml(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(Ml(h)||!isFinite(h))&&Mt(n).then(p=>p.text()).then(p=>{var m;let f=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(f){let g=new URL(f,n).toString();Ah(g).then(S=>{Ml(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ll.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()}generateLiveUrl(){let e=Ie(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as wO,debounce as PO,ErrorCategory as Mh,fromEvent as $h,isNonNullable as AO,isNullable as kO,map as dE,merge as pE,observableFrom as hE,Subscription as RO,ValueSubject as LO,VideoQuality as MO}from"@vkontakte/videoplayer-shared/es2015";var Eo=class{constructor(e){this.subscription=new RO;this.videoState=new Q("stopped");this.manifests$=new LO([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),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"),L(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(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return wO(t)}};this.textTracksManager=new pt(e.source.url),this.params=e,this.video=He(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:MO.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(Re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),kl(Ie(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:Mh.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Mh.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Qe(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(dE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Lt(this.video,t.isLooped,i)),this.subscription.add(ze(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(dt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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 p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&AO(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===f);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Re(m.url)))}let c=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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(dE(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!G.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(pE($h(o,"addtrack"),$h(o,"removetrack"),$h(o,"change"),hE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=pE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,hE(["init"])).pipe(PO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ge(this.video)}prepare(){var a,n;let e=this.selectManifest();if(kO(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=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Mh.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var bE=j(nr(),1),Bh=j(fr(),1),gE=j(jt(),1);import{assertNever as $O,assertNonNullable as fE,debounce as BO,ErrorCategory as mE,isHigherOrEqual as DO,isLowerOrEqual as CO,isNonNullable as VO,merge as OO,observableFrom as _O,Subscription as FO,map as NO}from"@vkontakte/videoplayer-shared/es2015";var wo=class{constructor(e){this.subscription=new FO;this.videoState=new Q("stopped");this.trackUrls={};this.textTracksManager=new pt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?L(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return $O(e)}};this.params=e,this.video=He(e.container,e.tuning),this.params.output.element$.next(this.video),(0,bE.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Bh.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:mE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Qe(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(NO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Lt(this.video,t.isLooped,i)),this.subscription.add(ze(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(dt(this.video,t.playbackRate,r.playbackRateState$,i)),a(ht(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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&&VO(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=OO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,_O(["init"])).pipe(BO(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),Ge(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;fE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];fE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ji(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Re(t))}playIfAllowed(){We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:mE.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let h=ii(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,Bh.default)(this.trackUrls).map(c=>c.track);if(!r||!a||Kr(e,n[0].quality,(d=(0,gE.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?CO(r,e.max):!0,u=e.min?DO(r,e.min):!0;o&&u||i(e)}};import{assertNever as vE,debounce as HO,merge as yE,observableFrom as GO,Subscription as zO,map as TE,ValueSubject as QO,ErrorCategory as Ch,VideoQuality as WO}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as UO}from"@vkontakte/videoplayer-shared/es2015";var SE=["stun:videostun.mycdn.me:80"],qO=1e3,jO=3,Dh=()=>null,$l=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=Dh;this.externalStopCallback=Dh;this.externalErrorCallback=Dh;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 x(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 x(this,null,function*(){try{let e={iceServers:[{urls:SE}]};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 x(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return x(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:UO.WTF,message:e.message})}onPeerConnectionStream(e){return x(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 x(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),qO)}normalizeOptions(e={}){let t={stunServerList:SE,maxRetryNumber:jO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Po=class{constructor(e){this.videoState=new Q("stopped");this.maxSeekBackTime$=new QO(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"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return vE(e)}};this.subscription=new zO,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=He(e.container,e.tuning),this.liveStreamClient=new $l(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),Ge(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ch.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(yE(this.videoState.stateChangeStarted$.pipe(TE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(TE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Qe(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(ht(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(ze(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 vE(n.to)}},i)).add(yE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,GO(["init"])).pipe(HO(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(Re(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:WO.INVARIANT}),this.video.srcObject=e,L(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:Ch.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){We(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ch.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ao=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ro,assertNonNullable as Qi,ErrorCategory as Bl,filter as AE,isNonNullable as kE,isNullable as t_,map as i_,merge as r_,once as s_,Subject as Fe,Subscription as RE,ValueSubject as J,flattenObject as Vh}from"@vkontakte/videoplayer-shared/es2015";import{Observable as YO,map as IE,Subscription as KO,Subject as XO}from"@vkontakte/videoplayer-shared/es2015";var xE=s=>new YO(e=>{let t=new KO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(IE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(IE(({type:l})=>l!==void 0)),n=new XO,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as JO,Subscription as ZO,combine as e_,filter as wE,once as PE}from"@vkontakte/videoplayer-shared/es2015";function EE(){return new(window.AudioContext||window.webkitAudioContext)}var ko=class ko{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new le;this.subscriptions=new ZO;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(wE(a=>!!a.type),PE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){G.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(e_({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(wE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),PE()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return x(this,null,function*(){let{volumeMultiplier:t}=this,i=EE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:ko.errorId,category:JO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${ko.errorId} exception`,thrown:e})}};ko.errorId="VolumeMultiplierManager";var ws=ko;var a_={chunkDuration:5e3,maxParallelRequests:5},Lo=class{constructor(e){this.current$=new J({type:void 0});this.providerError$=new Fe;this.noAvailableProvidersError$=new Fe;this.volumeMultiplierError$=new Fe;this.providerOutput={position$:new J(0),duration$:new J(1/0),volume$:new J({muted:!1,volume:1}),availableVideoStreams$:new J([]),currentVideoStream$:new J(void 0),availableVideoTracks$:new J([]),currentVideoTrack$:new J(void 0),availableAudioStreams$:new J([]),currentAudioStream$:new J(void 0),availableAudioTracks$:new J([]),currentVideoSegmentLength$:new J(0),currentAudioSegmentLength$:new J(0),isAudioAvailable$:new J(!0),autoVideoTrackLimitingAvailable$:new J(!1),autoVideoTrackLimits$:new J(void 0),currentBuffer$:new J(void 0),isBuffering$:new J(!0),error$:new Fe,fetcherError$:new Fe,fetcherRecoverableError$:new Fe,warning$:new Fe,willSeekEvent$:new Fe,soundProhibitedEvent$:new Fe,seekedEvent$:new Fe,loopedEvent$:new Fe,endedEvent$:new Fe,firstBytesEvent$:new Fe,loadedMetadataEvent$:new Fe,firstFrameEvent$:new Fe,canplay$:new Fe,isLive$:new J(void 0),isLiveEnded$:new J(null),isLowLatency$:new J(!1),canChangePlaybackSpeed$:new J(!0),liveTime$:new J(void 0),liveBufferTime$:new J(void 0),liveLatency$:new J(void 0),severeStallOccurred$:new Fe,availableTextTracks$:new J([]),currentTextTrack$:new J(void 0),hostname$:new J(void 0),httpConnectionType$:new J(void 0),httpConnectionReused$:new J(void 0),inPiP$:new J(!1),inFullscreen$:new J(!1),element$:new J(void 0),elementVisible$:new J(!0),availableSources$:new J(void 0),is3DVideo$:new J(!1),playbackState$:new J(""),getCurrentTime$:new J(null)};this.subscription=new RE;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=rx([...ax(this.params.tuning),...sx(this.params.tuning)],this.params.tuning).filter(l=>kE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Oh.default)(r,l)),...t.filter(l=>(0,Oh.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Vh(a)),this.screenFormatsIterator=new Ao(a);let n=[..._p(!0),..._p(!1)];this.chromecastFormatsIterator=new Ao(n.filter(l=>kE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ws.isSupported()&&(this.volumeMultiplierManager=new ws(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(t_(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Bl.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"),e.destroy();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})}let a=this.providerOutput.isBuffering$;a.getValue()||a.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 Ro(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Qi(u),this.params.tuning.useNewDashProvider?new vo(B(E({},o),{source:u,sourceHls:l})):new Cn(B(E({},o),{source:u,sourceHls:l}))}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Qi(u),this.params.tuning.useNewDashProvider?new yo(B(E({},o),{source:u})):new Vn(B(E({},o),{source:u}))}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Qi(u),G.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Eo(B(E({},o),{source:u})):new Io(B(E({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Qi(u),new xo(B(E({},o),{source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Qi(u),new wo(B(E({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Qi(u),new rT(B(E({},o),{source:u,config:B(E({},a_),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Qi(u),new Po({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ro(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Qi(o),new Da({connection:o,meta:a,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 Ro(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ro(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 Ro(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return B(E({},e),{url:i(e.url)})}return(0,ME.default)((0,LE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new RE,t=!1,i=0;return e.add(r_(this.providerOutput.error$.pipe(AE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),xE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(i_(r=>({id:`ProviderHangup:${r}`,category:Bl.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(AE(({to:a})=>a==="playing"),s_()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Bl.NETWORK,u=r.category===Bl.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n=B(E({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d}),d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Vh(n)):this.tracer.error("providerError",Vh(n))})),e}};import{fromEvent as Dl,once as n_,combine as o_,Subscription as $E,ValueSubject as _h,map as u_,filter as l_,isNonNullable as Cl,now as kt,safeStorage as Fh}from"@vkontakte/videoplayer-shared/es2015";var c_=5e3,BE="one_video_throughput",DE="one_video_rtt",Mi=window.navigator.connection,CE=()=>{let s=Mi==null?void 0:Mi.downlink;if(Cl(s)&&s!==10)return s*1e3},VE=()=>{let s=Mi==null?void 0:Mi.rtt;if(Cl(s)&&s!==3e3)return s},OE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Nh=class s{constructor(e){this.subscription=new $E;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(BE)||(e.useBrowserEstimation?CE():void 0)||c_,i=(a=(r=s.load(DE))!=null?r:e.useBrowserEstimation?VE():void 0)!=null?a:0;if(this.throughput$=new _h(t),this.rtt$=new _h(i),this.rttAdjustedThroughput$=new _h(OE(t,i,e.rttPenaltyRequestSize)),this.throughput=Ai.getSmoothedValue(t,-1,e),this.rtt=Ai.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=CE();u&&this.throughput.next(u);let l=VE();Cl(l)&&this.rtt.next(l)};Mi&&"onchange"in Mi&&this.subscription.add(Dl(Mi,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Fh.set(BE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Fh.set(DE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(o_({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(u_(({throughput:n,rtt:o})=>OE(n,o,e.rttPenaltyRequestSize)),l_(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=kt(),r=new $E;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Dl(e,"progress").pipe(n_()).subscribe(a=>{t=a.loaded,i=kt()}));break;case 1:case 0:r.add(Dl(e,"loadstart").subscribe(()=>{t=0,i=kt()}));break}r.add(Dl(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=kt(),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,a=kt(),n=0,o=kt(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=h=>x(this,[h],function*({done:d,value:c}){if(d)!t&&this.addRawSpeed(r,kt()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=kt();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(n,m,1,t),n=c.byteLength,a=kt()}else n+=c.byteLength;o=kt()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&kt()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,kt()-o,this.concurrentDownloads.size),n=0,o=kt());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(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=Fh.get(e);if(Cl(t))return(i=parseInt(t,10))!=null?i:void 0}},_E=Nh;import{fillWithDefault as d_,VideoQuality as Vl}from"@vkontakte/videoplayer-shared/es2015";var FE={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:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Vl.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Vl.Q_720P,trafficSavingLimit:Vl.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Vl.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,useOldFetherInNewDashProvider:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!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,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},NE=s=>{var e;return B(E({},d_(s,FE)),{configName:[...(e=s.configName)!=null?e:[],...FE.configName]})};import{assertNonNullable as Ol,combine as $i,ErrorCategory as _l,filter as Y,filterChanged as ae,fromEvent as qh,isNonNullable as HE,isNullable as S_,Logger as v_,map as re,mapTo as GE,merge as Wi,now as Fl,once as Z,Subject as oe,Subscription as zE,tap as jh,ValueSubject as _,isHigher as y_,isInvariantQuality as QE,flattenObject as Yi,throttle as Hh,getTraceSubscriptionMethod as WE,Tracer as T_,InternalsExposure as I_}from"@vkontakte/videoplayer-shared/es2015";import{merge as p_,map as h_,filter as UE,isNonNullable as f_}from"@vkontakte/videoplayer-shared/es2015";var Uh=({seekState:s,position$:e})=>p_(s.stateChangeEnded$.pipe(h_(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),UE(f_)),e.pipe(UE(()=>s.getState().state==="none")));import{assertNonNullable as m_}from"@vkontakte/videoplayer-shared/es2015";var qE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return m_(e,`Wrong container or containerId {${s.container}}`),e};import{filter as b_,once as g_}from"@vkontakte/videoplayer-shared/es2015";var jE=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(b_(r=>r.length>0),g_()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Nl=class{constructor(e={configName:[]},t=T_.createRootTracer(!1)){this.subscription=new zE;this.logger=new v_;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new _(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new _(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new Q("stopped"),seekState:new Q({state:"none"}),volume:new Q({volume:1,muted:!1}),videoTrack:new Q(void 0),videoStream:new Q(void 0),audioStream:new Q(void 0),autoVideoTrackSwitching:new Q(!0),autoVideoTrackLimits:new Q({}),isLooped:new Q(!1),isLowLatency:new Q(!1),playbackRate:new Q(1),externalTextTracks:new Q([]),internalTextTracks:new Q([]),currentTextTrack:new Q(void 0),textTrackCuesSettings:new Q({}),cameraOrientation:new Q({x:0,y:0})};this.info={playbackState$:new _(void 0),position$:new _(0),duration$:new _(1/0),muted$:new _(!1),volume$:new _(1),availableVideoStreams$:new _([]),currentVideoStream$:new _(void 0),availableQualities$:new _([]),availableQualitiesFps$:new _({}),currentQuality$:new _(void 0),isAutoQualityEnabled$:new _(!0),autoQualityLimitingAvailable$:new _(!1),autoQualityLimits$:new _({}),predefinedQualityLimitType$:new _("unknown"),availableAudioStreams$:new _([]),currentAudioStream$:new _(void 0),availableAudioTracks$:new _([]),isAudioAvailable$:new _(!0),currentPlaybackRate$:new _(1),currentBuffer$:new _({start:0,end:0}),isBuffering$:new _(!0),isStalled$:new _(!1),isEnded$:new _(!1),isLooped$:new _(!1),isLive$:new _(void 0),isLiveEnded$:new _(null),canChangePlaybackSpeed$:new _(void 0),atLiveEdge$:new _(void 0),atLiveDurationEdge$:new _(void 0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),currentFormat$:new _(void 0),availableTextTracks$:new _([]),currentTextTrack$:new _(void 0),throughputEstimation$:new _(void 0),rttEstimation$:new _(void 0),videoBitrate$:new _(void 0),hostname$:new _(void 0),httpConnectionType$:new _(void 0),httpConnectionReused$:new _(void 0),surface$:new _("none"),chromecastState$:new _("NOT_AVAILABLE"),chromecastDeviceName$:new _(void 0),intrinsicVideoSize$:new _(void 0),availableSources$:new _(void 0),is3DVideo$:new _(!1),currentVideoSegmentLength$:new _(0),currentAudioSegmentLength$:new _(0)};this.events={inited$:new oe,ready$:new oe,started$:new oe,playing$:new oe,paused$:new oe,stopped$:new oe,willStart$:new oe,willResume$:new oe,willPause$:new oe,willStop$:new oe,willDestruct$:new oe,watchCoverageRecord$:new oe,watchCoverageLive$:new oe,managedError$:new oe,fatalError$:new oe,fetcherRecoverableError$:new oe,ended$:new oe,looped$:new oe,seeked$:new oe,willSeek$:new oe,autoplaySoundProhibited$:new oe,firstBytes$:new oe,loadedMetadata$:new oe,firstFrame$:new oe,canplay$:new oe,log$:new oe,fetcherError$:new oe,severeStallOccured$:new oe};this.experimental={element$:new _(void 0),tuningConfigName$:new _([]),enableDebugTelemetry$:new _(!1),dumpTelemetry:Ry,getCurrentTime$:new _(null)};if(this.initLogs(),this.tuning=NE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Fo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new _E(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new I_("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let m=typeof f;return(0,YE.default)(["number","string","boolean"],m)?f:f===null?null:`<${m}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:_l.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var l,d,c;let u=e,{container:n}=u,o=Qh(u,["container"]);this.tracer.log("initVideo",Yi(o)),this.domContainer=qE(e),this.chromecastInitializer.contentId=(l=e.meta)==null?void 0:l.videoId,this.providerContainer=new Lo({sources:e.sources,meta:(d=e.meta)!=null?d:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],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,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?G.isInited$.pipe(Y(n=>!!n),Z()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),qh(document,"visibilitychange").pipe(Z()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(Y(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(Y(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(Y(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(Y(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(Y(i=>!!i),Z()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(Y(i=>!!i),Z()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),a=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:a,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{Ol(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Y(i=>i.length>0),Z()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Yi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{var i;Ol(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Yi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>E({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{var t;jE(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.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",E({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(Y(i=>!!i),Z()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(Y(t=>!!t),Z()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(Y(i=>!!i),Z()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(Y(e=>e),Z()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(Y(e=>!!e),Z()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(S_(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return HE(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(Wi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(re(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(tp(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Y(({from:e})=>e==="stopped"),Z()).subscribe(()=>{this.initedAt=Fl(),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",Yi(n)),n.state==="requested"?this.desiredState.seekState.setState(B(E({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:_l.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Z()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Yi(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(re(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(re(n=>n.destination),ae()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add($i({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(re(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>QE(u)?1:QE(l)?-1:y_(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(ae()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(Y(n=>HE(n))).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(ae((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(ae((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(ae()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ae()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ae()).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(re(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.isLiveEnded$.pipe(jh(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add($i({hasLiveOffsetByPaused:Wi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(re(n=>n.to),ae(),re(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($i({atLiveEdge:$i({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Uh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(re(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),ae(),jh(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(re(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add($i({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(re(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ae(),jh(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(re(n=>n.muted),ae()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(re(n=>n.volume),ae()).subscribe(this.info.volume$)).add(Uh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Wi(e.providerOutput.endedEvent$.pipe(GE(!0)),e.providerOutput.seekedEvent$.pipe(GE(!1))).pipe(ae()).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.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(re(n=>({id:n?`No${n}`:"NoProviders",category:_l.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.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(Z(),re(n=>n!=null?n:Fl()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Z(),re(()=>Fl()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Z(),re(()=>Fl()-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 _(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new _(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Y(({to:n})=>n==="playing"),Z()).subscribe(()=>i.next(!1)));let r=0,a=Wi(e.providerOutput.isBuffering$,t,i).pipe(re(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ae());this.subscription.add(a.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(Wi(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(Wi(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(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(re(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 zE;this.subscription.add(t),this.subscription.add(e.current$.pipe(ae((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Y(i=>i.length>0),Z()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=ii(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Wi(this.desiredState.videoTrack.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(re(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;Ol(this.providerContainer),Ol(e),ky(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Ay(i)),this.providerContainer.current$.subscribe(({type:i})=>_a("provider",i)),e.duration$.subscribe(i=>_a("duration",i)),e.availableVideoTracks$.pipe(Y(i=>!!i.length),Z()).subscribe(i=>_a("tracks",i)),this.events.fatalError$.subscribe(new nt("fatalError")),this.events.managedError$.subscribe(new nt("managedError")),e.position$.subscribe(new nt("position")),e.currentVideoTrack$.pipe(re(i=>i==null?void 0:i.quality)).subscribe(new nt("quality")),this.info.currentBuffer$.subscribe(new nt("buffer")),e.isBuffering$.subscribe(new nt("isBuffering"))].forEach(i=>this.subscription.add(i)),_a("codecs",G.video.supportedCodecs)}initTracerSubscription(){let e=WE(this.tracer.log.bind(this.tracer)),t=WE(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(ae()).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($i({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(Y(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),ae((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(Y(i=>i>0),ae()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(Y(i=>i>0),ae()).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($i({currentBuffer:this.info.currentBuffer$.pipe(Y(i=>i.end>0),ae((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(ae())}).pipe(Hh(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(ae()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(ae()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(ae()).subscribe(e("canChangePlaybackSpeed"))).add($i({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Y(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Hh(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(ae(),Y(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(ae(),Y(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(ae()).subscribe(e("muted"))).add(this.info.volume$.pipe(ae()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(ae(),Y(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add($i({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Y(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Hh(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(ae(),Y(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=()=>x(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:_l.DOM,message:String(r)})})});this.subscription.add(Wi(qh(document,"visibilitychange"),qh(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Yi({quality:t,availableTracks:Yi(e),track:Yi(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}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ga()}};import{Subscription as eie,Observable as tie,Subject as iie,ValueSubject as rie,VideoQuality as sie}from"@vkontakte/videoplayer-shared/es2015";var aie=`@vkontakte/videoplayer-core@${Wh}`;export{$o as ChromecastState,Kl as HttpConnectionType,tie as Observable,ct as PlaybackState,Nl as Player,Bo as PredefinedQualityLimits,aie as SDK_VERSION,iie as Subject,eie as Subscription,Xl as Surface,Wh as VERSION,rie as ValueSubject,vi as VideoFormat,sie as VideoQuality,G as clientChecker,Oa as isMobile};
|
|
185
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Zp=H(qt(),1);import{videoSizeToQuality as pV,throttleFn as hV}from"@vkontakte/videoplayer-shared/es2015";var Px=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Oi(a):void 0)!=null?u:pV({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},kx=({id:s,bitrate:e})=>({id:s,bitrate:e}),Rx=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Mx=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),eh=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Zp.default)(i.split("."),0),isDefault:r}),th=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Zp.default)(r.split("."),0)}),ih=s=>"url"in s,st=s=>s.type==="template",ao=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Lx=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},Ir=(s,e)=>{for(let t of s)if(e(t))return t;return null},Bx=s=>{let e=!1,t=hV(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var Dx=s=>{if(!(s!=null&&s.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(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={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 a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},ki=(s,e)=>{let t=s;t=(0,rh.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Cx.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,rh.default)(t,n,(o,u)=>$x(a)?o:$x(u)?a:(0,Vx.default)(a,parseInt(u,10),"0"))}return t},_x=(s,e)=>{var $,w,F,M,j,N,K,P,L,R,A,O,de,Fe,ue,ee,Ee,we,Ae,Ne,At,Lt,Gt,ii,Li,Is,xs,Es,ws,As,Ps,ks,Rs,Ms,Ls,Bs,$s,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,zs,Qs,Gs,Ws,Ys,Ks,Xs,Js,Zs,ea,ta,ia,ra;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(fe=>{var q,Ge;return(Ge=(q=fe.textContent)==null?void 0:q.trim())!=null?Ge:""}),o=($=(0,Ox.default)(n,0))!=null?$:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],T=y.reduce((fe,q)=>B(x({},fe),{[q.id]:q.children}),{}),I=y.reduce((fe,q)=>B(x({},fe),{[q.id]:q.getAttribute("duration")}),{});v?S=Dx(v):(0,sh.default)(I).filter(fe=>fe).length&&!u?S=(0,sh.default)(I).reduce((fe,q)=>{var Ge;return fe+((Ge=Dx(q))!=null?Ge:0)},0):m&&(S=parseInt(m,10));let k=0,C=(F=(w=a.getAttribute("profiles"))==null?void 0:w.split(","))!=null?F:[];for(let fe of y.map(q=>q.id))for(let q of T[fe]){let Ge=(M=q.getAttribute("id"))!=null?M:"id"+(k++).toString(10),Bt=(j=q.getAttribute("mimeType"))!=null?j:"",Wi=(N=q.getAttribute("codecs"))!=null?N:"",Yi=(K=q.getAttribute("contentType"))!=null?K:Bt==null?void 0:Bt.split("/")[0],Cl=(L=(P=q.getAttribute("profiles"))==null?void 0:P.split(","))!=null?L:[],sa=(A=Ax((R=q.getAttribute("lang"))!=null?R:""))!=null?A:{},ri=(Fe=(de=(O=q.querySelector("Label"))==null?void 0:O.textContent)==null?void 0:de.trim())!=null?Fe:void 0,Vl=q.querySelectorAll("Representation"),Ol=q.querySelector("SegmentTemplate"),_l=(ee=(ue=q.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?ee:void 0,ht=Yi,G={id:Ge,language:sa.language,isDefault:_l==="main",label:ri,codecs:Wi,hdr:ht==="video"&&as(Wi),mime:Bt,representations:[]};for(let U of Vl){let Re=(Ee=U.getAttribute("lang"))!=null?Ee:void 0,$t=(Ae=(we=ri!=null?ri:q.getAttribute("label"))!=null?we:U.getAttribute("label"))!=null?Ae:void 0,si=(Lt=(At=(Ne=U.querySelector("BaseURL"))==null?void 0:Ne.textContent)==null?void 0:At.trim())!=null?Lt:"",We=new URL(si||o,e).toString(),Me=(Gt=U.getAttribute("mimeType"))!=null?Gt:Bt,ai=(Li=(ii=U.getAttribute("codecs"))!=null?ii:Wi)!=null?Li:"",ni;if(Yi==="text"){let Le=U.getAttribute("id")||"",oi=((Is=sa.privateuse)==null?void 0:Is.includes("x-auto"))||Le.includes("_auto"),Ye=U.querySelector("SegmentTemplate");if(Ye){let Dt={representationId:(xs=U.getAttribute("id"))!=null?xs:void 0,bandwidth:(Es=U.getAttribute("bandwidth"))!=null?Es:void 0},ui=parseInt((ws=U.getAttribute("bandwidth"))!=null?ws:"",10)/1e3,li=(Ps=parseInt((As=Ye.getAttribute("startNumber"))!=null?As:"",10))!=null?Ps:1,ft=parseInt((ks=Ye.getAttribute("timescale"))!=null?ks:"",10),Ki=(Rs=Ye.querySelectorAll("SegmentTimeline S"))!=null?Rs:[],mt=Ye.getAttribute("media");if(!mt)continue;let ci=[],di=0,pi="",bt=0,Ct=li,se=0;for(let me of Ki){let Ke=parseInt((Ms=me.getAttribute("d"))!=null?Ms:"",10),ce=parseInt((Ls=me.getAttribute("r"))!=null?Ls:"",10)||0,Be=parseInt((Bs=me.getAttribute("t"))!=null?Bs:"",10);se=Number.isFinite(Be)?Be:se;let Xe=Ke/ft*1e3,$e=se/ft*1e3;for(let ve=0;ve<ce+1;ve++){let De=ki(mt,B(x({},Dt),{segmentNumber:Ct.toString(10),segmentTime:(se+ve*Ke).toString(10)})),gt=($e!=null?$e:0)+ve*Xe,Ot=gt+Xe;Ct++,ci.push({time:{from:gt,to:Ot},url:De})}se+=(ce+1)*Ke,di+=(ce+1)*Xe}bt=se/ft*1e3,pi=ki(mt,B(x({},Dt),{segmentNumber:Ct.toString(10),segmentTime:se.toString(10)}));let Vt={time:{from:bt,to:1/0},url:pi},Pe={type:"template",baseUrl:We,segmentTemplateUrl:mt,initUrl:"",totalSegmentsDurationMs:di,segments:ci,nextSegmentBeyondManifest:Vt,timescale:ft};ni={id:Le,kind:"text",segmentReference:Pe,profiles:[],duration:S,bitrate:ui,mime:"",codecs:"",width:0,height:0,isAuto:oi}}else ni={id:Le,isAuto:oi,kind:"text",url:We}}else{let Le=(Ds=($s=U.getAttribute("contentType"))!=null?$s:Me==null?void 0:Me.split("/")[0])!=null?Ds:Yi,oi=(Vs=(Cs=q.getAttribute("profiles"))==null?void 0:Cs.split(","))!=null?Vs:[],Ye=parseInt((Os=U.getAttribute("width"))!=null?Os:"",10),Dt=parseInt((_s=U.getAttribute("height"))!=null?_s:"",10),ui=parseInt((Fs=U.getAttribute("bandwidth"))!=null?Fs:"",10)/1e3,li=(Ns=U.getAttribute("frameRate"))!=null?Ns:"",ft=(Us=U.getAttribute("quality"))!=null?Us:void 0,Ki=li?_u(li):void 0,mt=(qs=U.getAttribute("id"))!=null?qs:"id"+(k++).toString(10),ci=Le==="video"?`${Dt}p`:Le==="audio"?`${ui}Kbps`:ai,di=`${mt}@${ci}`,pi=[...C,...Cl,...oi],bt,Ct=U.querySelector("SegmentBase"),se=(js=U.querySelector("SegmentTemplate"))!=null?js:Ol;if(Ct){let Pe=(zs=(Hs=U.querySelector("SegmentBase Initialization"))==null?void 0:Hs.getAttribute("range"))!=null?zs:"",[me,Ke]=Pe.split("-").map(De=>parseInt(De,10)),ce={from:me,to:Ke},Be=(Qs=U.querySelector("SegmentBase"))==null?void 0:Qs.getAttribute("indexRange"),[Xe,$e]=Be?Be.split("-").map(De=>parseInt(De,10)):[],ve=Be?{from:Xe,to:$e}:void 0;bt={type:"byteRange",url:We,initRange:ce,indexRange:ve}}else if(se){let Pe={representationId:(Gs=U.getAttribute("id"))!=null?Gs:void 0,bandwidth:(Ws=U.getAttribute("bandwidth"))!=null?Ws:void 0},me=parseInt((Ys=se.getAttribute("timescale"))!=null?Ys:"",10),Ke=(Ks=se.getAttribute("initialization"))!=null?Ks:"",ce=se.getAttribute("media"),Be=(Js=parseInt((Xs=se.getAttribute("startNumber"))!=null?Xs:"",10))!=null?Js:1,Xe=ki(Ke,Pe);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let $e=(Zs=se.querySelectorAll("SegmentTimeline S"))!=null?Zs:[],ve=[],De=0,gt="",Ot=0;if($e.length){let hi=Be,be=0;for(let St of $e){let ye=parseInt((ea=St.getAttribute("d"))!=null?ea:"",10),Je=parseInt((ta=St.getAttribute("r"))!=null?ta:"",10)||0,fi=parseInt((ia=St.getAttribute("t"))!=null?ia:"",10);be=Number.isFinite(fi)?fi:be;let Xi=ye/me*1e3,Ji=be/me*1e3;for(let mi=0;mi<Je+1;mi++){let Nl=ki(ce,B(x({},Pe),{segmentNumber:hi.toString(10),segmentTime:(be+mi*ye).toString(10)})),aa=(Ji!=null?Ji:0)+mi*Xi,Ul=aa+Xi;hi++,ve.push({time:{from:aa,to:Ul},url:Nl})}be+=(Je+1)*ye,De+=(Je+1)*Xi}Ot=be/me*1e3,gt=ki(ce,B(x({},Pe),{segmentNumber:hi.toString(10),segmentTime:be.toString(10)}))}else if(fV(S)){let be=parseInt((ra=se.getAttribute("duration"))!=null?ra:"",10)/me*1e3,St=Math.ceil(S/be),ye=0;for(let Je=1;Je<St;Je++){let fi=ki(ce,B(x({},Pe),{segmentNumber:Je.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:fi}),ye+=be}Ot=ye,gt=ki(ce,B(x({},Pe),{segmentNumber:St.toString(10),segmentTime:ye.toString(10)}))}let Fl={time:{from:Ot,to:1/0},url:gt};bt={type:"template",baseUrl:We,segmentTemplateUrl:ce,initUrl:Xe,totalSegmentsDurationMs:De,segments:ve,nextSegmentBeyondManifest:Fl,timescale:me}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Le||!Me)continue;let Vt={video:"video",audio:"audio",text:"text"}[Le];if(!Vt)continue;ht||(ht=Vt),ni={id:di,kind:Vt,segmentReference:bt,profiles:pi,duration:S,bitrate:ui,mime:Me,codecs:ai,width:Ye,height:Dt,fps:Ki,quality:ft}}G.language||(G.language=Re),G.label||(G.label=$t),G.mime||(G.mime=Me),G.codecs||(G.codecs=ai),G.hdr||(G.hdr=ht==="video"&&as(ai)),G.representations.push(ni)}if(ht){let U=r[ht].find(Re=>Re.id===G.id);if(U&&G.representations.every(Re=>st(Re.segmentReference)))for(let Re of U.representations){let $t=G.representations.find(Me=>Me.id===Re.id),si=$t==null?void 0:$t.segmentReference,We=Re.segmentReference;We.segments.push(...si.segments),We.nextSegmentBeyondManifest=si.nextSegmentBeyondManifest}else r[ht].push(G)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{fromEvent as mV,Subscription as bV}from"@vkontakte/videoplayer-shared/es2015";var ll=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var cl=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new bV;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(mV(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!z(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=ll(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var no=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Er(0);this.currentLowLatencySegmentLength$=new Er(0);this.currentSegmentLength$=new Er(0);this.onLastSegment$=new Er(!1);this.fullyBuffered$=new Er(!1);this.playingRepresentation$=new Er(void 0);this.playingRepresentationInit$=new Er(void 0);this.error$=new SV;this.gaps=[];this.subscription=new vV;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new le;this.switchAbortController=new le;this.destroyAbortController=new le;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Hi(this.destroyAbortController.signal,function(e){return X(this,null,function*(){let t=this.representations.get(e);pt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Sx(this.sourceBuffer),this.sourceBufferBufferedDiff=new cl(this.mediaSource,this.sourceBuffer),this.subscription.add(nh(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(nh(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:xr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!z(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,is(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Oe(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),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),a=this.parsedInitData.get(t.id);pt(i,"No init buffer for starting representation"),pt(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))})}.bind(this));this.switchTo=Hi(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);pt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Qe(a)||Qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),pt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ms(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Zi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Hi(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);pt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Qe(a)||Qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),pt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ms(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Zi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Hi(this.destroyAbortController.signal,function(e){return X(this,null,function*(){var u,l;let t=(u=(0,hl.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!st(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);pt(r);let a=this.segments.get(i);pt(a,"No segments for starting representation");let n=this.initData.get(i);if(pt(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],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}switchToWithPreviousAbort(e,t=!1){!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,Hi(this.switchAbortController.signal,function(i,r=!1){return X(this,null,function*(){this.switchingToRepresentationId=i;let a=this.representations.get(i);pt(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Qe(o)||Qe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),pt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ms(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!Qe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return E(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new le,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(Qe(e)||Qe(this.downloadingRepresentationId)||Qe(this.playingRepresentationId)||Qe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||ms(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(pt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ms(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=Oe(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&is(this.sourceBuffer.buffered)>=this.bufferLimit){let d=Oe(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,pl.default)(u,r))d="high";else{let c=(0,bs.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&Oe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,bs.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Oe(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;ms(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,hl.default)(e==null?void 0:e.streams[this.kind],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,a,n;let t=(i=(0,hl.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!st(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>B(x({},p),{status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,bs.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;pt(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!st(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.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=ki(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a: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,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&ei&&ei(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ei&&ei(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:h,to:p}},f)=>{let m=h<=i&&p>=i,g=h>i||m||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+S||p<=i+S;return(c==="none"||c==="partially_ejected"&&g&&v&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(He(this.sourceBuffer.buffered,h)&&He(this.sourceBuffer.buffered,p)))&&g&&v});if(r===-1)return null;if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,i="auto"){return E(this,null,function*(){st(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return E(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:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Hi(o,function(){return X(this,null,function*(){let d=oh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=dl(),!d)return;let c=new DataView(d),h=so(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),ao(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())st(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return E(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:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Hi(n,function(){return X(this,null,function*(){let u=oh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),nh(window,"online").pipe(gV()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=dl(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ao(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(st(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,bs.default)(e,0).byte.from,to:(0,bs.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>E(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=dl(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:xr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!st(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=dl();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:xr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,pl.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return E(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=so(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return E(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!z(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let{segment:d}=l,c=d.byte.from-i,h=d.byte.to-i,p=h-c+1,f=c<r,m=h<=r;if(f){if(d.status==="downloading"&&m){d.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(g,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?g:so(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(d.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,a))&&!a.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}}})}onSegmentFullyAppended(e,t){if(!(Qe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer))){!this.isLive&&Q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(He(this.sourceBuffer.buffered,e.segment.time.from,100)&&He(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:xr.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ih(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&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,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=ts(()=>(0,Fx.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return E(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Hi(this.destroyAbortController.signal,function(){return X(this,null,function*(){let o=oh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,so(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&st(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:xr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return E(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 E(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Qe(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push(x({},o.time));let u=ih(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let h of c)(0,pl.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=Lx(r),(yield Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1})}abortBuffer(){return E(this,null,function*(){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Qe(e)?0:Oe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!z(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||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=ts(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:xr.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Qe(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||Qe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=ll(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],h=e[d+1];u||(u=c-t<=n&&h+t>=o),(n>=c&&n<h-t||o>c+t&&o<=h)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:xr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as oo,assertNever as Nx,fromEvent as Ux,merge as yV,now as uo,Subject as qx,ValueSubject as uh,flattenObject as gs,ErrorCategory as lo,SubscriptionRemovable as TV}from"@vkontakte/videoplayer-shared/es2015";var ml=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new uh(void 0);this.lastConnectionReused$=new uh(void 0);this.lastRequestFirstBytes$=new uh(void 0);this.recoverableError$=new qx;this.error$=new qx;this.abortAllController=new le;this.subscription=new TV;this.fetchManifest=oo(this.abortAllController.signal,function(e){return X(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ui(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=ju(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(fl);return r?(t.log("success",gs({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",gs({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=oo(this.abortAllController.signal,function(l){return X(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var j,N,K;let d=e,c=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let P=new URL(d,location.href);P.searchParams.append("bytes",`${i.from}-${i.to}`),d=P.toString();break}default:Nx(t)}this.requestQuic&&(d=Ui(d));let p=this.abortAllController.signal,f;if(n){let P=new le;if(f=yV(Ux(this.abortAllController.signal,"abort"),Ux(n,"abort")).subscribe(()=>{try{P.abort()}catch(L){fl(L)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{P.abort()}catch(L){fl(L)}p=P.signal}let m=uo();h.log("startRequest",gs({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(d,{priority:a,headers:c,signal:p}),S=uo();if(!g)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(f),null;if((j=this.throughputEstimator)==null||j.addRawRtt(S-m),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);let P=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:P}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let P=uo(),L={requestStartedAt:m,requestEndedAt:P,duration:P-m};return h.log("endRequest",gs(L)),h.end(),g.arrayBuffer()}let v=g.body;if(o){let P;[v,P]=g.body.tee(),(N=this.throughputEstimator)==null||N.trackStream(P,u)}let y=v.getReader(),T,I=parseInt((K=g.headers.get("content-length"))!=null?K:"",10);Number.isFinite(I)&&(T=I),!T&&i&&(T=i.to-i.from+1);let k=0,C=T?new Uint8Array(T):new Uint8Array(0),V=!1,$=P=>{this.unsubscribeAbortSubscription(f),V=!0,fl(P)},w=oo(p,function(R){return X(this,arguments,function*({done:P,value:L}){if(k===0&&this.lastRequestFirstBytes$.next(uo()-m),p.aborted){this.unsubscribeAbortSubscription(f);return}if(!P&&L){if(T)C.set(L,k),k+=L.byteLength;else{let A=new Uint8Array(C.length+L.length);A.set(C),A.set(L,C.length),C=A,k+=L.byteLength}r==null||r(new DataView(C.buffer),k),yield y==null?void 0:y.read().then(w,$)}})}.bind(this));yield y==null?void 0:y.read().then(w,$),this.unsubscribeAbortSubscription(f);let F=uo(),M={failed:V,requestStartedAt:m,requestEndedAt:F,duration:F-m};return V?(h.error("endRequest",gs(M)),h.end(),null):(h.log("endRequest",gs(M)),h.end(),C.buffer)})}.bind(this));this.fetchByteRangeRepresentation=oo(this.abortAllController.signal,function(e,t,i){return X(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}})}.bind(this));this.fetchTemplateRepresentation=oo(this.abortAllController.signal,function(e,t){return X(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=>B(x({},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"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=qu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return E(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:Nx(r)}})}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}doFetch(e,t){return E(this,null,function*(){let i=yield Mt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:lo.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:lo.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:lo.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:lo.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:lo.FATAL})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},fl=s=>{if(!ao(s))throw s};import{isNullable as IV,ValueSubject as xV}from"@vkontakte/videoplayer-shared/es2015";var co=class s{constructor(e,t){this.currentRepresentation$=new xV(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!IV(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(B(x({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&st(t.segmentReference))}};var kV=["progress","play","seeked","stalled","waiting"],RV=["timeupdate","progress","loadeddata","playing","seeked"];var Sl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new hh;this.representationSubscription=new hh;this.state$=new Y("none");this.currentVideoRepresentation$=new Se(void 0);this.currentVideoRepresentationInit$=new Se(void 0);this.currentAudioRepresentation$=new Se(void 0);this.currentVideoSegmentLength$=new Se(0);this.currentAudioSegmentLength$=new Se(0);this.error$=new gl;this.lastConnectionType$=new Se(void 0);this.lastConnectionReused$=new Se(void 0);this.lastRequestFirstBytes$=new Se(void 0);this.currentLiveTextRepresentation$=new Se(null);this.isLive$=new Se(!1);this.isActiveLive$=new Se(!1);this.isLowLatency$=new Se(!1);this.liveDuration$=new Se(0);this.liveSeekableDuration$=new Se(0);this.liveAvailabilityStartTime$=new Se(0);this.liveStreamStatus$=new Se(void 0);this.bufferLength$=new Se(0);this.liveLatency$=new Se(void 0);this.liveLoadBufferLength$=new Se(0);this.livePositionFromPlayer$=new Se(0);this.currentStallDuration$=new Se(0);this.videoLastDataObtainedTimestamp$=new Se(0);this.fetcherRecoverableError$=new gl;this.fetcherError$=new gl;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new gl;this.gapWatchdogActive=!1;this.destroyController=new le;this.initManifest=ch(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ie(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:Qt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ch(this.destroyController.signal,function(){return X(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:Qt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=_x(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Ou(e))!=null?n:{id:"ManifestParsing",category:Qt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=Et())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=Ju(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);Q.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a=B(x({},t),{streams:r});return this.tracer.log("updateManifestEnd",ho(a)),a})}.bind(this));this.initRepresentations=ch(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",ho({initialVideo:e,initialAudio:t,sourceHls:i})),Ss(this.manifest),Ss(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new hh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(ti(p,"error").pipe(bl(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Qt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?hu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Gr())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.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new no("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],fo(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new no("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}co.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new co(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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(wr(...RV.map(p=>ti(this.element,p))).pipe(ys(p=>this.element?Oe(this.element.buffered,this.element.currentTime*1e3):0),po(),PV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(wr(ti(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(po()).subscribe(f=>this.liveStreamEndTimestamp=ph())),this.subscription.add(ti(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=dh(1e3).subscribe(f=>{let m=Ci(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ti(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(vs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ys(({isActiveLive:f,isLowLatency:m})=>f&&m),po()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ls(this.element,1)})),this.representationSubscription.add(vs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(bl(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(vs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(bl(({isLive:f})=>f),po((f,m)=>m.bufferLength<f.bufferLength),ys(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Ci(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(vs({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=f-S;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(T)>v&&(I=1+Math.sign(T)*y),ls(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var I,k;return(k=(I=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?k:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(vs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(zx(1e3)).subscribe(g=>E(this,[g],function*({liveLoadBufferLength:f,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=Ci(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,C=isFinite(f)?f:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(V?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),w="active_low_latency"):v!==0&&C<T?w="live_forward_buffering":C<T+k&&(w="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let F=p-(T+I),M=this.normolizeLiveOffset(Math.trunc(v+F/S)),j=Math.abs(M-v),N=0;!f||j<=this.tuning.dashCmafLive.offsetCalculationError?N=v:M>0&&j>this.tuning.dashCmafLive.offsetCalculationError&&(N=M),this.manifestUrlString=Ie(this.manifestUrlString,N,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,yield this.updateLive())}),f=>{this.error$.next({id:"updateLive",category:Qt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=wr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ys(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=wr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ys(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=vs({allBuffersFull:l,someBufferEnded:d}).pipe(po(),ys(({allBuffersFull:p,someBufferEnded:f})=>p&&f),bl(p=>p));if(this.representationSubscription.add(wr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Qt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(wr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(f=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){f();return}this.error$.next({id:"OpenOfStream",category:Qt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,fh.default)((0,fh.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),st(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&fo(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,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=dh(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Qt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new ml({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=wi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,x({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return E(this,null,function*(){var r,a,n;Ss(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ph()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ie(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){Ss(this.element),this.state$.setState("running");let e=ti(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(zx(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(wr(...kV.map(t=>ti(this.element,t)),ti(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:Qt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(ti(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ti(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&He(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var f,m,g,S,v,y,T,I,k,C,V;if(!this.element||((f=this.source)==null?void 0:f.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let a={timeInWaiting:r},n=ph(),o=100,u=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(v=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?v:0,d=(T=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?T:0,c=(k=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?k:0,h=d<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((h||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let $=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive($).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:Qt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),a.liveLastOffset=$}else{let $=this.element.currentTime*1e3;(C=this.videoBufferManager)==null||C.maintain($),(V=this.audioBufferManager)==null||V.maintain($),a.position=$}this.tracer.log("stallIntervalCallback",ho(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=dh(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:Qt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return E(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return E(this,null,function*(){var r,a,n,o,u;Ss(this.element),Ss(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=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),He(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(Hx(this.element)||Hx(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ho({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;fo(this.element)&&fo(this.source)&&fo(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),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.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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=AV(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return E(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.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",ho({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};import{combine as MV,map as LV,observeElementSize as BV,Subscription as $V,ValueSubject as mh,noop as DV}from"@vkontakte/videoplayer-shared/es2015";var vl=class{constructor(){this.subscription=new $V;this.pipSize$=new mh(void 0);this.videoSize$=new mh(void 0);this.elementSize$=new mh(void 0);this.pictureInPictureWindowRemoveEventListener=DV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(BV(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(MV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(LV(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Ar=class{constructor(e){this.subscription=new NV;this.videoState=new Y("stopped");this.droppedFramesManager=new Zr;this.stallsManager=new al;this.elementSizeManager=new vl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new _i;this.audioTrackSwitchHistory=new _i;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),D(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"),D(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&D(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;default:return VV(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new hs(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:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new kt(e.source.url),this.params=e,this.video=nt(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(je(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 Sl({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=lt(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:Qx.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(bh(c=>!!c.length),Wx()).subscribe(c=>{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:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(gh(c=>c.to.state!=="none"),yl());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(bh(Gx),Wx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(gh(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Kt(this.video,t.isLooped,r)),this.subscription.add(ut(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Rt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),D(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),D(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),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 h=this.player.getStreams();if(OV(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let m of h.audio){f.push(eh(m));let g=[];for(let S of m.representations){let v=kx(S);g.push(v),this.audioTracksMap.set(v,{stream:m,representation:S})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(f)}let p=[];for(let f of h.video){p.push(th(f));let m=[];for(let g of f.representations){let S=Px(B(x({},g),{streamId:f.id}));S&&(m.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,m)}this.params.output.availableVideoStreams$.next(p);for(let f of h.text)for(let m of f.representations){let g=Rx(f,m);this.textTracksMap.set(g,{stream:f,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&Bx(o)||null;this.subscription.add(Tl(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,FV(this.video,"progress")).pipe(bh(()=>this.videoTracksMap.size>0)).subscribe(()=>E(this,null,function*(){let c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||h||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:f}=this.selectedRepresentations;if(!p)return;let m=Ir(this.videoTracksMap.keys(),S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===p.id});Gx(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")yield this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),f){let S=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",f.id,S)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(yl()).subscribe(c=>{let h=Ir(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(th(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(yl()).subscribe(c=>{let h=Ir(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(eh(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var h,p;if(c!=null&&c.is3dVideo&&((h=this.params.tuning.spherical)!=null&&h.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(gh(({to:c})=>c==="ready"),yl());this.subscription.add(Tl(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Sh(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Tl(l,this.player.state$.stateChangeEnded$,Sh(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Tl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Sh(["init"])).pipe(_V(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var V,$,w,F,M,j,N,K,P,L,R,A;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Va:Ca,t=this.params.tuning.useNewAutoSelectVideoTrack?Mu:Ru,i=this.params.tuning.useNewAutoSelectVideoTrack?Zt:ku,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(V=r.videoTrack.getState())==null?void 0:V.id,u=Ir(this.videoTracksMap.keys(),O=>O.id===o),l=a.currentVideoTrack$.getValue(),d=((F=(w=r.videoStream.getState())!=null?w:u&&(($=this.videoTracksMap.get(u))==null?void 0:$.stream))!=null?F:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Ir(this.videoStreamsMap.keys(),O=>O.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=Oe(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(f,m||1/0),1),S=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(S==null?void 0:S.id)&&Ir(this.audioStreamsMap.keys(),O=>O.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(v){if(u&&!n){let O=e(u,h,(j=this.audioStreamsMap.get(v))!=null?j:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(N=O==null?void 0:O.bitrate)!=null?N:-1/0)}if(l){let O=e(l,h,(K=this.audioStreamsMap.get(v))!=null?K:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(P=O==null?void 0:O.bitrate)!=null?P:-1/0)}}let T=u;(n||!T)&&(T=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let I=v&&t(T,h,(L=this.audioStreamsMap.get(v))!=null?L:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),k=(R=this.videoTracksMap.get(T))==null?void 0:R.representation,C=I&&((A=this.audioTracksMap.get(I))==null?void 0:A.representation);k&&C?(this.selectedRepresentations.video=k,this.selectedRepresentations.audio=C):k&&!C&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=k,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Qx.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),ot(this.video),this.tracer.end()}};var mo=class extends Ar{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as vh,merge as Yx,filter as Kx,filterChanged as UV,isNullable as yh,map as Xx,ValueSubject as Th,isNonNullable as qV}from"@vkontakte/videoplayer-shared/es2015";var bo=class extends Ar{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new Th(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(Xx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(vh({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Xx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Kx(o=>qV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(vh({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Yx(i.playbackRateState$,new Th(1))}).pipe(Kx(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||yh(l)||(e=o-l)})).add(vh({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Yx(i.playbackRateState$,new Th(1))}).pipe(UV((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||yh(o)||yh(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Mx(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Jx="X-Playback-Duration",Ih=s=>E(void 0,null,function*(){var r;let e=yield Mt(s),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(Jx)?parseInt(e.headers.get(Jx),10):void 0});import{assertNever as ZV,combine as eO,debounce as tO,ErrorCategory as El,filter as iO,filterChanged as rO,isNonNullable as tE,isNullable as wl,map as iE,merge as sO,observableFrom as aO,Subscription as nO,ValueSubject as wh,VideoQuality as oO}from"@vkontakte/videoplayer-shared/es2015";var Eh=H(Xc(),1);import{videoSizeToQuality as jV,getExponentialDelay as HV}from"@vkontakte/videoplayer-shared/es2015";var zV=s=>{let e=null;if(s.QUALITY&&(e=Oi(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=jV({width:t,height:i})}return e!=null?e:null},QV=(s,e)=>{var a,n;let t=s.split(`
|
|
186
|
+
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,Eh.default)(l[1].split(",").map(v=>v.split("="))),h=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,p=zV(c),f;c.BANDWIDTH&&(f=parseInt(c.BANDWIDTH,10)/1e3||void 0),!f&&c["AVERAGE-BANDWIDTH"]&&(f=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,g;if(c.RESOLUTION){let[v,y]=c.RESOLUTION.split("x").map(T=>parseInt(T,10));v&&y&&(g={width:v,height:y})}let S=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:S,bandwidth:f,size:g,fps:m})}if(d){let c=(0,Eh.default)(d[1].split(",").map(m=>{let g=m.indexOf("=");return[m.substring(0,g),m.substring(g+1)]}).map(([m,g])=>[m,g.replace(/^"|"$/g,"")])),h=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=c.LANGUAGE,f=c.NAME;h&&p&&r.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},GV=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),xh=0,Zx=(r,...a)=>E(void 0,[r,...a],function*(s,e=s,t,i){let o=yield(yield Mt(s,i)).text();xh+=1;try{let{qualityManifests:u,textTracks:l}=QV(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(xh<=t.manifestRetryMaxCount)return yield GV(HV(xh-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Zx(s,e,t)}return{qualityManifests:[],textTracks:[]}}),Il=Zx;import{isNonNullable as WV,Subscription as YV,throttle as KV,ValueSubject as eE,Subject as XV,ErrorCategory as JV}from"@vkontakte/videoplayer-shared/es2015";var xl=class{constructor(e,t,i,r,a){this.subscription=new YV;this.abortControllers={destroy:new le,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new eE(null);this.getCurrentTime$=new eE(null);this.error$=new XV;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(KV(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return E(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=yield this.fetchManifestData();yield this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return E(this,null,function*(){try{let i=yield this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}})}parseTextTracks(e,t){return E(this,null,function*(){for(let i of e){let r=new URL(i.url,t).toString(),n=yield(yield Mt(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}})}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
187
|
+
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:l}),a=a+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(WV(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([B(x({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return E(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new le;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return E(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:JV.WTF,thrown:t,message:e})}};var go=class{constructor(e){this.subscription=new nO;this.videoState=new Y("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new wh([]);this.liveOffset=new hr;this.manifestStartTime$=new wh(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),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"),D(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(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),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&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?D(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),D(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"&&D(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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(D(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return ZV(t)}};var i;this.params=e,this.video=nt(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:oO.INVARIANT,url:this.params.source.url};let t=(r,a)=>Il(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new xl(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new kt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:El.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:El.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(je(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new wh((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:El.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=lt(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ut(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),a(Rt(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),D(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),D(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.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(rO(),iE(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&tE(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(je(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(eO({startTime:this.manifestStartTime$.pipe(iO(tE)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(iE(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=sO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,aO(["init"])).pipe(tO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),ot(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(wl(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:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[d,"mq"],[c,"lq"]]){let f=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,f)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ie(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Ih(n).then(d=>{var c;if(!wl(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(wl(h)||!isFinite(h))&&Mt(n).then(p=>p.text()).then(p=>{var m;let f=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(f){let g=new URL(f,n).toString();Ih(g).then(S=>{wl(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:El.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()}generateLiveUrl(){let e=Ie(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as uO,debounce as lO,ErrorCategory as Ah,fromEvent as Ph,isNonNullable as cO,isNullable as dO,map as rE,merge as sE,observableFrom as aE,Subscription as pO,ValueSubject as hO,VideoQuality as fO}from"@vkontakte/videoplayer-shared/es2015";var So=class{constructor(e){this.subscription=new pO;this.videoState=new Y("stopped");this.manifests$=new hO([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),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"),D(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(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?D(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),D(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"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return uO(t)}};this.textTracksManager=new kt(e.source.url),this.params=e,this.video=nt(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:fO.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(je(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Il(Ie(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:Ah.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Ah.WTF,message:"HlsProvider internal logic error",thrown:o})},r=lt(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(rE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Kt(this.video,t.isLooped,i)),this.subscription.add(ut(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),D(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),D(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 p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&cO(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===f);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(je(m.url)))}let c=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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(rE(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!Q.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(sE(Ph(o,"addtrack"),Ph(o,"removetrack"),Ph(o,"change"),aE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=sE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,aE(["init"])).pipe(lO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ot(this.video)}prepare(){var a,n;let e=this.selectManifest();if(dO(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=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ah.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var uE=H(sr(),1),kh=H(pr(),1),lE=H(qt(),1);import{assertNever as mO,assertNonNullable as nE,debounce as bO,ErrorCategory as oE,isHigherOrEqual as gO,isLowerOrEqual as SO,isNonNullable as vO,merge as yO,observableFrom as TO,Subscription as IO,map as xO}from"@vkontakte/videoplayer-shared/es2015";var vo=class{constructor(e){this.subscription=new IO;this.videoState=new Y("stopped");this.trackUrls={};this.textTracksManager=new kt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),D(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?D(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),D(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"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;default:return mO(e)}};this.params=e,this.video=nt(e.container,e.tuning),this.params.output.element$.next(this.video),(0,uE.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,kh.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:oE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=lt(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(xO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Kt(this.video,t.isLooped,i)),this.subscription.add(ut(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),a(Rt(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),D(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),D(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&&vO(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=yO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,TO(["init"])).pipe(bO(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),ot(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;nE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];nE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ui(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(je(t))}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oE.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let h=Zt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,kh.default)(this.trackUrls).map(c=>c.track);if(!r||!a||Wr(e,n[0].quality,(d=(0,lE.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?SO(r,e.max):!0,u=e.min?gO(r,e.min):!0;o&&u||i(e)}};import{assertNever as dE,debounce as PO,merge as pE,observableFrom as kO,Subscription as RO,map as hE,ValueSubject as MO,ErrorCategory as Mh,VideoQuality as LO}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as EO}from"@vkontakte/videoplayer-shared/es2015";var cE=["stun:videostun.mycdn.me:80"],wO=1e3,AO=3,Rh=()=>null,Al=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=Rh;this.externalStopCallback=Rh;this.externalErrorCallback=Rh;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 E(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 E(this,null,function*(){try{let e={iceServers:[{urls:cE}]};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 E(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return E(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:EO.WTF,message:e.message})}onPeerConnectionStream(e){return E(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 E(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),wO)}normalizeOptions(e={}){let t={stunServerList:cE,maxRetryNumber:AO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var yo=class{constructor(e){this.videoState=new Y("stopped");this.maxSeekBackTime$=new MO(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"),D(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),D(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"&&D(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&D(this.params.desiredState.playbackState,"paused");return;default:return dE(e)}};this.subscription=new RO,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=nt(e.container,e.tuning),this.liveStreamClient=new Al(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),ot(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Mh.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(pE(this.videoState.stateChangeStarted$.pipe(hE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(hE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=lt(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(Rt(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(ut(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 dE(n.to)}},i)).add(pE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,kO(["init"])).pipe(PO(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(je(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:LO.INVARIANT}),this.video.srcObject=e,D(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:Mh.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ct(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),D(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Mh.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var To=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as xo,assertNonNullable as zi,ErrorCategory as Pl,filter as vE,isNonNullable as yE,isNullable as _O,map as FO,merge as NO,once as UO,Subject as _e,Subscription as TE,ValueSubject as J,flattenObject as Lh}from"@vkontakte/videoplayer-shared/es2015";import{Observable as BO,map as fE,Subscription as $O,Subject as DO}from"@vkontakte/videoplayer-shared/es2015";var mE=s=>new BO(e=>{let t=new $O,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(fE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(fE(({type:l})=>l!==void 0)),n=new DO,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as CO,Subscription as VO,combine as OO,filter as gE,once as SE}from"@vkontakte/videoplayer-shared/es2015";function bE(){return new(window.AudioContext||window.webkitAudioContext)}var Io=class Io{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new le;this.subscriptions=new VO;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(gE(a=>!!a.type),SE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){Q.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(OO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(gE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),SE()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return E(this,null,function*(){let{volumeMultiplier:t}=this,i=bE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Io.errorId,category:CO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Io.errorId} exception`,thrown:e})}};Io.errorId="VolumeMultiplierManager";var Ts=Io;var qO={chunkDuration:5e3,maxParallelRequests:5},Eo=class{constructor(e){this.current$=new J({type:void 0});this.providerError$=new _e;this.noAvailableProvidersError$=new _e;this.volumeMultiplierError$=new _e;this.providerOutput={position$:new J(0),duration$:new J(1/0),volume$:new J({muted:!1,volume:1}),availableVideoStreams$:new J([]),currentVideoStream$:new J(void 0),availableVideoTracks$:new J([]),currentVideoTrack$:new J(void 0),availableAudioStreams$:new J([]),currentAudioStream$:new J(void 0),availableAudioTracks$:new J([]),currentVideoSegmentLength$:new J(0),currentAudioSegmentLength$:new J(0),isAudioAvailable$:new J(!0),autoVideoTrackLimitingAvailable$:new J(!1),autoVideoTrackLimits$:new J(void 0),currentBuffer$:new J(void 0),isBuffering$:new J(!0),error$:new _e,fetcherError$:new _e,fetcherRecoverableError$:new _e,warning$:new _e,willSeekEvent$:new _e,soundProhibitedEvent$:new _e,seekedEvent$:new _e,loopedEvent$:new _e,endedEvent$:new _e,firstBytesEvent$:new _e,loadedMetadataEvent$:new _e,firstFrameEvent$:new _e,canplay$:new _e,isLive$:new J(void 0),isLiveEnded$:new J(null),isLowLatency$:new J(!1),canChangePlaybackSpeed$:new J(!0),liveTime$:new J(void 0),liveBufferTime$:new J(void 0),liveLatency$:new J(void 0),severeStallOccurred$:new _e,availableTextTracks$:new J([]),currentTextTrack$:new J(void 0),hostname$:new J(void 0),httpConnectionType$:new J(void 0),httpConnectionReused$:new J(void 0),inPiP$:new J(!1),inFullscreen$:new J(!1),element$:new J(void 0),elementVisible$:new J(!0),availableSources$:new J(void 0),is3DVideo$:new J(!1),playbackState$:new J(""),getCurrentTime$:new J(null)};this.subscription=new TE;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=JI([...ex(this.params.tuning),...ZI(this.params.tuning)],this.params.tuning).filter(l=>yE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Bh.default)(r,l)),...t.filter(l=>(0,Bh.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Lh(a)),this.screenFormatsIterator=new To(a);let n=[...Bp(!0),...Bp(!1)];this.chromecastFormatsIterator=new To(n.filter(l=>yE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Ts.isSupported()&&(this.volumeMultiplierManager=new Ts(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(_O(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Pl.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"),e.destroy();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})}let a=this.providerOutput.isBuffering$;a.getValue()||a.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 xo(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return zi(u),this.params.tuning.useNewDashProvider?new mo(B(x({},o),{source:u,sourceHls:l})):new Ln(B(x({},o),{source:u,sourceHls:l}))}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return zi(u),this.params.tuning.useNewDashProvider?new bo(B(x({},o),{source:u})):new Bn(B(x({},o),{source:u}))}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return zi(u),new So(B(x({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return zi(u),new go(B(x({},o),{source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let u=this.applyFailoverHost(t[e]);return zi(u),new vo(B(x({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return zi(u),new Jy(B(x({},o),{source:u,config:B(x({},qO),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return zi(u),new yo({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return xo(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return zi(o),new Ra({connection:o,meta:a,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 xo(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return xo(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 xo(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return B(x({},e),{url:i(e.url)})}return(0,xE.default)((0,IE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new TE,t=!1,i=0;return e.add(NO(this.providerOutput.error$.pipe(vE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),mE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(FO(r=>({id:`ProviderHangup:${r}`,category:Pl.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(vE(({to:a})=>a==="playing"),UO()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Pl.NETWORK,u=r.category===Pl.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n=B(x({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d}),d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Lh(n)):this.tracer.error("providerError",Lh(n))})),e}};import{fromEvent as kl,once as jO,combine as HO,Subscription as EE,ValueSubject as $h,map as zO,filter as QO,isNonNullable as Rl,now as wt,safeStorage as Dh}from"@vkontakte/videoplayer-shared/es2015";var GO=5e3,wE="one_video_throughput",AE="one_video_rtt",Ri=window.navigator.connection,PE=()=>{let s=Ri==null?void 0:Ri.downlink;if(Rl(s)&&s!==10)return s*1e3},kE=()=>{let s=Ri==null?void 0:Ri.rtt;if(Rl(s)&&s!==3e3)return s},RE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Ch=class s{constructor(e){this.subscription=new EE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(wE)||(e.useBrowserEstimation?PE():void 0)||GO,i=(a=(r=s.load(AE))!=null?r:e.useBrowserEstimation?kE():void 0)!=null?a:0;if(this.throughput$=new $h(t),this.rtt$=new $h(i),this.rttAdjustedThroughput$=new $h(RE(t,i,e.rttPenaltyRequestSize)),this.throughput=wi.getSmoothedValue(t,-1,e),this.rtt=wi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=PE();u&&this.throughput.next(u);let l=kE();Rl(l)&&this.rtt.next(l)};Ri&&"onchange"in Ri&&this.subscription.add(kl(Ri,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Dh.set(wE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Dh.set(AE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(HO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(zO(({throughput:n,rtt:o})=>RE(n,o,e.rttPenaltyRequestSize)),QO(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=wt(),r=new EE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(kl(e,"progress").pipe(jO()).subscribe(a=>{t=a.loaded,i=wt()}));break;case 1:case 0:r.add(kl(e,"loadstart").subscribe(()=>{t=0,i=wt()}));break}r.add(kl(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=wt(),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,a=wt(),n=0,o=wt(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=h=>E(this,[h],function*({done:d,value:c}){if(d)!t&&this.addRawSpeed(r,wt()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=wt();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(n,m,1,t),n=c.byteLength,a=wt()}else n+=c.byteLength;o=wt()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&wt()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,wt()-o,this.concurrentDownloads.size),n=0,o=wt());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(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=Dh.get(e);if(Rl(t))return(i=parseInt(t,10))!=null?i:void 0}},ME=Ch;import{fillWithDefault as WO,VideoQuality as Ml}from"@vkontakte/videoplayer-shared/es2015";var LE={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:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ml.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ml.Q_720P,trafficSavingLimit:Ml.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ml.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!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,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},BE=s=>{var e;return B(x({},WO(s,LE)),{configName:[...(e=s.configName)!=null?e:[],...LE.configName]})};import{assertNonNullable as Ll,combine as Mi,ErrorCategory as Bl,filter as W,filterChanged as ae,fromEvent as Oh,isNonNullable as VE,isNullable as t_,Logger as i_,map as re,mapTo as OE,merge as Qi,now as $l,once as Z,Subject as oe,Subscription as _E,tap as _h,ValueSubject as _,isHigher as r_,isInvariantQuality as FE,flattenObject as Gi,throttle as Fh,getTraceSubscriptionMethod as NE,TracerFactory as s_,InternalsExposure as a_}from"@vkontakte/videoplayer-shared/es2015";import{merge as YO,map as KO,filter as $E,isNonNullable as XO}from"@vkontakte/videoplayer-shared/es2015";var Vh=({seekState:s,position$:e})=>YO(s.stateChangeEnded$.pipe(KO(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),$E(XO)),e.pipe($E(()=>s.getState().state==="none")));import{assertNonNullable as JO}from"@vkontakte/videoplayer-shared/es2015";var DE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return JO(e,`Wrong container or containerId {${s.container}}`),e};import{filter as ZO,once as e_}from"@vkontakte/videoplayer-shared/es2015";var CE=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(ZO(r=>r.length>0),e_()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Dl=class{constructor(e={configName:[]},t=s_.createRootTracer(!1)){this.subscription=new _E;this.logger=new i_;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new _(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new _(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new Y("stopped"),seekState:new Y({state:"none"}),volume:new Y({volume:1,muted:!1}),videoTrack:new Y(void 0),videoStream:new Y(void 0),audioStream:new Y(void 0),autoVideoTrackSwitching:new Y(!0),autoVideoTrackLimits:new Y({}),isLooped:new Y(!1),isLowLatency:new Y(!1),playbackRate:new Y(1),externalTextTracks:new Y([]),internalTextTracks:new Y([]),currentTextTrack:new Y(void 0),textTrackCuesSettings:new Y({}),cameraOrientation:new Y({x:0,y:0})};this.info={playbackState$:new _(void 0),position$:new _(0),duration$:new _(1/0),muted$:new _(!1),volume$:new _(1),availableVideoStreams$:new _([]),currentVideoStream$:new _(void 0),availableQualities$:new _([]),availableQualitiesFps$:new _({}),currentQuality$:new _(void 0),isAutoQualityEnabled$:new _(!0),autoQualityLimitingAvailable$:new _(!1),autoQualityLimits$:new _({}),predefinedQualityLimitType$:new _("unknown"),availableAudioStreams$:new _([]),currentAudioStream$:new _(void 0),availableAudioTracks$:new _([]),isAudioAvailable$:new _(!0),currentPlaybackRate$:new _(1),currentBuffer$:new _({start:0,end:0}),isBuffering$:new _(!0),isStalled$:new _(!1),isEnded$:new _(!1),isLooped$:new _(!1),isLive$:new _(void 0),isLiveEnded$:new _(null),canChangePlaybackSpeed$:new _(void 0),atLiveEdge$:new _(void 0),atLiveDurationEdge$:new _(void 0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),currentFormat$:new _(void 0),availableTextTracks$:new _([]),currentTextTrack$:new _(void 0),throughputEstimation$:new _(void 0),rttEstimation$:new _(void 0),videoBitrate$:new _(void 0),hostname$:new _(void 0),httpConnectionType$:new _(void 0),httpConnectionReused$:new _(void 0),surface$:new _("none"),chromecastState$:new _("NOT_AVAILABLE"),chromecastDeviceName$:new _(void 0),intrinsicVideoSize$:new _(void 0),availableSources$:new _(void 0),is3DVideo$:new _(!1),currentVideoSegmentLength$:new _(0),currentAudioSegmentLength$:new _(0)};this.events={inited$:new oe,ready$:new oe,started$:new oe,playing$:new oe,paused$:new oe,stopped$:new oe,willStart$:new oe,willResume$:new oe,willPause$:new oe,willStop$:new oe,willDestruct$:new oe,watchCoverageRecord$:new oe,watchCoverageLive$:new oe,managedError$:new oe,fatalError$:new oe,fetcherRecoverableError$:new oe,ended$:new oe,looped$:new oe,seeked$:new oe,willSeek$:new oe,autoplaySoundProhibited$:new oe,firstBytes$:new oe,loadedMetadata$:new oe,firstFrame$:new oe,canplay$:new oe,log$:new oe,fetcherError$:new oe,severeStallOccured$:new oe};this.experimental={element$:new _(void 0),tuningConfigName$:new _([]),enableDebugTelemetry$:new _(!1),dumpTelemetry:Ey,getCurrentTime$:new _(null)};if(this.initLogs(),this.tuning=BE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new $o({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ME(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new a_("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let m=typeof f;return(0,UE.default)(["number","string","boolean"],m)?f:f===null?null:`<${m}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Bl.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var l,d,c;let u=e,{container:n}=u,o=qh(u,["container"]);this.tracer.log("initVideo",Gi(o)),this.domContainer=DE(e),this.chromecastInitializer.contentId=(l=e.meta)==null?void 0:l.videoId,this.providerContainer=new Eo({sources:e.sources,meta:(d=e.meta)!=null?d:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],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,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?Q.isInited$.pipe(W(n=>!!n),Z()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Oh(document,"visibilitychange").pipe(Z()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,a=i.getTransition(),n=(o=a==null?void 0:a.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{Ll(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(W(i=>i.length>0),Z()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Gi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{var i;Ll(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Gi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>x({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{var t;CE(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.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",x({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(W(t=>!!t),Z()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(W(i=>!!i),Z()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(W(e=>e),Z()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(W(e=>!!e),Z()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(t_(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return VE(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(Qi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(re(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(re(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Yd(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(W(({from:e})=>e==="stopped"),Z()).subscribe(()=>{this.initedAt=$l(),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",Gi(n)),n.state==="requested"?this.desiredState.seekState.setState(B(x({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Bl.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Z()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Gi(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(re(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(re(n=>n.destination),ae()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Mi({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(re(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>FE(u)?1:FE(l)?-1:r_(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(ae()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(W(n=>VE(n))).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(ae((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(ae((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(ae()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ae()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ae()).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(re(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.isLiveEnded$.pipe(_h(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Mi({hasLiveOffsetByPaused:Qi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(re(n=>n.to),ae(),re(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(Mi({atLiveEdge:Mi({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Vh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(re(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),ae(),_h(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(re(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Mi({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(re(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ae(),_h(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(re(n=>n.muted),ae()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(re(n=>n.volume),ae()).subscribe(this.info.volume$)).add(Vh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Qi(e.providerOutput.endedEvent$.pipe(OE(!0)),e.providerOutput.seekedEvent$.pipe(OE(!1))).pipe(ae()).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.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(re(n=>({id:n?`No${n}`:"NoProviders",category:Bl.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.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(Z(),re(n=>n!=null?n:$l()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Z(),re(()=>$l()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Z(),re(()=>$l()-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 _(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new _(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(W(({to:n})=>n==="playing"),Z()).subscribe(()=>i.next(!1)));let r=0,a=Qi(e.providerOutput.isBuffering$,t,i).pipe(re(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ae());this.subscription.add(a.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(Qi(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(Qi(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(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(re(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 _E;this.subscription.add(t),this.subscription.add(e.current$.pipe(ae((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(W(i=>i.length>0),Z()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Zt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Qi(this.desiredState.videoTrack.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(re(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(re(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(re(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;Ll(this.providerContainer),Ll(e),xy(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Iy(i)),this.providerContainer.current$.subscribe(({type:i})=>Da("provider",i)),e.duration$.subscribe(i=>Da("duration",i)),e.availableVideoTracks$.pipe(W(i=>!!i.length),Z()).subscribe(i=>Da("tracks",i)),this.events.fatalError$.subscribe(new tt("fatalError")),this.events.managedError$.subscribe(new tt("managedError")),e.position$.subscribe(new tt("position")),e.currentVideoTrack$.pipe(re(i=>i==null?void 0:i.quality)).subscribe(new tt("quality")),this.info.currentBuffer$.subscribe(new tt("buffer")),e.isBuffering$.subscribe(new tt("isBuffering"))].forEach(i=>this.subscription.add(i)),Da("codecs",Q.video.supportedCodecs)}initTracerSubscription(){let e=NE(this.tracer.log.bind(this.tracer)),t=NE(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(ae()).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(Mi({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(W(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),ae((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(W(i=>i>0),ae()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(W(i=>i>0),ae()).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(Mi({currentBuffer:this.info.currentBuffer$.pipe(W(i=>i.end>0),ae((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(ae())}).pipe(Fh(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(ae()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(ae()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(ae()).subscribe(e("canChangePlaybackSpeed"))).add(Mi({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(W(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Fh(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(ae(),W(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(ae(),W(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(ae()).subscribe(e("muted"))).add(this.info.volume$.pipe(ae()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(ae(),W(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Mi({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(W(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Fh(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(ae(),W(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=()=>E(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:Bl.DOM,message:String(r)})})});this.subscription.add(Qi(Oh(document,"visibilitychange"),Oh(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Gi({quality:t,availableTracks:Gi(e),track:Gi(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}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ua()}};import{Subscription as pte,Observable as hte,Subject as fte,ValueSubject as mte,VideoQuality as bte}from"@vkontakte/videoplayer-shared/es2015";var gte=`@vkontakte/videoplayer-core@${jh}`;export{Ao as ChromecastState,Hl as HttpConnectionType,hte as Observable,at as PlaybackState,Dl as Player,Po as PredefinedQualityLimits,gte as SDK_VERSION,fte as Subject,pte as Subscription,zl as Surface,jh as VERSION,mte as ValueSubject,bi as VideoFormat,bte as VideoQuality,Q as clientChecker,$a as isMobile};
|