@vkontakte/videoplayer-core 2.0.134-dev.29c5fea5.0 → 2.0.134-dev.ae2fd074.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 +14 -14
- package/es2015.esm.js +15 -15
- package/es2018.cjs.js +13 -13
- package/es2018.esm.js +15 -15
- package/es2024.cjs.js +13 -13
- package/es2024.esm.js +15 -15
- package/esnext.cjs.js +13 -13
- package/esnext.esm.js +15 -15
- package/evergreen.esm.js +14 -14
- package/package.json +2 -2
- package/types/utils/tuningConfig.d.ts +2 -1
package/es2015.esm.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.134-dev.
|
|
3
|
-
* Thu, 05 Jun 2025
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.134-dev.ae2fd074.0
|
|
3
|
+
* Thu, 05 Jun 2025 13:16:35 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.29c5fea5.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 KE=Object.create;var Yl=Object.defineProperty,XE=Object.defineProperties,JE=Object.getOwnPropertyDescriptor,ZE=Object.getOwnPropertyDescriptors,ew=Object.getOwnPropertyNames,Lo=Object.getOwnPropertySymbols,tw=Object.getPrototypeOf,Kl=Object.prototype.hasOwnProperty,Qh=Object.prototype.propertyIsEnumerable;var iw=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var rt=Math.pow,zh=(s,e,t)=>e in s?Yl(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,E=(s,e)=>{for(var t in e||(e={}))Kl.call(e,t)&&zh(s,t,e[t]);if(Lo)for(var t of Lo(e))Qh.call(e,t)&&zh(s,t,e[t]);return s},B=(s,e)=>XE(s,ZE(e));var Wh=(s,e)=>{var t={};for(var i in s)Kl.call(s,i)&&e.indexOf(i)<0&&(t[i]=s[i]);if(s!=null&&Lo)for(var i of Lo(s))e.indexOf(i)<0&&Qh.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))!Kl.call(s,r)&&r!==t&&Yl(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?Yl(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((Zl,Kh)=>{"use strict";var la=function(s){return s&&s.Math===Math&&s};Kh.exports=la(typeof globalThis=="object"&&globalThis)||la(typeof window=="object"&&window)||la(typeof self=="object"&&self)||la(typeof global=="object"&&global)||la(typeof Zl=="object"&&Zl)||function(){return this}()||Function("return this")()});var Ue=b((P_,Xh)=>{"use strict";Xh.exports=function(s){try{return!!s()}catch(e){return!0}}});var ca=b((A_,Jh)=>{"use strict";var sw=Ue();Jh.exports=!sw(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var ec=b((k_,rf)=>{"use strict";var aw=ca(),tf=Function.prototype,Zh=tf.apply,ef=tf.call;rf.exports=typeof Reflect=="object"&&Reflect.apply||(aw?ef.bind(Zh):function(){return ef.apply(Zh,arguments)})});var Ve=b((R_,nf)=>{"use strict";var sf=ca(),af=Function.prototype,tc=af.call,nw=sf&&af.bind.bind(tc,tc);nf.exports=sf?nw:function(s){return function(){return tc.apply(s,arguments)}}});var ir=b((L_,uf)=>{"use strict";var of=Ve(),ow=of({}.toString),uw=of("".slice);uf.exports=function(s){return uw(ow(s),8,-1)}});var ic=b((M_,lf)=>{"use strict";var lw=ir(),cw=Ve();lf.exports=function(s){if(lw(s)==="Function")return cw(s)}});var Te=b(($_,cf)=>{"use strict";var rc=typeof document=="object"&&document.all;cf.exports=typeof rc=="undefined"&&rc!==void 0?function(s){return typeof s=="function"||s===rc}:function(s){return typeof s=="function"}});var Tt=b((B_,df)=>{"use strict";var dw=Ue();df.exports=!dw(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var It=b((D_,pf)=>{"use strict";var pw=ca(),Bo=Function.prototype.call;pf.exports=pw?Bo.bind(Bo):function(){return Bo.apply(Bo,arguments)}});var sc=b(mf=>{"use strict";var hf={}.propertyIsEnumerable,ff=Object.getOwnPropertyDescriptor,hw=ff&&!hf.call({1:2},1);mf.f=hw?function(e){var t=ff(this,e);return!!t&&t.enumerable}:hf});var da=b((V_,bf)=>{"use strict";bf.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var Sf=b((O_,gf)=>{"use strict";var fw=Ve(),mw=Ue(),bw=ir(),ac=Object,gw=fw("".split);gf.exports=mw(function(){return!ac("z").propertyIsEnumerable(0)})?function(s){return bw(s)==="String"?gw(s,""):ac(s)}:ac});var Rr=b((__,vf)=>{"use strict";vf.exports=function(s){return s==null}});var Di=b((F_,yf)=>{"use strict";var Sw=Rr(),vw=TypeError;yf.exports=function(s){if(Sw(s))throw new vw("Can't call method on "+s);return s}});var rr=b((N_,Tf)=>{"use strict";var yw=Sf(),Tw=Di();Tf.exports=function(s){return yw(Tw(s))}});var xt=b((U_,If)=>{"use strict";var Iw=Te();If.exports=function(s){return typeof s=="object"?s!==null:Iw(s)}});var Lr=b((q_,xf)=>{"use strict";xf.exports={}});var yi=b((j_,wf)=>{"use strict";var nc=Lr(),oc=xe(),xw=Te(),Ef=function(s){return xw(s)?s:void 0};wf.exports=function(s,e){return arguments.length<2?Ef(nc[s])||Ef(oc[s]):nc[s]&&nc[s][e]||oc[s]&&oc[s][e]}});var pa=b((H_,Pf)=>{"use strict";var Ew=Ve();Pf.exports=Ew({}.isPrototypeOf)});var sr=b((G_,Rf)=>{"use strict";var ww=xe(),Af=ww.navigator,kf=Af&&Af.userAgent;Rf.exports=kf?String(kf):""});var lc=b((z_,Cf)=>{"use strict";var Df=xe(),uc=sr(),Lf=Df.process,Mf=Df.Deno,$f=Lf&&Lf.versions||Mf&&Mf.version,Bf=$f&&$f.v8,Ft,Do;Bf&&(Ft=Bf.split("."),Do=Ft[0]>0&&Ft[0]<4?1:+(Ft[0]+Ft[1]));!Do&&uc&&(Ft=uc.match(/Edge\/(\d+)/),(!Ft||Ft[1]>=74)&&(Ft=uc.match(/Chrome\/(\d+)/),Ft&&(Do=+Ft[1])));Cf.exports=Do});var cc=b((Q_,Of)=>{"use strict";var Vf=lc(),Pw=Ue(),Aw=xe(),kw=Aw.String;Of.exports=!!Object.getOwnPropertySymbols&&!Pw(function(){var s=Symbol("symbol detection");return!kw(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Vf&&Vf<41})});var dc=b((W_,_f)=>{"use strict";var Rw=cc();_f.exports=Rw&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var pc=b((Y_,Ff)=>{"use strict";var Lw=yi(),Mw=Te(),$w=pa(),Bw=dc(),Dw=Object;Ff.exports=Bw?function(s){return typeof s=="symbol"}:function(s){var e=Lw("Symbol");return Mw(e)&&$w(e.prototype,Dw(s))}});var ha=b((K_,Nf)=>{"use strict";var Cw=String;Nf.exports=function(s){try{return Cw(s)}catch(e){return"Object"}}});var Kt=b((X_,Uf)=>{"use strict";var Vw=Te(),Ow=ha(),_w=TypeError;Uf.exports=function(s){if(Vw(s))return s;throw new _w(Ow(s)+" is not a function")}});var fa=b((J_,qf)=>{"use strict";var Fw=Kt(),Nw=Rr();qf.exports=function(s,e){var t=s[e];return Nw(t)?void 0:Fw(t)}});var Hf=b((Z_,jf)=>{"use strict";var hc=It(),fc=Te(),mc=xt(),Uw=TypeError;jf.exports=function(s,e){var t,i;if(e==="string"&&fc(t=s.toString)&&!mc(i=hc(t,s))||fc(t=s.valueOf)&&!mc(i=hc(t,s))||e!=="string"&&fc(t=s.toString)&&!mc(i=hc(t,s)))return i;throw new Uw("Can't convert object to primitive value")}});var Nt=b((eF,Gf)=>{"use strict";Gf.exports=!0});var Wf=b((tF,Qf)=>{"use strict";var zf=xe(),qw=Object.defineProperty;Qf.exports=function(s,e){try{qw(zf,s,{value:e,configurable:!0,writable:!0})}catch(t){zf[s]=e}return e}});var ma=b((iF,Xf)=>{"use strict";var jw=Nt(),Hw=xe(),Gw=Wf(),Yf="__core-js_shared__",Kf=Xf.exports=Hw[Yf]||Gw(Yf,{});(Kf.versions||(Kf.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 bc=b((rF,Zf)=>{"use strict";var Jf=ma();Zf.exports=function(s,e){return Jf[s]||(Jf[s]=e||{})}});var Mr=b((sF,em)=>{"use strict";var zw=Di(),Qw=Object;em.exports=function(s){return Qw(zw(s))}});var Ut=b((aF,tm)=>{"use strict";var Ww=Ve(),Yw=Mr(),Kw=Ww({}.hasOwnProperty);tm.exports=Object.hasOwn||function(e,t){return Kw(Yw(e),t)}});var gc=b((nF,im)=>{"use strict";var Xw=Ve(),Jw=0,Zw=Math.random(),eP=Xw(1 .toString);im.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+eP(++Jw+Zw,36)}});var qe=b((oF,sm)=>{"use strict";var tP=xe(),iP=bc(),rm=Ut(),rP=gc(),sP=cc(),aP=dc(),$r=tP.Symbol,Sc=iP("wks"),nP=aP?$r.for||$r:$r&&$r.withoutSetter||rP;sm.exports=function(s){return rm(Sc,s)||(Sc[s]=sP&&rm($r,s)?$r[s]:nP("Symbol."+s)),Sc[s]}});var um=b((uF,om)=>{"use strict";var oP=It(),am=xt(),nm=pc(),uP=fa(),lP=Hf(),cP=qe(),dP=TypeError,pP=cP("toPrimitive");om.exports=function(s,e){if(!am(s)||nm(s))return s;var t=uP(s,pP),i;if(t){if(e===void 0&&(e="default"),i=oP(t,s,e),!am(i)||nm(i))return i;throw new dP("Can't convert object to primitive value")}return e===void 0&&(e="number"),lP(s,e)}});var vc=b((lF,lm)=>{"use strict";var hP=um(),fP=pc();lm.exports=function(s){var e=hP(s,"string");return fP(e)?e:e+""}});var Co=b((cF,dm)=>{"use strict";var mP=xe(),cm=xt(),yc=mP.document,bP=cm(yc)&&cm(yc.createElement);dm.exports=function(s){return bP?yc.createElement(s):{}}});var Tc=b((dF,pm)=>{"use strict";var gP=Tt(),SP=Ue(),vP=Co();pm.exports=!gP&&!SP(function(){return Object.defineProperty(vP("div"),"a",{get:function(){return 7}}).a!==7})});var mm=b(fm=>{"use strict";var yP=Tt(),TP=It(),IP=sc(),xP=da(),EP=rr(),wP=vc(),PP=Ut(),AP=Tc(),hm=Object.getOwnPropertyDescriptor;fm.f=yP?hm:function(e,t){if(e=EP(e),t=wP(t),AP)try{return hm(e,t)}catch(i){}if(PP(e,t))return xP(!TP(IP.f,e,t),e[t])}});var Ic=b((hF,bm)=>{"use strict";var kP=Ue(),RP=Te(),LP=/#|\.prototype\./,ba=function(s,e){var t=$P[MP(s)];return t===DP?!0:t===BP?!1:RP(e)?kP(e):!!e},MP=ba.normalize=function(s){return String(s).replace(LP,".").toLowerCase()},$P=ba.data={},BP=ba.NATIVE="N",DP=ba.POLYFILL="P";bm.exports=ba});var Br=b((fF,Sm)=>{"use strict";var gm=ic(),CP=Kt(),VP=ca(),OP=gm(gm.bind);Sm.exports=function(s,e){return CP(s),e===void 0?s:VP?OP(s,e):function(){return s.apply(e,arguments)}}});var xc=b((mF,vm)=>{"use strict";var _P=Tt(),FP=Ue();vm.exports=_P&&FP(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Xt=b((bF,ym)=>{"use strict";var NP=xt(),UP=String,qP=TypeError;ym.exports=function(s){if(NP(s))return s;throw new qP(UP(s)+" is not an object")}});var ar=b(Im=>{"use strict";var jP=Tt(),HP=Tc(),GP=xc(),Vo=Xt(),Tm=vc(),zP=TypeError,Ec=Object.defineProperty,QP=Object.getOwnPropertyDescriptor,wc="enumerable",Pc="configurable",Ac="writable";Im.f=jP?GP?function(e,t,i){if(Vo(e),t=Tm(t),Vo(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Ac in i&&!i[Ac]){var r=QP(e,t);r&&r[Ac]&&(e[t]=i.value,i={configurable:Pc in i?i[Pc]:r[Pc],enumerable:wc in i?i[wc]:r[wc],writable:!1})}return Ec(e,t,i)}:Ec:function(e,t,i){if(Vo(e),t=Tm(t),Vo(i),HP)try{return Ec(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,xm)=>{"use strict";var WP=Tt(),YP=ar(),KP=da();xm.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,wm)=>{"use strict";var ga=xe(),XP=ec(),JP=ic(),ZP=Te(),eA=mm().f,tA=Ic(),Cr=Lr(),iA=Br(),Vr=Dr(),Em=Ut();ma();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};wm.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?ga:r?ga[t]:ga[t]&&ga[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&&Em(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,ga):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",Em(Cr,c)||Vr(Cr,c,{}),Vr(Cr[c],h,p),s.real&&u&&(l||!u[h])&&Vr(u,h,p)))}});var Am=b((yF,Pm)=>{"use strict";var sA=Math.ceil,aA=Math.floor;Pm.exports=Math.trunc||function(e){var t=+e;return(t>0?aA:sA)(t)}});var Sa=b((TF,km)=>{"use strict";var nA=Am();km.exports=function(s){var e=+s;return e!==e||e===0?0:nA(e)}});var Lm=b((IF,Rm)=>{"use strict";var oA=Sa(),uA=Math.max,lA=Math.min;Rm.exports=function(s,e){var t=oA(s);return t<0?uA(t+e,0):lA(t,e)}});var kc=b((xF,Mm)=>{"use strict";var cA=Sa(),dA=Math.min;Mm.exports=function(s){var e=cA(s);return e>0?dA(e,9007199254740991):0}});var Or=b((EF,$m)=>{"use strict";var pA=kc();$m.exports=function(s){return pA(s.length)}});var Rc=b((wF,Dm)=>{"use strict";var hA=rr(),fA=Lm(),mA=Or(),Bm=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}};Dm.exports={includes:Bm(!0),indexOf:Bm(!1)}});var va=b((PF,Cm)=>{"use strict";Cm.exports=function(){}});var Vm=b(()=>{"use strict";var bA=ke(),gA=Rc().includes,SA=Ue(),vA=va(),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,Om)=>{"use strict";var TA=yi();Om.exports=TA});var Fm=b((LF,_m)=>{"use strict";Vm();var IA=Ci();_m.exports=IA("Array","includes")});var Um=b((MF,Nm)=>{"use strict";var xA=Fm();Nm.exports=xA});var Et=b(($F,qm)=>{"use strict";var EA=Um();qm.exports=EA});var Fo=b((HF,Km)=>{"use strict";var $A=bc(),BA=gc(),Ym=$A("keys");Km.exports=function(s){return Ym[s]||(Ym[s]=BA(s))}});var Jm=b((GF,Xm)=>{"use strict";var DA=Ue();Xm.exports=!DA(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var No=b((zF,eb)=>{"use strict";var CA=Ut(),VA=Te(),OA=Mr(),_A=Fo(),FA=Jm(),Zm=_A("IE_PROTO"),$c=Object,NA=$c.prototype;eb.exports=FA?$c.getPrototypeOf:function(s){var e=OA(s);if(CA(e,Zm))return e[Zm];var t=e.constructor;return VA(t)&&e instanceof t?t.prototype:e instanceof $c?NA:null}});var Uo=b((QF,tb)=>{"use strict";tb.exports={}});var sb=b((WF,rb)=>{"use strict";var UA=Ve(),Bc=Ut(),qA=rr(),jA=Rc().indexOf,HA=Uo(),ib=UA([].push);rb.exports=function(s,e){var t=qA(s),i=0,r=[],a;for(a in t)!Bc(HA,a)&&Bc(t,a)&&ib(r,a);for(;e.length>i;)Bc(t,a=e[i++])&&(~jA(r,a)||ib(r,a));return r}});var Dc=b((YF,ab)=>{"use strict";ab.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Cc=b((KF,nb)=>{"use strict";var GA=sb(),zA=Dc();nb.exports=Object.keys||function(e){return GA(e,zA)}});var Vc=b((XF,db)=>{"use strict";var ub=Tt(),QA=Ue(),lb=Ve(),WA=No(),YA=Cc(),KA=rr(),XA=sc().f,cb=lb(XA),JA=lb([].push),ZA=ub&&QA(function(){var s=Object.create(null);return s[2]=2,!cb(s,2)}),ob=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++],(!ub||(r?u in t:cb(t,u)))&&JA(o,s?[u,t[u]]:t[u]);return o}};db.exports={entries:ob(!0),values:ob(!1)}});var pb=b(()=>{"use strict";var ek=ke(),tk=Vc().entries;ek({target:"Object",stat:!0},{entries:function(e){return tk(e)}})});var fb=b((eN,hb)=>{"use strict";pb();var ik=Lr();hb.exports=ik.Object.entries});var bb=b((tN,mb)=>{"use strict";var rk=fb();mb.exports=rk});var nr=b((iN,gb)=>{"use strict";var sk=bb();gb.exports=sk});var or=b((rN,Sb)=>{"use strict";Sb.exports={}});var Tb=b((sN,yb)=>{"use strict";var ak=xe(),nk=Te(),vb=ak.WeakMap;yb.exports=nk(vb)&&/native code/.test(String(vb))});var Nc=b((aN,Eb)=>{"use strict";var ok=Tb(),xb=xe(),uk=xt(),lk=Dr(),Oc=Ut(),_c=ma(),ck=Fo(),dk=Uo(),Ib="Object already initialized",Fc=xb.TypeError,pk=xb.WeakMap,qo,ya,jo,hk=function(s){return jo(s)?ya(s):qo(s,{})},fk=function(s){return function(e){var t;if(!uk(e)||(t=ya(e)).type!==s)throw new Fc("Incompatible receiver, "+s+" required");return t}};ok||_c.state?(qt=_c.state||(_c.state=new pk),qt.get=qt.get,qt.has=qt.has,qt.set=qt.set,qo=function(s,e){if(qt.has(s))throw new Fc(Ib);return e.facade=s,qt.set(s,e),e},ya=function(s){return qt.get(s)||{}},jo=function(s){return qt.has(s)}):(ur=ck("state"),dk[ur]=!0,qo=function(s,e){if(Oc(s,ur))throw new Fc(Ib);return e.facade=s,lk(s,ur,e),e},ya=function(s){return Oc(s,ur)?s[ur]:{}},jo=function(s){return Oc(s,ur)});var qt,ur;Eb.exports={set:qo,get:ya,has:jo,enforce:hk,getterFor:fk}});var jc=b((nN,Pb)=>{"use strict";var Uc=Tt(),mk=Ut(),wb=Function.prototype,bk=Uc&&Object.getOwnPropertyDescriptor,qc=mk(wb,"name"),gk=qc&&function(){}.name==="something",Sk=qc&&(!Uc||Uc&&bk(wb,"name").configurable);Pb.exports={EXISTS:qc,PROPER:gk,CONFIGURABLE:Sk}});var kb=b(Ab=>{"use strict";var vk=Tt(),yk=xc(),Tk=ar(),Ik=Xt(),xk=rr(),Ek=Cc();Ab.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 Hc=b((uN,Rb)=>{"use strict";var wk=yi();Rb.exports=wk("document","documentElement")});var Wc=b((lN,Vb)=>{"use strict";var Pk=Xt(),Ak=kb(),Lb=Dc(),kk=Uo(),Rk=Hc(),Lk=Co(),Mk=Fo(),Mb=">",$b="<",zc="prototype",Qc="script",Db=Mk("IE_PROTO"),Gc=function(){},Cb=function(s){return $b+Qc+Mb+s+$b+"/"+Qc+Mb},Bb=function(s){s.write(Cb("")),s.close();var e=s.parentWindow.Object;return s=null,e},$k=function(){var s=Lk("iframe"),e="java"+Qc+":",t;return s.style.display="none",Rk.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Cb("document.F=Object")),t.close(),t.F},Ho,Go=function(){try{Ho=new ActiveXObject("htmlfile")}catch(e){}Go=typeof document!="undefined"?document.domain&&Ho?Bb(Ho):$k():Bb(Ho);for(var s=Lb.length;s--;)delete Go[zc][Lb[s]];return Go()};kk[Db]=!0;Vb.exports=Object.create||function(e,t){var i;return e!==null?(Gc[zc]=Pk(e),i=new Gc,Gc[zc]=null,i[Db]=e):i=Go(),t===void 0?i:Ak.f(i,t)}});var _r=b((cN,Ob)=>{"use strict";var Bk=Dr();Ob.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Bk(s,e,t),s}});var Jc=b((dN,Nb)=>{"use strict";var Dk=Ue(),Ck=Te(),Vk=xt(),Ok=Wc(),_b=No(),_k=_r(),Fk=qe(),Nk=Nt(),Xc=Fk("iterator"),Fb=!1,Ti,Yc,Kc;[].keys&&(Kc=[].keys(),"next"in Kc?(Yc=_b(_b(Kc)),Yc!==Object.prototype&&(Ti=Yc)):Fb=!0);var Uk=!Vk(Ti)||Dk(function(){var s={};return Ti[Xc].call(s)!==s});Uk?Ti={}:Nk&&(Ti=Ok(Ti));Ck(Ti[Xc])||_k(Ti,Xc,function(){return this});Nb.exports={IteratorPrototype:Ti,BUGGY_SAFARI_ITERATORS:Fb}});var zo=b((pN,qb)=>{"use strict";var qk=qe(),jk=qk("toStringTag"),Ub={};Ub[jk]="z";qb.exports=String(Ub)==="[object z]"});var Ta=b((hN,jb)=>{"use strict";var Hk=zo(),Gk=Te(),Qo=ir(),zk=qe(),Qk=zk("toStringTag"),Wk=Object,Yk=Qo(function(){return arguments}())==="Arguments",Kk=function(s,e){try{return s[e]}catch(t){}};jb.exports=Hk?Qo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Kk(e=Wk(s),Qk))=="string"?t:Yk?Qo(e):(i=Qo(e))==="Object"&&Gk(e.callee)?"Arguments":i}});var Gb=b((fN,Hb)=>{"use strict";var Xk=zo(),Jk=Ta();Hb.exports=Xk?{}.toString:function(){return"[object "+Jk(this)+"]"}});var Ia=b((mN,Qb)=>{"use strict";var Zk=zo(),eR=ar().f,tR=Dr(),iR=Ut(),rR=Gb(),sR=qe(),zb=sR("toStringTag");Qb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(iR(r,zb)||eR(r,zb,{configurable:!0,value:e}),i&&!Zk&&tR(r,"toString",rR))}});var Yb=b((bN,Wb)=>{"use strict";var aR=Jc().IteratorPrototype,nR=Wc(),oR=da(),uR=Ia(),lR=or(),cR=function(){return this};Wb.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 Xb=b((gN,Kb)=>{"use strict";var dR=Ve(),pR=Kt();Kb.exports=function(s,e,t){try{return dR(pR(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Zb=b((SN,Jb)=>{"use strict";var hR=xt();Jb.exports=function(s){return hR(s)||s===null}});var tg=b((vN,eg)=>{"use strict";var fR=Zb(),mR=String,bR=TypeError;eg.exports=function(s){if(fR(s))return s;throw new bR("Can't set "+mR(s)+" as a prototype")}});var Zc=b((yN,ig)=>{"use strict";var gR=Xb(),SR=xt(),vR=Di(),yR=tg();ig.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 hg=b((TN,pg)=>{"use strict";var TR=ke(),IR=It(),Wo=Nt(),cg=jc(),xR=Te(),ER=Yb(),rg=No(),sg=Zc(),wR=Ia(),PR=Dr(),ed=_r(),AR=qe(),ag=or(),dg=Jc(),kR=cg.PROPER,RR=cg.CONFIGURABLE,ng=dg.IteratorPrototype,Yo=dg.BUGGY_SAFARI_ITERATORS,xa=AR("iterator"),og="keys",Ea="values",ug="entries",lg=function(){return this};pg.exports=function(s,e,t,i,r,a,n){ER(t,e,i);var o=function(S){if(S===r&&h)return h;if(!Yo&&S&&S in d)return d[S];switch(S){case og:return function(){return new t(this,S)};case Ea:return function(){return new t(this,S)};case ug:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[xa]||d["@@iterator"]||r&&d[r],h=!Yo&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=rg(p.call(new s)),f!==Object.prototype&&f.next&&(!Wo&&rg(f)!==ng&&(sg?sg(f,ng):xR(f[xa])||ed(f,xa,lg)),wR(f,u,!0,!0),Wo&&(ag[u]=lg))),kR&&r===Ea&&c&&c.name!==Ea&&(!Wo&&RR?PR(d,"name",Ea):(l=!0,h=function(){return IR(c,this)})),r)if(m={values:o(Ea),keys:a?h:o(og),entries:o(ug)},n)for(g in m)(Yo||l||!(g in d))&&ed(d,g,m[g]);else TR({target:e,proto:!0,forced:Yo||l},m);return(!Wo||n)&&d[xa]!==h&&ed(d,xa,h,{name:r}),ag[e]=h,m}});var mg=b((IN,fg)=>{"use strict";fg.exports=function(s,e){return{value:s,done:e}}});var id=b((xN,yg)=>{"use strict";var LR=rr(),td=va(),bg=or(),Sg=Nc(),MR=ar().f,$R=hg(),Ko=mg(),BR=Nt(),DR=Tt(),vg="Array Iterator",CR=Sg.set,VR=Sg.getterFor(vg);yg.exports=$R(Array,"Array",function(s,e){CR(this,{type:vg,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,Ko(void 0,!0);switch(s.kind){case"keys":return Ko(t,!1);case"values":return Ko(e[t],!1)}return Ko([t,e[t]],!1)},"values");var gg=bg.Arguments=bg.Array;td("keys");td("values");td("entries");if(!BR&&DR&&gg.name!=="values")try{MR(gg,"name",{value:"values"})}catch(s){}});var Ig=b((EN,Tg)=>{"use strict";var OR=qe(),_R=or(),FR=OR("iterator"),NR=Array.prototype;Tg.exports=function(s){return s!==void 0&&(_R.Array===s||NR[FR]===s)}});var rd=b((wN,Eg)=>{"use strict";var UR=Ta(),xg=fa(),qR=Rr(),jR=or(),HR=qe(),GR=HR("iterator");Eg.exports=function(s){if(!qR(s))return xg(s,GR)||xg(s,"@@iterator")||jR[UR(s)]}});var Pg=b((PN,wg)=>{"use strict";var zR=It(),QR=Kt(),WR=Xt(),YR=ha(),KR=rd(),XR=TypeError;wg.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 Rg=b((AN,kg)=>{"use strict";var JR=It(),Ag=Xt(),ZR=fa();kg.exports=function(s,e,t){var i,r;Ag(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 Ag(i),t}});var Jo=b((kN,Bg)=>{"use strict";var eL=Br(),tL=It(),iL=Xt(),rL=ha(),sL=Ig(),aL=Or(),Lg=pa(),nL=Pg(),oL=rd(),Mg=Rg(),uL=TypeError,Xo=function(s,e){this.stopped=s,this.result=e},$g=Xo.prototype;Bg.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&&Mg(l,"normal",v),new Xo(!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&&Lg($g,p))return p;return new Xo(!1)}l=nL(s,d)}for(f=a?s.next:l.next;!(m=tL(f,l)).done;){try{p=S(m.value)}catch(v){Mg(l,"throw",v)}if(typeof p=="object"&&p&&Lg($g,p))return p}return new Xo(!1)}});var Cg=b((RN,Dg)=>{"use strict";var lL=Tt(),cL=ar(),dL=da();Dg.exports=function(s,e,t){lL?cL.f(s,e,dL(0,t)):s[e]=t}});var Vg=b(()=>{"use strict";var pL=ke(),hL=Jo(),fL=Cg();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 _g=b(($N,Og)=>{"use strict";id();Vg();var mL=Lr();Og.exports=mL.Object.fromEntries});var Ng=b((BN,Fg)=>{"use strict";Fg.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 qg=b(()=>{"use strict";id();var bL=Ng(),gL=xe(),SL=Ia(),Ug=or();for(Zo in bL)SL(gL[Zo],Zo),Ug[Zo]=Ug.Array;var Zo});var Hg=b((VN,jg)=>{"use strict";var vL=_g();qg();jg.exports=vL});var sd=b((ON,Gg)=>{"use strict";var yL=Hg();Gg.exports=yL});var zg=b(()=>{"use strict"});var ad=b((NN,Qg)=>{"use strict";var wa=xe(),TL=sr(),IL=ir(),eu=function(s){return TL.slice(0,s.length)===s};Qg.exports=function(){return eu("Bun/")?"BUN":eu("Cloudflare-Workers")?"CLOUDFLARE":eu("Deno/")?"DENO":eu("Node.js/")?"NODE":wa.Bun&&typeof Bun.version=="string"?"BUN":wa.Deno&&typeof Deno.version=="object"?"DENO":IL(wa.process)==="process"?"NODE":wa.window&&wa.document?"BROWSER":"REST"}()});var tu=b((UN,Wg)=>{"use strict";var xL=ad();Wg.exports=xL==="NODE"});var Kg=b((qN,Yg)=>{"use strict";var EL=ar();Yg.exports=function(s,e,t){return EL.f(s,e,t)}});var Zg=b((jN,Jg)=>{"use strict";var wL=yi(),PL=Kg(),AL=qe(),kL=Tt(),Xg=AL("species");Jg.exports=function(s){var e=wL(s);kL&&e&&!e[Xg]&&PL(e,Xg,{configurable:!0,get:function(){return this}})}});var tS=b((HN,eS)=>{"use strict";var RL=pa(),LL=TypeError;eS.exports=function(s,e){if(RL(e,s))return s;throw new LL("Incorrect invocation")}});var od=b((GN,iS)=>{"use strict";var ML=Ve(),$L=Te(),nd=ma(),BL=ML(Function.toString);$L(nd.inspectSource)||(nd.inspectSource=function(s){return BL(s)});iS.exports=nd.inspectSource});var ld=b((zN,oS)=>{"use strict";var DL=Ve(),CL=Ue(),rS=Te(),VL=Ta(),OL=yi(),_L=od(),sS=function(){},aS=OL("Reflect","construct"),ud=/^\s*(?:class|function)\b/,FL=DL(ud.exec),NL=!ud.test(sS),Pa=function(e){if(!rS(e))return!1;try{return aS(sS,[],e),!0}catch(t){return!1}},nS=function(e){if(!rS(e))return!1;switch(VL(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return NL||!!FL(ud,_L(e))}catch(t){return!0}};nS.sham=!0;oS.exports=!aS||CL(function(){var s;return Pa(Pa.call)||!Pa(Object)||!Pa(function(){s=!0})||s})?nS:Pa});var lS=b((QN,uS)=>{"use strict";var UL=ld(),qL=ha(),jL=TypeError;uS.exports=function(s){if(UL(s))return s;throw new jL(qL(s)+" is not a constructor")}});var cd=b((WN,dS)=>{"use strict";var cS=Xt(),HL=lS(),GL=Rr(),zL=qe(),QL=zL("species");dS.exports=function(s,e){var t=cS(s).constructor,i;return t===void 0||GL(i=cS(t)[QL])?e:HL(i)}});var hS=b((YN,pS)=>{"use strict";var WL=Ve();pS.exports=WL([].slice)});var mS=b((KN,fS)=>{"use strict";var YL=TypeError;fS.exports=function(s,e){if(s<e)throw new YL("Not enough arguments");return s}});var dd=b((XN,bS)=>{"use strict";var KL=sr();bS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(KL)});var yd=b((JN,wS)=>{"use strict";var wt=xe(),XL=ec(),JL=Br(),gS=Te(),ZL=Ut(),ES=Ue(),SS=Hc(),eM=hS(),vS=Co(),tM=mS(),iM=dd(),rM=tu(),gd=wt.setImmediate,Sd=wt.clearImmediate,sM=wt.process,pd=wt.Dispatch,aM=wt.Function,yS=wt.MessageChannel,nM=wt.String,hd=0,Aa={},TS="onreadystatechange",ka,lr,fd,md;ES(function(){ka=wt.location});var vd=function(s){if(ZL(Aa,s)){var e=Aa[s];delete Aa[s],e()}},bd=function(s){return function(){vd(s)}},IS=function(s){vd(s.data)},xS=function(s){wt.postMessage(nM(s),ka.protocol+"//"+ka.host)};(!gd||!Sd)&&(gd=function(e){tM(arguments.length,1);var t=gS(e)?e:aM(e),i=eM(arguments,1);return Aa[++hd]=function(){XL(t,void 0,i)},lr(hd),hd},Sd=function(e){delete Aa[e]},rM?lr=function(s){sM.nextTick(bd(s))}:pd&&pd.now?lr=function(s){pd.now(bd(s))}:yS&&!iM?(fd=new yS,md=fd.port2,fd.port1.onmessage=IS,lr=JL(md.postMessage,md)):wt.addEventListener&&gS(wt.postMessage)&&!wt.importScripts&&ka&&ka.protocol!=="file:"&&!ES(xS)?(lr=xS,wt.addEventListener("message",IS,!1)):TS in vS("script")?lr=function(s){SS.appendChild(vS("script"))[TS]=function(){SS.removeChild(this),vd(s)}}:lr=function(s){setTimeout(bd(s),0)});wS.exports={set:gd,clear:Sd}});var kS=b((ZN,AS)=>{"use strict";var PS=xe(),oM=Tt(),uM=Object.getOwnPropertyDescriptor;AS.exports=function(s){if(!oM)return PS[s];var e=uM(PS,s);return e&&e.value}});var Td=b((eU,LS)=>{"use strict";var RS=function(){this.head=null,this.tail=null};RS.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}}};LS.exports=RS});var $S=b((tU,MS)=>{"use strict";var lM=sr();MS.exports=/ipad|iphone|ipod/i.test(lM)&&typeof Pebble!="undefined"});var DS=b((iU,BS)=>{"use strict";var cM=sr();BS.exports=/web0s(?!.*chrome)/i.test(cM)});var US=b((rU,NS)=>{"use strict";var Nr=xe(),dM=kS(),CS=Br(),Id=yd().set,pM=Td(),hM=dd(),fM=$S(),mM=DS(),xd=tu(),VS=Nr.MutationObserver||Nr.WebKitMutationObserver,OS=Nr.document,_S=Nr.process,iu=Nr.Promise,Pd=dM("queueMicrotask"),Fr,Ed,wd,ru,FS;Pd||(Ra=new pM,La=function(){var s,e;for(xd&&(s=_S.domain)&&s.exit();e=Ra.get();)try{e()}catch(t){throw Ra.head&&Fr(),t}s&&s.enter()},!hM&&!xd&&!mM&&VS&&OS?(Ed=!0,wd=OS.createTextNode(""),new VS(La).observe(wd,{characterData:!0}),Fr=function(){wd.data=Ed=!Ed}):!fM&&iu&&iu.resolve?(ru=iu.resolve(void 0),ru.constructor=iu,FS=CS(ru.then,ru),Fr=function(){FS(La)}):xd?Fr=function(){_S.nextTick(La)}:(Id=CS(Id,Nr),Fr=function(){Id(La)}),Pd=function(s){Ra.head||Fr(),Ra.add(s)});var Ra,La;NS.exports=Pd});var jS=b((sU,qS)=>{"use strict";qS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var su=b((aU,HS)=>{"use strict";HS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var cr=b((nU,GS)=>{"use strict";var bM=xe();GS.exports=bM.Promise});var Ur=b((oU,YS)=>{"use strict";var gM=xe(),Ma=cr(),SM=Te(),vM=Ic(),yM=od(),TM=qe(),zS=ad(),IM=Nt(),Ad=lc(),QS=Ma&&Ma.prototype,xM=TM("species"),kd=!1,WS=SM(gM.PromiseRejectionEvent),EM=vM("Promise",function(){var s=yM(Ma),e=s!==String(Ma);if(!e&&Ad===66||IM&&!(QS.catch&&QS.finally))return!0;if(!Ad||Ad<51||!/native code/.test(s)){var t=new Ma(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[xM]=i,kd=t.then(function(){})instanceof i,!kd)return!0}return!e&&(zS==="BROWSER"||zS==="DENO")&&!WS});YS.exports={CONSTRUCTOR:EM,REJECTION_EVENT:WS,SUBCLASSING:kd}});var qr=b((uU,XS)=>{"use strict";var KS=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=KS(e),this.reject=KS(t)};XS.exports.f=function(s){return new PM(s)}});var bv=b(()=>{"use strict";var AM=ke(),kM=Nt(),uu=tu(),Vi=xe(),zr=It(),JS=_r(),ZS=Zc(),RM=Ia(),LM=Zg(),MM=Kt(),ou=Te(),$M=xt(),BM=tS(),DM=cd(),sv=yd().set,Bd=US(),CM=jS(),VM=su(),OM=Td(),av=Nc(),lu=cr(),Dd=Ur(),nv=qr(),cu="Promise",ov=Dd.CONSTRUCTOR,_M=Dd.REJECTION_EVENT,FM=Dd.SUBCLASSING,Rd=av.getterFor(cu),NM=av.set,jr=lu&&lu.prototype,dr=lu,au=jr,uv=Vi.TypeError,Ld=Vi.document,Cd=Vi.process,Md=nv.f,UM=Md,qM=!!(Ld&&Ld.createEvent&&Vi.dispatchEvent),lv="unhandledrejection",jM="rejectionhandled",ev=0,cv=1,HM=2,Vd=1,dv=2,nu,tv,GM,iv,pv=function(s){var e;return $M(s)&&ou(e=s.then)?e:!1},hv=function(s,e){var t=e.value,i=e.state===cv,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===dv&&QM(e),e.rejection=Vd),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new uv("Promise-chain cycle")):(l=pv(u))?zr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},fv=function(s,e){s.notified||(s.notified=!0,Bd(function(){for(var t=s.reactions,i;i=t.get();)hv(i,s);s.notified=!1,e&&!s.rejection&&zM(s)}))},mv=function(s,e,t){var i,r;qM?(i=Ld.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===lv&&CM("Unhandled promise rejection",t)},zM=function(s){zr(sv,Vi,function(){var e=s.facade,t=s.value,i=rv(s),r;if(i&&(r=VM(function(){uu?Cd.emit("unhandledRejection",t,e):mv(lv,e,t)}),s.rejection=uu||rv(s)?dv:Vd,r.error))throw r.value})},rv=function(s){return s.rejection!==Vd&&!s.parent},QM=function(s){zr(sv,Vi,function(){var e=s.facade;uu?Cd.emit("rejectionHandled",e):mv(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,fv(s,!0))},$d=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new uv("Promise can't be resolved itself");var i=pv(e);i?Bd(function(){var r={done:!1};try{zr(i,e,Hr($d,r,s),Hr(Gr,r,s))}catch(a){Gr(r,a,s)}}):(s.value=e,s.state=cv,fv(s,!1))}catch(r){Gr({done:!1},r,s)}}};if(ov&&(dr=function(e){BM(this,au),MM(e),zr(nu,this);var t=Rd(this);try{e(Hr($d,t),Hr(Gr,t))}catch(i){Gr(t,i)}},au=dr.prototype,nu=function(e){NM(this,{type:cu,done:!1,notified:!1,parent:!1,reactions:new OM,rejection:!1,state:ev,value:void 0})},nu.prototype=JS(au,"then",function(e,t){var i=Rd(this),r=Md(DM(this,dr));return i.parent=!0,r.ok=ou(e)?e:!0,r.fail=ou(t)&&t,r.domain=uu?Cd.domain:void 0,i.state===ev?i.reactions.add(r):Bd(function(){hv(r,i)}),r.promise}),tv=function(){var s=new nu,e=Rd(s);this.promise=s,this.resolve=Hr($d,e),this.reject=Hr(Gr,e)},nv.f=Md=function(s){return s===dr||s===GM?new tv(s):UM(s)},!kM&&ou(lu)&&jr!==Object.prototype)){iv=jr.then,FM||JS(jr,"then",function(e,t){var i=this;return new dr(function(r,a){zr(iv,i,r,a)}).then(e,t)},{unsafe:!0});try{delete jr.constructor}catch(s){}ZS&&ZS(jr,au)}AM({global:!0,constructor:!0,wrap:!0,forced:ov},{Promise:dr});RM(dr,cu,!1,!0);LM(cu)});var Tv=b((dU,yv)=>{"use strict";var WM=qe(),Sv=WM("iterator"),vv=!1;try{gv=0,Od={next:function(){return{done:!!gv++}},return:function(){vv=!0}},Od[Sv]=function(){return this},Array.from(Od,function(){throw 2})}catch(s){}var gv,Od;yv.exports=function(s,e){try{if(!e&&!vv)return!1}catch(r){return!1}var t=!1;try{var i={};i[Sv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var _d=b((pU,Iv)=>{"use strict";var YM=cr(),KM=Tv(),XM=Ur().CONSTRUCTOR;Iv.exports=XM||!KM(function(s){YM.all(s).then(void 0,function(){})})});var xv=b(()=>{"use strict";var JM=ke(),ZM=It(),e$=Kt(),t$=qr(),i$=su(),r$=Jo(),s$=_d();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 wv=b(()=>{"use strict";var a$=ke(),n$=Nt(),o$=Ur().CONSTRUCTOR,Nd=cr(),u$=yi(),l$=Te(),c$=_r(),Ev=Nd&&Nd.prototype;a$({target:"Promise",proto:!0,forced:o$,real:!0},{catch:function(s){return this.then(void 0,s)}});!n$&&l$(Nd)&&(Fd=u$("Promise").prototype.catch,Ev.catch!==Fd&&c$(Ev,"catch",Fd,{unsafe:!0}));var Fd});var Pv=b(()=>{"use strict";var d$=ke(),p$=It(),h$=Kt(),f$=qr(),m$=su(),b$=Jo(),g$=_d();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 Av=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 Ud=b((TU,kv)=>{"use strict";var T$=Xt(),I$=xt(),x$=qr();kv.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 Mv=b(()=>{"use strict";var E$=ke(),w$=yi(),Rv=Nt(),P$=cr(),Lv=Ur().CONSTRUCTOR,A$=Ud(),k$=w$("Promise"),R$=Rv&&!Lv;E$({target:"Promise",stat:!0,forced:Rv||Lv},{resolve:function(e){return A$(R$&&this===k$?P$:this,e)}})});var $v=b(()=>{"use strict";bv();xv();wv();Pv();Av();Mv()});var Vv=b(()=>{"use strict";var L$=ke(),M$=Nt(),du=cr(),$$=Ue(),Dv=yi(),Cv=Te(),B$=cd(),Bv=Ud(),D$=_r(),jd=du&&du.prototype,C$=!!du&&$$(function(){jd.finally.call({then:function(){}},function(){})});L$({target:"Promise",proto:!0,real:!0,forced:C$},{finally:function(s){var e=B$(this,Dv("Promise")),t=Cv(s);return this.then(t?function(i){return Bv(e,s()).then(function(){return i})}:s,t?function(i){return Bv(e,s()).then(function(){throw i})}:s)}});!M$&&Cv(du)&&(qd=Dv("Promise").prototype.finally,jd.finally!==qd&&D$(jd,"finally",qd,{unsafe:!0}));var qd});var _v=b((kU,Ov)=>{"use strict";zg();$v();Vv();var V$=Ci();Ov.exports=V$("Promise","finally")});var Nv=b((RU,Fv)=>{"use strict";var O$=_v();Fv.exports=O$});var $a=b((LU,Uv)=>{"use strict";var _$=Nv();Uv.exports=_$});var ey=b(()=>{"use strict";var J$=ke(),Z$=Vc().values;J$({target:"Object",stat:!0},{values:function(e){return Z$(e)}})});var iy=b((f1,ty)=>{"use strict";ey();var eB=Lr();ty.exports=eB.Object.values});var sy=b((m1,ry)=>{"use strict";var tB=iy();ry.exports=tB});var fr=b((b1,ay)=>{"use strict";var iB=sy();ay.exports=iB});var Iy=b(()=>{"use strict";var wB=ke(),PB=Mr(),AB=Or(),kB=Sa(),RB=va();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 Ey=b((kq,xy)=>{"use strict";Iy();var LB=Ci();xy.exports=LB("Array","at")});var Py=b((Rq,wy)=>{"use strict";var MB=Ey();wy.exports=MB});var jt=b((Lq,Ay)=>{"use strict";var $B=Py();Ay.exports=$B});var pp=b((SH,nT)=>{"use strict";var pD=ir();nT.exports=Array.isArray||function(e){return pD(e)==="Array"}});var uT=b((vH,oT)=>{"use strict";var hD=TypeError,fD=9007199254740991;oT.exports=function(s){if(s>fD)throw hD("Maximum allowed index exceeded");return s}});var dT=b((yH,cT)=>{"use strict";var mD=pp(),bD=Or(),gD=uT(),SD=Br(),lT=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=lT(s,e,c,h,u,a-1)-1):(gD(u+1),s[u]=c),u++),l++;return u};cT.exports=lT});var mT=b((TH,fT)=>{"use strict";var pT=pp(),vD=ld(),yD=xt(),TD=qe(),ID=TD("species"),hT=Array;fT.exports=function(s){var e;return pT(s)&&(e=s.constructor,vD(e)&&(e===hT||pT(e.prototype))?e=void 0:yD(e)&&(e=e[ID],e===null&&(e=void 0))),e===void 0?hT:e}});var gT=b((IH,bT)=>{"use strict";var xD=mT();bT.exports=function(s,e){return new(xD(s))(e===0?0:e)}});var ST=b(()=>{"use strict";var ED=ke(),wD=dT(),PD=Kt(),AD=Mr(),kD=Or(),RD=gT();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 vT=b(()=>{"use strict";var LD=va();LD("flatMap")});var TT=b((AH,yT)=>{"use strict";ST();vT();var MD=Ci();yT.exports=MD("Array","flatMap")});var xT=b((kH,IT)=>{"use strict";var $D=TT();IT.exports=$D});var Wa=b((RH,ET)=>{"use strict";var BD=xT();ET.exports=BD});var Ya=b((LH,wT)=>{"use strict";var DD=Ta(),CD=String;wT.exports=function(s){if(DD(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return CD(s)}});var hp=b((MH,PT)=>{"use strict";PT.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 RT=b(($H,kT)=>{"use strict";var VD=Ve(),OD=Di(),_D=Ya(),mp=hp(),AT=VD("".replace),FD=RegExp("^["+mp+"]+"),ND=RegExp("(^|[^"+mp+"])["+mp+"]+$"),fp=function(s){return function(e){var t=_D(OD(e));return s&1&&(t=AT(t,FD,"")),s&2&&(t=AT(t,ND,"$1")),t}};kT.exports={start:fp(1),end:fp(2),trim:fp(3)}});var BT=b((BH,$T)=>{"use strict";var UD=jc().PROPER,qD=Ue(),LT=hp(),MT="\u200B\x85\u180E";$T.exports=function(s){return qD(function(){return!!LT[s]()||MT[s]()!==MT||UD&<[s].name!==s})}});var bp=b((DH,DT)=>{"use strict";var jD=RT().start,HD=BT();DT.exports=HD("trimStart")?function(){return jD(this)}:"".trimStart});var VT=b(()=>{"use strict";var GD=ke(),CT=bp();GD({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==CT},{trimLeft:CT})});var _T=b(()=>{"use strict";VT();var zD=ke(),OT=bp();zD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==OT},{trimStart:OT})});var NT=b((FH,FT)=>{"use strict";_T();var QD=Ci();FT.exports=QD("String","trimLeft")});var qT=b((NH,UT)=>{"use strict";var WD=NT();UT.exports=WD});var HT=b((UH,jT)=>{"use strict";var YD=qT();jT.exports=YD});var aI=b(()=>{"use strict"});var nI=b(()=>{"use strict"});var uI=b((E3,oI)=>{"use strict";var S0=xt(),v0=ir(),y0=qe(),T0=y0("match");oI.exports=function(s){var e;return S0(s)&&((e=s[T0])!==void 0?!!e:v0(s)==="RegExp")}});var cI=b((w3,lI)=>{"use strict";var I0=Xt();lI.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 hI=b((P3,pI)=>{"use strict";var x0=It(),E0=Ut(),w0=pa(),P0=cI(),dI=RegExp.prototype;pI.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in dI)&&!E0(s,"flags")&&w0(dI,s)?x0(P0,s):e}});var mI=b((A3,fI)=>{"use strict";var Ip=Ve(),A0=Mr(),k0=Math.floor,yp=Ip("".charAt),R0=Ip("".replace),Tp=Ip("".slice),L0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,M0=/\$([$&'`]|\d{1,2})/g;fI.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(yp(d,0)){case"$":return"$";case"&":return s;case"`":return Tp(e,0,t);case"'":return Tp(e,n);case"<":c=r[Tp(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?yp(d,1):i[p-1]+yp(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var SI=b(()=>{"use strict";var $0=ke(),B0=It(),Ep=Ve(),bI=Di(),D0=Te(),C0=Rr(),V0=uI(),ns=Ya(),O0=fa(),_0=hI(),F0=mI(),N0=qe(),U0=Nt(),q0=N0("replace"),j0=TypeError,xp=Ep("".indexOf),H0=Ep("".replace),gI=Ep("".slice),G0=Math.max;$0({target:"String",proto:!0},{replaceAll:function(e,t){var i=bI(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!C0(e)){if(r=V0(e),r&&(a=ns(bI(_0(e))),!~xp(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=xp(o,u);h!==-1;)p=l?ns(t(u,h,o)):F0(u,o,h,[],void 0,t),m+=gI(o,f,h)+p,f=h+d,h=h+c>o.length?-1:xp(o,u,h+c);return f<o.length&&(m+=gI(o,f)),m}})});var yI=b((L3,vI)=>{"use strict";aI();nI();SI();var z0=Ci();vI.exports=z0("String","replaceAll")});var II=b((M3,TI)=>{"use strict";var Q0=yI();TI.exports=Q0});var wp=b(($3,xI)=>{"use strict";var W0=II();xI.exports=W0});var wI=b((B3,EI)=>{"use strict";var Y0=Sa(),K0=Ya(),X0=Di(),J0=RangeError;EI.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 LI=b((D3,RI)=>{"use strict";var kI=Ve(),Z0=kc(),PI=Ya(),eC=wI(),tC=Di(),iC=kI(eC),rC=kI("".slice),sC=Math.ceil,AI=function(s){return function(e,t,i){var r=PI(tC(e)),a=Z0(t),n=r.length,o=i===void 0?" ":PI(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)}};RI.exports={start:AI(!1),end:AI(!0)}});var $I=b((C3,MI)=>{"use strict";var aC=sr();MI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(aC)});var BI=b(()=>{"use strict";var nC=ke(),oC=LI().start,uC=$I();nC({target:"String",proto:!0,forced:uC},{padStart:function(e){return oC(this,e,arguments.length>1?arguments[1]:void 0)}})});var CI=b((_3,DI)=>{"use strict";BI();var lC=Ci();DI.exports=lC("String","padStart")});var OI=b((F3,VI)=>{"use strict";var cC=CI();VI.exports=cC});var Pp=b((N3,_I)=>{"use strict";var dC=OI();_I.exports=dC});var Yh="2.0.134-dev.ae2fd074.0";var lt=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(lt||{}),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 Mo=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Mo||{}),Xl=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Xl||{});var Jl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Jl||{}),$o=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))($o||{});var YE=j(Et(),1);import{assertNever as Wm,assertNonNullable as wA,isNonNullable as Oo,ValueSubject as Lc,Subject as PA,Subscription as AA,merge as kA,observableFrom as RA,fromEvent as Hm,map as Gm,tap as zm,filterChanged as LA,isNullable as Mc,ErrorCategory as Qm}from"@vkontakte/videoplayer-shared/es2015";var jm=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 Lc(void 0);this.castState$=new Lc("NOT_AVAILABLE");this.errorEvent$=new PA;this.realCastState$=new Lc("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=Oo((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||jm("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Qm.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(){Oo(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Mc(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Mc(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(Hm(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 Wm(r.sessionState)}})).add(kA(Hm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(zm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Gm(r=>r.castState)),RA([i.getCastState()])).pipe(LA(),Gm(MA),zm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=Oo(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;(Mc(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"?Oo(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:Qm.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 Wm(s)}};var _h=j(Et(),1),LE=j(nr(),1),ME=j(sd(),1);var Xv=j($a(),1);import{assertNever as qv}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:qv(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:qv(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 pu,merge as jv}from"@vkontakte/videoplayer-shared/es2015";var Q=class{constructor(e){this.transitionStarted$=new pu;this.transitionEnded$=new pu;this.transitionUpdated$=new pu;this.forceChanged$=new pu;this.stateChangeStarted$=jv(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=jv(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 Hv=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 Gv,ErrorCategory as zv,fromEvent as hr,isNonNullable as Qv,map as Wv,merge as Yv,observableFrom as U$,Subject as q$,Subscription as Hd,timeout as j$,getHighestQuality as H$}from"@vkontakte/videoplayer-shared/es2015";var G$=5,z$=5,Q$=500,Kv=7e3,Ba=class{constructor(e){this.subscription=new Hd;this.loadMediaTimeoutSubscription=new Hd;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(Hv(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 Hd;this.subscription.add(e),this.subscription.add(Yv(this.videoState.stateChangeStarted$.pipe(Wv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Wv(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(Gv(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=Yv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,U$(["init"])).pipe(Gv(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:zv.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 Qv(o)&&(n.metadata.title=o),Qv(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$(Kv).subscribe(()=>a(`timeout(${Kv})`)))});(0,Xv.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:zv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var cp=j(Et(),1);import{clearVideoElement as Zv}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as W$}from"@vkontakte/videoplayer-shared/es2015";var Jv=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 Gd=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)}},zd=window.WeakMap?new WeakMap:new Gd,Qd=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)})},je=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Zv(i):(i=document.createElement("video"),s.appendChild(i)),zd.set(i,r);let a=new K$;return a.add(X$(i,e)),Qd.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},He=s=>{let e=Qd.get(s);e==null||e.unsubscribe(),Qd.delete(s);let t=zd.get(s);zd.delete(s),t?Zv(s):Jv(s)};var Yd=j(fr(),1);import{assertNonNullable as Da,isNonNullable as Zt,isNullable as aB,fromEvent as Wr,merge as ny,observableFrom as oy,filterChanged as uy,map as Ca,Subject as ly,Subscription as nB,ValueSubject as oB,ErrorCategory as uB}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Wd,isNullable as rB,Subscription as sB}from"@vkontakte/videoplayer-shared/es2015";var hu=(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)=>hu(e,()=>s.loop,i=>{Wd(i)&&(s.loop=i)},{onError:t}),Ge=(s,e,t,i)=>hu(e,()=>({muted:s.muted,volume:s.volume}),r=>{Wd(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}),ct=(s,e,t,i)=>hu(e,()=>s.playbackRate,r=>{Wd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),_i=hu;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},Kd=class s{constructor(e){this.available$=new ly;this.current$=new oB(void 0);this.error$=new ly;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,Yd.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(Ca(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(_i(t.externalTextTracks,()=>(0,Yd.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(Ca(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(){Da(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(ny(Wr(e,"addtrack"),Wr(e,"removetrack"),oy(["init"])).pipe(Ca(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),uy((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(ny(Wr(e,"change"),oy(["init"])).pipe(Ca(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ca(i=>i&&this.htmlTextTrackToITextTrack(i).id),uy()).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){Da(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){Da(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){Da(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){Da(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},dt=Kd;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 cy=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},Xd=s=>{let e=cy(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},dy=s=>{let e=cy(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as st,map as ei,merge as yu,filterChanged as vy,isNonNullable as yy,Subject as vB,filter as Zd,mapTo as ep,combine as yB,once as TB,throttle as IB,ErrorCategory as xB,ValueSubject as Ty,Subscription as EB}from"@vkontakte/videoplayer-shared/es2015";var dB=3,py=(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 fu=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 hy=j(Et(),1);var Va=()=>{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 mu=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,hy.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=Va()}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 bu=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 Pt=()=>window.ManagedMediaSource||window.MediaSource,Yr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},fy=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},gu=()=>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"',my='video/webm; codecs="vp09.00.10.08"',by='video/webm; codecs="av01.0.00M.08"',mB='audio/mp4; codecs="mp4a.40.2"',bB='audio/webm; codecs="opus"',gy,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:by})})),window.navigator.mediaCapabilities.decodingInfo(B(E({},s),{video:B(E({},s.video),{contentType:my})}))]);gy={DASH_WEBM_AV1:e,DASH_WEBM:t}});gB().catch(s=>{console.log(pB),console.error(s)});var Su=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 gy}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:fy(),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=Pt())==null?void 0:l.isTypeSupported)!=null&&d.call(l,hB)),k=!!((h=(c=Pt())==null?void 0:c.isTypeSupported)!=null&&h.call(c,fB)),C=!!((f=(p=Pt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,mB));this._codecs={h264:I,h265:k,vp9:!!((g=(m=Pt())==null?void 0:m.isTypeSupported)!=null&&g.call(m,my)),av1:!!((v=(S=Pt())==null?void 0:S.isTypeSupported)!=null&&v.call(S,by)),aac:C,opus:!!((T=(y=Pt())==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 Sy="audio/mpeg",vu=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,Sy))},this._codecs={mp3:!!((r=(i=Pt())==null?void 0:i.isTypeSupported)!=null&&r.call(i,Sy))}}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 Jd=class{constructor(){this.isInited$=new SB(!1);this._displayChecker=new bu,this._deviceChecker=new mu(this._displayChecker),this._browserChecker=new fu,this._videoChecker=new Su(this._deviceChecker,this._browserChecker),this._audioChecker=new vu,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 Jd;var ze=s=>{let e=w=>st(s,w).pipe(ep(void 0)),t=new EB,i=()=>t.unsubscribe(),r=yu(st(s,"progress"),st(s,"timeupdate")).pipe(ei(()=>py(s.buffered,s.currentTime))),a=G.browser.isSafari?yB({play:e("play").pipe(TB()),playing:e("playing")}).pipe(ep(void 0)):e("playing"),n=st(s,"volumechange").pipe(ei(()=>({muted:s.muted,volume:s.volume}))),o=st(s,"ratechange").pipe(ei(()=>s.playbackRate)),u=st(s,"error").pipe(Zd(()=>!!(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=st(s,"timeupdate").pipe(ei(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new vB,h=.3,p;t.add(yu(...d.map(w=>st(s,w))).subscribe(w=>{let F=s.currentTime;s.loop&&yy(p)&&yy(F)&&p>=s.duration-h&&F<=h&&c.next(p),p=F}));let f=e("pause").pipe(Zd(()=>!s.error&&p!==s.duration)),m=st(s,"enterpictureinpicture"),g=st(s,"leavepictureinpicture"),S=new Ty(dy(s));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new Ty(Xd(s)),y=st(s,"fullscreenchange");t.add(y.pipe(ei(()=>Xd(s))).subscribe(v));let T=.1,I=1e3,k=st(s,"timeupdate").pipe(ei(w=>s.duration-s.currentTime<T),vy()),C=yu(k.pipe(Zd(w=>!s.loop&&w)),st(s,"ended")).pipe(IB(I),ep(void 0)),D=yu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>st(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),vy());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$:st(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 nt=j(jt(),1),rp=j(Et(),1),br=j(nr(),1);import{isNonNullable as ne,isNullable as wu,now as Oy,isHigher as Pu,isHigherOrEqual as Xr,isInvariantQuality as Au,isLowerOrEqual as Jr,videoSizeToQuality as _y,assertNotEmptyArray as ku,assertNonNullable as Fy}from"@vkontakte/videoplayer-shared/es2015";var tp=!1,Ii={},ky=s=>{tp=s},Ry=()=>{Ii={}},Ly=s=>{s(Ii)},Oa=(s,e)=>{var t;tp&&(Ii.meta=(t=Ii.meta)!=null?t:{},Ii.meta[s]=e)},at=class{constructor(e){this.name=e}next(e){var i,r;if(!tp)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 My,isLowerOrEqual as Oq,isNonNullable as Tu,isNullable as DB,videoHeightToQuality as Iu}from"@vkontakte/videoplayer-shared/es2015";function ip(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function xu(s,e,t){return!!s&&ip(s,e,t)==="high_quality"}function Kr(s,e,t){return DB(s)||Tu(s.min)&&Tu(s.max)&&My(s.max,s.min)||Tu(s.min)&&e&&BB(s.min,e)||Tu(s.max)&&t&&My(s.max,t)}function $y({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Kr({max:s!=null&&s.max?Iu(s.max):void 0,min:s!=null&&s.min?Iu(s.min):void 0},e?Iu(e):void 0,t?Iu(t):void 0)}var Ny=new at("best_bitrate"),Ru=(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]=Oy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Lu='Assertion "ABR Tracks is empty array" failed',Eu=new WeakMap,By=new WeakMap,Dy=new WeakMap,_a=(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,nt.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,nt.default)(a,-1);return o&&(0,rp.default)(n,o)?o:n.length?(0,nt.default)(n,-1):(0,nt.default)(a,0)},Fa=(s,e,t,i)=>{var u;let r=Eu.get(e);r||(r=[...e].sort(Zr(1)),Eu.set(e,r));let a=Eu.get(t);a||(a=[...t].sort(Zr(1)),Eu.set(t,a));let n=Dy.get(s);n||(n=a.filter(l=>ne(l.bitrate)&&ne(s.bitrate)?s.bitrate/l.bitrate>i:!0),Dy.set(s,n));let o=(u=(0,nt.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,nt.default)(a,-1);return o&&(0,rp.default)(n,o)?o:n.length?(0,nt.default)(n,-1):(0,nt.default)(a,0)},Cy=s=>"quality"in s,Mu=(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]&&Oy()-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=Cy(o)?"video":"audio",l=Cy(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
|
-
`}),o}return i==null||i.recordSwitch(t),t},CB=(s,e)=>Math.log(e)/Math.log(s),
|
|
9
|
+
`}),o}return i==null||i.recordSwitch(t),t},CB=(s,e)=>Math.log(e)/Math.log(s),Uy=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&G.display.pixelRatio){let a=G.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=CB(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return xu(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}},Vy=new WeakMap,ii=(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 H,N,K,A,$;ku(s,Lu);let{containerSizeFactor:g,containerSizeLimit:S}=Uy({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&ne(o)?o:1,y=Vy.get(s);y||(y=s.filter(R=>!Au(R.quality)).sort((R,P)=>Pu(R.quality,P.quality)?-1:1),Vy.set(s,y));let T=(H=(0,nt.default)(y,-1))==null?void 0:H.quality,I=(N=(0,nt.default)(y,0))==null?void 0:N.quality,k=Kr(r,I,T),C=v*Ru(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),V={},D=null;for(let R of y){let P=!0;if(S)if(R.size)P=R.size.width<=S.width&&R.size.height<=S.height;else{let Ne=S&&_y(S);P=Ne?Jr(R.quality,Ne):!0}if(!P){V[R.quality]="FitsContainer";continue}let O=p||t,de=ne(O)&&isFinite(O)&&ne(R.bitrate)?O-a>=R.bitrate*C:!0,Fe=xu(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&&!Au(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Pu(R.quality,u.quality)){V[R.quality]="Buffer";continue}if(!!c&&Xr(R.quality,c)&&!Fe){V[R.quality]="DroppedFramesLimit";continue}if(!!h&&Xr(R.quality,h)&&!Fe){V[R.quality]="StallsLimit";continue}let we=k||(wu(r==null?void 0:r.max)||Jr(R.quality,r.max))&&(wu(r==null?void 0:r.min)||Xr(R.quality,r.min)),Pe=ne(d)&&!d?Jr(R.quality,i.backgroundVideoQualityLimit):!0;if(!we||!Pe){V[R.quality]="FitsQualityLimits";continue}D||(D=R)}D&&D.bitrate&&Ny.next(D.bitrate);let w=(K=D!=null?D:(0,nt.default)(y,-1))!=null?K:s[0],F=l==null?void 0:l.last,M=Mu(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
12
|
${s.map(R=>{var P,O;return`{ id: ${R.id}, quality: ${R.quality}, bitrate: ${R.bitrate}, size: ${(P=R.size)==null?void 0:P.width}:${(O=R.size)==null?void 0:O.height} }`}).join(`
|
|
@@ -39,7 +39,7 @@ var KE=Object.create;var Wl=Object.defineProperty,XE=Object.defineProperties,JE=
|
|
|
39
39
|
|
|
40
40
|
[best video track] ${D==null?void 0:D.quality}
|
|
41
41
|
[selected video track] ${M==null?void 0:M.quality}
|
|
42
|
-
`}),M}
|
|
42
|
+
`}),M},$u=(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,A,$,R;ku(s,Lu);let{containerSizeFactor:g,containerSizeLimit:S}=Uy({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&ne(o)?o:1,y=s.filter(P=>!Au(P.quality)).sort((P,O)=>Pu(P.quality,O.quality)?-1:1),T=(N=(0,nt.default)(y,-1))==null?void 0:N.quality,I=(K=(0,nt.default)(y,0))==null?void 0:K.quality,k=Kr(r,I,T),C=v*Ru(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),V={},w=y.filter(P=>{let O=!0;if(S)if(P.size)O=P.size.width<=S.width&&P.size.height<=S.height;else{let Rt=S&&_y(S);O=Rt?Jr(P.quality,Rt):!0}if(!O)return V[P.quality]="FitsContainer",!1;let de=p||t,Fe=ne(de)&&isFinite(de)&&ne(P.bitrate)?de-a>=P.bitrate*C:!0,ue=xu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===P.quality;if(!Fe&&!ue)return V[P.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&ne(i.minBufferToSwitchUp)&&u&&!Au(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Pu(P.quality,u.quality))return V[P.quality]="Buffer",!1;if(!!c&&Xr(P.quality,c)&&!ue)return V[P.quality]="DroppedFramesLimit",!1;if(!!h&&Xr(P.quality,h)&&!ue)return V[P.quality]="StallsLimit",!1;let Pe=k||(wu(r==null?void 0:r.max)||Jr(P.quality,r.max))&&(wu(r==null?void 0:r.min)||Xr(P.quality,r.min)),Ne=ne(d)&&!d?Jr(P.quality,i.backgroundVideoQualityLimit):!0;return!Pe||!Ne?(V[P.quality]="FitsQualityLimits",!1):!0})[0];w&&w.bitrate&&Ny.next(w.bitrate);let F=(A=w!=null?w:(0,nt.default)(y,-1))!=null?A:s[0],M=l==null?void 0:l.last,H=Mu(i,f,F,l);return ne(l)&&H.quality!==(M==null?void 0:M.quality)&&f({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
45
|
${s.map(P=>{var O,de;return`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate}, size: ${(O=P.size)==null?void 0:O.width}:${(de=P.size)==null?void 0:de.height} }`}).join(`
|
|
@@ -72,7 +72,7 @@ var KE=Object.create;var Wl=Object.defineProperty,XE=Object.defineProperties,JE=
|
|
|
72
72
|
|
|
73
73
|
[best video track] ${w==null?void 0:w.quality}
|
|
74
74
|
[selected video track] ${H==null?void 0:H.quality}
|
|
75
|
-
`}),H},
|
|
75
|
+
`}),H},Bu=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{ku(t,Lu);let d=r.considerPlaybackRate&&ne(a)?a:1,c=[...t].sort(Zr(-1)),h=s.bitrate;Fy(h);let p=d*Ru(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=_a(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&&Mu(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(`
|
|
@@ -93,7 +93,7 @@ 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},Du=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{ku(t,Lu);let d=r.considerPlaybackRate&&ne(a)?a:1,c=By.get(t);c||(c=[...t].sort(Zr(-1)),By.set(t,c));let h=s.bitrate;Fy(h);let p=d*Ru(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Fa(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&&Mu(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(`
|
|
@@ -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 Re=s=>new URL(s).hostname;import{assertNever as Jy,assertNonNullable as Zy,combine as iD,debounce as rD,ErrorCategory as eT,filter as tT,filterChanged as sD,isNonNullable as up,map as _u,merge as iT,observableFrom as aD,once as nD,Subscription as oD,ValueSubject as lp,videoQualityToHeight as rT,videoSizeToQuality as uD}from"@vkontakte/videoplayer-shared/es2015";var Wy=j(jt(),1);var jy=j(Et(),1);var qy=s=>{if(s instanceof DOMException&&(0,jy.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"))},Qe=(s,e)=>x(void 0,null,function*(){let t=s.muted;try{yield s.play()}catch(i){if(!qy(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{yield s.play()}catch(r){return qy(r)&&(s.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as Vu,isNullable as _B,assertNonNullable as qa}from"@vkontakte/videoplayer-shared/es2015";var Gy=j(fr(),1);import{isNonNullable as Hy,assertNonNullable as Cu,now as VB}from"@vkontakte/videoplayer-shared/es2015";function Oe(){return VB()}function sp(s){return Oe()-s}function ap(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 zy(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;Cu(d);let M=sp(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=()=>(Cu(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;Cu(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,Gy.default)($).length)?T():(c&&c(),e($))}else T()}),n.addEventListener("error",()=>{T()}),h){let A=()=>{Cu(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)=>(Hy(M)&&(m=M),Hy(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 Na=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 Qy=j(fr(),1);var Ua=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,Qy.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 Ou=1e4,np=3;var NB=6e4,UB=10,qB=1,jB=500,ja=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 Na(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ap(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=ap(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||{};!$y({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Wy.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||Vu(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=()=>{zy(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 Ua(np,Ou,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(Ou).withBitrateReporting(this.bitrateSwitcher).withRetryCount(np).withFinally(()=>{u=null}).send()},p=(T,I,k)=>{qa(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(Vu(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(Ou).withRetryCount(np).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&&(qa(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(),qa(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 Ne=()=>{l||c()&&C.seek(()=>{c()&&(M=Oe(),$(),A())})};Pe>0?H=window.setTimeout(()=>{this.paused?A():Ne()},Pe):Ne()},$=()=>{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?A():(v(),this._initPlayerWith(e));return}de(Ee)}else A()},R=(ee,Ee)=>{if(!c()||!this.sourceBuffer)return;let we,Pe,Ne,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"),Ne=this.sourceBuffer.buffered.length,Ne!==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())},Fe=ee=>{c()&&(qa(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(),Vu(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,qa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Vu(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&&sp(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(Ou).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;Qe(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 Xy=j(nr(),1);import{debounce as HB,filter as Yy,fromEvent as GB,interval as zB,isHigher as QB,isInvariantQuality as WB,isLower as YB,merge as KB,Subject as Ky,Subscription as XB}from"@vkontakte/videoplayer-shared/es2015";var op=class{constructor(){this.onDroopedVideoFramesLimit$=new Ky;this.subscription=new XB;this.playing=!1;this.tracks=[];this.forceChecker$=new Ky;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(Yy(()=>this.playing),Yy(()=>{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,Xy.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=op;import{map as JB,Observable as ZB}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as eD}from"@vkontakte/videoplayer-shared/es2015";var Ha=()=>{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||Ha()))},E(E({},i),e));r.observe(s);let a=eD(document,"visibilitychange").pipe(JB(n=>!document.hidden||Ha())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),pt=tD;var lD=["paused","playing","ready"],cD=["paused","playing","ready"],Ga=class{constructor(e){this.subscription=new oD;this.videoState=new Q("stopped");this.representations$=new lp([]);this.droppedFramesManager=new ts;this.maxSeekBackTime$=new lp(1/0);this.zeroTime$=new lp(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:eT.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),up(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,cp.default)(cD,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,cp.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 Jy(e)}};this.textTracksManager=new dt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:eT.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(iT(this.videoState.stateChangeStarted$.pipe(_u(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_u(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=je(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=ze(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(_u(r=>r.map(({track:a})=>a)),tT(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(),_u(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(iD({zeroTime:this.zeroTime$.pipe(tT(up)),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(Ge(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ct(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(pt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&rT(r),min:a&&rT(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 Jy(r.to)}},t)).add(iT(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),He(this.video)}createLiveDashPlayer(){let e=new ja({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&&up(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;Zy(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;Zy(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 sT=Ga;var gx=j(Et(),1);var At=(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 fx,filter as Kp,filterChanged as dl,fromEvent as YC,isNonNullable as mx,map as Xp,merge as pl,observableFrom as Jp,once as bx,Subscription as KC}from"@vkontakte/videoplayer-shared/es2015";var Fu=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 Fu{constructor(){super(),this.listeners||Fu.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)}},za=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&&(za.prototype[Symbol.toStringTag]="AbortController",is.prototype[Symbol.toStringTag]="AbortSignal");function Nu(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 dp(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Nu({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,Qa=dD()&&Nu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),aT=Qa?dp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Mt=Qa?aT.fetch:window.fetch,mH=Qa?aT.Request:window.Request,le=Qa?za:window.AbortController,bH=Qa?is:window.AbortSignal;var Hp=j(Wa(),1);var GT=j(HT(),1);import{ErrorCategory as Ka}from"@vkontakte/videoplayer-shared/es2015";var Uu=s=>{if(!s)return{id:"EmptyResponse",category:Ka.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Ka.NETWORK,message:`UV Error ${s}`};let e=(0,GT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ka.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:Ka.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ka.PARSER,message:"Response is valid XML, but parser failed"}};var We=(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 Up,assertNonNullable as ps,combine as hs,ErrorCategory as Gt,filter as rl,filterChanged as Ln,flattenObject as Mn,fromEvent as ki,getTraceSubscriptionMethod as kC,interval as qp,isNonNullable as $n,isNullable as ux,map as fs,merge as yr,now as jp,Subject as sl,Subscription as lx,tap as RC,throttle as LC,ValueSubject as ge}from"@vkontakte/videoplayer-shared/es2015";var Hu=j(Et(),1),ls=j(jt(),1),Gu=j(Wa(),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),zT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),QT=!zT(window.requestIdleCallback)||!zT(window.cancelIdleCallback),rs=QT?KD:window.requestIdleCallback,ri=QT?XD:window.cancelIdleCallback;var JI=j($a(),1);import{assertNever as JD,ErrorCategory as WT,Subject as YT}from"@vkontakte/videoplayer-shared/es2015";var ZD=18,KT=!1;try{KT=G.browser.isSafari&&!!G.browser.safariVersion&&G.browser.safariVersion<=ZD}catch(s){console.error(s)}var gp=class{constructor(e){this.bufferFull$=new YT;this.error$=new YT;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:WT.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)};KT&&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:WT.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)}}},XT=gp;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 ht,ErrorCategory as wi,fromEvent as Cp,getExponentialDelay as Vp,isNonNullable as us,isNullable as Ye,now as ju,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 Xa=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 Ja=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 Za=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 en=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 tn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rn=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 sn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var an=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var nn=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 on=class extends pe{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var un=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 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.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 dn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hn=class extends pe{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var fn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var mn=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 bn=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 gn=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 Sn=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var vn=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 yn=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:Ja,moov:Za,mvhd:en,moof:tn,mdat:rn,sidx:gr,trak:sn,mdia:ln,mfhd:hn,tkhd:cn,traf:fn,tfhd:mn,tfdt:bn,trun:gn,minf:dn,sv3d:an,st3d:nn,prhd:on,proj:pn,equi:un,uuid:Xa,stbl:Sn,stsd:vn,avc1:yn,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},JT={validateData:s0,parseInit:c0,getIndexRange:()=>{},parseSegments:a0,parseFeedableSegmentChunk:n0,getChunkEndTime:l0,getServerLatencyTimestamps:o0,getTimescaleFromIndex:u0};var In=j(Et(),1);import{assertNonNullable as vp,isNonNullable as iI,isNullable as p0}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as d0}from"@vkontakte/videoplayer-shared/es2015";var ZT={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"}},eI=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=Tn(s,t),r=i in ZT,a=r?ZT[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=Tn(u),c=l*rt(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}},Tn=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*rt(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*rt(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*rt(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 Tn(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=eI(i);if(!e(r))return;r.type==="master"&&Sr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},tI=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=eI(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 rI=[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=Tn(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,In.default)(rI,h)&&(o=!0),!o}),vp(e,"Failed to parse webm Segment start"),vp(t,"Failed to parse webm Segment end"),vp(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=>iI(o.time)&&iI(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,In.default)(rI,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,In.default)(h0,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,In.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},sI={validateData:tI,parseInit:f0,getIndexRange:m0,parseSegments:b0,parseFeedableSegmentChunk:g0};var xn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return sI;case"mp4":return JT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var $p=j(wp(),1),QI=j(nr(),1),WI=j(Pp(),1),YI=j(jt(),1),Bp=j(fr(),1);var FI=j(Et(),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,FI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as fC,isNullable as GI}from"@vkontakte/videoplayer-shared/es2015";var qu=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var NI=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>${`
|
|
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 kp=j(jt(),1);import{videoSizeToQuality as hC}from"@vkontakte/videoplayer-shared/es2015";var UI=({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}},qI=({id:s,bitrate:e})=>({id:s,bitrate:e}),jI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),HI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Rp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,kp.default)(i.split("."),0),isDefault:r}),Lp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,kp.default)(r.split("."),0)}),Mp=s=>"url"in s,ot=s=>s.type==="template",En=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var zI=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,$p.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,QI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,$p.default)(t,n,(o,u)=>GI(a)?o:GI(u)?a:(0,WI.default)(a,parseInt(u,10),"0"))}return t},KI=(s,e)=>{var D,w,F,M,H,N,K,A,$,R,P,O,de,Fe,ue,ee,Ee,we,Pe,Ne,Rt,$t,Yt,ai,Bi,ws,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;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,Xe;return(Xe=(q=fe.textContent)==null?void 0:q.trim())!=null?Xe:""}),o=(D=(0,YI.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=zI(v):(0,Bp.default)(I).filter(fe=>fe).length&&!u?S=(0,Bp.default)(I).reduce((fe,q)=>{var Xe;return fe+((Xe=zI(q))!=null?Xe: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 Xe=(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],ql=($=(A=q.getAttribute("profiles"))==null?void 0:A.split(","))!=null?$:[],oa=(P=NI((R=q.getAttribute("lang"))!=null?R:""))!=null?P:{},ni=(Fe=(de=(O=q.querySelector("Label"))==null?void 0:O.textContent)==null?void 0:de.trim())!=null?Fe:void 0,jl=q.querySelectorAll("Representation"),Hl=q.querySelector("SegmentTemplate"),Gl=(ee=(ue=q.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?ee:void 0,mt=Xi,W={id:Xe,language:oa.language,isDefault:Gl==="main",label:ni,codecs:Ki,hdr:mt==="video"&&os(Ki),mime:Bt,representations:[]};for(let U of jl){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=(Ne=U.querySelector("BaseURL"))==null?void 0:Ne.textContent)==null?void 0:Rt.trim())!=null?$t:"",Je=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=((ws=oa.privateuse)==null?void 0:ws.includes("x-auto"))||$e.includes("_auto"),Ze=U.querySelector("SegmentTemplate");if(Ze){let Ct={representationId:(Ps=U.getAttribute("id"))!=null?Ps:void 0,bandwidth:(As=U.getAttribute("bandwidth"))!=null?As:void 0},di=parseInt((ks=U.getAttribute("bandwidth"))!=null?ks:"",10)/1e3,pi=(Ls=parseInt((Rs=Ze.getAttribute("startNumber"))!=null?Rs:"",10))!=null?Ls:1,bt=parseInt((Ms=Ze.getAttribute("timescale"))!=null?Ms:"",10),Ji=($s=Ze.querySelectorAll("SegmentTimeline S"))!=null?$s:[],gt=Ze.getAttribute("media");if(!gt)continue;let hi=[],fi=0,mi="",St=0,Vt=pi,se=0;for(let me of Ji){let et=parseInt((Bs=me.getAttribute("d"))!=null?Bs:"",10),ce=parseInt((Ds=me.getAttribute("r"))!=null?Ds:"",10)||0,Be=parseInt((Cs=me.getAttribute("t"))!=null?Cs:"",10);se=Number.isFinite(Be)?Be:se;let tt=et/bt*1e3,De=se/bt*1e3;for(let ve=0;ve<ce+1;ve++){let Ce=Ei(gt,B(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:(se+ve*et).toString(10)})),vt=(De!=null?De:0)+ve*tt,_t=vt+tt;Vt++,hi.push({time:{from:vt,to:_t},url:Ce})}se+=(ce+1)*et,fi+=(ce+1)*tt}St=se/bt*1e3,mi=Ei(gt,B(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:se.toString(10)}));let Ot={time:{from:St,to:1/0},url:mi},Ae={type:"template",baseUrl:Je,segmentTemplateUrl:gt,initUrl:"",totalSegmentsDurationMs:fi,segments:hi,nextSegmentBeyondManifest:Ot,timescale:bt};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:Je}}else{let $e=(Os=(Vs=U.getAttribute("contentType"))!=null?Vs:Me==null?void 0:Me.split("/")[0])!=null?Os:Xi,ci=(Fs=(_s=q.getAttribute("profiles"))==null?void 0:_s.split(","))!=null?Fs:[],Ze=parseInt((Ns=U.getAttribute("width"))!=null?Ns:"",10),Ct=parseInt((Us=U.getAttribute("height"))!=null?Us:"",10),di=parseInt((qs=U.getAttribute("bandwidth"))!=null?qs:"",10)/1e3,pi=(js=U.getAttribute("frameRate"))!=null?js:"",bt=(Hs=U.getAttribute("quality"))!=null?Hs:void 0,Ji=pi?qu(pi):void 0,gt=(Gs=U.getAttribute("id"))!=null?Gs:"id"+(k++).toString(10),hi=$e==="video"?`${Ct}p`:$e==="audio"?`${di}Kbps`:ui,fi=`${gt}@${hi}`,mi=[...C,...ql,...ci],St,Vt=U.querySelector("SegmentBase"),se=(zs=U.querySelector("SegmentTemplate"))!=null?zs:Hl;if(Vt){let Ae=(Ws=(Qs=U.querySelector("SegmentBase Initialization"))==null?void 0:Qs.getAttribute("range"))!=null?Ws:"",[me,et]=Ae.split("-").map(Ce=>parseInt(Ce,10)),ce={from:me,to:et},Be=(Ys=U.querySelector("SegmentBase"))==null?void 0:Ys.getAttribute("indexRange"),[tt,De]=Be?Be.split("-").map(Ce=>parseInt(Ce,10)):[],ve=Be?{from:tt,to:De}:void 0;St={type:"byteRange",url:Je,initRange:ce,indexRange:ve}}else if(se){let Ae={representationId:(Ks=U.getAttribute("id"))!=null?Ks:void 0,bandwidth:(Xs=U.getAttribute("bandwidth"))!=null?Xs:void 0},me=parseInt((Js=se.getAttribute("timescale"))!=null?Js:"",10),et=(Zs=se.getAttribute("initialization"))!=null?Zs:"",ce=se.getAttribute("media"),Be=(ta=parseInt((ea=se.getAttribute("startNumber"))!=null?ea:"",10))!=null?ta:1,tt=Ei(et,Ae);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let De=(ia=se.querySelectorAll("SegmentTimeline S"))!=null?ia:[],ve=[],Ce=0,vt="",_t=0;if(De.length){let bi=Be,be=0;for(let yt of De){let ye=parseInt((ra=yt.getAttribute("d"))!=null?ra:"",10),it=parseInt((sa=yt.getAttribute("r"))!=null?sa:"",10)||0,gi=parseInt((aa=yt.getAttribute("t"))!=null?aa:"",10);be=Number.isFinite(gi)?gi:be;let Zi=ye/me*1e3,er=be/me*1e3;for(let Si=0;Si<it+1;Si++){let Ql=Ei(ce,B(E({},Ae),{segmentNumber:bi.toString(10),segmentTime:(be+Si*ye).toString(10)})),ua=(er!=null?er:0)+Si*Zi,Wl=ua+Zi;bi++,ve.push({time:{from:ua,to:Wl},url:Ql})}be+=(it+1)*ye,Ce+=(it+1)*Zi}_t=be/me*1e3,vt=Ei(ce,B(E({},Ae),{segmentNumber:bi.toString(10),segmentTime:be.toString(10)}))}else if(fC(S)){let be=parseInt((na=se.getAttribute("duration"))!=null?na:"",10)/me*1e3,yt=Math.ceil(S/be),ye=0;for(let it=1;it<yt;it++){let gi=Ei(ce,B(E({},Ae),{segmentNumber:it.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:gi}),ye+=be}_t=ye,vt=Ei(ce,B(E({},Ae),{segmentNumber:yt.toString(10),segmentTime:ye.toString(10)}))}let zl={time:{from:_t,to:1/0},url:vt};St={type:"template",baseUrl:Je,segmentTemplateUrl:ce,initUrl:tt,totalSegmentsDurationMs:Ce,segments:ve,nextSegmentBeyondManifest:zl,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;mt||(mt=Ot),li={id:fi,kind:Ot,segmentReference:St,profiles:mi,duration:S,bitrate:di,mime:Me,codecs:ui,width:Ze,height:Ct,fps:Ji,quality:bt}}W.language||(W.language=Le),W.label||(W.label=Dt),W.mime||(W.mime=Me),W.codecs||(W.codecs=ui),W.hdr||(W.hdr=mt==="video"&&os(ui)),W.representations.push(li)}if(mt){let U=r[mt].find(Le=>Le.id===W.id);if(U&&W.representations.every(Le=>ot(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,Je=Le.segmentReference;Je.segments.push(...oi.segments),Je.nextSegmentBeyondManifest=oi.nextSegmentBeyondManifest}else r[mt].push(W)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as XI}from"@vkontakte/videoplayer-shared/es2015";var z=(s,e)=>XI(s)&&XI(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 wn=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);ht(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new XT(this.sourceBuffer),this.subscription.add(Cp(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(Cp(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);ht(i,"No init buffer for starting representation"),ht(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);ht(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ye(a)||Ye(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ht(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);ht(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ye(a)||Ye(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ht(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,Gu.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||!ot(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);ht(r);let a=this.segments.get(i);ht(a,"No segments for starting representation");let n=this.initData.get(i);if(ht(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);ht(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ye(o)||Ye(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),ht(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(){!Ye(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(Ye(e)||Ye(this.downloadingRepresentationId)||Ye(this.playingRepresentationId)||Ye(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(ht(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,Hu.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,Gu.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,Gu.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||!ot(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;ht(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(!ot(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)&&!(We(this.sourceBuffer.buffered,h)&&We(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*(){ot(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=Vp(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=ju(),!d)return;let c=new DataView(d),h=xn(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]),En(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())ot(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=Vp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Cp(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=ju(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),En(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ot(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=ju(),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(!ot(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=ju();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,Hu.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=xn(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=xn(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(!(Ye(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer))){!this.isLive&&G.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(We(this.sourceBuffer.buffered,e.segment.time.from,100)&&We(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",Mp(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,JI.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=Vp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,xn(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&&ot(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||Ye(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=Mp(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,Hu.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||Ye(e)?0:At(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(Ye(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||Ye(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 zu=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 Pn,assertNever as ZI,fromEvent as ex,merge as vC,now as An,Subscription as yC,Subject as tx,ValueSubject as Op,flattenObject as cs,ErrorCategory as kn}from"@vkontakte/videoplayer-shared/es2015";var Qu=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Yu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new Op(void 0);this.lastConnectionReused$=new Op(void 0);this.lastRequestFirstBytes$=new Op(void 0);this.recoverableError$=new tx;this.error$=new tx;this.abortAllController=new le;this.subscription=new yC;this.fetchManifest=Pn(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=Qu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Wu);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=Pn(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:ZI(t)}this.requestQuic&&(d=ji(d));let p=this.abortAllController.signal,f;if(n){let N=new le;if(f=vC(ex(this.abortAllController.signal,"abort"),ex(n,"abort")).subscribe(()=>{try{N.abort()}catch(K){Wu(K)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(K){Wu(K)}p=N.signal}let m=An();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=An();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=An(),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,Wu(N)},D=Pn(p,function(A){return X(this,arguments,function*({done:N,value:K}){if(I===0&&this.lastRequestFirstBytes$.next(An()-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=An(),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=Pn(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=Pn(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}=zu(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:ZI(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:kn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:kn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:kn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:kn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:kn.FATAL})}})}},Wu=s=>{if(!En(s))throw s};var Pi=(s,e,t)=>t*e+(1-t)*s,_p=(s,e)=>s.reduce((t,i)=>t+i,0)/e,ix=(s,e,t,i)=>{let r=0,a=t,n=_p(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 rx}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 rx(e.initial),this.debounced$=new rx(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new at(`raw_${t}`),this.smoothedSeries$=new at(`smoothed_${t}`),this.reportedSeries$=new at(`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+=rt(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=_p(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Pi(this.emaSmoothed,e,this.params.emaAlpha);let i=ix(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 ds=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as IC,ValueSubject as xC}from"@vkontakte/videoplayer-shared/es2015";var Rn=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&&ot(t.segmentReference))}};var el=j(jt(),1);import{assertNever as tl}from"@vkontakte/videoplayer-shared/es2015";var sx=(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]},ax=({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"]},nx=({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"]},Fp=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 lx;this.representationSubscription=new lx;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=Up(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=Up(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=KI(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Uu(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=Pt())==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",Mn(a)),a})}.bind(this));this.initRepresentations=Up(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",Mn({initialVideo:e,initialAudio:t,sourceHls:i})),ps(this.manifest),ps(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?gu():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 wn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],$n(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new wn("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Rn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Rn(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(fs(p=>this.element?At(this.element.buffered,this.element.currentTime*1e3):0),Ln(),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(Ln()).subscribe(f=>this.liveStreamEndTimestamp=jp())),this.subscription.add(ki(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=qp(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(hs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(fs(({isActiveLive:f,isLowLatency:m})=>f&&m),Ln()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ds(this.element,1)})),this.representationSubscription.add(hs({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(hs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(rl(({isLive:f})=>f),Ln((f,m)=>m.bufferLength<f.bufferLength),fs(({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(hs({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),ds(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(hs({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(fs(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=yr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(fs(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=hs({allBuffersFull:l,someBufferEnded:d}).pipe(Ln(),fs(({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,Hp.default)((0,Hp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),ot(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&$n(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=qp(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 Yu({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;ps(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?jp()-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(){ps(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&&We(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=jp(),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",Mn(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=qp(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;ps(this.element),ps(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),We(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(ux(this.element)||ux(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Mn({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;$n(this.element)&&$n(this.source)&&$n(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",Mn(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/rt(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*rt(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 dx=`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 px=`#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),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 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,e.byteLength-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 ms=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(dx,this.gl.VERTEX_SHADER),i=this.createShader(px,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 Bn,once as VC,Subscription as OC,ValueSubject as Gp,isNonNullable as _C,safeStorage as zp,filterChanged as FC}from"@vkontakte/videoplayer-shared/es2015";var ul="stalls_manager_metrics",Qp="stalls_manager_abr_params",hx="stalls_manager_default_tuning_abr_params",Wp=class{constructor(){this.isSeeked$=new Gp(!1);this.isBuffering$=new Gp(!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 Gp(!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(Qp):{};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=Bn(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Bn()-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(hx)),{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}=E({},this.abrParams);this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(Qp),this.setStoredData(hx,{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(Qp,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=zp.get(e))!=null?i:t)}setStoredData(e,t){zp.set(e,JSON.stringify(t))}removeStoredData(e){zp.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=Bn())),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=Bn(),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&&Bn()-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=Wp;import{combine as NC,map as UC,observeElementSize as qC,Subscription as jC,ValueSubject as Yp,noop as HC}from"@vkontakte/videoplayer-shared/es2015";var cl=class{constructor(){this.subscription=new jC;this.pipSize$=new Yp(void 0);this.videoSize$=new Yp(void 0);this.elementSize$=new Yp(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 ms(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 dt(e.source.url),this.params=e,this.video=je(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=ze(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:fx.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(Kp(l=>!!l.length),bx()).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(Xp(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(Kp(mx),bx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Xp(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(Ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ct(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(pt(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(Rp(p));let f=[];for(let m of p.representations){let g=qI(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(Lp(h));let p=[];for(let f of h.representations){let m=UI(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=jI(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(Kp(()=>this.videoTracksMap.size>0)).subscribe(()=>x(this,null,function*(){let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,gx.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});mx(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(Lp(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(Rp(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(Xp(({to:l})=>l==="ready"),dl());this.subscription.add(pl(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Jp(["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$,Jp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=pl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Jp(["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,Fe;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Fa:_a,t=this.params.tuning.useNewAutoSelectVideoTrack?Du:Bu,i=this.params.tuning.useNewAutoSelectVideoTrack?ii:$u,{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=At(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&&((Fe=this.audioTracksMap.get(C))==null?void 0:Fe.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(){Qe(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:fx.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),He(this.video),this.tracer.end()}};var Dn=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 Zp,merge as Sx,filter as vx,filterChanged as XC,isNullable as eh,map as yx,ValueSubject as th,isNonNullable as JC}from"@vkontakte/videoplayer-shared/es2015";var Cn=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 th(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(yx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Zp({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(yx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(vx(o=>JC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Zp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Sx(i.playbackRateState$,new th(1))}).pipe(vx(({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||eh(l)||(e=o-l)})).add(Zp({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Sx(i.playbackRateState$,new th(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||eh(o)||eh(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=HI(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 Ih,filterChanged as wl,fromEvent as QV,isNonNullable as Zx,map as xh,merge as Pl,observableFrom as Eh,once as eE,Subscription as WV}from"@vkontakte/videoplayer-shared/es2015";var yh=j(Wa(),1);import{abortable as bh,assertNonNullable as ys,combine as Ts,ErrorCategory as Qt,filter as Tl,filterChanged as mo,flattenObject as bo,fromEvent as si,getTraceSubscriptionMethod as DV,interval as gh,isNonNullable as go,isNullable as Kx,map as Is,merge as Ar,now as Sh,Subject as Il,Subscription as vh,tap as CV,throttle as Xx,ValueSubject as Se}from"@vkontakte/videoplayer-shared/es2015";var gl=j(Et(),1),Ss=j(jt(),1),Sl=j(Wa(),1);var Gx=j($a(),1);import{assertNever as ZC,ErrorCategory as Tx,Subject as Ix}from"@vkontakte/videoplayer-shared/es2015";var eV=18,xx=!1;try{xx=G.browser.isSafari&&!!G.browser.safariVersion&&G.browser.safariVersion<=eV}catch(s){console.error(s)}var ih=class{constructor(e){this.bufferFull$=new Ix;this.error$=new Ix;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:Tx.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)};xx&&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:Tx.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)}}},Ex=ih;import{abortable as zi,assertNonNullable as ft,ErrorCategory as wr,fromEvent as ml,getExponentialDelay as hh,isNonNullable as gs,isNullable as Ke,now as bl,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),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 bs=class extends ie{};var Vn=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 On=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 _n=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 Fn=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 Nn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Un=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 qn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var jn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hn=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 Gn=class extends he{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var zn=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 Qn=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.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 Yn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Kn=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xn=class extends he{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Jn=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.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 eo=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 to=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 io=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ro=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 so=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:On,moov:_n,mvhd:Fn,moof:Nn,mdat:Un,sidx:Ir,trak:qn,mdia:Qn,mfhd:Xn,tkhd:Wn,traf:Jn,tfhd:Zn,tfdt:eo,trun:to,minf:Yn,sv3d:jn,st3d:Hn,prhd:Gn,proj:Kn,equi:zn,uuid:Vn,stbl:io,stsd:ro,avc1:so,unknown:bs},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,e.byteLength-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 bs(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},wx={validateData:aV,parseInit:dV,getIndexRange:()=>{},parseSegments:nV,parseFeedableSegmentChunk:oV,getChunkEndTime:cV,getServerLatencyTimestamps:uV,getTimescaleFromIndex:lV};var no=j(Et(),1);import{assertNonNullable as sh,isNonNullable as Rx,isNullable as hV}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as pV}from"@vkontakte/videoplayer-shared/es2015";var Px={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"}},Ax=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=ao(s,t),r=i in Px,a=r?Px[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=ao(u),c=l*rt(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}},ao=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*rt(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*rt(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*rt(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 ao(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=Ax(i);if(!e(r))return;r.type==="master"&&xr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},kx=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Ax(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 Lx=[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=ao(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,no.default)(Lx,h)&&(o=!0),!o}),sh(e,"Failed to parse webm Segment start"),sh(t,"Failed to parse webm Segment end"),sh(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=>Rx(o.time)&&Rx(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,no.default)(Lx,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,no.default)(fV,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,no.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},Mx={validateData:kx,parseInit:mV,getIndexRange:bV,parseSegments:gV,parseFeedableSegmentChunk:SV};var oo=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Mx;case"mp4":return wx}}throw new ReferenceError(`Unsupported mime type ${s}`)};var ch=j(wp(),1),Ux=j(nr(),1),qx=j(Pp(),1),jx=j(jt(),1),dh=j(fr(),1);import{isNonNullable as IV,isNullable as Fx}from"@vkontakte/videoplayer-shared/es2015";var $x=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>${`
|
|
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 nh=j(jt(),1);import{videoSizeToQuality as yV,throttleFn as TV}from"@vkontakte/videoplayer-shared/es2015";var Bx=({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}},Dx=({id:s,bitrate:e})=>({id:s,bitrate:e}),Cx=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Vx=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),oh=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,nh.default)(i.split("."),0),isDefault:r}),uh=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,nh.default)(r.split("."),0)}),lh=s=>"url"in s,ut=s=>s.type==="template",uo=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Ox=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},_x=s=>{let e=!1,t=TV(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};var Nx=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,ch.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Ux.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,ch.default)(t,n,(o,u)=>Fx(a)?o:Fx(u)?a:(0,qx.default)(a,parseInt(u,10),"0"))}return t},Hx=(s,e)=>{var D,w,F,M,H,N,K,A,$,R,P,O,de,Fe,ue,ee,Ee,we,Pe,Ne,Rt,$t,Yt,ai,Bi,ws,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;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,Xe;return(Xe=(q=fe.textContent)==null?void 0:q.trim())!=null?Xe:""}),o=(D=(0,jx.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=Nx(v):(0,dh.default)(I).filter(fe=>fe).length&&!u?S=(0,dh.default)(I).reduce((fe,q)=>{var Xe;return fe+((Xe=Nx(q))!=null?Xe: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 Xe=(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],ql=($=(A=q.getAttribute("profiles"))==null?void 0:A.split(","))!=null?$:[],oa=(P=$x((R=q.getAttribute("lang"))!=null?R:""))!=null?P:{},ni=(Fe=(de=(O=q.querySelector("Label"))==null?void 0:O.textContent)==null?void 0:de.trim())!=null?Fe:void 0,jl=q.querySelectorAll("Representation"),Hl=q.querySelector("SegmentTemplate"),Gl=(ee=(ue=q.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?ee:void 0,mt=Xi,W={id:Xe,language:oa.language,isDefault:Gl==="main",label:ni,codecs:Ki,hdr:mt==="video"&&os(Ki),mime:Bt,representations:[]};for(let U of jl){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=(Ne=U.querySelector("BaseURL"))==null?void 0:Ne.textContent)==null?void 0:Rt.trim())!=null?$t:"",Je=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=((ws=oa.privateuse)==null?void 0:ws.includes("x-auto"))||$e.includes("_auto"),Ze=U.querySelector("SegmentTemplate");if(Ze){let Ct={representationId:(Ps=U.getAttribute("id"))!=null?Ps:void 0,bandwidth:(As=U.getAttribute("bandwidth"))!=null?As:void 0},di=parseInt((ks=U.getAttribute("bandwidth"))!=null?ks:"",10)/1e3,pi=(Ls=parseInt((Rs=Ze.getAttribute("startNumber"))!=null?Rs:"",10))!=null?Ls:1,bt=parseInt((Ms=Ze.getAttribute("timescale"))!=null?Ms:"",10),Ji=($s=Ze.querySelectorAll("SegmentTimeline S"))!=null?$s:[],gt=Ze.getAttribute("media");if(!gt)continue;let hi=[],fi=0,mi="",St=0,Vt=pi,se=0;for(let me of Ji){let et=parseInt((Bs=me.getAttribute("d"))!=null?Bs:"",10),ce=parseInt((Ds=me.getAttribute("r"))!=null?Ds:"",10)||0,Be=parseInt((Cs=me.getAttribute("t"))!=null?Cs:"",10);se=Number.isFinite(Be)?Be:se;let tt=et/bt*1e3,De=se/bt*1e3;for(let ve=0;ve<ce+1;ve++){let Ce=Li(gt,B(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:(se+ve*et).toString(10)})),vt=(De!=null?De:0)+ve*tt,_t=vt+tt;Vt++,hi.push({time:{from:vt,to:_t},url:Ce})}se+=(ce+1)*et,fi+=(ce+1)*tt}St=se/bt*1e3,mi=Li(gt,B(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:se.toString(10)}));let Ot={time:{from:St,to:1/0},url:mi},Ae={type:"template",baseUrl:Je,segmentTemplateUrl:gt,initUrl:"",totalSegmentsDurationMs:fi,segments:hi,nextSegmentBeyondManifest:Ot,timescale:bt};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:Je}}else{let $e=(Os=(Vs=U.getAttribute("contentType"))!=null?Vs:Me==null?void 0:Me.split("/")[0])!=null?Os:Xi,ci=(Fs=(_s=q.getAttribute("profiles"))==null?void 0:_s.split(","))!=null?Fs:[],Ze=parseInt((Ns=U.getAttribute("width"))!=null?Ns:"",10),Ct=parseInt((Us=U.getAttribute("height"))!=null?Us:"",10),di=parseInt((qs=U.getAttribute("bandwidth"))!=null?qs:"",10)/1e3,pi=(js=U.getAttribute("frameRate"))!=null?js:"",bt=(Hs=U.getAttribute("quality"))!=null?Hs:void 0,Ji=pi?qu(pi):void 0,gt=(Gs=U.getAttribute("id"))!=null?Gs:"id"+(k++).toString(10),hi=$e==="video"?`${Ct}p`:$e==="audio"?`${di}Kbps`:ui,fi=`${gt}@${hi}`,mi=[...C,...ql,...ci],St,Vt=U.querySelector("SegmentBase"),se=(zs=U.querySelector("SegmentTemplate"))!=null?zs:Hl;if(Vt){let Ae=(Ws=(Qs=U.querySelector("SegmentBase Initialization"))==null?void 0:Qs.getAttribute("range"))!=null?Ws:"",[me,et]=Ae.split("-").map(Ce=>parseInt(Ce,10)),ce={from:me,to:et},Be=(Ys=U.querySelector("SegmentBase"))==null?void 0:Ys.getAttribute("indexRange"),[tt,De]=Be?Be.split("-").map(Ce=>parseInt(Ce,10)):[],ve=Be?{from:tt,to:De}:void 0;St={type:"byteRange",url:Je,initRange:ce,indexRange:ve}}else if(se){let Ae={representationId:(Ks=U.getAttribute("id"))!=null?Ks:void 0,bandwidth:(Xs=U.getAttribute("bandwidth"))!=null?Xs:void 0},me=parseInt((Js=se.getAttribute("timescale"))!=null?Js:"",10),et=(Zs=se.getAttribute("initialization"))!=null?Zs:"",ce=se.getAttribute("media"),Be=(ta=parseInt((ea=se.getAttribute("startNumber"))!=null?ea:"",10))!=null?ta:1,tt=Li(et,Ae);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let De=(ia=se.querySelectorAll("SegmentTimeline S"))!=null?ia:[],ve=[],Ce=0,vt="",_t=0;if(De.length){let bi=Be,be=0;for(let yt of De){let ye=parseInt((ra=yt.getAttribute("d"))!=null?ra:"",10),it=parseInt((sa=yt.getAttribute("r"))!=null?sa:"",10)||0,gi=parseInt((aa=yt.getAttribute("t"))!=null?aa:"",10);be=Number.isFinite(gi)?gi:be;let Zi=ye/me*1e3,er=be/me*1e3;for(let Si=0;Si<it+1;Si++){let Ql=Li(ce,B(E({},Ae),{segmentNumber:bi.toString(10),segmentTime:(be+Si*ye).toString(10)})),ua=(er!=null?er:0)+Si*Zi,Wl=ua+Zi;bi++,ve.push({time:{from:ua,to:Wl},url:Ql})}be+=(it+1)*ye,Ce+=(it+1)*Zi}_t=be/me*1e3,vt=Li(ce,B(E({},Ae),{segmentNumber:bi.toString(10),segmentTime:be.toString(10)}))}else if(IV(S)){let be=parseInt((na=se.getAttribute("duration"))!=null?na:"",10)/me*1e3,yt=Math.ceil(S/be),ye=0;for(let it=1;it<yt;it++){let gi=Li(ce,B(E({},Ae),{segmentNumber:it.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:gi}),ye+=be}_t=ye,vt=Li(ce,B(E({},Ae),{segmentNumber:yt.toString(10),segmentTime:ye.toString(10)}))}let zl={time:{from:_t,to:1/0},url:vt};St={type:"template",baseUrl:Je,segmentTemplateUrl:ce,initUrl:tt,totalSegmentsDurationMs:Ce,segments:ve,nextSegmentBeyondManifest:zl,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;mt||(mt=Ot),li={id:fi,kind:Ot,segmentReference:St,profiles:mi,duration:S,bitrate:di,mime:Me,codecs:ui,width:Ze,height:Ct,fps:Ji,quality:bt}}W.language||(W.language=Le),W.label||(W.label=Dt),W.mime||(W.mime=Me),W.codecs||(W.codecs=ui),W.hdr||(W.hdr=mt==="video"&&os(ui)),W.representations.push(li)}if(mt){let U=r[mt].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,Je=Le.segmentReference;Je.segments.push(...oi.segments),Je.nextSegmentBeyondManifest=oi.nextSegmentBeyondManifest}else r[mt].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 lo=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);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 Ex(this.sourceBuffer),this.tuning.dash.useSourceBufferBufferedDiff?this.sourceBufferBufferedDiff=new fl(this.mediaSource,this.sourceBuffer):this.subscription.add(ml(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments()})),this.tuning.dash.useSourceBufferUpdateendMaintain&&this.subscription.add(ml(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(ml(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=At(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);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=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);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();gs(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);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();gs(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,Sl.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,zi(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();gs(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)||gs(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);gs(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=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,gl.default)(u,r))d="high";else{let c=(0,Ss.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)&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Ss.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,persistent:!0}),i=a.time.to;gs(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,Sl.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,Sl.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,Ss.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){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!ut(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)&&!(We(this.sourceBuffer.buffered,h)&&We(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*(){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 zi(o,function(){return X(this,null,function*(){let d=hh(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=bl(),!d)return;let c=new DataView(d),h=oo(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]),uo(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 zi(n,function(){return X(this,null,function*(){let u=hh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),ml(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=bl(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),uo(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,Ss.default)(e,0).byte.from,to:(0,Ss.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=bl(),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(!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=bl();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,gl.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=oo(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:oo(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(!(Ke(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer))){!this.isLive&&G.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(We(this.sourceBuffer.buffered,e.segment.time.from,100)&&We(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",lh(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=hh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,oo(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&&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: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||Ke(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push(E({},o.time));let u=lh(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,gl.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=Ox(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||Ke(e)?0:At(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(Ke(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||Ke(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 co,assertNever as zx,fromEvent as Qx,merge as kV,now as po,Subject as Wx,ValueSubject as fh,flattenObject as vs,ErrorCategory as ho,SubscriptionRemovable as RV}from"@vkontakte/videoplayer-shared/es2015";var yl=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new fh(void 0);this.lastConnectionReused$=new fh(void 0);this.lastRequestFirstBytes$=new fh(void 0);this.recoverableError$=new Wx;this.error$=new Wx;this.abortAllController=new le;this.subscription=new RV;this.fetchManifest=co(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=Qu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(vl);return r?(t.log("success",vs({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",vs({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=co(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($){vl($)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch($){vl($)}p=A.signal}let m=po();h.log("startRequest",vs({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=po();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=po(),$={requestStartedAt:m,requestEndedAt:A,duration:A-m};return h.log("endRequest",vs($)),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,vl(A)},w=co(p,function(R){return X(this,arguments,function*({done:A,value:$}){if(k===0&&this.lastRequestFirstBytes$.next(po()-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=po(),M={failed:V,requestStartedAt:m,requestEndedAt:F,duration:F-m};return V?(h.error("endRequest",vs(M)),h.end(),null):(h.log("endRequest",vs(M)),h.end(),C.buffer)})}.bind(this));this.fetchByteRangeRepresentation=co(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=co(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}=zu(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:ho.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ho.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ho.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ho.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:ho.FATAL})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},vl=s=>{if(!uo(s))throw s};import{isNullable as LV,ValueSubject as MV}from"@vkontakte/videoplayer-shared/es2015";var fo=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&&ut(t.segmentReference))}};var VV=["progress","play","seeked","stalled","waiting"],OV=["timeupdate","progress","loadeddata","playing","seeked"];var xl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new vh;this.representationSubscription=new vh;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 Il;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 Il;this.fetcherError$=new Il;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Il;this.gapWatchdogActive=!1;this.destroyController=new le;this.initManifest=bh(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=bh(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=Hx(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Uu(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=Pt())==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",bo(a)),a})}.bind(this));this.initRepresentations=bh(this.destroyController.signal,function(e,t,i){return X(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",bo({initialVideo:e,initialAudio:t,sourceHls:i})),ys(this.manifest),ys(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new vh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(si(p,"error").pipe(Tl(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?gu():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 lo("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],go(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new lo("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}fo.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new fo(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(Is(p=>this.element?At(this.element.buffered,this.element.currentTime*1e3):0),mo(),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(mo()).subscribe(f=>this.liveStreamEndTimestamp=Sh())),this.subscription.add(si(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=gh(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(Ts({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Is(({isActiveLive:f,isLowLatency:m})=>f&&m),mo()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ds(this.element,1)})),this.representationSubscription.add(Ts({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Tl(({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(Ts({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Tl(({isLive:f})=>f),mo((f,m)=>m.bufferLength<f.bufferLength),Is(({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(Ts({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),ds(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(Ts({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(Is(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Ar(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Is(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=Ts({allBuffersFull:l,someBufferEnded:d}).pipe(mo(),Is(({allBuffersFull:p,someBufferEnded:f})=>p&&f),Tl(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,yh.default)((0,yh.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&&go(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=gh(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 yl({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;ys(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Sh()-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(){ys(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&&We(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=Sh(),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",bo(a))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=gh(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;ys(this.element),ys(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),We(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",bo({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;go(this.element)&&go(this.source)&&go(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",bo({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 Th,noop as qV}from"@vkontakte/videoplayer-shared/es2015";var El=class{constructor(){this.subscription=new UV;this.pipSize$=new Th(void 0);this.videoSize$=new Th(void 0);this.elementSize$=new Th(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 El;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 ms(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 dt(e.source.url),this.params=e,this.video=je(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 xl({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=ze(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(Ih(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(xh(c=>c.to.state!=="none"),wl());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(Ih(Zx),eE()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(xh(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(Ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ct(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(pt(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(oh(m));let g=[];for(let S of m.representations){let v=Dx(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(uh(f));let m=[];for(let g of f.representations){let S=Bx(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=Cx(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&&_x(o)||null;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$,QV(this.video,"progress")).pipe(Ih(()=>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(wl()).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(uh(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(wl()).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(oh(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(xh(({to:c})=>c==="ready"),wl());this.subscription.add(Pl(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Eh(["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(Pl(l,this.player.state$.stateChangeEnded$,Eh(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Pl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Eh(["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?Fa:_a,t=this.params.tuning.useNewAutoSelectVideoTrack?Du:Bu,i=this.params.tuning.useNewAutoSelectVideoTrack?ii:$u,{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=At(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(){Qe(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),He(this.video),this.tracer.end()}};var So=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 wh,merge as tE,filter as iE,filterChanged as YV,isNullable as Ph,map as rE,ValueSubject as Ah,isNonNullable as KV}from"@vkontakte/videoplayer-shared/es2015";var vo=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 Ah(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(wh({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(wh({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:tE(i.playbackRateState$,new Ah(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||Ph(l)||(e=o-l)})).add(wh({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:tE(i.playbackRateState$,new Ah(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||Ph(o)||Ph(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=Vx(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($a(),1);import{assertNever as yo,assertNonNullable as sE,debounce as XV,ErrorCategory as Al,filter as JV,isNonNullable as ZV,isNullable as eO,map as kl,merge as tO,Observable as iO,observableFrom as rO,Subscription as sO,videoSizeToQuality as aO}from"@vkontakte/videoplayer-shared/es2015";var Wt={};var xs=(s,e)=>new iO(t=>{let i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)}),To=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:yo(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:yo(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:yo(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:yo(e)}break;default:yo(t)}};this.textTracksManager=new dt(e.source.url),this.video=je(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),He(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Al.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:Al.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=ze(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(Ge(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ct(this.video,e.playbackRate,r.playbackRateState$,i)),a(pt(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(kl(l=>l.to)),this.params.output.playbackState$),this.subscription.add(xs(this.hls,Wt.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Al.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(xs(this.hls,Wt.Events.MANIFEST_PARSED).pipe(kl(({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(xs(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(xs(this.hls,Wt.Events.LEVEL_LOADING).pipe(kl(({url:l})=>Re(l))),t.hostname$),a(xs(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=xs(this.hls,Wt.Events.LEVEL_SWITCHED).pipe(kl(({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 Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Al.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",kh=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 Ml,filter as vO,filterChanged as yO,isNonNullable as lE,isNullable as $l,map as cE,merge as TO,observableFrom as IO,Subscription as xO,ValueSubject as Mh,VideoQuality as EO}from"@vkontakte/videoplayer-shared/es2015";var Lh=j(sd(),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,Lh.default)(l[1].split(",").map(v=>v.split("="))),h=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,p=uO(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,Lh.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}},cO=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),Rh=0,oE=(r,...a)=>x(void 0,[r,...a],function*(s,e=s,t,i){let o=yield(yield Mt(s,i)).text();Rh+=1;try{let{qualityManifests:u,textTracks:l}=lO(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(Rh<=t.manifestRetryMaxCount)return yield cO(oO(Rh-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),oE(s,e,t)}return{qualityManifests:[],textTracks:[]}}),Rl=oE;import{isNonNullable as dO,Subscription as pO,throttle as hO,ValueSubject as uE,Subject as fO,ErrorCategory as mO}from"@vkontakte/videoplayer-shared/es2015";var Ll=class{constructor(e,t,i,r,a){this.subscription=new pO;this.abortControllers={destroy:new le,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new uE(null);this.getCurrentTime$=new uE(null);this.error$=new fO;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(hO(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 x(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 x(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 x(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(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 Io=class{constructor(e){this.subscription=new xO;this.videoState=new Q("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Mh([]);this.liveOffset=new mr;this.manifestStartTime$=new Mh(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=je(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)=>Rl(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 Ll(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new dt(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:Ml.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:Ml.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 Mh((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:Ml.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ze(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(Ge(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ct(this.video,t.playbackRate,r.playbackRateState$,i)),a(pt(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),He(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if($l(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(),kh(n).then(d=>{var c;if(!$l(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();($l(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();kh(g).then(S=>{$l(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){Qe(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:Ml.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 $h,fromEvent as Bh,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 xo=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 dt(e.source.url),this.params=e,this.video=je(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),Rl(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:$h.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:$h.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ze(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(Ge(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ct(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(Bh(o,"addtrack"),Bh(o,"removetrack"),Bh(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),He(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(){Qe(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:$h.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var bE=j(nr(),1),Dh=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 Eo=class{constructor(e){this.subscription=new FO;this.videoState=new Q("stopped");this.trackUrls={};this.textTracksManager=new dt;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=je(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,Dh.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=ze(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(Ge(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ct(this.video,t.playbackRate,r.playbackRateState$,i)),a(pt(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),He(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(){Qe(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,Dh.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 Vh,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,Ch=()=>null,Bl=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=Ch;this.externalStopCallback=Ch;this.externalErrorCallback=Ch;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 wo=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=je(e.container,e.tuning),this.liveStreamClient=new Bl(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),He(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Vh.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=ze(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(pt(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(Ge(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:Vh.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Qe(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:Vh.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Po=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 ko,assertNonNullable as Qi,ErrorCategory as Dl,filter as AE,isNonNullable as kE,isNullable as t_,map as i_,merge as r_,once as s_,Subject as _e,Subscription as RE,ValueSubject as J,flattenObject as Oh}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 Ao=class Ao{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:Ao.errorId,category:JO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ao.errorId} exception`,thrown:e})}};Ao.errorId="VolumeMultiplierManager";var Es=Ao;var a_={chunkDuration:5e3,maxParallelRequests:5},Ro=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 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=sx([...nx(this.params.tuning),...ax(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,_h.default)(r,l)),...t.filter(l=>(0,_h.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",Oh(a)),this.screenFormatsIterator=new Po(a);let n=[...Fp(!0),...Fp(!1)];this.chromecastFormatsIterator=new Po(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&&Es.isSupported()&&(this.volumeMultiplierManager=new Es(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:Dl.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 ko(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 So(B(E({},o),{source:u,sourceHls:l})):new Dn(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 vo(B(E({},o),{source:u})):new Cn(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 xo(B(E({},o),{source:u})):new To(B(E({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Qi(u),new Io(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 Eo(B(E({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Qi(u),new sT(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 wo({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 ko(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 Ba({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 ko(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ko(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 ko(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:Dl.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===Dl.NETWORK,u=r.category===Dl.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",Oh(n)):this.tracer.error("providerError",Oh(n))})),e}};import{fromEvent as Cl,once as n_,combine as o_,Subscription as $E,ValueSubject as Fh,map as u_,filter as l_,isNonNullable as Vl,now as kt,safeStorage as Nh}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(Vl(s)&&s!==10)return s*1e3},VE=()=>{let s=Mi==null?void 0:Mi.rtt;if(Vl(s)&&s!==3e3)return s},OE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Uh=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 Fh(t),this.rtt$=new Fh(i),this.rttAdjustedThroughput$=new Fh(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();Vl(l)&&this.rtt.next(l)};Mi&&"onchange"in Mi&&this.subscription.add(Cl(Mi,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Nh.set(BE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Nh.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(Cl(e,"progress").pipe(n_()).subscribe(a=>{t=a.loaded,i=kt()}));break;case 1:case 0:r.add(Cl(e,"loadstart").subscribe(()=>{t=0,i=kt()}));break}r.add(Cl(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=Nh.get(e);if(Vl(t))return(i=parseInt(t,10))!=null?i:void 0}},_E=Uh;import{fillWithDefault as d_,VideoQuality as Ol}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:Ol.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ol.Q_720P,trafficSavingLimit:Ol.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:Ol.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,useSourceBufferUpdateendMaintain:!1,useSourceBufferBufferedDiff:!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 _l,combine as $i,ErrorCategory as Fl,filter as Y,filterChanged as ae,fromEvent as jh,isNonNullable as HE,isNullable as S_,Logger as v_,map as re,mapTo as GE,merge as Wi,now as Nl,once as Z,Subject as oe,Subscription as zE,tap as Hh,ValueSubject as _,isHigher as y_,isInvariantQuality as QE,flattenObject as Yi,throttle as Gh,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 qh=({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 Ul=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:Ly,getCurrentTime$:new _(null)};if(this.initLogs(),this.tuning=NE(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 _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:Fl.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=Wh(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 Ro({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"),jh(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(()=>{_l(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;_l(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(ip(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Y(({from:e})=>e==="stopped"),Z()).subscribe(()=>{this.initedAt=Nl(),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:Fl.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(Hh(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:qh({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(),Hh(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(),Hh(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(qh({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:Fl.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:Nl()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Z(),re(()=>Nl()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Z(),re(()=>Nl()-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;_l(this.providerContainer),_l(e),Ry(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>ky(i)),this.providerContainer.current$.subscribe(({type:i})=>Oa("provider",i)),e.duration$.subscribe(i=>Oa("duration",i)),e.availableVideoTracks$.pipe(Y(i=>!!i.length),Z()).subscribe(i=>Oa("tracks",i)),this.events.fatalError$.subscribe(new at("fatalError")),this.events.managedError$.subscribe(new at("managedError")),e.position$.subscribe(new at("position")),e.currentVideoTrack$.pipe(re(i=>i==null?void 0:i.quality)).subscribe(new at("quality")),this.info.currentBuffer$.subscribe(new at("buffer")),e.isBuffering$.subscribe(new at("isBuffering"))].forEach(i=>this.subscription.add(i)),Oa("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(Gh(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),Gh(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),Gh(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:Fl.DOM,message:String(r)})})});this.subscription.add(Wi(jh(document,"visibilitychange"),jh(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&&!Ha()}};import{Subscription as Zte,Observable as eie,Subject as tie,ValueSubject as iie,VideoQuality as rie}from"@vkontakte/videoplayer-shared/es2015";var sie=`@vkontakte/videoplayer-core@${Yh}`;export{Mo as ChromecastState,Xl as HttpConnectionType,eie as Observable,lt as PlaybackState,Ul as Player,$o as PredefinedQualityLimits,sie as SDK_VERSION,tie as Subject,Zte as Subscription,Jl as Surface,Yh as VERSION,iie as ValueSubject,vi as VideoFormat,rie as VideoQuality,G as clientChecker,Va as isMobile};
|