@vkontakte/videoplayer-core 2.0.131-dev.ffcf4d9f.0 → 2.0.132-beta.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 +27 -27
- package/es2015.esm.js +26 -26
- package/es2018.cjs.js +24 -24
- package/es2018.esm.js +35 -35
- package/es2024.cjs.js +31 -31
- package/es2024.esm.js +29 -29
- package/esnext.cjs.js +31 -31
- package/esnext.esm.js +29 -29
- package/evergreen.esm.js +36 -36
- package/package.json +2 -2
- package/types/providers/DashProviderNew/baseDashProvider.d.ts +2 -2
- package/types/providers/DashProviderNew/lib/buffer.d.ts +0 -2
- package/types/providers/DashProviderNew/lib/utils.d.ts +0 -5
- package/types/providers/utils/HTMLVideoElement/observable.d.ts +0 -1
- package/types/providers/utils/StallsManager.d.ts +1 -1
- package/types/utils/tuningConfig.d.ts +0 -2
- package/types/providers/DashProviderNew/lib/sourceBufferBufferedDiff.d.ts +0 -19
- package/types/providers/utils/StallsManager.vktv.d.ts +0 -5
package/es2015.esm.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.132-beta.0
|
|
3
|
+
* Mon, 19 May 2025 12:13:52 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-132/doc/
|
|
5
5
|
*/
|
|
6
|
-
var YE=Object.create;var Yl=Object.defineProperty,KE=Object.defineProperties,XE=Object.getOwnPropertyDescriptor,JE=Object.getOwnPropertyDescriptors,ZE=Object.getOwnPropertyNames,Mo=Object.getOwnPropertySymbols,ew=Object.getPrototypeOf,Kl=Object.prototype.hasOwnProperty,Hh=Object.prototype.propertyIsEnumerable;var tw=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var st=Math.pow,jh=(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)&&jh(s,t,e[t]);if(Mo)for(var t of Mo(e))Hh.call(e,t)&&jh(s,t,e[t]);return s},D=(s,e)=>KE(s,JE(e));var Gh=(s,e)=>{var t={};for(var i in s)Kl.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&&Hh.call(s,i)&&(t[i]=s[i]);return t};var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var iw=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ZE(e))!Kl.call(s,r)&&r!==t&&Yl(s,r,{get:()=>e[r],enumerable:!(i=XE(e,r))||i.enumerable});return s};var j=(s,e,t)=>(t=s!=null?YE(ew(s)):{},iw(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[tw("asyncIterator")]=()=>a,r("next"),r("throw"),r("return"),a};var xe=b((Zl,Qh)=>{"use strict";var la=function(s){return s&&s.Math===Math&&s};Qh.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 qe=b((P_,Wh)=>{"use strict";Wh.exports=function(s){try{return!!s()}catch(e){return!0}}});var ca=b((A_,Yh)=>{"use strict";var rw=qe();Yh.exports=!rw(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var ec=b((k_,Zh)=>{"use strict";var sw=ca(),Jh=Function.prototype,Kh=Jh.apply,Xh=Jh.call;Zh.exports=typeof Reflect=="object"&&Reflect.apply||(sw?Xh.bind(Kh):function(){return Xh.apply(Kh,arguments)})});var Ve=b((R_,rf)=>{"use strict";var ef=ca(),tf=Function.prototype,tc=tf.call,aw=ef&&tf.bind.bind(tc,tc);rf.exports=ef?aw:function(s){return function(){return tc.apply(s,arguments)}}});var ir=b((L_,af)=>{"use strict";var sf=Ve(),nw=sf({}.toString),ow=sf("".slice);af.exports=function(s){return ow(nw(s),8,-1)}});var ic=b((M_,nf)=>{"use strict";var uw=ir(),lw=Ve();nf.exports=function(s){if(uw(s)==="Function")return lw(s)}});var Te=b(($_,of)=>{"use strict";var rc=typeof document=="object"&&document.all;of.exports=typeof rc=="undefined"&&rc!==void 0?function(s){return typeof s=="function"||s===rc}:function(s){return typeof s=="function"}});var It=b((B_,uf)=>{"use strict";var cw=qe();uf.exports=!cw(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var xt=b((D_,lf)=>{"use strict";var dw=ca(),Do=Function.prototype.call;lf.exports=dw?Do.bind(Do):function(){return Do.apply(Do,arguments)}});var sc=b(pf=>{"use strict";var cf={}.propertyIsEnumerable,df=Object.getOwnPropertyDescriptor,pw=df&&!cf.call({1:2},1);pf.f=pw?function(e){var t=df(this,e);return!!t&&t.enumerable}:cf});var da=b((V_,hf)=>{"use strict";hf.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var mf=b((O_,ff)=>{"use strict";var hw=Ve(),fw=qe(),mw=ir(),ac=Object,bw=hw("".split);ff.exports=fw(function(){return!ac("z").propertyIsEnumerable(0)})?function(s){return mw(s)==="String"?bw(s,""):ac(s)}:ac});var Rr=b((__,bf)=>{"use strict";bf.exports=function(s){return s==null}});var Bi=b((F_,gf)=>{"use strict";var gw=Rr(),Sw=TypeError;gf.exports=function(s){if(gw(s))throw new Sw("Can't call method on "+s);return s}});var rr=b((N_,Sf)=>{"use strict";var vw=mf(),yw=Bi();Sf.exports=function(s){return vw(yw(s))}});var Et=b((U_,vf)=>{"use strict";var Tw=Te();vf.exports=function(s){return typeof s=="object"?s!==null:Tw(s)}});var Lr=b((q_,yf)=>{"use strict";yf.exports={}});var vi=b((j_,If)=>{"use strict";var nc=Lr(),oc=xe(),Iw=Te(),Tf=function(s){return Iw(s)?s:void 0};If.exports=function(s,e){return arguments.length<2?Tf(nc[s])||Tf(oc[s]):nc[s]&&nc[s][e]||oc[s]&&oc[s][e]}});var pa=b((H_,xf)=>{"use strict";var xw=Ve();xf.exports=xw({}.isPrototypeOf)});var sr=b((G_,Pf)=>{"use strict";var Ew=xe(),Ef=Ew.navigator,wf=Ef&&Ef.userAgent;Pf.exports=wf?String(wf):""});var lc=b((z_,$f)=>{"use strict";var Mf=xe(),uc=sr(),Af=Mf.process,kf=Mf.Deno,Rf=Af&&Af.versions||kf&&kf.version,Lf=Rf&&Rf.v8,Ft,Co;Lf&&(Ft=Lf.split("."),Co=Ft[0]>0&&Ft[0]<4?1:+(Ft[0]+Ft[1]));!Co&&uc&&(Ft=uc.match(/Edge\/(\d+)/),(!Ft||Ft[1]>=74)&&(Ft=uc.match(/Chrome\/(\d+)/),Ft&&(Co=+Ft[1])));$f.exports=Co});var cc=b((Q_,Df)=>{"use strict";var Bf=lc(),ww=qe(),Pw=xe(),Aw=Pw.String;Df.exports=!!Object.getOwnPropertySymbols&&!ww(function(){var s=Symbol("symbol detection");return!Aw(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Bf&&Bf<41})});var dc=b((W_,Cf)=>{"use strict";var kw=cc();Cf.exports=kw&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var pc=b((Y_,Vf)=>{"use strict";var Rw=vi(),Lw=Te(),Mw=pa(),$w=dc(),Bw=Object;Vf.exports=$w?function(s){return typeof s=="symbol"}:function(s){var e=Rw("Symbol");return Lw(e)&&Mw(e.prototype,Bw(s))}});var ha=b((K_,Of)=>{"use strict";var Dw=String;Of.exports=function(s){try{return Dw(s)}catch(e){return"Object"}}});var Wt=b((X_,_f)=>{"use strict";var Cw=Te(),Vw=ha(),Ow=TypeError;_f.exports=function(s){if(Cw(s))return s;throw new Ow(Vw(s)+" is not a function")}});var fa=b((J_,Ff)=>{"use strict";var _w=Wt(),Fw=Rr();Ff.exports=function(s,e){var t=s[e];return Fw(t)?void 0:_w(t)}});var Uf=b((Z_,Nf)=>{"use strict";var hc=xt(),fc=Te(),mc=Et(),Nw=TypeError;Nf.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 Nw("Can't convert object to primitive value")}});var Nt=b((eF,qf)=>{"use strict";qf.exports=!0});var Gf=b((tF,Hf)=>{"use strict";var jf=xe(),Uw=Object.defineProperty;Hf.exports=function(s,e){try{Uw(jf,s,{value:e,configurable:!0,writable:!0})}catch(t){jf[s]=e}return e}});var ma=b((iF,Wf)=>{"use strict";var qw=Nt(),jw=xe(),Hw=Gf(),zf="__core-js_shared__",Qf=Wf.exports=jw[zf]||Hw(zf,{});(Qf.versions||(Qf.versions=[])).push({version:"3.38.0",mode:qw?"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,Kf)=>{"use strict";var Yf=ma();Kf.exports=function(s,e){return Yf[s]||(Yf[s]=e||{})}});var Mr=b((sF,Xf)=>{"use strict";var Gw=Bi(),zw=Object;Xf.exports=function(s){return zw(Gw(s))}});var Ut=b((aF,Jf)=>{"use strict";var Qw=Ve(),Ww=Mr(),Yw=Qw({}.hasOwnProperty);Jf.exports=Object.hasOwn||function(e,t){return Yw(Ww(e),t)}});var gc=b((nF,Zf)=>{"use strict";var Kw=Ve(),Xw=0,Jw=Math.random(),Zw=Kw(1 .toString);Zf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Zw(++Xw+Jw,36)}});var je=b((oF,tm)=>{"use strict";var eP=xe(),tP=bc(),em=Ut(),iP=gc(),rP=cc(),sP=dc(),$r=eP.Symbol,Sc=tP("wks"),aP=sP?$r.for||$r:$r&&$r.withoutSetter||iP;tm.exports=function(s){return em(Sc,s)||(Sc[s]=rP&&em($r,s)?$r[s]:aP("Symbol."+s)),Sc[s]}});var am=b((uF,sm)=>{"use strict";var nP=xt(),im=Et(),rm=pc(),oP=fa(),uP=Uf(),lP=je(),cP=TypeError,dP=lP("toPrimitive");sm.exports=function(s,e){if(!im(s)||rm(s))return s;var t=oP(s,dP),i;if(t){if(e===void 0&&(e="default"),i=nP(t,s,e),!im(i)||rm(i))return i;throw new cP("Can't convert object to primitive value")}return e===void 0&&(e="number"),uP(s,e)}});var vc=b((lF,nm)=>{"use strict";var pP=am(),hP=pc();nm.exports=function(s){var e=pP(s,"string");return hP(e)?e:e+""}});var Vo=b((cF,um)=>{"use strict";var fP=xe(),om=Et(),yc=fP.document,mP=om(yc)&&om(yc.createElement);um.exports=function(s){return mP?yc.createElement(s):{}}});var Tc=b((dF,lm)=>{"use strict";var bP=It(),gP=qe(),SP=Vo();lm.exports=!bP&&!gP(function(){return Object.defineProperty(SP("div"),"a",{get:function(){return 7}}).a!==7})});var pm=b(dm=>{"use strict";var vP=It(),yP=xt(),TP=sc(),IP=da(),xP=rr(),EP=vc(),wP=Ut(),PP=Tc(),cm=Object.getOwnPropertyDescriptor;dm.f=vP?cm:function(e,t){if(e=xP(e),t=EP(t),PP)try{return cm(e,t)}catch(i){}if(wP(e,t))return IP(!yP(TP.f,e,t),e[t])}});var Ic=b((hF,hm)=>{"use strict";var AP=qe(),kP=Te(),RP=/#|\.prototype\./,ba=function(s,e){var t=MP[LP(s)];return t===BP?!0:t===$P?!1:kP(e)?AP(e):!!e},LP=ba.normalize=function(s){return String(s).replace(RP,".").toLowerCase()},MP=ba.data={},$P=ba.NATIVE="N",BP=ba.POLYFILL="P";hm.exports=ba});var Br=b((fF,mm)=>{"use strict";var fm=ic(),DP=Wt(),CP=ca(),VP=fm(fm.bind);mm.exports=function(s,e){return DP(s),e===void 0?s:CP?VP(s,e):function(){return s.apply(e,arguments)}}});var xc=b((mF,bm)=>{"use strict";var OP=It(),_P=qe();bm.exports=OP&&_P(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Yt=b((bF,gm)=>{"use strict";var FP=Et(),NP=String,UP=TypeError;gm.exports=function(s){if(FP(s))return s;throw new UP(NP(s)+" is not an object")}});var ar=b(vm=>{"use strict";var qP=It(),jP=Tc(),HP=xc(),Oo=Yt(),Sm=vc(),GP=TypeError,Ec=Object.defineProperty,zP=Object.getOwnPropertyDescriptor,wc="enumerable",Pc="configurable",Ac="writable";vm.f=qP?HP?function(e,t,i){if(Oo(e),t=Sm(t),Oo(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Ac in i&&!i[Ac]){var r=zP(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(Oo(e),t=Sm(t),Oo(i),jP)try{return Ec(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new GP("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Dr=b((SF,ym)=>{"use strict";var QP=It(),WP=ar(),YP=da();ym.exports=QP?function(s,e,t){return WP.f(s,e,YP(1,t))}:function(s,e,t){return s[e]=t,s}});var ke=b((vF,Im)=>{"use strict";var ga=xe(),KP=ec(),XP=ic(),JP=Te(),ZP=pm().f,eA=Ic(),Cr=Lr(),tA=Br(),Vr=Dr(),Tm=Ut();ma();var iA=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 KP(s,this,arguments)};return e.prototype=s.prototype,e};Im.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=eA(i?h:t+(r?".":"#")+h,s.forced),d=!l&&n&&Tm(n,h),f=o[h],d&&(s.dontCallGetSet?(S=ZP(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=tA(p,ga):s.wrap&&d?g=iA(p):a&&JP(p)?g=XP(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&Vr(g,"sham",!0),Vr(o,h,g),a&&(c=t+"Prototype",Tm(Cr,c)||Vr(Cr,c,{}),Vr(Cr[c],h,p),s.real&&u&&(l||!u[h])&&Vr(u,h,p)))}});var Em=b((yF,xm)=>{"use strict";var rA=Math.ceil,sA=Math.floor;xm.exports=Math.trunc||function(e){var t=+e;return(t>0?sA:rA)(t)}});var Sa=b((TF,wm)=>{"use strict";var aA=Em();wm.exports=function(s){var e=+s;return e!==e||e===0?0:aA(e)}});var Am=b((IF,Pm)=>{"use strict";var nA=Sa(),oA=Math.max,uA=Math.min;Pm.exports=function(s,e){var t=nA(s);return t<0?oA(t+e,0):uA(t,e)}});var kc=b((xF,km)=>{"use strict";var lA=Sa(),cA=Math.min;km.exports=function(s){var e=lA(s);return e>0?cA(e,9007199254740991):0}});var Or=b((EF,Rm)=>{"use strict";var dA=kc();Rm.exports=function(s){return dA(s.length)}});var Rc=b((wF,Mm)=>{"use strict";var pA=rr(),hA=Am(),fA=Or(),Lm=function(s){return function(e,t,i){var r=pA(e),a=fA(r);if(a===0)return!s&&-1;var n=hA(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}};Mm.exports={includes:Lm(!0),indexOf:Lm(!1)}});var va=b((PF,$m)=>{"use strict";$m.exports=function(){}});var Bm=b(()=>{"use strict";var mA=ke(),bA=Rc().includes,gA=qe(),SA=va(),vA=gA(function(){return!Array(1).includes()});mA({target:"Array",proto:!0,forced:vA},{includes:function(e){return bA(this,e,arguments.length>1?arguments[1]:void 0)}});SA("includes")});var Di=b((RF,Dm)=>{"use strict";var yA=vi();Dm.exports=yA});var Vm=b((LF,Cm)=>{"use strict";Bm();var TA=Di();Cm.exports=TA("Array","includes")});var _m=b((MF,Om)=>{"use strict";var IA=Vm();Om.exports=IA});var wt=b(($F,Fm)=>{"use strict";var xA=_m();Fm.exports=xA});var No=b((HF,Qm)=>{"use strict";var MA=bc(),$A=gc(),zm=MA("keys");Qm.exports=function(s){return zm[s]||(zm[s]=$A(s))}});var Ym=b((GF,Wm)=>{"use strict";var BA=qe();Wm.exports=!BA(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Uo=b((zF,Xm)=>{"use strict";var DA=Ut(),CA=Te(),VA=Mr(),OA=No(),_A=Ym(),Km=OA("IE_PROTO"),$c=Object,FA=$c.prototype;Xm.exports=_A?$c.getPrototypeOf:function(s){var e=VA(s);if(DA(e,Km))return e[Km];var t=e.constructor;return CA(t)&&e instanceof t?t.prototype:e instanceof $c?FA:null}});var qo=b((QF,Jm)=>{"use strict";Jm.exports={}});var tb=b((WF,eb)=>{"use strict";var NA=Ve(),Bc=Ut(),UA=rr(),qA=Rc().indexOf,jA=qo(),Zm=NA([].push);eb.exports=function(s,e){var t=UA(s),i=0,r=[],a;for(a in t)!Bc(jA,a)&&Bc(t,a)&&Zm(r,a);for(;e.length>i;)Bc(t,a=e[i++])&&(~qA(r,a)||Zm(r,a));return r}});var Dc=b((YF,ib)=>{"use strict";ib.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Cc=b((KF,rb)=>{"use strict";var HA=tb(),GA=Dc();rb.exports=Object.keys||function(e){return HA(e,GA)}});var Vc=b((XF,ub)=>{"use strict";var ab=It(),zA=qe(),nb=Ve(),QA=Uo(),WA=Cc(),YA=rr(),KA=sc().f,ob=nb(KA),XA=nb([].push),JA=ab&&zA(function(){var s=Object.create(null);return s[2]=2,!ob(s,2)}),sb=function(s){return function(e){for(var t=YA(e),i=WA(t),r=JA&&QA(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!ab||(r?u in t:ob(t,u)))&&XA(o,s?[u,t[u]]:t[u]);return o}};ub.exports={entries:sb(!0),values:sb(!1)}});var lb=b(()=>{"use strict";var ZA=ke(),ek=Vc().entries;ZA({target:"Object",stat:!0},{entries:function(e){return ek(e)}})});var db=b((eN,cb)=>{"use strict";lb();var tk=Lr();cb.exports=tk.Object.entries});var hb=b((tN,pb)=>{"use strict";var ik=db();pb.exports=ik});var nr=b((iN,fb)=>{"use strict";var rk=hb();fb.exports=rk});var or=b((rN,mb)=>{"use strict";mb.exports={}});var Sb=b((sN,gb)=>{"use strict";var sk=xe(),ak=Te(),bb=sk.WeakMap;gb.exports=ak(bb)&&/native code/.test(String(bb))});var Nc=b((aN,Tb)=>{"use strict";var nk=Sb(),yb=xe(),ok=Et(),uk=Dr(),Oc=Ut(),_c=ma(),lk=No(),ck=qo(),vb="Object already initialized",Fc=yb.TypeError,dk=yb.WeakMap,jo,ya,Ho,pk=function(s){return Ho(s)?ya(s):jo(s,{})},hk=function(s){return function(e){var t;if(!ok(e)||(t=ya(e)).type!==s)throw new Fc("Incompatible receiver, "+s+" required");return t}};nk||_c.state?(qt=_c.state||(_c.state=new dk),qt.get=qt.get,qt.has=qt.has,qt.set=qt.set,jo=function(s,e){if(qt.has(s))throw new Fc(vb);return e.facade=s,qt.set(s,e),e},ya=function(s){return qt.get(s)||{}},Ho=function(s){return qt.has(s)}):(ur=lk("state"),ck[ur]=!0,jo=function(s,e){if(Oc(s,ur))throw new Fc(vb);return e.facade=s,uk(s,ur,e),e},ya=function(s){return Oc(s,ur)?s[ur]:{}},Ho=function(s){return Oc(s,ur)});var qt,ur;Tb.exports={set:jo,get:ya,has:Ho,enforce:pk,getterFor:hk}});var jc=b((nN,xb)=>{"use strict";var Uc=It(),fk=Ut(),Ib=Function.prototype,mk=Uc&&Object.getOwnPropertyDescriptor,qc=fk(Ib,"name"),bk=qc&&function(){}.name==="something",gk=qc&&(!Uc||Uc&&mk(Ib,"name").configurable);xb.exports={EXISTS:qc,PROPER:bk,CONFIGURABLE:gk}});var wb=b(Eb=>{"use strict";var Sk=It(),vk=xc(),yk=ar(),Tk=Yt(),Ik=rr(),xk=Cc();Eb.f=Sk&&!vk?Object.defineProperties:function(e,t){Tk(e);for(var i=Ik(t),r=xk(t),a=r.length,n=0,o;a>n;)yk.f(e,o=r[n++],i[o]);return e}});var Hc=b((uN,Pb)=>{"use strict";var Ek=vi();Pb.exports=Ek("document","documentElement")});var Wc=b((lN,Bb)=>{"use strict";var wk=Yt(),Pk=wb(),Ab=Dc(),Ak=qo(),kk=Hc(),Rk=Vo(),Lk=No(),kb=">",Rb="<",zc="prototype",Qc="script",Mb=Lk("IE_PROTO"),Gc=function(){},$b=function(s){return Rb+Qc+kb+s+Rb+"/"+Qc+kb},Lb=function(s){s.write($b("")),s.close();var e=s.parentWindow.Object;return s=null,e},Mk=function(){var s=Rk("iframe"),e="java"+Qc+":",t;return s.style.display="none",kk.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write($b("document.F=Object")),t.close(),t.F},Go,zo=function(){try{Go=new ActiveXObject("htmlfile")}catch(e){}zo=typeof document!="undefined"?document.domain&&Go?Lb(Go):Mk():Lb(Go);for(var s=Ab.length;s--;)delete zo[zc][Ab[s]];return zo()};Ak[Mb]=!0;Bb.exports=Object.create||function(e,t){var i;return e!==null?(Gc[zc]=wk(e),i=new Gc,Gc[zc]=null,i[Mb]=e):i=zo(),t===void 0?i:Pk.f(i,t)}});var _r=b((cN,Db)=>{"use strict";var $k=Dr();Db.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:$k(s,e,t),s}});var Jc=b((dN,Ob)=>{"use strict";var Bk=qe(),Dk=Te(),Ck=Et(),Vk=Wc(),Cb=Uo(),Ok=_r(),_k=je(),Fk=Nt(),Xc=_k("iterator"),Vb=!1,yi,Yc,Kc;[].keys&&(Kc=[].keys(),"next"in Kc?(Yc=Cb(Cb(Kc)),Yc!==Object.prototype&&(yi=Yc)):Vb=!0);var Nk=!Ck(yi)||Bk(function(){var s={};return yi[Xc].call(s)!==s});Nk?yi={}:Fk&&(yi=Vk(yi));Dk(yi[Xc])||Ok(yi,Xc,function(){return this});Ob.exports={IteratorPrototype:yi,BUGGY_SAFARI_ITERATORS:Vb}});var Qo=b((pN,Fb)=>{"use strict";var Uk=je(),qk=Uk("toStringTag"),_b={};_b[qk]="z";Fb.exports=String(_b)==="[object z]"});var Ta=b((hN,Nb)=>{"use strict";var jk=Qo(),Hk=Te(),Wo=ir(),Gk=je(),zk=Gk("toStringTag"),Qk=Object,Wk=Wo(function(){return arguments}())==="Arguments",Yk=function(s,e){try{return s[e]}catch(t){}};Nb.exports=jk?Wo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Yk(e=Qk(s),zk))=="string"?t:Wk?Wo(e):(i=Wo(e))==="Object"&&Hk(e.callee)?"Arguments":i}});var qb=b((fN,Ub)=>{"use strict";var Kk=Qo(),Xk=Ta();Ub.exports=Kk?{}.toString:function(){return"[object "+Xk(this)+"]"}});var Ia=b((mN,Hb)=>{"use strict";var Jk=Qo(),Zk=ar().f,eR=Dr(),tR=Ut(),iR=qb(),rR=je(),jb=rR("toStringTag");Hb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(tR(r,jb)||Zk(r,jb,{configurable:!0,value:e}),i&&!Jk&&eR(r,"toString",iR))}});var zb=b((bN,Gb)=>{"use strict";var sR=Jc().IteratorPrototype,aR=Wc(),nR=da(),oR=Ia(),uR=or(),lR=function(){return this};Gb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=aR(sR,{next:nR(+!i,t)}),oR(s,r,!1,!0),uR[r]=lR,s}});var Wb=b((gN,Qb)=>{"use strict";var cR=Ve(),dR=Wt();Qb.exports=function(s,e,t){try{return cR(dR(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Kb=b((SN,Yb)=>{"use strict";var pR=Et();Yb.exports=function(s){return pR(s)||s===null}});var Jb=b((vN,Xb)=>{"use strict";var hR=Kb(),fR=String,mR=TypeError;Xb.exports=function(s){if(hR(s))return s;throw new mR("Can't set "+fR(s)+" as a prototype")}});var Zc=b((yN,Zb)=>{"use strict";var bR=Wb(),gR=Et(),SR=Bi(),vR=Jb();Zb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=bR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return SR(r),vR(a),gR(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var cg=b((TN,lg)=>{"use strict";var yR=ke(),TR=xt(),Yo=Nt(),og=jc(),IR=Te(),xR=zb(),eg=Uo(),tg=Zc(),ER=Ia(),wR=Dr(),ed=_r(),PR=je(),ig=or(),ug=Jc(),AR=og.PROPER,kR=og.CONFIGURABLE,rg=ug.IteratorPrototype,Ko=ug.BUGGY_SAFARI_ITERATORS,xa=PR("iterator"),sg="keys",Ea="values",ag="entries",ng=function(){return this};lg.exports=function(s,e,t,i,r,a,n){xR(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 sg:return function(){return new t(this,S)};case Ea:return function(){return new t(this,S)};case ag: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=!Ko&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=eg(p.call(new s)),f!==Object.prototype&&f.next&&(!Yo&&eg(f)!==rg&&(tg?tg(f,rg):IR(f[xa])||ed(f,xa,ng)),ER(f,u,!0,!0),Yo&&(ig[u]=ng))),AR&&r===Ea&&c&&c.name!==Ea&&(!Yo&&kR?wR(d,"name",Ea):(l=!0,h=function(){return TR(c,this)})),r)if(m={values:o(Ea),keys:a?h:o(sg),entries:o(ag)},n)for(g in m)(Ko||l||!(g in d))&&ed(d,g,m[g]);else yR({target:e,proto:!0,forced:Ko||l},m);return(!Yo||n)&&d[xa]!==h&&ed(d,xa,h,{name:r}),ig[e]=h,m}});var pg=b((IN,dg)=>{"use strict";dg.exports=function(s,e){return{value:s,done:e}}});var id=b((xN,gg)=>{"use strict";var RR=rr(),td=va(),hg=or(),mg=Nc(),LR=ar().f,MR=cg(),Xo=pg(),$R=Nt(),BR=It(),bg="Array Iterator",DR=mg.set,CR=mg.getterFor(bg);gg.exports=MR(Array,"Array",function(s,e){DR(this,{type:bg,target:RR(s),index:0,kind:e})},function(){var s=CR(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 fg=hg.Arguments=hg.Array;td("keys");td("values");td("entries");if(!$R&&BR&&fg.name!=="values")try{LR(fg,"name",{value:"values"})}catch(s){}});var vg=b((EN,Sg)=>{"use strict";var VR=je(),OR=or(),_R=VR("iterator"),FR=Array.prototype;Sg.exports=function(s){return s!==void 0&&(OR.Array===s||FR[_R]===s)}});var rd=b((wN,Tg)=>{"use strict";var NR=Ta(),yg=fa(),UR=Rr(),qR=or(),jR=je(),HR=jR("iterator");Tg.exports=function(s){if(!UR(s))return yg(s,HR)||yg(s,"@@iterator")||qR[NR(s)]}});var xg=b((PN,Ig)=>{"use strict";var GR=xt(),zR=Wt(),QR=Yt(),WR=ha(),YR=rd(),KR=TypeError;Ig.exports=function(s,e){var t=arguments.length<2?YR(s):e;if(zR(t))return QR(GR(t,s));throw new KR(WR(s)+" is not iterable")}});var Pg=b((AN,wg)=>{"use strict";var XR=xt(),Eg=Yt(),JR=fa();wg.exports=function(s,e,t){var i,r;Eg(s);try{if(i=JR(s,"return"),!i){if(e==="throw")throw t;return t}i=XR(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Eg(i),t}});var Zo=b((kN,Lg)=>{"use strict";var ZR=Br(),eL=xt(),tL=Yt(),iL=ha(),rL=vg(),sL=Or(),Ag=pa(),aL=xg(),nL=rd(),kg=Pg(),oL=TypeError,Jo=function(s,e){this.stopped=s,this.result=e},Rg=Jo.prototype;Lg.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=ZR(e,i),l,d,c,h,p,f,m,g=function(v){return l&&kg(l,"normal",v),new Jo(!0,v)},S=function(v){return r?(tL(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=nL(s),!d)throw new oL(iL(s)+" is not iterable");if(rL(d)){for(c=0,h=sL(s);h>c;c++)if(p=S(s[c]),p&&Ag(Rg,p))return p;return new Jo(!1)}l=aL(s,d)}for(f=a?s.next:l.next;!(m=eL(f,l)).done;){try{p=S(m.value)}catch(v){kg(l,"throw",v)}if(typeof p=="object"&&p&&Ag(Rg,p))return p}return new Jo(!1)}});var $g=b((RN,Mg)=>{"use strict";var uL=It(),lL=ar(),cL=da();Mg.exports=function(s,e,t){uL?lL.f(s,e,cL(0,t)):s[e]=t}});var Bg=b(()=>{"use strict";var dL=ke(),pL=Zo(),hL=$g();dL({target:"Object",stat:!0},{fromEntries:function(e){var t={};return pL(e,function(i,r){hL(t,i,r)},{AS_ENTRIES:!0}),t}})});var Cg=b(($N,Dg)=>{"use strict";id();Bg();var fL=Lr();Dg.exports=fL.Object.fromEntries});var Og=b((BN,Vg)=>{"use strict";Vg.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 Fg=b(()=>{"use strict";id();var mL=Og(),bL=xe(),gL=Ia(),_g=or();for(eu in mL)gL(bL[eu],eu),_g[eu]=_g.Array;var eu});var Ug=b((VN,Ng)=>{"use strict";var SL=Cg();Fg();Ng.exports=SL});var sd=b((ON,qg)=>{"use strict";var vL=Ug();qg.exports=vL});var jg=b(()=>{"use strict"});var ad=b((NN,Hg)=>{"use strict";var wa=xe(),yL=sr(),TL=ir(),tu=function(s){return yL.slice(0,s.length)===s};Hg.exports=function(){return tu("Bun/")?"BUN":tu("Cloudflare-Workers")?"CLOUDFLARE":tu("Deno/")?"DENO":tu("Node.js/")?"NODE":wa.Bun&&typeof Bun.version=="string"?"BUN":wa.Deno&&typeof Deno.version=="object"?"DENO":TL(wa.process)==="process"?"NODE":wa.window&&wa.document?"BROWSER":"REST"}()});var iu=b((UN,Gg)=>{"use strict";var IL=ad();Gg.exports=IL==="NODE"});var Qg=b((qN,zg)=>{"use strict";var xL=ar();zg.exports=function(s,e,t){return xL.f(s,e,t)}});var Kg=b((jN,Yg)=>{"use strict";var EL=vi(),wL=Qg(),PL=je(),AL=It(),Wg=PL("species");Yg.exports=function(s){var e=EL(s);AL&&e&&!e[Wg]&&wL(e,Wg,{configurable:!0,get:function(){return this}})}});var Jg=b((HN,Xg)=>{"use strict";var kL=pa(),RL=TypeError;Xg.exports=function(s,e){if(kL(e,s))return s;throw new RL("Incorrect invocation")}});var od=b((GN,Zg)=>{"use strict";var LL=Ve(),ML=Te(),nd=ma(),$L=LL(Function.toString);ML(nd.inspectSource)||(nd.inspectSource=function(s){return $L(s)});Zg.exports=nd.inspectSource});var ld=b((zN,sS)=>{"use strict";var BL=Ve(),DL=qe(),eS=Te(),CL=Ta(),VL=vi(),OL=od(),tS=function(){},iS=VL("Reflect","construct"),ud=/^\s*(?:class|function)\b/,_L=BL(ud.exec),FL=!ud.test(tS),Pa=function(e){if(!eS(e))return!1;try{return iS(tS,[],e),!0}catch(t){return!1}},rS=function(e){if(!eS(e))return!1;switch(CL(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return FL||!!_L(ud,OL(e))}catch(t){return!0}};rS.sham=!0;sS.exports=!iS||DL(function(){var s;return Pa(Pa.call)||!Pa(Object)||!Pa(function(){s=!0})||s})?rS:Pa});var nS=b((QN,aS)=>{"use strict";var NL=ld(),UL=ha(),qL=TypeError;aS.exports=function(s){if(NL(s))return s;throw new qL(UL(s)+" is not a constructor")}});var cd=b((WN,uS)=>{"use strict";var oS=Yt(),jL=nS(),HL=Rr(),GL=je(),zL=GL("species");uS.exports=function(s,e){var t=oS(s).constructor,i;return t===void 0||HL(i=oS(t)[zL])?e:jL(i)}});var cS=b((YN,lS)=>{"use strict";var QL=Ve();lS.exports=QL([].slice)});var pS=b((KN,dS)=>{"use strict";var WL=TypeError;dS.exports=function(s,e){if(s<e)throw new WL("Not enough arguments");return s}});var dd=b((XN,hS)=>{"use strict";var YL=sr();hS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(YL)});var yd=b((JN,IS)=>{"use strict";var Pt=xe(),KL=ec(),XL=Br(),fS=Te(),JL=Ut(),TS=qe(),mS=Hc(),ZL=cS(),bS=Vo(),eM=pS(),tM=dd(),iM=iu(),gd=Pt.setImmediate,Sd=Pt.clearImmediate,rM=Pt.process,pd=Pt.Dispatch,sM=Pt.Function,gS=Pt.MessageChannel,aM=Pt.String,hd=0,Aa={},SS="onreadystatechange",ka,lr,fd,md;TS(function(){ka=Pt.location});var vd=function(s){if(JL(Aa,s)){var e=Aa[s];delete Aa[s],e()}},bd=function(s){return function(){vd(s)}},vS=function(s){vd(s.data)},yS=function(s){Pt.postMessage(aM(s),ka.protocol+"//"+ka.host)};(!gd||!Sd)&&(gd=function(e){eM(arguments.length,1);var t=fS(e)?e:sM(e),i=ZL(arguments,1);return Aa[++hd]=function(){KL(t,void 0,i)},lr(hd),hd},Sd=function(e){delete Aa[e]},iM?lr=function(s){rM.nextTick(bd(s))}:pd&&pd.now?lr=function(s){pd.now(bd(s))}:gS&&!tM?(fd=new gS,md=fd.port2,fd.port1.onmessage=vS,lr=XL(md.postMessage,md)):Pt.addEventListener&&fS(Pt.postMessage)&&!Pt.importScripts&&ka&&ka.protocol!=="file:"&&!TS(yS)?(lr=yS,Pt.addEventListener("message",vS,!1)):SS in bS("script")?lr=function(s){mS.appendChild(bS("script"))[SS]=function(){mS.removeChild(this),vd(s)}}:lr=function(s){setTimeout(bd(s),0)});IS.exports={set:gd,clear:Sd}});var wS=b((ZN,ES)=>{"use strict";var xS=xe(),nM=It(),oM=Object.getOwnPropertyDescriptor;ES.exports=function(s){if(!nM)return xS[s];var e=oM(xS,s);return e&&e.value}});var Td=b((eU,AS)=>{"use strict";var PS=function(){this.head=null,this.tail=null};PS.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}}};AS.exports=PS});var RS=b((tU,kS)=>{"use strict";var uM=sr();kS.exports=/ipad|iphone|ipod/i.test(uM)&&typeof Pebble!="undefined"});var MS=b((iU,LS)=>{"use strict";var lM=sr();LS.exports=/web0s(?!.*chrome)/i.test(lM)});var _S=b((rU,OS)=>{"use strict";var Nr=xe(),cM=wS(),$S=Br(),Id=yd().set,dM=Td(),pM=dd(),hM=RS(),fM=MS(),xd=iu(),BS=Nr.MutationObserver||Nr.WebKitMutationObserver,DS=Nr.document,CS=Nr.process,ru=Nr.Promise,Pd=cM("queueMicrotask"),Fr,Ed,wd,su,VS;Pd||(Ra=new dM,La=function(){var s,e;for(xd&&(s=CS.domain)&&s.exit();e=Ra.get();)try{e()}catch(t){throw Ra.head&&Fr(),t}s&&s.enter()},!pM&&!xd&&!fM&&BS&&DS?(Ed=!0,wd=DS.createTextNode(""),new BS(La).observe(wd,{characterData:!0}),Fr=function(){wd.data=Ed=!Ed}):!hM&&ru&&ru.resolve?(su=ru.resolve(void 0),su.constructor=ru,VS=$S(su.then,su),Fr=function(){VS(La)}):xd?Fr=function(){CS.nextTick(La)}:(Id=$S(Id,Nr),Fr=function(){Id(La)}),Pd=function(s){Ra.head||Fr(),Ra.add(s)});var Ra,La;OS.exports=Pd});var NS=b((sU,FS)=>{"use strict";FS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var au=b((aU,US)=>{"use strict";US.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var cr=b((nU,qS)=>{"use strict";var mM=xe();qS.exports=mM.Promise});var Ur=b((oU,zS)=>{"use strict";var bM=xe(),Ma=cr(),gM=Te(),SM=Ic(),vM=od(),yM=je(),jS=ad(),TM=Nt(),Ad=lc(),HS=Ma&&Ma.prototype,IM=yM("species"),kd=!1,GS=gM(bM.PromiseRejectionEvent),xM=SM("Promise",function(){var s=vM(Ma),e=s!==String(Ma);if(!e&&Ad===66||TM&&!(HS.catch&&HS.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[IM]=i,kd=t.then(function(){})instanceof i,!kd)return!0}return!e&&(jS==="BROWSER"||jS==="DENO")&&!GS});zS.exports={CONSTRUCTOR:xM,REJECTION_EVENT:GS,SUBCLASSING:kd}});var qr=b((uU,WS)=>{"use strict";var QS=Wt(),EM=TypeError,wM=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new EM("Bad Promise constructor");e=i,t=r}),this.resolve=QS(e),this.reject=QS(t)};WS.exports.f=function(s){return new wM(s)}});var hv=b(()=>{"use strict";var PM=ke(),AM=Nt(),lu=iu(),Ci=xe(),zr=xt(),YS=_r(),KS=Zc(),kM=Ia(),RM=Kg(),LM=Wt(),uu=Te(),MM=Et(),$M=Jg(),BM=cd(),tv=yd().set,Bd=_S(),DM=NS(),CM=au(),VM=Td(),iv=Nc(),cu=cr(),Dd=Ur(),rv=qr(),du="Promise",sv=Dd.CONSTRUCTOR,OM=Dd.REJECTION_EVENT,_M=Dd.SUBCLASSING,Rd=iv.getterFor(du),FM=iv.set,jr=cu&&cu.prototype,dr=cu,nu=jr,av=Ci.TypeError,Ld=Ci.document,Cd=Ci.process,Md=rv.f,NM=Md,UM=!!(Ld&&Ld.createEvent&&Ci.dispatchEvent),nv="unhandledrejection",qM="rejectionhandled",XS=0,ov=1,jM=2,Vd=1,uv=2,ou,JS,HM,ZS,lv=function(s){var e;return MM(s)&&uu(e=s.then)?e:!1},cv=function(s,e){var t=e.value,i=e.state===ov,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===uv&&zM(e),e.rejection=Vd),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new av("Promise-chain cycle")):(l=lv(u))?zr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},dv=function(s,e){s.notified||(s.notified=!0,Bd(function(){for(var t=s.reactions,i;i=t.get();)cv(i,s);s.notified=!1,e&&!s.rejection&&GM(s)}))},pv=function(s,e,t){var i,r;UM?(i=Ld.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Ci.dispatchEvent(i)):i={promise:e,reason:t},!OM&&(r=Ci["on"+s])?r(i):s===nv&&DM("Unhandled promise rejection",t)},GM=function(s){zr(tv,Ci,function(){var e=s.facade,t=s.value,i=ev(s),r;if(i&&(r=CM(function(){lu?Cd.emit("unhandledRejection",t,e):pv(nv,e,t)}),s.rejection=lu||ev(s)?uv:Vd,r.error))throw r.value})},ev=function(s){return s.rejection!==Vd&&!s.parent},zM=function(s){zr(tv,Ci,function(){var e=s.facade;lu?Cd.emit("rejectionHandled",e):pv(qM,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=jM,dv(s,!0))},$d=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new av("Promise can't be resolved itself");var i=lv(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=ov,dv(s,!1))}catch(r){Gr({done:!1},r,s)}}};if(sv&&(dr=function(e){$M(this,nu),LM(e),zr(ou,this);var t=Rd(this);try{e(Hr($d,t),Hr(Gr,t))}catch(i){Gr(t,i)}},nu=dr.prototype,ou=function(e){FM(this,{type:du,done:!1,notified:!1,parent:!1,reactions:new VM,rejection:!1,state:XS,value:void 0})},ou.prototype=YS(nu,"then",function(e,t){var i=Rd(this),r=Md(BM(this,dr));return i.parent=!0,r.ok=uu(e)?e:!0,r.fail=uu(t)&&t,r.domain=lu?Cd.domain:void 0,i.state===XS?i.reactions.add(r):Bd(function(){cv(r,i)}),r.promise}),JS=function(){var s=new ou,e=Rd(s);this.promise=s,this.resolve=Hr($d,e),this.reject=Hr(Gr,e)},rv.f=Md=function(s){return s===dr||s===HM?new JS(s):NM(s)},!AM&&uu(cu)&&jr!==Object.prototype)){ZS=jr.then,_M||YS(jr,"then",function(e,t){var i=this;return new dr(function(r,a){zr(ZS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete jr.constructor}catch(s){}KS&&KS(jr,nu)}PM({global:!0,constructor:!0,wrap:!0,forced:sv},{Promise:dr});kM(dr,du,!1,!0);RM(du)});var Sv=b((dU,gv)=>{"use strict";var QM=je(),mv=QM("iterator"),bv=!1;try{fv=0,Od={next:function(){return{done:!!fv++}},return:function(){bv=!0}},Od[mv]=function(){return this},Array.from(Od,function(){throw 2})}catch(s){}var fv,Od;gv.exports=function(s,e){try{if(!e&&!bv)return!1}catch(r){return!1}var t=!1;try{var i={};i[mv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var _d=b((pU,vv)=>{"use strict";var WM=cr(),YM=Sv(),KM=Ur().CONSTRUCTOR;vv.exports=KM||!YM(function(s){WM.all(s).then(void 0,function(){})})});var yv=b(()=>{"use strict";var XM=ke(),JM=xt(),ZM=Wt(),e$=qr(),t$=au(),i$=Zo(),r$=_d();XM({target:"Promise",stat:!0,forced:r$},{all:function(e){var t=this,i=e$.f(t),r=i.resolve,a=i.reject,n=t$(function(){var o=ZM(t.resolve),u=[],l=0,d=1;i$(e,function(c){var h=l++,p=!1;d++,JM(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 Iv=b(()=>{"use strict";var s$=ke(),a$=Nt(),n$=Ur().CONSTRUCTOR,Nd=cr(),o$=vi(),u$=Te(),l$=_r(),Tv=Nd&&Nd.prototype;s$({target:"Promise",proto:!0,forced:n$,real:!0},{catch:function(s){return this.then(void 0,s)}});!a$&&u$(Nd)&&(Fd=o$("Promise").prototype.catch,Tv.catch!==Fd&&l$(Tv,"catch",Fd,{unsafe:!0}));var Fd});var xv=b(()=>{"use strict";var c$=ke(),d$=xt(),p$=Wt(),h$=qr(),f$=au(),m$=Zo(),b$=_d();c$({target:"Promise",stat:!0,forced:b$},{race:function(e){var t=this,i=h$.f(t),r=i.reject,a=f$(function(){var n=p$(t.resolve);m$(e,function(o){d$(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var Ev=b(()=>{"use strict";var g$=ke(),S$=qr(),v$=Ur().CONSTRUCTOR;g$({target:"Promise",stat:!0,forced:v$},{reject:function(e){var t=S$.f(this),i=t.reject;return i(e),t.promise}})});var Ud=b((TU,wv)=>{"use strict";var y$=Yt(),T$=Et(),I$=qr();wv.exports=function(s,e){if(y$(s),T$(e)&&e.constructor===s)return e;var t=I$.f(s),i=t.resolve;return i(e),t.promise}});var kv=b(()=>{"use strict";var x$=ke(),E$=vi(),Pv=Nt(),w$=cr(),Av=Ur().CONSTRUCTOR,P$=Ud(),A$=E$("Promise"),k$=Pv&&!Av;x$({target:"Promise",stat:!0,forced:Pv||Av},{resolve:function(e){return P$(k$&&this===A$?w$:this,e)}})});var Rv=b(()=>{"use strict";hv();yv();Iv();xv();Ev();kv()});var Bv=b(()=>{"use strict";var R$=ke(),L$=Nt(),pu=cr(),M$=qe(),Mv=vi(),$v=Te(),$$=cd(),Lv=Ud(),B$=_r(),jd=pu&&pu.prototype,D$=!!pu&&M$(function(){jd.finally.call({then:function(){}},function(){})});R$({target:"Promise",proto:!0,real:!0,forced:D$},{finally:function(s){var e=$$(this,Mv("Promise")),t=$v(s);return this.then(t?function(i){return Lv(e,s()).then(function(){return i})}:s,t?function(i){return Lv(e,s()).then(function(){throw i})}:s)}});!L$&&$v(pu)&&(qd=Mv("Promise").prototype.finally,jd.finally!==qd&&B$(jd,"finally",qd,{unsafe:!0}));var qd});var Cv=b((kU,Dv)=>{"use strict";jg();Rv();Bv();var C$=Di();Dv.exports=C$("Promise","finally")});var Ov=b((RU,Vv)=>{"use strict";var V$=Cv();Vv.exports=V$});var $a=b((LU,_v)=>{"use strict";var O$=Ov();_v.exports=O$});var Xv=b(()=>{"use strict";var X$=ke(),J$=Vc().values;X$({target:"Object",stat:!0},{values:function(e){return J$(e)}})});var Zv=b((f1,Jv)=>{"use strict";Xv();var Z$=Lr();Jv.exports=Z$.Object.values});var ty=b((m1,ey)=>{"use strict";var eB=Zv();ey.exports=eB});var fr=b((b1,iy)=>{"use strict";var tB=ty();iy.exports=tB});var Sy=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 yy=b((kq,vy)=>{"use strict";Sy();var LB=Di();vy.exports=LB("Array","at")});var Iy=b((Rq,Ty)=>{"use strict";var MB=yy();Ty.exports=MB});var jt=b((Lq,xy)=>{"use strict";var $B=Iy();xy.exports=$B});var pp=b((SH,iT)=>{"use strict";var pD=ir();iT.exports=Array.isArray||function(e){return pD(e)==="Array"}});var sT=b((vH,rT)=>{"use strict";var hD=TypeError,fD=9007199254740991;rT.exports=function(s){if(s>fD)throw hD("Maximum allowed index exceeded");return s}});var oT=b((yH,nT)=>{"use strict";var mD=pp(),bD=Or(),gD=sT(),SD=Br(),aT=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=aT(s,e,c,h,u,a-1)-1):(gD(u+1),s[u]=c),u++),l++;return u};nT.exports=aT});var dT=b((TH,cT)=>{"use strict";var uT=pp(),vD=ld(),yD=Et(),TD=je(),ID=TD("species"),lT=Array;cT.exports=function(s){var e;return uT(s)&&(e=s.constructor,vD(e)&&(e===lT||uT(e.prototype))?e=void 0:yD(e)&&(e=e[ID],e===null&&(e=void 0))),e===void 0?lT:e}});var hT=b((IH,pT)=>{"use strict";var xD=dT();pT.exports=function(s,e){return new(xD(s))(e===0?0:e)}});var fT=b(()=>{"use strict";var ED=ke(),wD=oT(),PD=Wt(),AD=Mr(),kD=Or(),RD=hT();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 mT=b(()=>{"use strict";var LD=va();LD("flatMap")});var gT=b((AH,bT)=>{"use strict";fT();mT();var MD=Di();bT.exports=MD("Array","flatMap")});var vT=b((kH,ST)=>{"use strict";var $D=gT();ST.exports=$D});var Ya=b((RH,yT)=>{"use strict";var BD=vT();yT.exports=BD});var Ka=b((LH,TT)=>{"use strict";var DD=Ta(),CD=String;TT.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,IT)=>{"use strict";IT.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 wT=b(($H,ET)=>{"use strict";var VD=Ve(),OD=Bi(),_D=Ka(),mp=hp(),xT=VD("".replace),FD=RegExp("^["+mp+"]+"),ND=RegExp("(^|[^"+mp+"])["+mp+"]+$"),fp=function(s){return function(e){var t=_D(OD(e));return s&1&&(t=xT(t,FD,"")),s&2&&(t=xT(t,ND,"$1")),t}};ET.exports={start:fp(1),end:fp(2),trim:fp(3)}});var RT=b((BH,kT)=>{"use strict";var UD=jc().PROPER,qD=qe(),PT=hp(),AT="\u200B\x85\u180E";kT.exports=function(s){return qD(function(){return!!PT[s]()||AT[s]()!==AT||UD&&PT[s].name!==s})}});var bp=b((DH,LT)=>{"use strict";var jD=wT().start,HD=RT();LT.exports=HD("trimStart")?function(){return jD(this)}:"".trimStart});var $T=b(()=>{"use strict";var GD=ke(),MT=bp();GD({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==MT},{trimLeft:MT})});var DT=b(()=>{"use strict";$T();var zD=ke(),BT=bp();zD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==BT},{trimStart:BT})});var VT=b((FH,CT)=>{"use strict";DT();var QD=Di();CT.exports=QD("String","trimLeft")});var _T=b((NH,OT)=>{"use strict";var WD=VT();OT.exports=WD});var NT=b((UH,FT)=>{"use strict";var YD=_T();FT.exports=YD});var tI=b(()=>{"use strict"});var iI=b(()=>{"use strict"});var sI=b((EG,rI)=>{"use strict";var S0=Et(),v0=ir(),y0=je(),T0=y0("match");rI.exports=function(s){var e;return S0(s)&&((e=s[T0])!==void 0?!!e:v0(s)==="RegExp")}});var nI=b((wG,aI)=>{"use strict";var I0=Yt();aI.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 lI=b((PG,uI)=>{"use strict";var x0=xt(),E0=Ut(),w0=pa(),P0=nI(),oI=RegExp.prototype;uI.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in oI)&&!E0(s,"flags")&&w0(oI,s)?x0(P0,s):e}});var dI=b((AG,cI)=>{"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;cI.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 fI=b(()=>{"use strict";var $0=ke(),B0=xt(),Ep=Ve(),pI=Bi(),D0=Te(),C0=Rr(),V0=sI(),ns=Ka(),O0=fa(),_0=lI(),F0=dI(),N0=je(),U0=Nt(),q0=N0("replace"),j0=TypeError,xp=Ep("".indexOf),H0=Ep("".replace),hI=Ep("".slice),G0=Math.max;$0({target:"String",proto:!0},{replaceAll:function(e,t){var i=pI(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!C0(e)){if(r=V0(e),r&&(a=ns(pI(_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+=hI(o,f,h)+p,f=h+d,h=h+c>o.length?-1:xp(o,u,h+c);return f<o.length&&(m+=hI(o,f)),m}})});var bI=b((LG,mI)=>{"use strict";tI();iI();fI();var z0=Di();mI.exports=z0("String","replaceAll")});var SI=b((MG,gI)=>{"use strict";var Q0=bI();gI.exports=Q0});var wp=b(($G,vI)=>{"use strict";var W0=SI();vI.exports=W0});var TI=b((BG,yI)=>{"use strict";var Y0=Sa(),K0=Ka(),X0=Bi(),J0=RangeError;yI.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 PI=b((DG,wI)=>{"use strict";var EI=Ve(),Z0=kc(),II=Ka(),eC=TI(),tC=Bi(),iC=EI(eC),rC=EI("".slice),sC=Math.ceil,xI=function(s){return function(e,t,i){var r=II(tC(e)),a=Z0(t),n=r.length,o=i===void 0?" ":II(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)}};wI.exports={start:xI(!1),end:xI(!0)}});var kI=b((CG,AI)=>{"use strict";var aC=sr();AI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(aC)});var RI=b(()=>{"use strict";var nC=ke(),oC=PI().start,uC=kI();nC({target:"String",proto:!0,forced:uC},{padStart:function(e){return oC(this,e,arguments.length>1?arguments[1]:void 0)}})});var MI=b((_G,LI)=>{"use strict";RI();var lC=Di();LI.exports=lC("String","padStart")});var BI=b((FG,$I)=>{"use strict";var cC=MI();$I.exports=cC});var Pp=b((NG,DI)=>{"use strict";var dC=BI();DI.exports=dC});var zh="2.0.131-dev.ffcf4d9f.0";var lt=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(lt||{}),Si=(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))(Si||{});var $o=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))($o||{}),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||{}),Bo=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Bo||{});var WE=j(wt(),1);import{assertNever as Gm,assertNonNullable as EA,isNonNullable as _o,ValueSubject as Lc,Subject as wA,Subscription as PA,merge as AA,observableFrom as kA,fromEvent as Um,map as qm,tap as jm,filterChanged as RA,isNullable as Mc,ErrorCategory as Hm}from"@vkontakte/videoplayer-shared/es2015";var Nm=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 Lc(void 0);this.castState$=new Lc("NOT_AVAILABLE");this.errorEvent$=new wA;this.realCastState$=new Lc("NOT_AVAILABLE");this.subscription=new PA;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||Nm("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Hm.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();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(Um(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 Gm(r.sessionState)}})).add(AA(Um(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(jm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),qm(r=>r.castState)),kA([i.getCastState()])).pipe(RA(),qm(LA),jm(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();EA(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"?_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:Hm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},LA=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 Gm(s)}};var Ch=j(wt(),1),RE=j(nr(),1),LE=j(sd(),1);var Wv=j($a(),1);import{assertNever as Fv}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:Fv(t)}return s},Vi=(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:Fv(e)}};var L=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as _$,Subject as hu,merge as Nv}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$=Nv(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Nv(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||_$(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 F$}from"@vkontakte/videoplayer-shared/es2015";var Uv=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 F$(s)}};import{assertNever as Qr,assertNonNullable as pr,debounce as qv,ErrorCategory as jv,fromEvent as hr,isNonNullable as Hv,map as Gv,merge as zv,observableFrom as N$,Subject as U$,Subscription as Hd,timeout as q$,getHighestQuality as j$}from"@vkontakte/videoplayer-shared/es2015";var H$=5,G$=5,z$=500,Qv=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(Uv(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(zv(this.videoState.stateChangeStarted$.pipe(Gv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Gv(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 U$;e.add(r.pipe(qv(z$)).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)>H$)&&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<G$&&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=zv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,N$(["init"])).pipe(qv(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=j$(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:jv.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 Hv(o)&&(n.metadata.title=o),Hv(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(q$(Qv).subscribe(()=>a(`timeout(${Qv})`)))});(0,Wv.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:jv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var cp=j(wt(),1);import{clearVideoElement as Kv}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as Q$}from"@vkontakte/videoplayer-shared/es2015";var Yv=s=>{try{s.pause(),s.playbackRate=0,Q$(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as W$,Subscription as Y$}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,K$=(s,e=20)=>{let t=0;return W$(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?Kv(i):(i=document.createElement("video"),s.appendChild(i)),zd.set(i,r);let a=new Y$;return a.add(K$(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},Ge=s=>{let e=Qd.get(s);e==null||e.unsubscribe(),Qd.delete(s);let t=zd.get(s);zd.delete(s),t?Kv(s):Yv(s)};var Yd=j(fr(),1);import{assertNonNullable as Da,isNonNullable as Xt,isNullable as sB,fromEvent as Wr,merge as ry,observableFrom as sy,filterChanged as ay,map as Ca,Subject as ny,Subscription as aB,ValueSubject as nB,ErrorCategory as oB}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Wd,isNullable as iB,Subscription as rB}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=iB(r),l=new rB;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=>{Wd(i)&&(s.loop=i)},{onError:t}),ze=(s,e,t,i)=>fu(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)=>fu(e,()=>s.playbackRate,r=>{Wd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Oi=fu;var uB=s=>["__",s.language,s.label].join("|"),lB=(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 ny;this.current$=new nB(void 0);this.error$=new ny;this.subscription=new aB;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:oB.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(Oi(t.internalTextTracks,()=>(0,Yd.default)(this.internalTracks),a=>{Xt(a)&&this.setInternal(a)},{equal:(a,n)=>Xt(a)&&Xt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ca(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Oi(t.externalTextTracks,()=>(0,Yd.default)(this.externalTracks),a=>{Xt(a)&&this.setExternal(a)},{equal:(a,n)=>Xt(a)&&Xt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ca(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Oi(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(Oi(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(ry(Wr(e,"addtrack"),Wr(e,"removetrack"),sy(["init"])).pipe(Ca(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ay((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(ry(Wr(e,"change"),sy(["init"])).pipe(Ca(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ca(i=>i&&this.htmlTextTrackToITextTrack(i).id),ay()).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;Xt(t.align)&&(r.align=t.align),Xt(t.position)&&(r.position=t.position),Xt(t.size)&&(r.size=t.size),Xt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){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:uB(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))(sB(e)||!lB(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 oy=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=oy(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},uy=s=>{let e=oy(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as pt,map as _i,merge as Zd,filterChanged as SB,isNonNullable as by,Subject as vB,filter as Oa,mapTo as ep,combine as yB,once as TB,throttle as IB,ErrorCategory as xB,ValueSubject as gy,Subscription as EB}from"@vkontakte/videoplayer-shared/es2015";var cB=3,ly=(s,e,t=cB)=>{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{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}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._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 cy=j(wt(),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 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,cy.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 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))},dy=()=>{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 dB=document.createElement("video"),pB='video/mp4; codecs="avc1.42000a,mp4a.40.2"',hB='video/mp4; codecs="hev1.1.6.L93.B0"',py='video/webm; codecs="vp09.00.10.08"',hy='video/webm; codecs="av01.0.00M.08"',fB='audio/mp4; codecs="mp4a.40.2"',mB='audio/webm; codecs="opus"',fy,bB=()=>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(D(E({},s),{video:D(E({},s.video),{contentType:hy})})),window.navigator.mediaCapabilities.decodingInfo(D(E({},s),{video:D(E({},s.video),{contentType:py})}))]);fy={DASH_WEBM_AV1:e,DASH_WEBM:t}});bB().catch(s=>{console.log(dB),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 fy}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:dy(),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,pB)),k=!!((h=(c=At())==null?void 0:c.isTypeSupported)!=null&&h.call(c,hB)),C=!!((f=(p=At())==null?void 0:p.isTypeSupported)!=null&&f.call(p,fB));this._codecs={h264:I,h265:k,vp9:!!((g=(m=At())==null?void 0:m.isTypeSupported)!=null&&g.call(m,py)),av1:!!((v=(S=At())==null?void 0:S.isTypeSupported)!=null&&v.call(S,hy)),aac:C,opus:!!((T=(y=At())==null?void 0:y.isTypeSupported)!=null&&T.call(y,mB)),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 my="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,my))},this._codecs={mp3:!!((r=(i=At())==null?void 0:i.isTypeSupported)!=null&&r.call(i,my))}}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 gB}from"@vkontakte/videoplayer-shared/es2015";var Jd=class{constructor(){this.isInited$=new gB(!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 Jd;var Qe=s=>{let e=P=>pt(s,P).pipe(ep(void 0)),t=new EB,i=()=>t.unsubscribe(),a=Zd(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>pt(s,P))).pipe(_i(P=>P.type==="ended"?s.readyState<2:s.readyState<3),SB()),n=Zd(pt(s,"progress"),pt(s,"timeupdate")).pipe(_i(()=>ly(s.buffered,s.currentTime))),o=G.browser.isSafari?yB({play:e("play").pipe(TB()),playing:e("playing")}).pipe(ep(void 0)):e("playing"),u=pt(s,"volumechange").pipe(_i(()=>({muted:s.muted,volume:s.volume}))),l=pt(s,"ratechange").pipe(_i(()=>s.playbackRate)),d=pt(s,"error").pipe(Oa(()=>!!(s.error||s.played.length)),_i(()=>{var U;let P=s.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:xB.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(U=s.error)!=null?U:void 0}})),c=pt(s,"timeupdate").pipe(_i(()=>s.currentTime)),h=new vB,p=.3,f;t.add(c.subscribe(P=>{s.loop&&by(f)&&by(P)&&f>=s.duration-p&&P<=p&&h.next(f),f=P}));let m=e("pause").pipe(Oa(()=>!s.error&&f!==s.duration)),g=pt(s,"enterpictureinpicture"),S=pt(s,"leavepictureinpicture"),v=new gy(uy(s));t.add(g.subscribe(()=>v.next(!0))),t.add(S.subscribe(()=>v.next(!1)));let y=new gy(Xd(s)),T=pt(s,"fullscreenchange");t.add(T.pipe(_i(()=>Xd(s))).subscribe(y));let I=.1,k=1e3,C=pt(s,"timeupdate").pipe(Oa(P=>s.duration-s.currentTime<I)),M=Zd(C.pipe(Oa(P=>!s.loop)),pt(s,"ended")).pipe(IB(k),ep(void 0)),_=C.pipe(Oa(P=>s.loop));return{playing$:o,pause$:m,canplay$:e("canplay"),ended$:M,looped$:h,loopExpected$:_,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:pt(s,"durationchange").pipe(_i(()=>s.duration)),isBuffering$:a,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:v,inFullscreen$:y,enterPip$:g,leavePip$:S,destroy:i}};import{VideoQuality as Fi}from"@vkontakte/videoplayer-shared/es2015";var Jt=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(wt(),1),br=j(nr(),1);import{isNonNullable as ne,isNullable as wu,now as By,isHigher as Pu,isHigherOrEqual as Xr,isInvariantQuality as Au,isLowerOrEqual as Jr,videoSizeToQuality as Dy,assertNotEmptyArray as ku,assertNonNullable as Cy}from"@vkontakte/videoplayer-shared/es2015";var tp=!1,Ti={},Ey=s=>{tp=s},wy=()=>{Ti={}},Py=s=>{s(Ti)},_a=(s,e)=>{var t;tp&&(Ti.meta=(t=Ti.meta)!=null?t:{},Ti.meta[s]=e)},at=class{constructor(e){this.name=e}next(e){var i,r;if(!tp)return;Ti.series=(i=Ti.series)!=null?i:{};let t=(r=Ti.series[this.name])!=null?r:[];t.push([Date.now(),e]),Ti.series[this.name]=t}};import{isHigher as BB,isHigherOrEqual as Vq,isLower as Ay,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)&&Ay(s.max,s.min)||Tu(s.min)&&e&&BB(s.min,e)||Tu(s.max)&&t&&Ay(s.max,t)}function ky({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 Vy=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]=By()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Lu='Assertion "ABR Tracks is empty array" failed',Eu=new WeakMap,Ry=new WeakMap,Ly=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,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)},Na=(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=Ly.get(s);n||(n=a.filter(l=>ne(l.bitrate)&&ne(s.bitrate)?s.bitrate/l.bitrate>i:!0),Ly.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)},My=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]&&By()-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=My(o)?"video":"audio",l=My(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var GE=Object.create;var zl=Object.defineProperty,zE=Object.defineProperties,QE=Object.getOwnPropertyDescriptor,WE=Object.getOwnPropertyDescriptors,YE=Object.getOwnPropertyNames,Lo=Object.getOwnPropertySymbols,KE=Object.getPrototypeOf,Ql=Object.prototype.hasOwnProperty,qh=Object.prototype.propertyIsEnumerable;var XE=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var st=Math.pow,Uh=(s,e,t)=>e in s?zl(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,E=(s,e)=>{for(var t in e||(e={}))Ql.call(e,t)&&Uh(s,t,e[t]);if(Lo)for(var t of Lo(e))qh.call(e,t)&&Uh(s,t,e[t]);return s},D=(s,e)=>zE(s,WE(e));var jh=(s,e)=>{var t={};for(var i in s)Ql.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 JE=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of YE(e))!Ql.call(s,r)&&r!==t&&zl(s,r,{get:()=>e[r],enumerable:!(i=QE(e,r))||i.enumerable});return s};var j=(s,e,t)=>(t=s!=null?GE(KE(s)):{},JE(e||!s||!s.__esModule?zl(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())}),ir=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 ir,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[XE("asyncIterator")]=()=>a,r("next"),r("throw"),r("return"),a};var xe=b((Kl,Gh)=>{"use strict";var la=function(s){return s&&s.Math===Math&&s};Gh.exports=la(typeof globalThis=="object"&&globalThis)||la(typeof window=="object"&&window)||la(typeof self=="object"&&self)||la(typeof global=="object"&&global)||la(typeof Kl=="object"&&Kl)||function(){return this}()||Function("return this")()});var qe=b((S_,zh)=>{"use strict";zh.exports=function(s){try{return!!s()}catch(e){return!0}}});var ca=b((v_,Qh)=>{"use strict";var ZE=qe();Qh.exports=!ZE(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Xl=b((y_,Xh)=>{"use strict";var ew=ca(),Kh=Function.prototype,Wh=Kh.apply,Yh=Kh.call;Xh.exports=typeof Reflect=="object"&&Reflect.apply||(ew?Yh.bind(Wh):function(){return Yh.apply(Wh,arguments)})});var Ve=b((T_,ef)=>{"use strict";var Jh=ca(),Zh=Function.prototype,Jl=Zh.call,tw=Jh&&Zh.bind.bind(Jl,Jl);ef.exports=Jh?tw:function(s){return function(){return Jl.apply(s,arguments)}}});var rr=b((I_,rf)=>{"use strict";var tf=Ve(),iw=tf({}.toString),rw=tf("".slice);rf.exports=function(s){return rw(iw(s),8,-1)}});var Zl=b((x_,sf)=>{"use strict";var sw=rr(),aw=Ve();sf.exports=function(s){if(sw(s)==="Function")return aw(s)}});var Te=b((E_,af)=>{"use strict";var ec=typeof document=="object"&&document.all;af.exports=typeof ec=="undefined"&&ec!==void 0?function(s){return typeof s=="function"||s===ec}:function(s){return typeof s=="function"}});var It=b((w_,nf)=>{"use strict";var nw=qe();nf.exports=!nw(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var xt=b((P_,of)=>{"use strict";var ow=ca(),Do=Function.prototype.call;of.exports=ow?Do.bind(Do):function(){return Do.apply(Do,arguments)}});var tc=b(cf=>{"use strict";var uf={}.propertyIsEnumerable,lf=Object.getOwnPropertyDescriptor,uw=lf&&!uf.call({1:2},1);cf.f=uw?function(e){var t=lf(this,e);return!!t&&t.enumerable}:uf});var da=b((k_,df)=>{"use strict";df.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var hf=b((R_,pf)=>{"use strict";var lw=Ve(),cw=qe(),dw=rr(),ic=Object,pw=lw("".split);pf.exports=cw(function(){return!ic("z").propertyIsEnumerable(0)})?function(s){return dw(s)==="String"?pw(s,""):ic(s)}:ic});var Rr=b((L_,ff)=>{"use strict";ff.exports=function(s){return s==null}});var Ci=b((M_,mf)=>{"use strict";var hw=Rr(),fw=TypeError;mf.exports=function(s){if(hw(s))throw new fw("Can't call method on "+s);return s}});var sr=b(($_,bf)=>{"use strict";var mw=hf(),bw=Ci();bf.exports=function(s){return mw(bw(s))}});var Et=b((D_,gf)=>{"use strict";var gw=Te();gf.exports=function(s){return typeof s=="object"?s!==null:gw(s)}});var Lr=b((B_,Sf)=>{"use strict";Sf.exports={}});var Si=b((C_,yf)=>{"use strict";var rc=Lr(),sc=xe(),Sw=Te(),vf=function(s){return Sw(s)?s:void 0};yf.exports=function(s,e){return arguments.length<2?vf(rc[s])||vf(sc[s]):rc[s]&&rc[s][e]||sc[s]&&sc[s][e]}});var pa=b((V_,Tf)=>{"use strict";var vw=Ve();Tf.exports=vw({}.isPrototypeOf)});var ar=b((O_,Ef)=>{"use strict";var yw=xe(),If=yw.navigator,xf=If&&If.userAgent;Ef.exports=xf?String(xf):""});var nc=b((__,Lf)=>{"use strict";var Rf=xe(),ac=ar(),wf=Rf.process,Pf=Rf.Deno,Af=wf&&wf.versions||Pf&&Pf.version,kf=Af&&Af.v8,Ft,Bo;kf&&(Ft=kf.split("."),Bo=Ft[0]>0&&Ft[0]<4?1:+(Ft[0]+Ft[1]));!Bo&&ac&&(Ft=ac.match(/Edge\/(\d+)/),(!Ft||Ft[1]>=74)&&(Ft=ac.match(/Chrome\/(\d+)/),Ft&&(Bo=+Ft[1])));Lf.exports=Bo});var oc=b((F_,$f)=>{"use strict";var Mf=nc(),Tw=qe(),Iw=xe(),xw=Iw.String;$f.exports=!!Object.getOwnPropertySymbols&&!Tw(function(){var s=Symbol("symbol detection");return!xw(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Mf&&Mf<41})});var uc=b((N_,Df)=>{"use strict";var Ew=oc();Df.exports=Ew&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var lc=b((U_,Bf)=>{"use strict";var ww=Si(),Pw=Te(),Aw=pa(),kw=uc(),Rw=Object;Bf.exports=kw?function(s){return typeof s=="symbol"}:function(s){var e=ww("Symbol");return Pw(e)&&Aw(e.prototype,Rw(s))}});var ha=b((q_,Cf)=>{"use strict";var Lw=String;Cf.exports=function(s){try{return Lw(s)}catch(e){return"Object"}}});var Kt=b((j_,Vf)=>{"use strict";var Mw=Te(),$w=ha(),Dw=TypeError;Vf.exports=function(s){if(Mw(s))return s;throw new Dw($w(s)+" is not a function")}});var fa=b((H_,Of)=>{"use strict";var Bw=Kt(),Cw=Rr();Of.exports=function(s,e){var t=s[e];return Cw(t)?void 0:Bw(t)}});var Ff=b((G_,_f)=>{"use strict";var cc=xt(),dc=Te(),pc=Et(),Vw=TypeError;_f.exports=function(s,e){var t,i;if(e==="string"&&dc(t=s.toString)&&!pc(i=cc(t,s))||dc(t=s.valueOf)&&!pc(i=cc(t,s))||e!=="string"&&dc(t=s.toString)&&!pc(i=cc(t,s)))return i;throw new Vw("Can't convert object to primitive value")}});var Nt=b((z_,Nf)=>{"use strict";Nf.exports=!0});var jf=b((Q_,qf)=>{"use strict";var Uf=xe(),Ow=Object.defineProperty;qf.exports=function(s,e){try{Ow(Uf,s,{value:e,configurable:!0,writable:!0})}catch(t){Uf[s]=e}return e}});var ma=b((W_,zf)=>{"use strict";var _w=Nt(),Fw=xe(),Nw=jf(),Hf="__core-js_shared__",Gf=zf.exports=Fw[Hf]||Nw(Hf,{});(Gf.versions||(Gf.versions=[])).push({version:"3.38.0",mode:_w?"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 hc=b((Y_,Wf)=>{"use strict";var Qf=ma();Wf.exports=function(s,e){return Qf[s]||(Qf[s]=e||{})}});var Mr=b((K_,Yf)=>{"use strict";var Uw=Ci(),qw=Object;Yf.exports=function(s){return qw(Uw(s))}});var Ut=b((X_,Kf)=>{"use strict";var jw=Ve(),Hw=Mr(),Gw=jw({}.hasOwnProperty);Kf.exports=Object.hasOwn||function(e,t){return Gw(Hw(e),t)}});var fc=b((J_,Xf)=>{"use strict";var zw=Ve(),Qw=0,Ww=Math.random(),Yw=zw(1 .toString);Xf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Yw(++Qw+Ww,36)}});var je=b((Z_,Zf)=>{"use strict";var Kw=xe(),Xw=hc(),Jf=Ut(),Jw=fc(),Zw=oc(),eP=uc(),$r=Kw.Symbol,mc=Xw("wks"),tP=eP?$r.for||$r:$r&&$r.withoutSetter||Jw;Zf.exports=function(s){return Jf(mc,s)||(mc[s]=Zw&&Jf($r,s)?$r[s]:tP("Symbol."+s)),mc[s]}});var rm=b((eF,im)=>{"use strict";var iP=xt(),em=Et(),tm=lc(),rP=fa(),sP=Ff(),aP=je(),nP=TypeError,oP=aP("toPrimitive");im.exports=function(s,e){if(!em(s)||tm(s))return s;var t=rP(s,oP),i;if(t){if(e===void 0&&(e="default"),i=iP(t,s,e),!em(i)||tm(i))return i;throw new nP("Can't convert object to primitive value")}return e===void 0&&(e="number"),sP(s,e)}});var bc=b((tF,sm)=>{"use strict";var uP=rm(),lP=lc();sm.exports=function(s){var e=uP(s,"string");return lP(e)?e:e+""}});var Co=b((iF,nm)=>{"use strict";var cP=xe(),am=Et(),gc=cP.document,dP=am(gc)&&am(gc.createElement);nm.exports=function(s){return dP?gc.createElement(s):{}}});var Sc=b((rF,om)=>{"use strict";var pP=It(),hP=qe(),fP=Co();om.exports=!pP&&!hP(function(){return Object.defineProperty(fP("div"),"a",{get:function(){return 7}}).a!==7})});var cm=b(lm=>{"use strict";var mP=It(),bP=xt(),gP=tc(),SP=da(),vP=sr(),yP=bc(),TP=Ut(),IP=Sc(),um=Object.getOwnPropertyDescriptor;lm.f=mP?um:function(e,t){if(e=vP(e),t=yP(t),IP)try{return um(e,t)}catch(i){}if(TP(e,t))return SP(!bP(gP.f,e,t),e[t])}});var vc=b((aF,dm)=>{"use strict";var xP=qe(),EP=Te(),wP=/#|\.prototype\./,ba=function(s,e){var t=AP[PP(s)];return t===RP?!0:t===kP?!1:EP(e)?xP(e):!!e},PP=ba.normalize=function(s){return String(s).replace(wP,".").toLowerCase()},AP=ba.data={},kP=ba.NATIVE="N",RP=ba.POLYFILL="P";dm.exports=ba});var Dr=b((nF,hm)=>{"use strict";var pm=Zl(),LP=Kt(),MP=ca(),$P=pm(pm.bind);hm.exports=function(s,e){return LP(s),e===void 0?s:MP?$P(s,e):function(){return s.apply(e,arguments)}}});var yc=b((oF,fm)=>{"use strict";var DP=It(),BP=qe();fm.exports=DP&&BP(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Xt=b((uF,mm)=>{"use strict";var CP=Et(),VP=String,OP=TypeError;mm.exports=function(s){if(CP(s))return s;throw new OP(VP(s)+" is not an object")}});var nr=b(gm=>{"use strict";var _P=It(),FP=Sc(),NP=yc(),Vo=Xt(),bm=bc(),UP=TypeError,Tc=Object.defineProperty,qP=Object.getOwnPropertyDescriptor,Ic="enumerable",xc="configurable",Ec="writable";gm.f=_P?NP?function(e,t,i){if(Vo(e),t=bm(t),Vo(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Ec in i&&!i[Ec]){var r=qP(e,t);r&&r[Ec]&&(e[t]=i.value,i={configurable:xc in i?i[xc]:r[xc],enumerable:Ic in i?i[Ic]:r[Ic],writable:!1})}return Tc(e,t,i)}:Tc:function(e,t,i){if(Vo(e),t=bm(t),Vo(i),FP)try{return Tc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new UP("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Br=b((cF,Sm)=>{"use strict";var jP=It(),HP=nr(),GP=da();Sm.exports=jP?function(s,e,t){return HP.f(s,e,GP(1,t))}:function(s,e,t){return s[e]=t,s}});var ke=b((dF,ym)=>{"use strict";var ga=xe(),zP=Xl(),QP=Zl(),WP=Te(),YP=cm().f,KP=vc(),Cr=Lr(),XP=Dr(),Vr=Br(),vm=Ut();ma();var JP=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 zP(s,this,arguments)};return e.prototype=s.prototype,e};ym.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=KP(i?h:t+(r?".":"#")+h,s.forced),d=!l&&n&&vm(n,h),f=o[h],d&&(s.dontCallGetSet?(S=YP(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=XP(p,ga):s.wrap&&d?g=JP(p):a&&WP(p)?g=QP(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&Vr(g,"sham",!0),Vr(o,h,g),a&&(c=t+"Prototype",vm(Cr,c)||Vr(Cr,c,{}),Vr(Cr[c],h,p),s.real&&u&&(l||!u[h])&&Vr(u,h,p)))}});var Im=b((pF,Tm)=>{"use strict";var ZP=Math.ceil,eA=Math.floor;Tm.exports=Math.trunc||function(e){var t=+e;return(t>0?eA:ZP)(t)}});var Sa=b((hF,xm)=>{"use strict";var tA=Im();xm.exports=function(s){var e=+s;return e!==e||e===0?0:tA(e)}});var wm=b((fF,Em)=>{"use strict";var iA=Sa(),rA=Math.max,sA=Math.min;Em.exports=function(s,e){var t=iA(s);return t<0?rA(t+e,0):sA(t,e)}});var wc=b((mF,Pm)=>{"use strict";var aA=Sa(),nA=Math.min;Pm.exports=function(s){var e=aA(s);return e>0?nA(e,9007199254740991):0}});var Or=b((bF,Am)=>{"use strict";var oA=wc();Am.exports=function(s){return oA(s.length)}});var Pc=b((gF,Rm)=>{"use strict";var uA=sr(),lA=wm(),cA=Or(),km=function(s){return function(e,t,i){var r=uA(e),a=cA(r);if(a===0)return!s&&-1;var n=lA(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}};Rm.exports={includes:km(!0),indexOf:km(!1)}});var va=b((SF,Lm)=>{"use strict";Lm.exports=function(){}});var Mm=b(()=>{"use strict";var dA=ke(),pA=Pc().includes,hA=qe(),fA=va(),mA=hA(function(){return!Array(1).includes()});dA({target:"Array",proto:!0,forced:mA},{includes:function(e){return pA(this,e,arguments.length>1?arguments[1]:void 0)}});fA("includes")});var Vi=b((TF,$m)=>{"use strict";var bA=Si();$m.exports=bA});var Bm=b((IF,Dm)=>{"use strict";Mm();var gA=Vi();Dm.exports=gA("Array","includes")});var Vm=b((xF,Cm)=>{"use strict";var SA=Bm();Cm.exports=SA});var wt=b((EF,Om)=>{"use strict";var vA=Vm();Om.exports=vA});var Fo=b((VF,Gm)=>{"use strict";var AA=hc(),kA=fc(),Hm=AA("keys");Gm.exports=function(s){return Hm[s]||(Hm[s]=kA(s))}});var Qm=b((OF,zm)=>{"use strict";var RA=qe();zm.exports=!RA(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var No=b((_F,Ym)=>{"use strict";var LA=Ut(),MA=Te(),$A=Mr(),DA=Fo(),BA=Qm(),Wm=DA("IE_PROTO"),Rc=Object,CA=Rc.prototype;Ym.exports=BA?Rc.getPrototypeOf:function(s){var e=$A(s);if(LA(e,Wm))return e[Wm];var t=e.constructor;return MA(t)&&e instanceof t?t.prototype:e instanceof Rc?CA:null}});var Uo=b((FF,Km)=>{"use strict";Km.exports={}});var Zm=b((NF,Jm)=>{"use strict";var VA=Ve(),Lc=Ut(),OA=sr(),_A=Pc().indexOf,FA=Uo(),Xm=VA([].push);Jm.exports=function(s,e){var t=OA(s),i=0,r=[],a;for(a in t)!Lc(FA,a)&&Lc(t,a)&&Xm(r,a);for(;e.length>i;)Lc(t,a=e[i++])&&(~_A(r,a)||Xm(r,a));return r}});var Mc=b((UF,eb)=>{"use strict";eb.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var $c=b((qF,tb)=>{"use strict";var NA=Zm(),UA=Mc();tb.exports=Object.keys||function(e){return NA(e,UA)}});var Dc=b((jF,nb)=>{"use strict";var rb=It(),qA=qe(),sb=Ve(),jA=No(),HA=$c(),GA=sr(),zA=tc().f,ab=sb(zA),QA=sb([].push),WA=rb&&qA(function(){var s=Object.create(null);return s[2]=2,!ab(s,2)}),ib=function(s){return function(e){for(var t=GA(e),i=HA(t),r=WA&&jA(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!rb||(r?u in t:ab(t,u)))&&QA(o,s?[u,t[u]]:t[u]);return o}};nb.exports={entries:ib(!0),values:ib(!1)}});var ob=b(()=>{"use strict";var YA=ke(),KA=Dc().entries;YA({target:"Object",stat:!0},{entries:function(e){return KA(e)}})});var lb=b((zF,ub)=>{"use strict";ob();var XA=Lr();ub.exports=XA.Object.entries});var db=b((QF,cb)=>{"use strict";var JA=lb();cb.exports=JA});var or=b((WF,pb)=>{"use strict";var ZA=db();pb.exports=ZA});var ur=b((YF,hb)=>{"use strict";hb.exports={}});var bb=b((KF,mb)=>{"use strict";var ek=xe(),tk=Te(),fb=ek.WeakMap;mb.exports=tk(fb)&&/native code/.test(String(fb))});var Oc=b((XF,vb)=>{"use strict";var ik=bb(),Sb=xe(),rk=Et(),sk=Br(),Bc=Ut(),Cc=ma(),ak=Fo(),nk=Uo(),gb="Object already initialized",Vc=Sb.TypeError,ok=Sb.WeakMap,qo,ya,jo,uk=function(s){return jo(s)?ya(s):qo(s,{})},lk=function(s){return function(e){var t;if(!rk(e)||(t=ya(e)).type!==s)throw new Vc("Incompatible receiver, "+s+" required");return t}};ik||Cc.state?(qt=Cc.state||(Cc.state=new ok),qt.get=qt.get,qt.has=qt.has,qt.set=qt.set,qo=function(s,e){if(qt.has(s))throw new Vc(gb);return e.facade=s,qt.set(s,e),e},ya=function(s){return qt.get(s)||{}},jo=function(s){return qt.has(s)}):(lr=ak("state"),nk[lr]=!0,qo=function(s,e){if(Bc(s,lr))throw new Vc(gb);return e.facade=s,sk(s,lr,e),e},ya=function(s){return Bc(s,lr)?s[lr]:{}},jo=function(s){return Bc(s,lr)});var qt,lr;vb.exports={set:qo,get:ya,has:jo,enforce:uk,getterFor:lk}});var Nc=b((JF,Tb)=>{"use strict";var _c=It(),ck=Ut(),yb=Function.prototype,dk=_c&&Object.getOwnPropertyDescriptor,Fc=ck(yb,"name"),pk=Fc&&function(){}.name==="something",hk=Fc&&(!_c||_c&&dk(yb,"name").configurable);Tb.exports={EXISTS:Fc,PROPER:pk,CONFIGURABLE:hk}});var xb=b(Ib=>{"use strict";var fk=It(),mk=yc(),bk=nr(),gk=Xt(),Sk=sr(),vk=$c();Ib.f=fk&&!mk?Object.defineProperties:function(e,t){gk(e);for(var i=Sk(t),r=vk(t),a=r.length,n=0,o;a>n;)bk.f(e,o=r[n++],i[o]);return e}});var Uc=b((eN,Eb)=>{"use strict";var yk=Si();Eb.exports=yk("document","documentElement")});var Gc=b((tN,Mb)=>{"use strict";var Tk=Xt(),Ik=xb(),wb=Mc(),xk=Uo(),Ek=Uc(),wk=Co(),Pk=Fo(),Pb=">",Ab="<",jc="prototype",Hc="script",Rb=Pk("IE_PROTO"),qc=function(){},Lb=function(s){return Ab+Hc+Pb+s+Ab+"/"+Hc+Pb},kb=function(s){s.write(Lb("")),s.close();var e=s.parentWindow.Object;return s=null,e},Ak=function(){var s=wk("iframe"),e="java"+Hc+":",t;return s.style.display="none",Ek.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Lb("document.F=Object")),t.close(),t.F},Ho,Go=function(){try{Ho=new ActiveXObject("htmlfile")}catch(e){}Go=typeof document!="undefined"?document.domain&&Ho?kb(Ho):Ak():kb(Ho);for(var s=wb.length;s--;)delete Go[jc][wb[s]];return Go()};xk[Rb]=!0;Mb.exports=Object.create||function(e,t){var i;return e!==null?(qc[jc]=Tk(e),i=new qc,qc[jc]=null,i[Rb]=e):i=Go(),t===void 0?i:Ik.f(i,t)}});var _r=b((iN,$b)=>{"use strict";var kk=Br();$b.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:kk(s,e,t),s}});var Yc=b((rN,Cb)=>{"use strict";var Rk=qe(),Lk=Te(),Mk=Et(),$k=Gc(),Db=No(),Dk=_r(),Bk=je(),Ck=Nt(),Wc=Bk("iterator"),Bb=!1,vi,zc,Qc;[].keys&&(Qc=[].keys(),"next"in Qc?(zc=Db(Db(Qc)),zc!==Object.prototype&&(vi=zc)):Bb=!0);var Vk=!Mk(vi)||Rk(function(){var s={};return vi[Wc].call(s)!==s});Vk?vi={}:Ck&&(vi=$k(vi));Lk(vi[Wc])||Dk(vi,Wc,function(){return this});Cb.exports={IteratorPrototype:vi,BUGGY_SAFARI_ITERATORS:Bb}});var zo=b((sN,Ob)=>{"use strict";var Ok=je(),_k=Ok("toStringTag"),Vb={};Vb[_k]="z";Ob.exports=String(Vb)==="[object z]"});var Ta=b((aN,_b)=>{"use strict";var Fk=zo(),Nk=Te(),Qo=rr(),Uk=je(),qk=Uk("toStringTag"),jk=Object,Hk=Qo(function(){return arguments}())==="Arguments",Gk=function(s,e){try{return s[e]}catch(t){}};_b.exports=Fk?Qo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Gk(e=jk(s),qk))=="string"?t:Hk?Qo(e):(i=Qo(e))==="Object"&&Nk(e.callee)?"Arguments":i}});var Nb=b((nN,Fb)=>{"use strict";var zk=zo(),Qk=Ta();Fb.exports=zk?{}.toString:function(){return"[object "+Qk(this)+"]"}});var Ia=b((oN,qb)=>{"use strict";var Wk=zo(),Yk=nr().f,Kk=Br(),Xk=Ut(),Jk=Nb(),Zk=je(),Ub=Zk("toStringTag");qb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(Xk(r,Ub)||Yk(r,Ub,{configurable:!0,value:e}),i&&!Wk&&Kk(r,"toString",Jk))}});var Hb=b((uN,jb)=>{"use strict";var eR=Yc().IteratorPrototype,tR=Gc(),iR=da(),rR=Ia(),sR=ur(),aR=function(){return this};jb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=tR(eR,{next:iR(+!i,t)}),rR(s,r,!1,!0),sR[r]=aR,s}});var zb=b((lN,Gb)=>{"use strict";var nR=Ve(),oR=Kt();Gb.exports=function(s,e,t){try{return nR(oR(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Wb=b((cN,Qb)=>{"use strict";var uR=Et();Qb.exports=function(s){return uR(s)||s===null}});var Kb=b((dN,Yb)=>{"use strict";var lR=Wb(),cR=String,dR=TypeError;Yb.exports=function(s){if(lR(s))return s;throw new dR("Can't set "+cR(s)+" as a prototype")}});var Kc=b((pN,Xb)=>{"use strict";var pR=zb(),hR=Et(),fR=Ci(),mR=Kb();Xb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=pR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return fR(r),mR(a),hR(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var ug=b((hN,og)=>{"use strict";var bR=ke(),gR=xt(),Wo=Nt(),ag=Nc(),SR=Te(),vR=Hb(),Jb=No(),Zb=Kc(),yR=Ia(),TR=Br(),Xc=_r(),IR=je(),eg=ur(),ng=Yc(),xR=ag.PROPER,ER=ag.CONFIGURABLE,tg=ng.IteratorPrototype,Yo=ng.BUGGY_SAFARI_ITERATORS,xa=IR("iterator"),ig="keys",Ea="values",rg="entries",sg=function(){return this};og.exports=function(s,e,t,i,r,a,n){vR(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 ig:return function(){return new t(this,S)};case Ea:return function(){return new t(this,S)};case rg: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=Jb(p.call(new s)),f!==Object.prototype&&f.next&&(!Wo&&Jb(f)!==tg&&(Zb?Zb(f,tg):SR(f[xa])||Xc(f,xa,sg)),yR(f,u,!0,!0),Wo&&(eg[u]=sg))),xR&&r===Ea&&c&&c.name!==Ea&&(!Wo&&ER?TR(d,"name",Ea):(l=!0,h=function(){return gR(c,this)})),r)if(m={values:o(Ea),keys:a?h:o(ig),entries:o(rg)},n)for(g in m)(Yo||l||!(g in d))&&Xc(d,g,m[g]);else bR({target:e,proto:!0,forced:Yo||l},m);return(!Wo||n)&&d[xa]!==h&&Xc(d,xa,h,{name:r}),eg[e]=h,m}});var cg=b((fN,lg)=>{"use strict";lg.exports=function(s,e){return{value:s,done:e}}});var Zc=b((mN,mg)=>{"use strict";var wR=sr(),Jc=va(),dg=ur(),hg=Oc(),PR=nr().f,AR=ug(),Ko=cg(),kR=Nt(),RR=It(),fg="Array Iterator",LR=hg.set,MR=hg.getterFor(fg);mg.exports=AR(Array,"Array",function(s,e){LR(this,{type:fg,target:wR(s),index:0,kind:e})},function(){var s=MR(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 pg=dg.Arguments=dg.Array;Jc("keys");Jc("values");Jc("entries");if(!kR&&RR&&pg.name!=="values")try{PR(pg,"name",{value:"values"})}catch(s){}});var gg=b((bN,bg)=>{"use strict";var $R=je(),DR=ur(),BR=$R("iterator"),CR=Array.prototype;bg.exports=function(s){return s!==void 0&&(DR.Array===s||CR[BR]===s)}});var ed=b((gN,vg)=>{"use strict";var VR=Ta(),Sg=fa(),OR=Rr(),_R=ur(),FR=je(),NR=FR("iterator");vg.exports=function(s){if(!OR(s))return Sg(s,NR)||Sg(s,"@@iterator")||_R[VR(s)]}});var Tg=b((SN,yg)=>{"use strict";var UR=xt(),qR=Kt(),jR=Xt(),HR=ha(),GR=ed(),zR=TypeError;yg.exports=function(s,e){var t=arguments.length<2?GR(s):e;if(qR(t))return jR(UR(t,s));throw new zR(HR(s)+" is not iterable")}});var Eg=b((vN,xg)=>{"use strict";var QR=xt(),Ig=Xt(),WR=fa();xg.exports=function(s,e,t){var i,r;Ig(s);try{if(i=WR(s,"return"),!i){if(e==="throw")throw t;return t}i=QR(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Ig(i),t}});var Jo=b((yN,kg)=>{"use strict";var YR=Dr(),KR=xt(),XR=Xt(),JR=ha(),ZR=gg(),eL=Or(),wg=pa(),tL=Tg(),iL=ed(),Pg=Eg(),rL=TypeError,Xo=function(s,e){this.stopped=s,this.result=e},Ag=Xo.prototype;kg.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=YR(e,i),l,d,c,h,p,f,m,g=function(v){return l&&Pg(l,"normal",v),new Xo(!0,v)},S=function(v){return r?(XR(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=iL(s),!d)throw new rL(JR(s)+" is not iterable");if(ZR(d)){for(c=0,h=eL(s);h>c;c++)if(p=S(s[c]),p&&wg(Ag,p))return p;return new Xo(!1)}l=tL(s,d)}for(f=a?s.next:l.next;!(m=KR(f,l)).done;){try{p=S(m.value)}catch(v){Pg(l,"throw",v)}if(typeof p=="object"&&p&&wg(Ag,p))return p}return new Xo(!1)}});var Lg=b((TN,Rg)=>{"use strict";var sL=It(),aL=nr(),nL=da();Rg.exports=function(s,e,t){sL?aL.f(s,e,nL(0,t)):s[e]=t}});var Mg=b(()=>{"use strict";var oL=ke(),uL=Jo(),lL=Lg();oL({target:"Object",stat:!0},{fromEntries:function(e){var t={};return uL(e,function(i,r){lL(t,i,r)},{AS_ENTRIES:!0}),t}})});var Dg=b((EN,$g)=>{"use strict";Zc();Mg();var cL=Lr();$g.exports=cL.Object.fromEntries});var Cg=b((wN,Bg)=>{"use strict";Bg.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 Og=b(()=>{"use strict";Zc();var dL=Cg(),pL=xe(),hL=Ia(),Vg=ur();for(Zo in dL)hL(pL[Zo],Zo),Vg[Zo]=Vg.Array;var Zo});var Fg=b((kN,_g)=>{"use strict";var fL=Dg();Og();_g.exports=fL});var td=b((RN,Ng)=>{"use strict";var mL=Fg();Ng.exports=mL});var Ug=b(()=>{"use strict"});var id=b(($N,qg)=>{"use strict";var wa=xe(),bL=ar(),gL=rr(),eu=function(s){return bL.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":gL(wa.process)==="process"?"NODE":wa.window&&wa.document?"BROWSER":"REST"}()});var tu=b((DN,jg)=>{"use strict";var SL=id();jg.exports=SL==="NODE"});var Gg=b((BN,Hg)=>{"use strict";var vL=nr();Hg.exports=function(s,e,t){return vL.f(s,e,t)}});var Wg=b((CN,Qg)=>{"use strict";var yL=Si(),TL=Gg(),IL=je(),xL=It(),zg=IL("species");Qg.exports=function(s){var e=yL(s);xL&&e&&!e[zg]&&TL(e,zg,{configurable:!0,get:function(){return this}})}});var Kg=b((VN,Yg)=>{"use strict";var EL=pa(),wL=TypeError;Yg.exports=function(s,e){if(EL(e,s))return s;throw new wL("Incorrect invocation")}});var sd=b((ON,Xg)=>{"use strict";var PL=Ve(),AL=Te(),rd=ma(),kL=PL(Function.toString);AL(rd.inspectSource)||(rd.inspectSource=function(s){return kL(s)});Xg.exports=rd.inspectSource});var nd=b((_N,iS)=>{"use strict";var RL=Ve(),LL=qe(),Jg=Te(),ML=Ta(),$L=Si(),DL=sd(),Zg=function(){},eS=$L("Reflect","construct"),ad=/^\s*(?:class|function)\b/,BL=RL(ad.exec),CL=!ad.test(Zg),Pa=function(e){if(!Jg(e))return!1;try{return eS(Zg,[],e),!0}catch(t){return!1}},tS=function(e){if(!Jg(e))return!1;switch(ML(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return CL||!!BL(ad,DL(e))}catch(t){return!0}};tS.sham=!0;iS.exports=!eS||LL(function(){var s;return Pa(Pa.call)||!Pa(Object)||!Pa(function(){s=!0})||s})?tS:Pa});var sS=b((FN,rS)=>{"use strict";var VL=nd(),OL=ha(),_L=TypeError;rS.exports=function(s){if(VL(s))return s;throw new _L(OL(s)+" is not a constructor")}});var od=b((NN,nS)=>{"use strict";var aS=Xt(),FL=sS(),NL=Rr(),UL=je(),qL=UL("species");nS.exports=function(s,e){var t=aS(s).constructor,i;return t===void 0||NL(i=aS(t)[qL])?e:FL(i)}});var uS=b((UN,oS)=>{"use strict";var jL=Ve();oS.exports=jL([].slice)});var cS=b((qN,lS)=>{"use strict";var HL=TypeError;lS.exports=function(s,e){if(s<e)throw new HL("Not enough arguments");return s}});var ud=b((jN,dS)=>{"use strict";var GL=ar();dS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(GL)});var gd=b((HN,yS)=>{"use strict";var Pt=xe(),zL=Xl(),QL=Dr(),pS=Te(),WL=Ut(),vS=qe(),hS=Uc(),YL=uS(),fS=Co(),KL=cS(),XL=ud(),JL=tu(),fd=Pt.setImmediate,md=Pt.clearImmediate,ZL=Pt.process,ld=Pt.Dispatch,eM=Pt.Function,mS=Pt.MessageChannel,tM=Pt.String,cd=0,Aa={},bS="onreadystatechange",ka,cr,dd,pd;vS(function(){ka=Pt.location});var bd=function(s){if(WL(Aa,s)){var e=Aa[s];delete Aa[s],e()}},hd=function(s){return function(){bd(s)}},gS=function(s){bd(s.data)},SS=function(s){Pt.postMessage(tM(s),ka.protocol+"//"+ka.host)};(!fd||!md)&&(fd=function(e){KL(arguments.length,1);var t=pS(e)?e:eM(e),i=YL(arguments,1);return Aa[++cd]=function(){zL(t,void 0,i)},cr(cd),cd},md=function(e){delete Aa[e]},JL?cr=function(s){ZL.nextTick(hd(s))}:ld&&ld.now?cr=function(s){ld.now(hd(s))}:mS&&!XL?(dd=new mS,pd=dd.port2,dd.port1.onmessage=gS,cr=QL(pd.postMessage,pd)):Pt.addEventListener&&pS(Pt.postMessage)&&!Pt.importScripts&&ka&&ka.protocol!=="file:"&&!vS(SS)?(cr=SS,Pt.addEventListener("message",gS,!1)):bS in fS("script")?cr=function(s){hS.appendChild(fS("script"))[bS]=function(){hS.removeChild(this),bd(s)}}:cr=function(s){setTimeout(hd(s),0)});yS.exports={set:fd,clear:md}});var xS=b((GN,IS)=>{"use strict";var TS=xe(),iM=It(),rM=Object.getOwnPropertyDescriptor;IS.exports=function(s){if(!iM)return TS[s];var e=rM(TS,s);return e&&e.value}});var Sd=b((zN,wS)=>{"use strict";var ES=function(){this.head=null,this.tail=null};ES.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}}};wS.exports=ES});var AS=b((QN,PS)=>{"use strict";var sM=ar();PS.exports=/ipad|iphone|ipod/i.test(sM)&&typeof Pebble!="undefined"});var RS=b((WN,kS)=>{"use strict";var aM=ar();kS.exports=/web0s(?!.*chrome)/i.test(aM)});var VS=b((YN,CS)=>{"use strict";var Nr=xe(),nM=xS(),LS=Dr(),vd=gd().set,oM=Sd(),uM=ud(),lM=AS(),cM=RS(),yd=tu(),MS=Nr.MutationObserver||Nr.WebKitMutationObserver,$S=Nr.document,DS=Nr.process,iu=Nr.Promise,xd=nM("queueMicrotask"),Fr,Td,Id,ru,BS;xd||(Ra=new oM,La=function(){var s,e;for(yd&&(s=DS.domain)&&s.exit();e=Ra.get();)try{e()}catch(t){throw Ra.head&&Fr(),t}s&&s.enter()},!uM&&!yd&&!cM&&MS&&$S?(Td=!0,Id=$S.createTextNode(""),new MS(La).observe(Id,{characterData:!0}),Fr=function(){Id.data=Td=!Td}):!lM&&iu&&iu.resolve?(ru=iu.resolve(void 0),ru.constructor=iu,BS=LS(ru.then,ru),Fr=function(){BS(La)}):yd?Fr=function(){DS.nextTick(La)}:(vd=LS(vd,Nr),Fr=function(){vd(La)}),xd=function(s){Ra.head||Fr(),Ra.add(s)});var Ra,La;CS.exports=xd});var _S=b((KN,OS)=>{"use strict";OS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var su=b((XN,FS)=>{"use strict";FS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var dr=b((JN,NS)=>{"use strict";var dM=xe();NS.exports=dM.Promise});var Ur=b((ZN,HS)=>{"use strict";var pM=xe(),Ma=dr(),hM=Te(),fM=vc(),mM=sd(),bM=je(),US=id(),gM=Nt(),Ed=nc(),qS=Ma&&Ma.prototype,SM=bM("species"),wd=!1,jS=hM(pM.PromiseRejectionEvent),vM=fM("Promise",function(){var s=mM(Ma),e=s!==String(Ma);if(!e&&Ed===66||gM&&!(qS.catch&&qS.finally))return!0;if(!Ed||Ed<51||!/native code/.test(s)){var t=new Ma(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[SM]=i,wd=t.then(function(){})instanceof i,!wd)return!0}return!e&&(US==="BROWSER"||US==="DENO")&&!jS});HS.exports={CONSTRUCTOR:vM,REJECTION_EVENT:jS,SUBCLASSING:wd}});var qr=b((eU,zS)=>{"use strict";var GS=Kt(),yM=TypeError,TM=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new yM("Bad Promise constructor");e=i,t=r}),this.resolve=GS(e),this.reject=GS(t)};zS.exports.f=function(s){return new TM(s)}});var dv=b(()=>{"use strict";var IM=ke(),xM=Nt(),uu=tu(),Oi=xe(),zr=xt(),QS=_r(),WS=Kc(),EM=Ia(),wM=Wg(),PM=Kt(),ou=Te(),AM=Et(),kM=Kg(),RM=od(),ZS=gd().set,Ld=VS(),LM=_S(),MM=su(),$M=Sd(),ev=Oc(),lu=dr(),Md=Ur(),tv=qr(),cu="Promise",iv=Md.CONSTRUCTOR,DM=Md.REJECTION_EVENT,BM=Md.SUBCLASSING,Pd=ev.getterFor(cu),CM=ev.set,jr=lu&&lu.prototype,pr=lu,au=jr,rv=Oi.TypeError,Ad=Oi.document,$d=Oi.process,kd=tv.f,VM=kd,OM=!!(Ad&&Ad.createEvent&&Oi.dispatchEvent),sv="unhandledrejection",_M="rejectionhandled",YS=0,av=1,FM=2,Dd=1,nv=2,nu,KS,NM,XS,ov=function(s){var e;return AM(s)&&ou(e=s.then)?e:!1},uv=function(s,e){var t=e.value,i=e.state===av,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===nv&&qM(e),e.rejection=Dd),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new rv("Promise-chain cycle")):(l=ov(u))?zr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},lv=function(s,e){s.notified||(s.notified=!0,Ld(function(){for(var t=s.reactions,i;i=t.get();)uv(i,s);s.notified=!1,e&&!s.rejection&&UM(s)}))},cv=function(s,e,t){var i,r;OM?(i=Ad.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Oi.dispatchEvent(i)):i={promise:e,reason:t},!DM&&(r=Oi["on"+s])?r(i):s===sv&&LM("Unhandled promise rejection",t)},UM=function(s){zr(ZS,Oi,function(){var e=s.facade,t=s.value,i=JS(s),r;if(i&&(r=MM(function(){uu?$d.emit("unhandledRejection",t,e):cv(sv,e,t)}),s.rejection=uu||JS(s)?nv:Dd,r.error))throw r.value})},JS=function(s){return s.rejection!==Dd&&!s.parent},qM=function(s){zr(ZS,Oi,function(){var e=s.facade;uu?$d.emit("rejectionHandled",e):cv(_M,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=FM,lv(s,!0))},Rd=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new rv("Promise can't be resolved itself");var i=ov(e);i?Ld(function(){var r={done:!1};try{zr(i,e,Hr(Rd,r,s),Hr(Gr,r,s))}catch(a){Gr(r,a,s)}}):(s.value=e,s.state=av,lv(s,!1))}catch(r){Gr({done:!1},r,s)}}};if(iv&&(pr=function(e){kM(this,au),PM(e),zr(nu,this);var t=Pd(this);try{e(Hr(Rd,t),Hr(Gr,t))}catch(i){Gr(t,i)}},au=pr.prototype,nu=function(e){CM(this,{type:cu,done:!1,notified:!1,parent:!1,reactions:new $M,rejection:!1,state:YS,value:void 0})},nu.prototype=QS(au,"then",function(e,t){var i=Pd(this),r=kd(RM(this,pr));return i.parent=!0,r.ok=ou(e)?e:!0,r.fail=ou(t)&&t,r.domain=uu?$d.domain:void 0,i.state===YS?i.reactions.add(r):Ld(function(){uv(r,i)}),r.promise}),KS=function(){var s=new nu,e=Pd(s);this.promise=s,this.resolve=Hr(Rd,e),this.reject=Hr(Gr,e)},tv.f=kd=function(s){return s===pr||s===NM?new KS(s):VM(s)},!xM&&ou(lu)&&jr!==Object.prototype)){XS=jr.then,BM||QS(jr,"then",function(e,t){var i=this;return new pr(function(r,a){zr(XS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete jr.constructor}catch(s){}WS&&WS(jr,au)}IM({global:!0,constructor:!0,wrap:!0,forced:iv},{Promise:pr});EM(pr,cu,!1,!0);wM(cu)});var bv=b((rU,mv)=>{"use strict";var jM=je(),hv=jM("iterator"),fv=!1;try{pv=0,Bd={next:function(){return{done:!!pv++}},return:function(){fv=!0}},Bd[hv]=function(){return this},Array.from(Bd,function(){throw 2})}catch(s){}var pv,Bd;mv.exports=function(s,e){try{if(!e&&!fv)return!1}catch(r){return!1}var t=!1;try{var i={};i[hv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Cd=b((sU,gv)=>{"use strict";var HM=dr(),GM=bv(),zM=Ur().CONSTRUCTOR;gv.exports=zM||!GM(function(s){HM.all(s).then(void 0,function(){})})});var Sv=b(()=>{"use strict";var QM=ke(),WM=xt(),YM=Kt(),KM=qr(),XM=su(),JM=Jo(),ZM=Cd();QM({target:"Promise",stat:!0,forced:ZM},{all:function(e){var t=this,i=KM.f(t),r=i.resolve,a=i.reject,n=XM(function(){var o=YM(t.resolve),u=[],l=0,d=1;JM(e,function(c){var h=l++,p=!1;d++,WM(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 yv=b(()=>{"use strict";var e$=ke(),t$=Nt(),i$=Ur().CONSTRUCTOR,Od=dr(),r$=Si(),s$=Te(),a$=_r(),vv=Od&&Od.prototype;e$({target:"Promise",proto:!0,forced:i$,real:!0},{catch:function(s){return this.then(void 0,s)}});!t$&&s$(Od)&&(Vd=r$("Promise").prototype.catch,vv.catch!==Vd&&a$(vv,"catch",Vd,{unsafe:!0}));var Vd});var Tv=b(()=>{"use strict";var n$=ke(),o$=xt(),u$=Kt(),l$=qr(),c$=su(),d$=Jo(),p$=Cd();n$({target:"Promise",stat:!0,forced:p$},{race:function(e){var t=this,i=l$.f(t),r=i.reject,a=c$(function(){var n=u$(t.resolve);d$(e,function(o){o$(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var Iv=b(()=>{"use strict";var h$=ke(),f$=qr(),m$=Ur().CONSTRUCTOR;h$({target:"Promise",stat:!0,forced:m$},{reject:function(e){var t=f$.f(this),i=t.reject;return i(e),t.promise}})});var _d=b((hU,xv)=>{"use strict";var b$=Xt(),g$=Et(),S$=qr();xv.exports=function(s,e){if(b$(s),g$(e)&&e.constructor===s)return e;var t=S$.f(s),i=t.resolve;return i(e),t.promise}});var Pv=b(()=>{"use strict";var v$=ke(),y$=Si(),Ev=Nt(),T$=dr(),wv=Ur().CONSTRUCTOR,I$=_d(),x$=y$("Promise"),E$=Ev&&!wv;v$({target:"Promise",stat:!0,forced:Ev||wv},{resolve:function(e){return I$(E$&&this===x$?T$:this,e)}})});var Av=b(()=>{"use strict";dv();Sv();yv();Tv();Iv();Pv()});var Mv=b(()=>{"use strict";var w$=ke(),P$=Nt(),du=dr(),A$=qe(),Rv=Si(),Lv=Te(),k$=od(),kv=_d(),R$=_r(),Nd=du&&du.prototype,L$=!!du&&A$(function(){Nd.finally.call({then:function(){}},function(){})});w$({target:"Promise",proto:!0,real:!0,forced:L$},{finally:function(s){var e=k$(this,Rv("Promise")),t=Lv(s);return this.then(t?function(i){return kv(e,s()).then(function(){return i})}:s,t?function(i){return kv(e,s()).then(function(){throw i})}:s)}});!P$&&Lv(du)&&(Fd=Rv("Promise").prototype.finally,Nd.finally!==Fd&&R$(Nd,"finally",Fd,{unsafe:!0}));var Fd});var Dv=b((yU,$v)=>{"use strict";Ug();Av();Mv();var M$=Vi();$v.exports=M$("Promise","finally")});var Cv=b((TU,Bv)=>{"use strict";var $$=Dv();Bv.exports=$$});var $a=b((IU,Vv)=>{"use strict";var D$=Cv();Vv.exports=D$});var Yv=b(()=>{"use strict";var Q$=ke(),W$=Dc().values;Q$({target:"Object",stat:!0},{values:function(e){return W$(e)}})});var Xv=b((n1,Kv)=>{"use strict";Yv();var Y$=Lr();Kv.exports=Y$.Object.values});var Zv=b((o1,Jv)=>{"use strict";var K$=Xv();Jv.exports=K$});var mr=b((u1,ey)=>{"use strict";var X$=Zv();ey.exports=X$});var gy=b(()=>{"use strict";var yD=ke(),TD=Mr(),ID=Or(),xD=Sa(),ED=va();yD({target:"Array",proto:!0},{at:function(e){var t=TD(this),i=ID(t),r=xD(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});ED("at")});var vy=b((yq,Sy)=>{"use strict";gy();var wD=Vi();Sy.exports=wD("Array","at")});var Ty=b((Tq,yy)=>{"use strict";var PD=vy();yy.exports=PD});var jt=b((Iq,Iy)=>{"use strict";var AD=Ty();Iy.exports=AD});var lp=b((cH,tT)=>{"use strict";var nB=rr();tT.exports=Array.isArray||function(e){return nB(e)==="Array"}});var rT=b((dH,iT)=>{"use strict";var oB=TypeError,uB=9007199254740991;iT.exports=function(s){if(s>uB)throw oB("Maximum allowed index exceeded");return s}});var nT=b((pH,aT)=>{"use strict";var lB=lp(),cB=Or(),dB=rT(),pB=Dr(),sT=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?pB(n,o):!1,c,h;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&lB(c)?(h=cB(c),u=sT(s,e,c,h,u,a-1)-1):(dB(u+1),s[u]=c),u++),l++;return u};aT.exports=sT});var cT=b((hH,lT)=>{"use strict";var oT=lp(),hB=nd(),fB=Et(),mB=je(),bB=mB("species"),uT=Array;lT.exports=function(s){var e;return oT(s)&&(e=s.constructor,hB(e)&&(e===uT||oT(e.prototype))?e=void 0:fB(e)&&(e=e[bB],e===null&&(e=void 0))),e===void 0?uT:e}});var pT=b((fH,dT)=>{"use strict";var gB=cT();dT.exports=function(s,e){return new(gB(s))(e===0?0:e)}});var hT=b(()=>{"use strict";var SB=ke(),vB=nT(),yB=Kt(),TB=Mr(),IB=Or(),xB=pT();SB({target:"Array",proto:!0},{flatMap:function(e){var t=TB(this),i=IB(t),r;return yB(e),r=xB(t,0),r.length=vB(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var fT=b(()=>{"use strict";var EB=va();EB("flatMap")});var bT=b((vH,mT)=>{"use strict";hT();fT();var wB=Vi();mT.exports=wB("Array","flatMap")});var ST=b((yH,gT)=>{"use strict";var PB=bT();gT.exports=PB});var Wa=b((TH,vT)=>{"use strict";var AB=ST();vT.exports=AB});var Ya=b((IH,yT)=>{"use strict";var kB=Ta(),RB=String;yT.exports=function(s){if(kB(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return RB(s)}});var cp=b((xH,TT)=>{"use strict";TT.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 ET=b((EH,xT)=>{"use strict";var LB=Ve(),MB=Ci(),$B=Ya(),pp=cp(),IT=LB("".replace),DB=RegExp("^["+pp+"]+"),BB=RegExp("(^|[^"+pp+"])["+pp+"]+$"),dp=function(s){return function(e){var t=$B(MB(e));return s&1&&(t=IT(t,DB,"")),s&2&&(t=IT(t,BB,"$1")),t}};xT.exports={start:dp(1),end:dp(2),trim:dp(3)}});var kT=b((wH,AT)=>{"use strict";var CB=Nc().PROPER,VB=qe(),wT=cp(),PT="\u200B\x85\u180E";AT.exports=function(s){return VB(function(){return!!wT[s]()||PT[s]()!==PT||CB&&wT[s].name!==s})}});var hp=b((PH,RT)=>{"use strict";var OB=ET().start,_B=kT();RT.exports=_B("trimStart")?function(){return OB(this)}:"".trimStart});var MT=b(()=>{"use strict";var FB=ke(),LT=hp();FB({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==LT},{trimLeft:LT})});var DT=b(()=>{"use strict";MT();var NB=ke(),$T=hp();NB({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==$T},{trimStart:$T})});var CT=b((MH,BT)=>{"use strict";DT();var UB=Vi();BT.exports=UB("String","trimLeft")});var OT=b(($H,VT)=>{"use strict";var qB=CT();VT.exports=qB});var FT=b((DH,_T)=>{"use strict";var jB=OT();_T.exports=jB});var eI=b(()=>{"use strict"});var tI=b(()=>{"use strict"});var rI=b((bG,iI)=>{"use strict";var p0=Et(),h0=rr(),f0=je(),m0=f0("match");iI.exports=function(s){var e;return p0(s)&&((e=s[m0])!==void 0?!!e:h0(s)==="RegExp")}});var aI=b((gG,sI)=>{"use strict";var b0=Xt();sI.exports=function(){var s=b0(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 uI=b((SG,oI)=>{"use strict";var g0=xt(),S0=Ut(),v0=pa(),y0=aI(),nI=RegExp.prototype;oI.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in nI)&&!S0(s,"flags")&&v0(nI,s)?g0(y0,s):e}});var cI=b((vG,lI)=>{"use strict";var vp=Ve(),T0=Mr(),I0=Math.floor,gp=vp("".charAt),x0=vp("".replace),Sp=vp("".slice),E0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,w0=/\$([$&'`]|\d{1,2})/g;lI.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=w0;return r!==void 0&&(r=T0(r),u=E0),x0(a,u,function(l,d){var c;switch(gp(d,0)){case"$":return"$";case"&":return s;case"`":return Sp(e,0,t);case"'":return Sp(e,n);case"<":c=r[Sp(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var p=I0(h/10);return p===0?l:p<=o?i[p-1]===void 0?gp(d,1):i[p-1]+gp(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var hI=b(()=>{"use strict";var P0=ke(),A0=xt(),Tp=Ve(),dI=Ci(),k0=Te(),R0=Rr(),L0=rI(),ns=Ya(),M0=fa(),$0=uI(),D0=cI(),B0=je(),C0=Nt(),V0=B0("replace"),O0=TypeError,yp=Tp("".indexOf),_0=Tp("".replace),pI=Tp("".slice),F0=Math.max;P0({target:"String",proto:!0},{replaceAll:function(e,t){var i=dI(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!R0(e)){if(r=L0(e),r&&(a=ns(dI($0(e))),!~yp(a,"g")))throw new O0("`.replaceAll` does not allow non-global regexes");if(n=M0(e,V0),n)return A0(n,e,i,t);if(C0&&r)return _0(ns(i),e,t)}for(o=ns(i),u=ns(e),l=k0(t),l||(t=ns(t)),d=u.length,c=F0(1,d),h=yp(o,u);h!==-1;)p=l?ns(t(u,h,o)):D0(u,o,h,[],void 0,t),m+=pI(o,f,h)+p,f=h+d,h=h+c>o.length?-1:yp(o,u,h+c);return f<o.length&&(m+=pI(o,f)),m}})});var mI=b((IG,fI)=>{"use strict";eI();tI();hI();var N0=Vi();fI.exports=N0("String","replaceAll")});var gI=b((xG,bI)=>{"use strict";var U0=mI();bI.exports=U0});var Ip=b((EG,SI)=>{"use strict";var q0=gI();SI.exports=q0});var yI=b((wG,vI)=>{"use strict";var j0=Sa(),H0=Ya(),G0=Ci(),z0=RangeError;vI.exports=function(e){var t=H0(G0(this)),i="",r=j0(e);if(r<0||r===1/0)throw new z0("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var wI=b((PG,EI)=>{"use strict";var xI=Ve(),Q0=wc(),TI=Ya(),W0=yI(),Y0=Ci(),K0=xI(W0),X0=xI("".slice),J0=Math.ceil,II=function(s){return function(e,t,i){var r=TI(Y0(e)),a=Q0(t),n=r.length,o=i===void 0?" ":TI(i),u,l;return a<=n||o===""?r:(u=a-n,l=K0(o,J0(u/o.length)),l.length>u&&(l=X0(l,0,u)),s?r+l:l+r)}};EI.exports={start:II(!1),end:II(!0)}});var AI=b((AG,PI)=>{"use strict";var Z0=ar();PI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Z0)});var kI=b(()=>{"use strict";var eC=ke(),tC=wI().start,iC=AI();eC({target:"String",proto:!0,forced:iC},{padStart:function(e){return tC(this,e,arguments.length>1?arguments[1]:void 0)}})});var LI=b((LG,RI)=>{"use strict";kI();var rC=Vi();RI.exports=rC("String","padStart")});var $I=b((MG,MI)=>{"use strict";var sC=LI();MI.exports=sC});var xp=b(($G,DI)=>{"use strict";var aC=$I();DI.exports=aC});var Hh="2.0.132-beta.0";var ct=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(ct||{}),gi=(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))(gi||{});var Mo=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Mo||{}),Wl=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Wl||{});var Yl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Yl||{}),$o=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))($o||{});var HE=j(wt(),1);import{assertNever as jm,assertNonNullable as yA,isNonNullable as Oo,ValueSubject as Ac,Subject as TA,Subscription as IA,merge as xA,observableFrom as EA,fromEvent as Fm,map as Nm,tap as Um,filterChanged as wA,isNullable as kc,ErrorCategory as qm}from"@vkontakte/videoplayer-shared/es2015";var _m=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 Ac(void 0);this.castState$=new Ac("NOT_AVAILABLE");this.errorEvent$=new TA;this.realCastState$=new Ac("NOT_AVAILABLE");this.subscription=new IA;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||_m("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();kc(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();kc(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(Fm(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 jm(r.sessionState)}})).add(xA(Fm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Um(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Nm(r=>r.castState)),EA([i.getCastState()])).pipe(wA(),Nm(PA),Um(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();yA(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(kc(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})}}},PA=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 jm(s)}};var Dh=j(wt(),1),wE=j(or(),1),PE=j(td(),1);var zv=j($a(),1);import{assertNever as Ov}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:Ov(t)}return s},_i=(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:Ov(e)}};var L=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as B$,Subject as pu,merge as _v}from"@vkontakte/videoplayer-shared/es2015";var z=class{constructor(e){this.transitionStarted$=new pu;this.transitionEnded$=new pu;this.transitionUpdated$=new pu;this.forceChanged$=new pu;this.stateChangeStarted$=_v(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=_v(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||B$(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 C$}from"@vkontakte/videoplayer-shared/es2015";var Fv=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 C$(s)}};import{assertNever as Qr,assertNonNullable as hr,debounce as Nv,ErrorCategory as Uv,fromEvent as fr,isNonNullable as qv,map as jv,merge as Hv,observableFrom as V$,Subject as O$,Subscription as Ud,timeout as _$,getHighestQuality as F$}from"@vkontakte/videoplayer-shared/es2015";var N$=5,U$=5,q$=500,Gv=7e3,Da=class{constructor(e){this.subscription=new Ud;this.loadMediaTimeoutSubscription=new Ud;this.videoState=new z("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(Fv(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 Ud;this.subscription.add(e),this.subscription.add(Hv(this.videoState.stateChangeStarted$.pipe(jv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(jv(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 O$;e.add(r.pipe(Nv(q$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(fr(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)>N$)&&r.next(o),a=o})),e.add(fr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(fr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(fr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(fr(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<U$&&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(fr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(fr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Hv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,V$(["init"])).pipe(Nv(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];hr(d);let c=F$(Object.keys(d));hr(c);let h=d[c];hr(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];hr(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];hr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];hr(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];hr(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:Uv.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(_$(Gv).subscribe(()=>a(`timeout(${Gv})`)))});(0,zv.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Uv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var op=j(wt(),1);import{clearVideoElement as Wv}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as j$}from"@vkontakte/videoplayer-shared/es2015";var Qv=s=>{try{s.pause(),s.playbackRate=0,j$(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as H$,Subscription as G$}from"@vkontakte/videoplayer-shared/es2015";var qd=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)}},jd=window.WeakMap?new WeakMap:new qd,Hd=window.WeakMap?new WeakMap:new Map,z$=(s,e=20)=>{let t=0;return H$(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?Wv(i):(i=document.createElement("video"),s.appendChild(i)),jd.set(i,r);let a=new G$;return a.add(z$(i,e)),Hd.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=Hd.get(s);e==null||e.unsubscribe(),Hd.delete(s);let t=jd.get(s);jd.delete(s),t?Wv(s):Qv(s)};var zd=j(mr(),1);import{assertNonNullable as Ba,isNonNullable as Zt,isNullable as eD,fromEvent as Wr,merge as ty,observableFrom as iy,filterChanged as ry,map as Ca,Subject as sy,Subscription as tD,ValueSubject as iD,ErrorCategory as rD}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Gd,isNullable as J$,Subscription as Z$}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=J$(r),l=new Z$;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=>{Gd(i)&&(s.loop=i)},{onError:t}),ze=(s,e,t,i)=>hu(e,()=>({muted:s.muted,volume:s.volume}),r=>{Gd(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)=>hu(e,()=>s.playbackRate,r=>{Gd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Fi=hu;var sD=s=>["__",s.language,s.label].join("|"),aD=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Qd=class s{constructor(e){this.available$=new sy;this.current$=new iD(void 0);this.error$=new sy;this.subscription=new tD;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:rD.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(Fi(t.internalTextTracks,()=>(0,zd.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(Fi(t.externalTextTracks,()=>(0,zd.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(Fi(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(Fi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Ba(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(ty(Wr(e,"addtrack"),Wr(e,"removetrack"),iy(["init"])).pipe(Ca(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ry((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(ty(Wr(e,"change"),iy(["init"])).pipe(Ca(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ca(i=>i&&this.htmlTextTrackToITextTrack(i).id),ry()).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){Ba(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:sD(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){Ba(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(eD(e)||!aD(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){Ba(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){Ba(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=Qd;var br=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 ay=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},Wd=s=>{let e=ay(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},ny=s=>{let e=ay(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as at,map as yi,merge as yu,filterChanged as fD,isNonNullable as fy,Subject as mD,filter as Kd,mapTo as Xd,combine as my,once as bD,throttle as gD,ErrorCategory as SD,ValueSubject as by,Subscription as vD}from"@vkontakte/videoplayer-shared/es2015";var nD=3,oy=(s,e,t=nD)=>{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{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}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._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 uy=j(wt(),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,uy.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 At=()=>window.ManagedMediaSource||window.MediaSource,Yr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},ly=()=>{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 oD=document.createElement("video"),uD='video/mp4; codecs="avc1.42000a,mp4a.40.2"',lD='video/mp4; codecs="hev1.1.6.L93.B0"',cy='video/webm; codecs="vp09.00.10.08"',dy='video/webm; codecs="av01.0.00M.08"',cD='audio/mp4; codecs="mp4a.40.2"',dD='audio/webm; codecs="opus"',py,pD=()=>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(D(E({},s),{video:D(E({},s.video),{contentType:dy})})),window.navigator.mediaCapabilities.decodingInfo(D(E({},s),{video:D(E({},s.video),{contentType:cy})}))]);py={DASH_WEBM_AV1:e,DASH_WEBM:t}});pD().catch(s=>{console.log(oD),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 py}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:ly(),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,uD)),k=!!((h=(c=At())==null?void 0:c.isTypeSupported)!=null&&h.call(c,lD)),C=!!((f=(p=At())==null?void 0:p.isTypeSupported)!=null&&f.call(p,cD));this._codecs={h264:I,h265:k,vp9:!!((g=(m=At())==null?void 0:m.isTypeSupported)!=null&&g.call(m,cy)),av1:!!((v=(S=At())==null?void 0:S.isTypeSupported)!=null&&v.call(S,dy)),aac:C,opus:!!((T=(y=At())==null?void 0:y.isTypeSupported)!=null&&T.call(y,dD)),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 hy="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,hy))},this._codecs={mp3:!!((r=(i=At())==null?void 0:i.isTypeSupported)!=null&&r.call(i,hy))}}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 hD}from"@vkontakte/videoplayer-shared/es2015";var Yd=class{constructor(){this.isInited$=new hD(!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 Yd;var Qe=s=>{let e=A=>at(s,A).pipe(Xd(void 0)),t=new vD,i=()=>t.unsubscribe(),r=yu(at(s,"progress"),at(s,"timeupdate")).pipe(yi(()=>oy(s.buffered,s.currentTime))),a=G.browser.isSafari?my({play:e("play").pipe(bD()),playing:e("playing")}).pipe(Xd(void 0)):e("playing"),n=at(s,"volumechange").pipe(yi(()=>({muted:s.muted,volume:s.volume}))),o=at(s,"ratechange").pipe(yi(()=>s.playbackRate)),u=at(s,"error").pipe(Kd(()=>!!(s.error||s.played.length)),yi(()=>{var F;let A=s.error;return{id:A?`MediaError#${A.code}`:"HtmlVideoError",category:SD.VIDEO_PIPELINE,message:A?A.message:"Error event from HTML video element",thrown:(F=s.error)!=null?F:void 0}})),l=at(s,"timeupdate").pipe(yi(()=>s.currentTime)),d=["waiting","seeking","seeked","timeupdate"],c=new mD,h=.3,p;t.add(yu(...d.map(A=>at(s,A))).subscribe(A=>{let F=s.currentTime;s.loop&&fy(p)&&fy(F)&&p>=s.duration-h&&F<=h&&c.next(p),p=F}));let f=e("pause").pipe(Kd(()=>!s.error&&p!==s.duration)),m=at(s,"enterpictureinpicture"),g=at(s,"leavepictureinpicture"),S=new by(ny(s));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new by(Wd(s)),y=at(s,"fullscreenchange");t.add(y.pipe(yi(()=>Wd(s))).subscribe(v));let T=.1,I=1e3,k=at(s,"timeupdate").pipe(yi(A=>s.duration-s.currentTime<T)),C=yu(k.pipe(Kd(A=>!s.loop&&A)),at(s,"ended")).pipe(gD(I),Xd(void 0)),_=my({latestNativeEvent:yu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>at(s,A))),endedExpected:k}).pipe(yi(({endedExpected:A})=>A?s.readyState<2:s.readyState<3),fD());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(yi(()=>s.duration)),isBuffering$:_,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Ni}from"@vkontakte/videoplayer-shared/es2015";var ei=s=>{switch(s){case"mobile":return Ni.Q_144P;case"lowest":return Ni.Q_240P;case"low":return Ni.Q_360P;case"sd":case"medium":return Ni.Q_480P;case"hd":case"high":return Ni.Q_720P;case"fullhd":case"full":return Ni.Q_1080P;case"quadhd":case"quad":return Ni.Q_1440P;case"ultrahd":case"ultra":return Ni.Q_2160P}};var ot=j(jt(),1),ep=j(wt(),1),gr=j(or(),1);import{isNonNullable as ne,isNullable as wu,now as $y,isHigher as Pu,isHigherOrEqual as Xr,isInvariantQuality as Au,isLowerOrEqual as Jr,videoSizeToQuality as Dy,assertNotEmptyArray as ku,assertNonNullable as By}from"@vkontakte/videoplayer-shared/es2015";var Jd=!1,Ti={},xy=s=>{Jd=s},Ey=()=>{Ti={}},wy=s=>{s(Ti)},Oa=(s,e)=>{var t;Jd&&(Ti.meta=(t=Ti.meta)!=null?t:{},Ti.meta[s]=e)},nt=class{constructor(e){this.name=e}next(e){var i,r;if(!Jd)return;Ti.series=(i=Ti.series)!=null?i:{};let t=(r=Ti.series[this.name])!=null?r:[];t.push([Date.now(),e]),Ti.series[this.name]=t}};import{isHigher as kD,isHigherOrEqual as kq,isLower as Py,isLowerOrEqual as Rq,isNonNullable as Tu,isNullable as RD,videoHeightToQuality as Iu}from"@vkontakte/videoplayer-shared/es2015";function Zd(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&&Zd(s,e,t)==="high_quality"}function Kr(s,e,t){return RD(s)||Tu(s.min)&&Tu(s.max)&&Py(s.max,s.min)||Tu(s.min)&&e&&kD(s.min,e)||Tu(s.max)&&t&&Py(s.max,t)}function Ay({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 Cy=new nt("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)),Ui=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=$y()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Lu='Assertion "ABR Tracks is empty array" failed',Eu=new WeakMap,ky=new WeakMap,Ry=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,ot.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,ot.default)(a,-1);return o&&(0,ep.default)(n,o)?o:n.length?(0,ot.default)(n,-1):(0,ot.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=Ry.get(s);n||(n=a.filter(l=>ne(l.bitrate)&&ne(s.bitrate)?s.bitrate/l.bitrate>i:!0),Ry.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,ep.default)(n,o)?o:n.length?(0,ot.default)(n,-1):(0,ot.default)(a,0)},Ly=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]&&$y()-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=Ly(o)?"video":"audio",l=Ly(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
|
-
`}),o}return i==null||i.recordSwitch(t),t},
|
|
9
|
+
`}),o}return i==null||i.recordSwitch(t),t},LD=(s,e)=>Math.log(e)/Math.log(s),Vy=({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=LD(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}},My=new WeakMap,ti=(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,P,$;ku(s,Lu);let{containerSizeFactor:g,containerSizeLimit:S}=Vy({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&ne(o)?o:1,y=My.get(s);y||(y=s.filter(R=>!Au(R.quality)).sort((R,w)=>Pu(R.quality,w.quality)?-1:1),My.set(s,y));let T=(H=(0,ot.default)(y,-1))==null?void 0:H.quality,I=(N=(0,ot.default)(y,0))==null?void 0:N.quality,k=Kr(r,I,T),C=v*Ru(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),B={},_=null;for(let R of y){let w=!0;if(S)if(R.size)w=R.size.width<=S.width&&R.size.height<=S.height;else{let Ue=S&&Dy(S);w=Ue?Jr(R.quality,Ue):!0}if(!w){B[R.quality]="FitsContainer";continue}let V=p||t,de=ne(V)&&isFinite(V)&&ne(R.bitrate)?V-a>=R.bitrate*C:!0,Ne=xu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===R.quality;if(!de&&!Ne){B[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)){B[R.quality]="Buffer";continue}if(!!c&&Xr(R.quality,c)&&!Ne){B[R.quality]="DroppedFramesLimit";continue}if(!!h&&Xr(R.quality,h)&&!Ne){B[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){B[R.quality]="FitsQualityLimits";continue}_||(_=R)}_&&_.bitrate&&Cy.next(_.bitrate);let A=(K=_!=null?_:(0,ot.default)(y,-1))!=null?K:s[0],F=l==null?void 0:l.last,M=Mu(i,f,A,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 w,V;return`{ id: ${R.id}, quality: ${R.quality}, bitrate: ${R.bitrate}, size: ${(w=R.size)==null?void 0:w.width}:${(V=R.size)==null?void 0:V.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,gr.default)(i!=null?i:{}).map(([R,w])=>`${R}: ${w}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
20
|
containerSizeFactor: ${g},
|
|
21
|
-
containerSizeLimit: ${(
|
|
21
|
+
containerSizeLimit: ${(P=S==null?void 0:S.width)!=null?P:0} x ${($=S==null?void 0:S.height)!=null?$:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${p},
|
|
24
24
|
reserve: ${a},
|
|
@@ -34,24 +34,24 @@ var YE=Object.create;var Yl=Object.defineProperty,KE=Object.defineProperties,XE=
|
|
|
34
34
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,gr.default)(B).map(([R,w])=>`${R}: ${w}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
40
|
[best video track] ${_==null?void 0:_.quality}
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`})
|
|
41
|
+
[selected video track] ${M==null?void 0:M.quality}
|
|
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,P,$,R;ku(s,Lu);let{containerSizeFactor:g,containerSizeLimit:S}=Vy({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&ne(o)?o:1,y=s.filter(w=>!Au(w.quality)).sort((w,V)=>Pu(w.quality,V.quality)?-1:1),T=(N=(0,ot.default)(y,-1))==null?void 0:N.quality,I=(K=(0,ot.default)(y,0))==null?void 0:K.quality,k=Kr(r,I,T),C=v*Ru(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),B={},A=y.filter(w=>{let V=!0;if(S)if(w.size)V=w.size.width<=S.width&&w.size.height<=S.height;else{let Rt=S&&Dy(S);V=Rt?Jr(w.quality,Rt):!0}if(!V)return B[w.quality]="FitsContainer",!1;let de=p||t,Ne=ne(de)&&isFinite(de)&&ne(w.bitrate)?de-a>=w.bitrate*C:!0,ue=xu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===w.quality;if(!Ne&&!ue)return B[w.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&ne(i.minBufferToSwitchUp)&&u&&!Au(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Pu(w.quality,u.quality))return B[w.quality]="Buffer",!1;if(!!c&&Xr(w.quality,c)&&!ue)return B[w.quality]="DroppedFramesLimit",!1;if(!!h&&Xr(w.quality,h)&&!ue)return B[w.quality]="StallsLimit",!1;let Pe=k||(wu(r==null?void 0:r.max)||Jr(w.quality,r.max))&&(wu(r==null?void 0:r.min)||Xr(w.quality,r.min)),Ue=ne(d)&&!d?Jr(w.quality,i.backgroundVideoQualityLimit):!0;return!Pe||!Ue?(B[w.quality]="FitsQualityLimits",!1):!0})[0];A&&A.bitrate&&Cy.next(A.bitrate);let F=(P=A!=null?A:(0,ot.default)(y,-1))!=null?P: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(w=>{var V,de;return`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate}, size: ${(V=w.size)==null?void 0:V.width}:${(de=w.size)==null?void 0:de.height} }`}).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,gr.default)(i!=null?i:{}).map(([w,V])=>`${w}: ${V}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
53
|
containerSizeFactor: ${g},
|
|
54
|
-
containerSizeLimit: ${(
|
|
54
|
+
containerSizeLimit: ${($=S==null?void 0:S.width)!=null?$:0} x ${(R=S==null?void 0:S.height)!=null?R:0},
|
|
55
55
|
estimatedThroughput: ${t},
|
|
56
56
|
stallsPredictedThroughput: ${p},
|
|
57
57
|
reserve: ${a},
|
|
@@ -67,19 +67,19 @@ var YE=Object.create;var Yl=Object.defineProperty,KE=Object.defineProperties,XE=
|
|
|
67
67
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
68
68
|
|
|
69
69
|
[limited video tracks]
|
|
70
|
-
${(0,
|
|
70
|
+
${(0,gr.default)(B).map(([w,V])=>`${w}: ${V}`).join(`
|
|
71
71
|
`)||"All tracks are available"}
|
|
72
72
|
|
|
73
|
-
[best video track] ${
|
|
73
|
+
[best video track] ${A==null?void 0:A.quality}
|
|
74
74
|
[selected video track] ${H==null?void 0:H.quality}
|
|
75
|
-
`}),H},
|
|
75
|
+
`}),H},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=[...t].sort(Zr(-1)),h=s.bitrate;By(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(`
|
|
79
79
|
`)}
|
|
80
80
|
|
|
81
81
|
[tuning]
|
|
82
|
-
${(0,
|
|
82
|
+
${(0,gr.default)(r!=null?r:{}).map(([y,T])=>`${y}: ${T}`).join(`
|
|
83
83
|
`)}
|
|
84
84
|
|
|
85
85
|
[limit params]
|
|
@@ -93,14 +93,14 @@ var YE=Object.create;var Yl=Object.defineProperty,KE=Object.defineProperties,XE=
|
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
95
|
[selected audio track] ${v==null?void 0:v.id}
|
|
96
|
-
`}),v},
|
|
96
|
+
`}),v},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=ky.get(t);c||(c=[...t].sort(Zr(-1)),ky.set(t,c));let h=s.bitrate;By(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(`
|
|
100
100
|
`)}
|
|
101
101
|
|
|
102
102
|
[tuning]
|
|
103
|
-
${(0,
|
|
103
|
+
${(0,gr.default)(r!=null?r:{}).map(([y,T])=>`${y}: ${T}`).join(`
|
|
104
104
|
`)}
|
|
105
105
|
|
|
106
106
|
[limit params]
|
|
@@ -114,14 +114,14 @@ var YE=Object.create;var Yl=Object.defineProperty,KE=Object.defineProperties,XE=
|
|
|
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 Wy,assertNonNullable as Yy,combine as iD,debounce as rD,ErrorCategory as Ky,filter as Xy,filterChanged as sD,isNonNullable as up,map as _u,merge as Jy,observableFrom as aD,once as nD,Subscription as oD,ValueSubject as lp,videoQualityToHeight as Zy,videoSizeToQuality as uD}from"@vkontakte/videoplayer-shared/es2015";var Hy=j(jt(),1);var Fy=j(wt(),1);var _y=s=>{if(s instanceof DOMException&&(0,Fy.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(!_y(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{yield s.play()}catch(r){return _y(r)&&(s.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as Vu,isNullable as _B,assertNonNullable as ja}from"@vkontakte/videoplayer-shared/es2015";var Uy=j(fr(),1);import{isNonNullable as Ny,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 qy(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 $=sp(d),H;if($<m){H=m-$,setTimeout(g,H);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,k()},S=$=>(a=$,U),v=$=>(c=$,U),y=()=>(p="json",U),T=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},I=$=>(h=$,U),k=()=>{d=Oe(),n=new r,n.open("get",s);let $=0,H,F=0,K=()=>(Cu(d),Math.max(d,Math.max(H||0,F||0)));if(a&&n.addEventListener("progress",A=>{let B=Oe();a.updateChunk&&A.loaded>$&&(a.updateChunk(K(),A.loaded-$),$=A.loaded,H=B)}),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:B,responseType:R}=n,w=B==null?void 0:B.byteLength;if(typeof w=="number"&&a){let V=w-$;V&&a.updateChunk&&a.updateChunk(K(),V)}R==="json"&&(!B||!(0,Uy.default)(B).length)?T():(c&&c(),e(B))}else T()}),n.addEventListener("error",()=>{T()}),h){let A=()=>{Cu(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(F=Oe(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=p,n.send(),U},U={withBitrateReporting:S,withParallel:I,withJSONResponse:y,withRetryCount:$=>(l=$,U),withRetryInterval:($,H)=>(Ny($)&&(m=$),Ny(H)&&(f=H),U),withTimeout:$=>(o=$,U),withFinally:v,send:k,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return U}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 jy=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,jy.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,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=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||{};!ky({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Hy.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=()=>{qy(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(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)=>{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 _=0;_<this.bufferStates.length;_++){let P=this.bufferStates[_];T=Math.min(T,P.buf),P.ts<k&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${T} drop=${C} jitter=${this.sourceJitter}`);let M=T-qB;this.sourceJitter>=0?M-=this.sourceJitter/2:this.sourceJitter-=1,M>3?f(1.15):M>1?f(1.1):M>.3?f(1.05):f(1)}},S=T=>{let I,k=()=>I&&I.start?I.start.length:0,C=A=>I.start[A]/1e3,M=A=>I.dur[A]/1e3,_=A=>I.fragIndex+A,P=(A,B)=>({chunkIdx:_(A),startTS:C(A),dur:M(A),discontinuity:B}),U=()=>{let A=0;if(I&&I.dur){let B=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,R=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,w=B;this.sourceJitter>1&&(w+=this.sourceJitter-1);let V=I.dur.length-1;for(;V>=0&&(w-=I.dur[V],!(w<=0));--V);A=Math.min(V,I.dur.length-1-R),A=Math.max(A,0)}return P(A,!0)},$=A=>{let B=k();if(!(B<=0)){if(Vu(A)){for(let R=0;R<B;R++)if(C(R)>A)return P(R)}return U()}},H=A=>{let B=k(),R=A?A.chunkIdx+1:0,w=R-I.fragIndex;if(!(B<=0)){if(!A||w<0||w-B>UB)return t(`Resync: offset=${w} bChunks=${B} chunk=`+JSON.stringify(A)),U();if(!(w>=B))return P(R-I.fragIndex,!1)}},F=(A,B,R)=>{l&&l.abort(),l=es(this.urlResolver.resolve(A,!0,this.lowLatency),B,R,()=>this._retryCallback()).withTimeout(Ou).withRetryCount(np).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,B)=>{F(T,R=>{if(!c())return;I=R;let w=!!I.lowLatency;w!==this.lowLatency&&m(w);let V=0;for(let de=0;de<I.dur.length;++de)V+=I.dur[de];V>0&&(ja(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(V/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($(B))},()=>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),M,_,P,U,$=0,H,F,K,A=()=>{H&&(clearTimeout(H),H=void 0);let ee=Math.max(jB,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=$+ee,we=Oe(),Pe=Math.min(1e4,Ee-we);$=we;let Ue=()=>{l||c()&&C.seek(()=>{c()&&($=Oe(),B(),A())})};Pe>0?H=window.setTimeout(()=>{this.paused?A():Ue()},Pe):Ue()},B=()=>{let ee;for(;ee=C.nextChunk(U);)U=ee,Ne(ee);let Ee=C.nextChunk(P);if(Ee){if(P&&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(),Qt=I.currentTime;!this.paused&&I.buffered.length>1&&F===Qt&&$t-K>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),F!==Qt&&(F=Qt,K=$t);let si=this._getBufferSizeSec();if(si>30)k(`Buffered ${si} seconds; delaying appendBuffer`),Rt(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:$t,buf:si}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch($i){if($i.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),Ue=this.sourceBuffer.buffered.length,Ue!==0&&(we=this.sourceBuffer.buffered.start(0),Pe=Qt,Pe-we>4&&this.sourceBuffer.remove(we,Pe-3)),Rt(1e3);else throw $i}}},w=()=>{_&&M&&(k([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(P)]),R(_,function(){_=null,B()}))},V=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),de=ee=>{c()&&p(V(ee),(Ee,we)=>{if(c()){if(we/=1e3,_=Ee,P=ee,n=ee.startTS,we){let Pe=Math.min(10,ee.dur/we);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}w()}},()=>this._handleNetworkError())},Ne=ee=>{c()&&(ja(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(V(ee),!1)))},ue=ee=>{c()&&(e.cachedHeader=ee,R(ee,()=>{M=!0,w()}))};a=!0,C.seek(ee=>{if(c()){if($=Oe(),!ee){A();return}U=ee,!_B(T)||ee.startTS>T?de(ee):(P=ee,B())}},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,ja(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;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 Qy=j(nr(),1);import{debounce as HB,filter as Gy,fromEvent as GB,interval as zB,isHigher as QB,isInvariantQuality as WB,isLower as YB,merge as KB,Subject as zy,Subscription as XB}from"@vkontakte/videoplayer-shared/es2015";var op=class{constructor(){this.onDroopedVideoFramesLimit$=new zy;this.subscription=new XB;this.playing=!1;this.tracks=[];this.forceChecker$=new zy;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(Gy(()=>this.playing),Gy(()=>{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,Qy.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 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 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:Ky.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=Jt(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 Wy(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:Ky.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Jy(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=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(_u(r=>r.map(({track:a})=>a)),Xy(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(Xy(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(ze(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(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&&Zy(r),min:a&&Zy(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 Wy(r.to)}},t)).add(Jy(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&&up(t)?t:Zt(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let m=(f=e.find(({track:g})=>g.id===a))==null?void 0:f.representation;Yy(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;Yy(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 eT=za;var fx=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 dx,filter as Wp,filterChanged as dl,fromEvent as YC,isNonNullable as px,map as Yp,merge as pl,observableFrom as Kp,once as hx,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)}},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 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,Wa=dD()&&Nu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),tT=Wa?dp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Mt=Wa?tT.fetch:window.fetch,mH=Wa?tT.Request:window.Request,le=Wa?Qa:window.AbortController,bH=Wa?is:window.AbortSignal;var Hp=j(Ya(),1);var UT=j(NT(),1);import{ErrorCategory as Xa}from"@vkontakte/videoplayer-shared/es2015";var Uu=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,UT.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 Up,assertNonNullable as ps,combine as hs,ErrorCategory as ti,filter as rl,filterChanged as Mn,flattenObject as $n,fromEvent as Ai,getTraceSubscriptionMethod as kC,interval as qp,isNonNullable as Bn,isNullable as sx,map as fs,merge as yr,now as jp,Subject as sl,Subscription as ax,tap as RC,throttle as LC,ValueSubject as ge}from"@vkontakte/videoplayer-shared/es2015";var Hu=j(wt(),1),ls=j(jt(),1),Gu=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),qT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),jT=!qT(window.requestIdleCallback)||!qT(window.cancelIdleCallback),rs=jT?KD:window.requestIdleCallback,ei=jT?XD:window.cancelIdleCallback;var WI=j($a(),1);import{assertNever as JD,ErrorCategory as HT,Subject as GT}from"@vkontakte/videoplayer-shared/es2015";var ZD=18,zT=!1;try{zT=G.browser.isSafari&&!!G.browser.safariVersion&&G.browser.safariVersion<=ZD}catch(s){console.error(s)}var gp=class{constructor(e){this.bufferFull$=new GT;this.error$=new GT;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:HT.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)};zT&&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:HT.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)}}},QT=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 ft,ErrorCategory as Ei,fromEvent as Cp,getExponentialDelay as Vp,isNonNullable as us,isNullable as Ke,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 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},Ii=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 Ii),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 Ii().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 Ii().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 Ii().parse(s);return(r=new Ui(t).find("sidx"))==null?void 0:r.timescale},l0=(s,e)=>{let i=new Ii().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 Ii().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},WT={validateData:s0,parseInit:c0,getIndexRange:()=>{},parseSegments:a0,parseFeedableSegmentChunk:n0,getChunkEndTime:l0,getServerLatencyTimestamps:o0,getTimescaleFromIndex:u0};var xn=j(wt(),1);import{assertNonNullable as vp,isNonNullable as JT,isNullable as p0}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as d0}from"@vkontakte/videoplayer-shared/es2015";var YT={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"}},KT=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 YT,a=r?YT[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=KT(i);if(!e(r))return;r.type==="master"&&Sr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},XT=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=KT(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 ZT=[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)(ZT,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=>JT(o.time)&&JT(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)(ZT,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},eI={validateData:XT,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 eI;case"mp4":return WT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var $p=j(wp(),1),jI=j(nr(),1),HI=j(Pp(),1),GI=j(jt(),1),Bp=j(fr(),1);var CI=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,CI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as fC,isNullable as UI}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 VI=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 Qy,assertNonNullable as Wy,combine as XD,debounce as JD,ErrorCategory as Yy,filter as Ky,filterChanged as ZD,isNonNullable as ap,map as _u,merge as Xy,observableFrom as eB,once as tB,Subscription as iB,ValueSubject as np,videoQualityToHeight as Jy,videoSizeToQuality as rB}from"@vkontakte/videoplayer-shared/es2015";var jy=j(jt(),1);var _y=j(wt(),1);var Oy=s=>{if(s instanceof DOMException&&(0,_y.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(!Oy(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{yield s.play()}catch(r){return Oy(r)&&(s.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as Vu,isNullable as DD,assertNonNullable as qa}from"@vkontakte/videoplayer-shared/es2015";var Ny=j(mr(),1);import{isNonNullable as Fy,assertNonNullable as Cu,now as MD}from"@vkontakte/videoplayer-shared/es2015";function Oe(){return MD()}function tp(s){return Oe()-s}function ip(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 Uy(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=tp(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",P=>{let $=Oe();a.updateChunk&&P.loaded>M&&(a.updateChunk(K(),P.loaded-M),M=P.loaded,H=$)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;Cu(n);let P=n.status;if(P>=200&&P<300){let{response:$,responseType:R}=n,w=$==null?void 0:$.byteLength;if(typeof w=="number"&&a){let V=w-M;V&&a.updateChunk&&a.updateChunk(K(),V)}R==="json"&&(!$||!(0,Ny.default)($).length)?T():(c&&c(),e($))}else T()}),n.addEventListener("error",()=>{T()}),h){let P=()=>{Cu(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(N=Oe(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=p,n.send(),F},F={withBitrateReporting:S,withParallel:I,withJSONResponse:y,withRetryCount:M=>(l=M,F),withRetryInterval:(M,H)=>(Fy(M)&&(m=M),Fy(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(mr(),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 BD}from"@vkontakte/videoplayer-shared/es2015";var Ou=1e4,rp=3;var CD=6e4,VD=10,OD=1,_D=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 BD,this.chunkRateEstimator=new Na(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ip(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=ip(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||{};!Ay({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,jy.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=()=>{Uy(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(rp,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(rp).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 _=0;_<this.bufferStates.length;_++){let A=this.bufferStates[_];T=Math.min(T,A.buf),A.ts<k&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${T} drop=${C} jitter=${this.sourceJitter}`);let B=T-OD;this.sourceJitter>=0?B-=this.sourceJitter/2:this.sourceJitter-=1,B>3?f(1.15):B>1?f(1.1):B>.3?f(1.05):f(1)}},S=T=>{let I,k=()=>I&&I.start?I.start.length:0,C=P=>I.start[P]/1e3,B=P=>I.dur[P]/1e3,_=P=>I.fragIndex+P,A=(P,$)=>({chunkIdx:_(P),startTS:C(P),dur:B(P),discontinuity:$}),F=()=>{let P=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,w=$;this.sourceJitter>1&&(w+=this.sourceJitter-1);let V=I.dur.length-1;for(;V>=0&&(w-=I.dur[V],!(w<=0));--V);P=Math.min(V,I.dur.length-1-R),P=Math.max(P,0)}return A(P,!0)},M=P=>{let $=k();if(!($<=0)){if(Vu(P)){for(let R=0;R<$;R++)if(C(R)>P)return A(R)}return F()}},H=P=>{let $=k(),R=P?P.chunkIdx+1:0,w=R-I.fragIndex;if(!($<=0)){if(!P||w<0||w-$>VD)return t(`Resync: offset=${w} bChunks=${$} chunk=`+JSON.stringify(P)),F();if(!(w>=$))return A(R-I.fragIndex,!1)}},N=(P,$,R)=>{l&&l.abort(),l=es(this.urlResolver.resolve(P,!0,this.lowLatency),$,R,()=>this._retryCallback()).withTimeout(Ou).withRetryCount(rp).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(P,$)=>{N(T,R=>{if(!c())return;I=R;let w=!!I.lowLatency;w!==this.lowLatency&&m(w);let V=0;for(let de=0;de<I.dur.length;++de)V+=I.dur[de];V>0&&(qa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(V/I.dur.length)),r({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,P(M($))},()=>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),B,_,A,F,M=0,H,N,K,P=()=>{H&&(clearTimeout(H),H=void 0);let ee=Math.max(_D,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(),$(),P())})};Pe>0?H=window.setTimeout(()=>{this.paused?P():Ue()},Pe):Ue()},$=()=>{let ee;for(;ee=C.nextChunk(F);)F=ee,Ne(ee);let Ee=C.nextChunk(A);if(Ee){if(A&&Ee.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?P():(v(),this._initPlayerWith(e));return}de(Ee)}else P()},R=(ee,Ee)=>{if(!c()||!this.sourceBuffer)return;let we,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 ri=this._getBufferSizeSec();if(ri>30)k(`Buffered ${ri} seconds; delaying appendBuffer`),Rt(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:$t,buf:ri}),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}}},w=()=>{_&&B&&(k([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(A)]),R(_,function(){_=null,$()}))},V=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),de=ee=>{c()&&p(V(ee),(Ee,we)=>{if(c()){if(we/=1e3,_=Ee,A=ee,n=ee.startTS,we){let Pe=Math.min(10,ee.dur/we);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}w()}},()=>this._handleNetworkError())},Ne=ee=>{c()&&(qa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(V(ee),!1)))},ue=ee=>{c()&&(e.cachedHeader=ee,R(ee,()=>{B=!0,w()}))};a=!0,C.seek(ee=>{if(c()){if(M=Oe(),!ee){P();return}F=ee,!DD(T)||ee.startTS>T?de(ee):(A=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&&tp(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;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))},CD))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var zy=j(or(),1);import{debounce as FD,filter as Hy,fromEvent as ND,interval as UD,isHigher as qD,isInvariantQuality as jD,isLower as HD,merge as GD,Subject as Gy,Subscription as zD}from"@vkontakte/videoplayer-shared/es2015";var sp=class{constructor(){this.onDroopedVideoFramesLimit$=new Gy;this.subscription=new zD;this.playing=!1;this.tracks=[];this.forceChecker$=new Gy;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&&!jD(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&&qD(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(ND(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=UD(this.droppedFramesChecker.checkTime).pipe(Hy(()=>this.playing),Hy(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(FD(this.droppedFramesChecker.checkTime)),i=GD(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,zy.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>HD(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=sp;import{map as QD,Observable as WD}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as YD}from"@vkontakte/videoplayer-shared/es2015";var Ha=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var KD=(s,e)=>new WD(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=YD(document,"visibilitychange").pipe(QD(n=>!document.hidden||Ha())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),ht=KD;var sB=["paused","playing","ready"],aB=["paused","playing","ready"],Ga=class{constructor(e){this.subscription=new iB;this.videoState=new z("stopped");this.representations$=new np([]);this.droppedFramesManager=new ts;this.maxSeekBackTime$=new np(1/0);this.zeroTime$=new np(void 0);this.liveOffset=new br;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:Yy.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=ei(u.name))!=null?i:rB(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),ap(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,op.default)(aB,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,op.default)(sB,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ie(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Ie(this.params.source.url,u))}return;default:return Qy(e)}};this.textTracksManager=new 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:Yy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Xy(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=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(_u(r=>r.map(({track:a})=>a)),Ky(r=>!!r.length),tB()).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(ZD(),_u(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(XD({zeroTime:this.zeroTime$.pipe(Ky(ap)),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&&Jy(r),min:a&&Jy(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Qy(r.to)}},t)).add(Xy(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,eB(["init"])).pipe(JD(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 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&&ap(t)?t:ti(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;Wy(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;Wy(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 Zy=Ga;var hx=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 NC,assertNonNullable as UC,debounce as qC,ErrorCategory as cx,filter as Gp,filterChanged as dl,fromEvent as jC,isNonNullable as dx,map as zp,merge as pl,observableFrom as Qp,once as px,Subscription as HC}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 up(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 Qa=Nu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),eT=Qa?up({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Mt=Qa?eT.fetch:window.fetch,oH=Qa?eT.Request:window.Request,le=Qa?za:window.AbortController,uH=Qa?is:window.AbortSignal;var Up=j(Wa(),1);var NT=j(FT(),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,NT.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 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 _p,assertNonNullable as ps,combine as hs,ErrorCategory as Gt,filter as rl,filterChanged as Ln,flattenObject as Mn,fromEvent as Ai,getTraceSubscriptionMethod as IC,interval as Fp,isNonNullable as $n,isNullable as rx,map as fs,merge as Tr,now as Np,Subject as sl,Subscription as sx,tap as xC,throttle as EC,ValueSubject as ge}from"@vkontakte/videoplayer-shared/es2015";var Hu=j(wt(),1),ls=j(jt(),1),Gu=j(Wa(),1);var HB=(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)},GB=s=>window.clearTimeout(s),UT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),qT=!UT(window.requestIdleCallback)||!UT(window.cancelIdleCallback),rs=qT?HB:window.requestIdleCallback,ii=qT?GB:window.cancelIdleCallback;var QI=j($a(),1);import{assertNever as zB,ErrorCategory as jT,Subject as HT}from"@vkontakte/videoplayer-shared/es2015";var QB=18,GT=!1;try{GT=G.browser.isSafari&&!!G.browser.safariVersion&&G.browser.safariVersion<=QB}catch(s){console.error(s)}var fp=class{constructor(e){this.bufferFull$=new HT;this.error$=new HT;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:jT.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)};GT&&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:jT.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:zB(t)}}},zT=fp;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 ji,assertNonNullable as ft,ErrorCategory as Ei,fromEvent as $p,getExponentialDelay as Dp,isNonNullable as us,isNullable as Ke,now as ju,once as cC,Subject as dC,Subscription as pC,ValueSubject as yr}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 Sr=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 YB={ftyp:Ja,moov:Za,mvhd:en,moof:tn,mdat:rn,sidx:Sr,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},Ii=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=YB[e];return i?new i(t,new s):new as(t,new s)}};var qi=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 XB=new TextDecoder("ascii"),JB=s=>XB.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",ZB=s=>{let e=new Sr(s,new Ii),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})},e0=(s,e)=>{let i=new Ii().parse(s),r=new qi(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)},t0=s=>{let t=new Ii().parse(s),i=new qi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},i0=s=>{var r;let t=new Ii().parse(s);return(r=new qi(t).find("sidx"))==null?void 0:r.timescale},r0=(s,e)=>{let i=new Ii().parse(s),a=new qi(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},s0=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 Ii().parse(s),r=new qi(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},QT={validateData:JB,parseInit:s0,getIndexRange:()=>{},parseSegments:ZB,parseFeedableSegmentChunk:e0,getChunkEndTime:r0,getServerLatencyTimestamps:t0,getTimescaleFromIndex:i0};var In=j(wt(),1);import{assertNonNullable as bp,isNonNullable as XT,isNullable as n0}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as a0}from"@vkontakte/videoplayer-shared/es2015";var WT={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"}},YT=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 WT,a=r?WT[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*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}},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)*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 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:a0(e)}},vr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=YT(i);if(!e(r))return;r.type==="master"&&vr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},KT=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=YT(s);return vr(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 JT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],o0=[231,22612,22743,167,171,163,160,175],u0=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return vr(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?vr(f,({tag:g,type:S,value:v})=>g===30321?(d=Ht(v,S)===1,!1):!0):a&&n&&(0,In.default)(JT,h)&&(o=!0),!o}),bp(e,"Failed to parse webm Segment start"),bp(t,"Failed to parse webm Segment end"),bp(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}}}},l0=s=>{if(n0(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},c0=(s,e)=>{let t=!1,i=!1,r=o=>XT(o.time)&&XT(o.position),a=[],n;return vr(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)(JT,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}}})},d0=s=>{let e=0,t=!1;try{vr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,In.default)(o0,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},ZT={validateData:KT,parseInit:u0,getIndexRange:l0,parseSegments:c0,parseFeedableSegmentChunk:d0};var xn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return ZT;case"mp4":return QT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Rp=j(Ip(),1),qI=j(or(),1),jI=j(xp(),1),HI=j(jt(),1),Lp=j(mr(),1);var BI=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,BI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as uC,isNullable as NI}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 CI=s=>{var e;try{let t=nC(),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 nC(){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 kp=j(jt(),1);import{videoSizeToQuality as hC}from"@vkontakte/videoplayer-shared/es2015";var OI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Jt(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}},_I=({id:s,bitrate:e})=>({id:s,bitrate:e}),FI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),NI=({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",wn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var qI=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},xi=(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,jI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,$p.default)(t,n,(o,u)=>UI(a)?o:UI(u)?a:(0,HI.default)(a,parseInt(u,10),"0"))}return t},zI=(s,e)=>{var _,P,U,$,H,F,K,A,B,R,w,V,de,Ne,ue,ee,Ee,we,Pe,Ue,Rt,$t,Qt,si,$i,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,Je;return(Je=(q=fe.textContent)==null?void 0:q.trim())!=null?Je:""}),o=(_=(0,GI.default)(n,0))!=null?_:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],T=y.reduce((fe,q)=>D(E({},fe),{[q.id]:q.children}),{}),I=y.reduce((fe,q)=>D(E({},fe),{[q.id]:q.getAttribute("duration")}),{});v?S=qI(v):(0,Bp.default)(I).filter(fe=>fe).length&&!u?S=(0,Bp.default)(I).reduce((fe,q)=>{var Je;return fe+((Je=qI(q))!=null?Je:0)},0):m&&(S=parseInt(m,10));let k=0,C=(U=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?U:[];for(let fe of y.map(q=>q.id))for(let q of T[fe]){let Je=($=q.getAttribute("id"))!=null?$:"id"+(k++).toString(10),Bt=(H=q.getAttribute("mimeType"))!=null?H:"",Ki=(F=q.getAttribute("codecs"))!=null?F:"",Xi=(K=q.getAttribute("contentType"))!=null?K:Bt==null?void 0:Bt.split("/")[0],ql=(B=(A=q.getAttribute("profiles"))==null?void 0:A.split(","))!=null?B:[],oa=(w=VI((R=q.getAttribute("lang"))!=null?R:""))!=null?w:{},ai=(Ne=(de=(V=q.querySelector("Label"))==null?void 0:V.textContent)==null?void 0:de.trim())!=null?Ne: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,bt=Xi,W={id:Je,language:oa.language,isDefault:Gl==="main",label:ai,codecs:Ki,hdr:bt==="video"&&os(Ki),mime:Bt,representations:[]};for(let N of jl){let Le=(Ee=N.getAttribute("lang"))!=null?Ee:void 0,Dt=(Pe=(we=ai!=null?ai:q.getAttribute("label"))!=null?we:N.getAttribute("label"))!=null?Pe:void 0,ni=($t=(Rt=(Ue=N.querySelector("BaseURL"))==null?void 0:Ue.textContent)==null?void 0:Rt.trim())!=null?$t:"",Ze=new URL(ni||o,e).toString(),Me=(Qt=N.getAttribute("mimeType"))!=null?Qt:Bt,oi=($i=(si=N.getAttribute("codecs"))!=null?si:Ki)!=null?$i:"",ui;if(Xi==="text"){let $e=N.getAttribute("id")||"",li=((ws=oa.privateuse)==null?void 0:ws.includes("x-auto"))||$e.includes("_auto"),et=N.querySelector("SegmentTemplate");if(et){let Ct={representationId:(Ps=N.getAttribute("id"))!=null?Ps:void 0,bandwidth:(As=N.getAttribute("bandwidth"))!=null?As:void 0},ci=parseInt((ks=N.getAttribute("bandwidth"))!=null?ks:"",10)/1e3,di=(Ls=parseInt((Rs=et.getAttribute("startNumber"))!=null?Rs:"",10))!=null?Ls:1,gt=parseInt((Ms=et.getAttribute("timescale"))!=null?Ms:"",10),Ji=($s=et.querySelectorAll("SegmentTimeline S"))!=null?$s:[],St=et.getAttribute("media");if(!St)continue;let pi=[],hi=0,fi="",vt=0,Vt=di,se=0;for(let me of Ji){let tt=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 it=tt/gt*1e3,De=se/gt*1e3;for(let ve=0;ve<ce+1;ve++){let Ce=xi(St,D(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:(se+ve*tt).toString(10)})),yt=(De!=null?De:0)+ve*it,_t=yt+it;Vt++,pi.push({time:{from:yt,to:_t},url:Ce})}se+=(ce+1)*tt,hi+=(ce+1)*it}vt=se/gt*1e3,fi=xi(St,D(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:se.toString(10)}));let Ot={time:{from:vt,to:1/0},url:fi},Ae={type:"template",baseUrl:Ze,segmentTemplateUrl:St,initUrl:"",totalSegmentsDurationMs:hi,segments:pi,nextSegmentBeyondManifest:Ot,timescale:gt};ui={id:$e,kind:"text",segmentReference:Ae,profiles:[],duration:S,bitrate:ci,mime:"",codecs:"",width:0,height:0,isAuto:li}}else ui={id:$e,isAuto:li,kind:"text",url:Ze}}else{let $e=(Os=(Vs=N.getAttribute("contentType"))!=null?Vs:Me==null?void 0:Me.split("/")[0])!=null?Os:Xi,li=(Fs=(_s=q.getAttribute("profiles"))==null?void 0:_s.split(","))!=null?Fs:[],et=parseInt((Ns=N.getAttribute("width"))!=null?Ns:"",10),Ct=parseInt((Us=N.getAttribute("height"))!=null?Us:"",10),ci=parseInt((qs=N.getAttribute("bandwidth"))!=null?qs:"",10)/1e3,di=(js=N.getAttribute("frameRate"))!=null?js:"",gt=(Hs=N.getAttribute("quality"))!=null?Hs:void 0,Ji=di?qu(di):void 0,St=(Gs=N.getAttribute("id"))!=null?Gs:"id"+(k++).toString(10),pi=$e==="video"?`${Ct}p`:$e==="audio"?`${ci}Kbps`:oi,hi=`${St}@${pi}`,fi=[...C,...ql,...li],vt,Vt=N.querySelector("SegmentBase"),se=(zs=N.querySelector("SegmentTemplate"))!=null?zs:Hl;if(Vt){let Ae=(Ws=(Qs=N.querySelector("SegmentBase Initialization"))==null?void 0:Qs.getAttribute("range"))!=null?Ws:"",[me,tt]=Ae.split("-").map(Ce=>parseInt(Ce,10)),ce={from:me,to:tt},Be=(Ys=N.querySelector("SegmentBase"))==null?void 0:Ys.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:(Ks=N.getAttribute("id"))!=null?Ks:void 0,bandwidth:(Xs=N.getAttribute("bandwidth"))!=null?Xs:void 0},me=parseInt((Js=se.getAttribute("timescale"))!=null?Js:"",10),tt=(Zs=se.getAttribute("initialization"))!=null?Zs:"",ce=se.getAttribute("media"),Be=(ta=parseInt((ea=se.getAttribute("startNumber"))!=null?ea:"",10))!=null?ta:1,it=xi(tt,Ae);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let De=(ia=se.querySelectorAll("SegmentTimeline S"))!=null?ia:[],ve=[],Ce=0,yt="",_t=0;if(De.length){let mi=Be,be=0;for(let Tt of De){let ye=parseInt((ra=Tt.getAttribute("d"))!=null?ra:"",10),rt=parseInt((sa=Tt.getAttribute("r"))!=null?sa:"",10)||0,bi=parseInt((aa=Tt.getAttribute("t"))!=null?aa:"",10);be=Number.isFinite(bi)?bi:be;let Zi=ye/me*1e3,er=be/me*1e3;for(let gi=0;gi<rt+1;gi++){let Ql=xi(ce,D(E({},Ae),{segmentNumber:mi.toString(10),segmentTime:(be+gi*ye).toString(10)})),ua=(er!=null?er:0)+gi*Zi,Wl=ua+Zi;mi++,ve.push({time:{from:ua,to:Wl},url:Ql})}be+=(rt+1)*ye,Ce+=(rt+1)*Zi}_t=be/me*1e3,yt=xi(ce,D(E({},Ae),{segmentNumber:mi.toString(10),segmentTime:be.toString(10)}))}else if(fC(S)){let be=parseInt((na=se.getAttribute("duration"))!=null?na:"",10)/me*1e3,Tt=Math.ceil(S/be),ye=0;for(let rt=1;rt<Tt;rt++){let bi=xi(ce,D(E({},Ae),{segmentNumber:rt.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:bi}),ye+=be}_t=ye,yt=xi(ce,D(E({},Ae),{segmentNumber:Tt.toString(10),segmentTime:ye.toString(10)}))}let zl={time:{from:_t,to:1/0},url:yt};vt={type:"template",baseUrl:Ze,segmentTemplateUrl:ce,initUrl:it,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;bt||(bt=Ot),ui={id:hi,kind:Ot,segmentReference:vt,profiles:fi,duration:S,bitrate:ci,mime:Me,codecs:oi,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=oi),W.hdr||(W.hdr=bt==="video"&&os(oi)),W.representations.push(ui)}if(bt){let N=r[bt].find(Le=>Le.id===W.id);if(N&&W.representations.every(Le=>ot(Le.segmentReference)))for(let Le of N.representations){let Dt=W.representations.find(Me=>Me.id===Le.id),ni=Dt==null?void 0:Dt.segmentReference,Ze=Le.segmentReference;Ze.segments.push(...ni.segments),Ze.nextSegmentBeyondManifest=ni.nextSegmentBeyondManifest}else r[bt].push(W)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as QI}from"@vkontakte/videoplayer-shared/es2015";var z=(s,e)=>QI(s)&&QI(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 QT(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:Ei.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ei.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:Ei.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,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);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,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=>D(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(!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=xi(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&ei&&ei(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ei&&ei(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:h,to:p}},f)=>{let m=h<=i&&p>=i,g=h>i||m||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+S||p<=i+S;return(c==="none"||c==="partially_ejected"&&g&&v&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(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*(){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=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())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),wn(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:Ei.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:Ei.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=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:Ei.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,WI.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,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&&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:Ei.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=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||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:Ei.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:Ei.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 An,assertNever as YI,fromEvent as KI,merge as vC,now as kn,Subscription as yC,Subject as XI,ValueSubject as Op,flattenObject as cs,ErrorCategory as Rn}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 XI;this.error$=new XI;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=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=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 $,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 F=new URL(d,location.href);F.searchParams.append("bytes",`${i.from}-${i.to}`),d=F.toString();break}default:YI(t)}this.requestQuic&&(d=ji(d));let p=this.abortAllController.signal,f;if(n){let F=new le;if(f=vC(KI(this.abortAllController.signal,"abort"),KI(n,"abort")).subscribe(()=>{try{F.abort()}catch(K){Wu(K)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{F.abort()}catch(K){Wu(K)}p=F.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(($=this.throughputEstimator)==null||$.addRawRtt(S-m),!g.ok||!g.body){f==null||f.unsubscribe();let F=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:F}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){f==null||f.unsubscribe();let F=kn(),K={requestStartedAt:m,requestEndedAt:F,duration:F-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,M=F=>{f==null||f.unsubscribe(),C=!0,Wu(F)},_=An(p,function(A){return X(this,arguments,function*({done:F,value:K}){if(I===0&&this.lastRequestFirstBytes$.next(kn()-m),p.aborted){f==null||f.unsubscribe();return}if(!F&&K){let B=new Uint8Array(k.length+K.length);B.set(k),B.set(K,k.length),k=B,I+=K.byteLength,r==null||r(new DataView(k.buffer),I),yield T==null?void 0:T.read().then(_,M)}})}.bind(this));yield T==null?void 0:T.read().then(_,M),f==null||f.unsubscribe();let P=kn(),U={failed:C,requestStartedAt:m,requestEndedAt:P,duration:P-m};return C?(h.error("endRequest",cs(U)),h.end(),null):(h.log("endRequest",cs(U)),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=>D(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:YI(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})}})}},Wu=s=>{if(!wn(s))throw s};var wi=(s,e,t)=>t*e+(1-t)*s,_p=(s,e)=>s.reduce((t,i)=>t+i,0)/e,JI=(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 ZI}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 ZI(e.initial),this.debounced$=new ZI(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+=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=wi(this.slow,e,this.params.emaAlphaSlow),this.fast=wi(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=wi(this.emaSmoothed,e,this.params.emaAlpha);let i=JI(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?wi(this.smoothed,t,this.params.emaAlpha):t}};var Pi=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 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(D(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 ex=(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]},tx=({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"]},ix=({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 ax;this.representationSubscription=new ax;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:ti.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:ti.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=zI(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Uu(e))!=null?n:{id:"ManifestParsing",category:ti.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=D(E({},t),{streams:r});return this.tracer.log("updateManifestEnd",$n(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",$n({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(Ai(p,"error").pipe(rl(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:ti.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=>Ai(this.element,p))).pipe(fs(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(Ai(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Mn()).subscribe(f=>this.liveStreamEndTimestamp=jp())),this.subscription.add(Ai(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=qp(1e3).subscribe(f=>{let m=Vi(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ai(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(hs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(fs(({isActiveLive:f,isLowLatency:m})=>f&&m),Mn()).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),Mn((f,m)=>m.bufferLength<f.bufferLength),fs(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Vi(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=Vi(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,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),_=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(_);let P="none";if(M?P="active_low_latency":this.isLowLatency$.getValue()&&_?(this.bufferManagers.forEach(U=>U.proceedLowLatencyLive()),P="active_low_latency"):v!==0&&C<T?P="live_forward_buffering":C<T+k&&(P="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let U=p-(T+I),$=this.normolizeLiveOffset(Math.trunc(v+U/S)),H=Math.abs($-v),F=0;!f||H<=this.tuning.dashCmafLive.offsetCalculationError?F=v:$>0&&H>this.tuning.dashCmafLive.offsetCalculationError&&(F=$),this.manifestUrlString=Ie(this.manifestUrlString,F,2)}(P==="live_with_target_offset"||P==="live_forward_buffering")&&(p=0,yield this.updateLive())}),f=>{this.error$.next({id:"updateLive",category:ti.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(Mn(),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:ti.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,m)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.readyState)==="open"){f();return}this.tuning.dash.rejectOnSourceOpenTimeout?m(new Error("Timeout reject when wait sourceopen event")):f()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.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&&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=qp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ti.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=Pi.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=>Ai(this.element,e)),Ai(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ti.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ai(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ai(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&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=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 M=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(M).catch(_=>{this.error$.next({id:"stallIntervalCallback",category:ti.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:_})}),r.liveLastOffset=M}else{let M=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(M),(C=this.audioBufferManager)==null||C.maintain(M),r.position=M}this.tracer.log("stallIntervalCallback",$n(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=qp(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ti.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),Ye(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(sx(this.element)||sx(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(){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.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=D(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 ox=`attribute vec2 a_vertex;
|
|
124
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var wp=j(jt(),1);import{videoSizeToQuality as oC}from"@vkontakte/videoplayer-shared/es2015";var VI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?ei(a):void 0)!=null?u:oC({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},OI=({id:s,bitrate:e})=>({id:s,bitrate:e}),_I=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),FI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Pp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,wp.default)(i.split("."),0),isDefault:r}),Ap=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,wp.default)(r.split("."),0)}),kp=s=>"url"in s,ut=s=>s.type==="template",En=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var UI=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},xi=(s,e)=>{let t=s;t=(0,Rp.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,Rp.default)(t,n,(o,u)=>NI(a)?o:NI(u)?a:(0,jI.default)(a,parseInt(u,10),"0"))}return t},GI=(s,e)=>{var _,A,F,M,H,N,K,P,$,R,w,V,de,Ne,ue,ee,Ee,we,Pe,Ue,Rt,$t,Yt,ri,Bi,ws,Ps,As,ks,Rs,Ls,Ms,$s,Ds,Bs,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,Je;return(Je=(q=fe.textContent)==null?void 0:q.trim())!=null?Je:""}),o=(_=(0,HI.default)(n,0))!=null?_:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],T=y.reduce((fe,q)=>D(E({},fe),{[q.id]:q.children}),{}),I=y.reduce((fe,q)=>D(E({},fe),{[q.id]:q.getAttribute("duration")}),{});v?S=UI(v):(0,Lp.default)(I).filter(fe=>fe).length&&!u?S=(0,Lp.default)(I).reduce((fe,q)=>{var Je;return fe+((Je=UI(q))!=null?Je:0)},0):m&&(S=parseInt(m,10));let k=0,C=(F=(A=a.getAttribute("profiles"))==null?void 0:A.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),Dt=(H=q.getAttribute("mimeType"))!=null?H:"",Xi=(N=q.getAttribute("codecs"))!=null?N:"",Ji=(K=q.getAttribute("contentType"))!=null?K:Dt==null?void 0:Dt.split("/")[0],Fl=($=(P=q.getAttribute("profiles"))==null?void 0:P.split(","))!=null?$:[],oa=(w=CI((R=q.getAttribute("lang"))!=null?R:""))!=null?w:{},si=(Ne=(de=(V=q.querySelector("Label"))==null?void 0:V.textContent)==null?void 0:de.trim())!=null?Ne:void 0,Nl=q.querySelectorAll("Representation"),Ul=q.querySelector("SegmentTemplate"),ql=(ee=(ue=q.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?ee:void 0,bt=Ji,Q={id:Je,language:oa.language,isDefault:ql==="main",label:si,codecs:Xi,hdr:bt==="video"&&os(Xi),mime:Dt,representations:[]};for(let U of Nl){let Le=(Ee=U.getAttribute("lang"))!=null?Ee:void 0,Bt=(Pe=(we=si!=null?si:q.getAttribute("label"))!=null?we:U.getAttribute("label"))!=null?Pe:void 0,ai=($t=(Rt=(Ue=U.querySelector("BaseURL"))==null?void 0:Ue.textContent)==null?void 0:Rt.trim())!=null?$t:"",Ze=new URL(ai||o,e).toString(),Me=(Yt=U.getAttribute("mimeType"))!=null?Yt:Dt,ni=(Bi=(ri=U.getAttribute("codecs"))!=null?ri:Xi)!=null?Bi:"",oi;if(Ji==="text"){let $e=U.getAttribute("id")||"",ui=((ws=oa.privateuse)==null?void 0:ws.includes("x-auto"))||$e.includes("_auto"),et=U.querySelector("SegmentTemplate");if(et){let Ct={representationId:(Ps=U.getAttribute("id"))!=null?Ps:void 0,bandwidth:(As=U.getAttribute("bandwidth"))!=null?As:void 0},li=parseInt((ks=U.getAttribute("bandwidth"))!=null?ks:"",10)/1e3,ci=(Ls=parseInt((Rs=et.getAttribute("startNumber"))!=null?Rs:"",10))!=null?Ls:1,gt=parseInt((Ms=et.getAttribute("timescale"))!=null?Ms:"",10),Zi=($s=et.querySelectorAll("SegmentTimeline S"))!=null?$s:[],St=et.getAttribute("media");if(!St)continue;let di=[],pi=0,hi="",vt=0,Vt=ci,se=0;for(let me of Zi){let tt=parseInt((Ds=me.getAttribute("d"))!=null?Ds:"",10),ce=parseInt((Bs=me.getAttribute("r"))!=null?Bs:"",10)||0,De=parseInt((Cs=me.getAttribute("t"))!=null?Cs:"",10);se=Number.isFinite(De)?De:se;let it=tt/gt*1e3,Be=se/gt*1e3;for(let ve=0;ve<ce+1;ve++){let Ce=xi(St,D(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:(se+ve*tt).toString(10)})),yt=(Be!=null?Be:0)+ve*it,_t=yt+it;Vt++,di.push({time:{from:yt,to:_t},url:Ce})}se+=(ce+1)*tt,pi+=(ce+1)*it}vt=se/gt*1e3,hi=xi(St,D(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:se.toString(10)}));let Ot={time:{from:vt,to:1/0},url:hi},Ae={type:"template",baseUrl:Ze,segmentTemplateUrl:St,initUrl:"",totalSegmentsDurationMs:pi,segments:di,nextSegmentBeyondManifest:Ot,timescale:gt};oi={id:$e,kind:"text",segmentReference:Ae,profiles:[],duration:S,bitrate:li,mime:"",codecs:"",width:0,height:0,isAuto:ui}}else oi={id:$e,isAuto:ui,kind:"text",url:Ze}}else{let $e=(Os=(Vs=U.getAttribute("contentType"))!=null?Vs:Me==null?void 0:Me.split("/")[0])!=null?Os:Ji,ui=(Fs=(_s=q.getAttribute("profiles"))==null?void 0:_s.split(","))!=null?Fs:[],et=parseInt((Ns=U.getAttribute("width"))!=null?Ns:"",10),Ct=parseInt((Us=U.getAttribute("height"))!=null?Us:"",10),li=parseInt((qs=U.getAttribute("bandwidth"))!=null?qs:"",10)/1e3,ci=(js=U.getAttribute("frameRate"))!=null?js:"",gt=(Hs=U.getAttribute("quality"))!=null?Hs:void 0,Zi=ci?qu(ci):void 0,St=(Gs=U.getAttribute("id"))!=null?Gs:"id"+(k++).toString(10),di=$e==="video"?`${Ct}p`:$e==="audio"?`${li}Kbps`:ni,pi=`${St}@${di}`,hi=[...C,...Fl,...ui],vt,Vt=U.querySelector("SegmentBase"),se=(zs=U.querySelector("SegmentTemplate"))!=null?zs:Ul;if(Vt){let Ae=(Ws=(Qs=U.querySelector("SegmentBase Initialization"))==null?void 0:Qs.getAttribute("range"))!=null?Ws:"",[me,tt]=Ae.split("-").map(Ce=>parseInt(Ce,10)),ce={from:me,to:tt},De=(Ys=U.querySelector("SegmentBase"))==null?void 0:Ys.getAttribute("indexRange"),[it,Be]=De?De.split("-").map(Ce=>parseInt(Ce,10)):[],ve=De?{from:it,to:Be}:void 0;vt={type:"byteRange",url:Ze,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),tt=(Zs=se.getAttribute("initialization"))!=null?Zs:"",ce=se.getAttribute("media"),De=(ta=parseInt((ea=se.getAttribute("startNumber"))!=null?ea:"",10))!=null?ta:1,it=xi(tt,Ae);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let Be=(ia=se.querySelectorAll("SegmentTimeline S"))!=null?ia:[],ve=[],Ce=0,yt="",_t=0;if(Be.length){let fi=De,be=0;for(let Tt of Be){let ye=parseInt((ra=Tt.getAttribute("d"))!=null?ra:"",10),rt=parseInt((sa=Tt.getAttribute("r"))!=null?sa:"",10)||0,mi=parseInt((aa=Tt.getAttribute("t"))!=null?aa:"",10);be=Number.isFinite(mi)?mi:be;let er=ye/me*1e3,tr=be/me*1e3;for(let bi=0;bi<rt+1;bi++){let Hl=xi(ce,D(E({},Ae),{segmentNumber:fi.toString(10),segmentTime:(be+bi*ye).toString(10)})),ua=(tr!=null?tr:0)+bi*er,Gl=ua+er;fi++,ve.push({time:{from:ua,to:Gl},url:Hl})}be+=(rt+1)*ye,Ce+=(rt+1)*er}_t=be/me*1e3,yt=xi(ce,D(E({},Ae),{segmentNumber:fi.toString(10),segmentTime:be.toString(10)}))}else if(uC(S)){let be=parseInt((na=se.getAttribute("duration"))!=null?na:"",10)/me*1e3,Tt=Math.ceil(S/be),ye=0;for(let rt=1;rt<Tt;rt++){let mi=xi(ce,D(E({},Ae),{segmentNumber:rt.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:mi}),ye+=be}_t=ye,yt=xi(ce,D(E({},Ae),{segmentNumber:Tt.toString(10),segmentTime:ye.toString(10)}))}let jl={time:{from:_t,to:1/0},url:yt};vt={type:"template",baseUrl:Ze,segmentTemplateUrl:ce,initUrl:it,totalSegmentsDurationMs:Ce,segments:ve,nextSegmentBeyondManifest:jl,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),oi={id:pi,kind:Ot,segmentReference:vt,profiles:hi,duration:S,bitrate:li,mime:Me,codecs:ni,width:et,height:Ct,fps:Zi,quality:gt}}Q.language||(Q.language=Le),Q.label||(Q.label=Bt),Q.mime||(Q.mime=Me),Q.codecs||(Q.codecs=ni),Q.hdr||(Q.hdr=bt==="video"&&os(ni)),Q.representations.push(oi)}if(bt){let U=r[bt].find(Le=>Le.id===Q.id);if(U&&Q.representations.every(Le=>ut(Le.segmentReference)))for(let Le of U.representations){let Bt=Q.representations.find(Me=>Me.id===Le.id),ai=Bt==null?void 0:Bt.segmentReference,Ze=Le.segmentReference;Ze.segments.push(...ai.segments),Ze.nextSegmentBeyondManifest=ai.nextSegmentBeyondManifest}else r[bt].push(Q)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as zI}from"@vkontakte/videoplayer-shared/es2015";var W=(s,e)=>zI(s)&&zI(e)&&s.readyState==="open"&&lC(s,e);function lC(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 yr(0);this.currentLowLatencySegmentLength$=new yr(0);this.currentSegmentLength$=new yr(0);this.onLastSegment$=new yr(!1);this.fullyBuffered$=new yr(!1);this.playingRepresentation$=new yr(void 0);this.playingRepresentationInit$=new yr(void 0);this.error$=new dC;this.gaps=[];this.subscription=new pC;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=ji(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 zT(this.sourceBuffer),this.subscription.add($p(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ei.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ei.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add($p(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ei.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!W(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=ji(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!W(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||!W(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 ir(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=ji(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!W(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||!W(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 ir(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=ji(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||!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){!W(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new le,ji(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||!W(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)||!W(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,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||!ut(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>D(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=xi(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&&ii&&ii(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ii&&ii(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&&W(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 ji(o,function(){return X(this,null,function*(){let d=Dp(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())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 ji(n,function(){return X(this,null,function*(){let u=Dp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),$p(window,"online").pipe(cC()).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(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=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:Ei.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=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:Ei.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||!W(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||!W(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(!(Ke(this.sourceBuffer)||!W(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:Ei.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",kp(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,QI.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?ji(this.destroyAbortController.signal,function(){return X(this,null,function*(){let o=Dp(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&&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:Ei.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||!W(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=kp(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||!W(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||!W(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||!W(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ke(e)?0:_e(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!W(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||!W(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:Ei.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ke(this.sourceBuffer)||!W(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:Ei.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Hi=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 WI,fromEvent as YI,merge as hC,now as An,Subscription as fC,Subject as KI,ValueSubject as Bp,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 Bp(void 0);this.lastConnectionReused$=new Bp(void 0);this.lastRequestFirstBytes$=new Bp(void 0);this.recoverableError$=new KI;this.error$=new KI;this.abortAllController=new le;this.subscription=new fC;this.fetchManifest=Pn(this.abortAllController.signal,function(e){return X(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Hi(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:WI(t)}this.requestQuic&&(d=Hi(d));let p=this.abortAllController.signal,f;if(n){let N=new le;if(f=hC(YI(this.abortAllController.signal,"abort"),YI(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,B=N=>{f==null||f.unsubscribe(),C=!0,Wu(N)},_=Pn(p,function(P){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(_,B)}})}.bind(this));yield T==null?void 0:T.read().then(_,B),f==null||f.unsubscribe();let A=An(),F={failed:C,requestStartedAt:m,requestEndedAt:A,duration:A-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=>D(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:WI(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 wi=(s,e,t)=>t*e+(1-t)*s,Cp=(s,e)=>s.reduce((t,i)=>t+i,0)/e,XI=(s,e,t,i)=>{let r=0,a=t,n=Cp(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 mC,ValueSubject as JI}from"@vkontakte/videoplayer-shared/es2015";var Gi=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 JI(e.initial),this.debounced$=new JI(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)&&(mC(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 Gi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=wi(this.slow,e,this.params.emaAlphaSlow),this.fast=wi(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 Gi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Cp(this.pastMeasures,this.takenMeasures);this.emaSmoothed=wi(this.emaSmoothed,e,this.params.emaAlpha);let i=XI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Ju=class extends Gi{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?wi(this.smoothed,t,this.params.emaAlpha):t}};var Pi=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 bC,ValueSubject as gC}from"@vkontakte/videoplayer-shared/es2015";var Rn=class s{constructor(e,t){this.currentRepresentation$=new gC(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(!bC(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(D(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 ZI=(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]},ex=({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"]},tx=({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"]},Vp=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 wC=["timeupdate","progress","play","seeked","stalled","waiting"],PC=["timeupdate","progress","loadeddata","playing","seeked"];var al=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new sx;this.representationSubscription=new sx;this.state$=new z("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=_p(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=_p(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=GI(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=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=D(E({},t),{streams:r});return this.tracer.log("updateManifestEnd",Mn(a)),a})}.bind(this));this.initRepresentations=_p(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(Ai(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(Tr(...PC.map(p=>Ai(this.element,p))).pipe(fs(p=>this.element?_e(this.element.buffered,this.element.currentTime*1e3):0),Ln(),xC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Tr(Ai(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ln()).subscribe(f=>this.liveStreamEndTimestamp=Np())),this.subscription.add(Ai(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Fp(1e3).subscribe(f=>{let m=_i(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ai(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(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=_i(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(EC(1e3)).subscribe(g=>x(this,[g],function*({liveLoadBufferLength:f,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=_i(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,B=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),_=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(_);let A="none";if(B?A="active_low_latency":this.isLowLatency$.getValue()&&_?(this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),A="active_low_latency"):v!==0&&C<T?A="live_forward_buffering":C<T+k&&(A="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),A==="live_forward_buffering"||A==="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)}(A==="live_with_target_offset"||A==="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=Tr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(fs(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Tr(...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(Tr(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(Tr(...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,Up.default)((0,Up.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&&$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=Fp(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=Pi.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"?Np()-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(Tr(...wC.map(e=>Ai(this.element,e)),Ai(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Gt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ai(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ai(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&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=Np(),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 B=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(B).catch(_=>{this.error$.next({id:"stallIntervalCallback",category:Gt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:_})}),r.liveLastOffset=B}else{let B=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(B),(C=this.audioBufferManager)==null||C.maintain(B),r.position=B}this.tracer.log("stallIntervalCallback",Mn(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Fp(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),Ye(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(rx(this.element)||rx(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=IC(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.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=D(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/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 nx=`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 ox=`#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 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(ox,this.gl.VERTEX_SHADER),i=this.createShader(ux,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 Gp,isNonNullable as _C,safeStorage as lx,filterChanged as FC}from"@vkontakte/videoplayer-shared/es2015";var ul="stalls_manager_metrics",cx="stalls_manager_abr_params",zp=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)}connect(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.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){return E(E({},this.abrParams),this.getStoredData(cx))}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()}updateStoredAbrParams(){let e=[],t=this.getStoredData(ul,"[]");if(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(cx,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=lx.get(e))!=null?i:t)}setStoredData(e,t){lx.set(e,JSON.stringify(t))}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?wi(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=zp;import{combine as NC,map as UC,observeElementSize as qC,Subscription as jC,ValueSubject as Qp,noop as HC}from"@vkontakte/videoplayer-shared/es2015";var cl=class{constructor(){this.subscription=new jC;this.pipSize$=new Qp(void 0);this.videoSize$=new Qp(void 0);this.elementSize$=new Qp(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=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:dx.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(Wp(l=>!!l.length),hx()).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(Yp(l=>l.to.state!=="none"),dl());this.stallsManager.connect({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(Wp(px),hx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Yp(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),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(ct(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(Rp(p));let f=[];for(let m of p.representations){let g=_I(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=OI(D(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=FI(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(Wp(()=>this.videoTracksMap.size>0)).subscribe(()=>x(this,null,function*(){let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,fx.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});px(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(Yp(({to:l})=>l==="ready"),dl());this.subscription.add(pl(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Kp(["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$,Kp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=pl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Kp(["init"])).pipe(WC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var P,U,$,H,F,K,A,B,R,w,V,de,Ne;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Na:Fa,t=this.params.tuning.useNewAutoSelectVideoTrack?Du:Bu,i=this.params.tuning.useNewAutoSelectVideoTrack?Zt:$u,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(P=r.videoTrack.getState())==null?void 0:P.id,l=[...this.videoTracksMap.keys()].find(({id:ue})=>ue===o),d=a.currentVideoTrack$.getValue(),c=((H=($=r.videoStream.getState())!=null?$:l&&((U=this.videoTracksMap.get(l))==null?void 0:U.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=(F=r.audioStream.getState())!=null?F: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,(B=ue==null?void 0:ue.bitrate)!=null?B:-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,(w=ue==null?void 0:ue.bitrate)!=null?w:-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,(V=this.audioStreamsMap.get(y))!=null?V:[],{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}),M=(de=this.videoTracksMap.get(k))==null?void 0:de.representation,_=C&&((Ne=this.audioTracksMap.get(C))==null?void 0:Ne.representation);if(M&&_)return[M,_];if(M&&!_&&this.audioTracksMap.size===0)return[M,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:dx.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 Xp,merge as mx,filter as bx,filterChanged as XC,isNullable as Jp,map as gx,ValueSubject as Zp,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 Zp(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(gx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Xp({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(gx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(bx(o=>JC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Xp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:mx(i.playbackRateState$,new Zp(1))}).pipe(bx(({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||Jp(l)||(e=o-l)})).add(Xp({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:mx(i.playbackRateState$,new Zp(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||Jp(o)||Jp(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=NI(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 Kx,filter as yh,filterChanged as wl,fromEvent as QV,isNonNullable as Xx,map as Th,merge as Pl,observableFrom as Ih,once as Jx,Subscription as WV}from"@vkontakte/videoplayer-shared/es2015";var Sh=j(Ya(),1);import{abortable as fh,assertNonNullable as ys,combine as Ts,ErrorCategory as ii,filter as yl,filterChanged as bo,flattenObject as go,fromEvent as ri,getTraceSubscriptionMethod as DV,interval as mh,isNonNullable as So,isNullable as Wx,map as Is,merge as Ar,now as bh,Subject as Tl,Subscription as gh,tap as CV,throttle as Yx,ValueSubject as Se}from"@vkontakte/videoplayer-shared/es2015";var bl=j(wt(),1),Ss=j(jt(),1),gl=j(Ya(),1);var jx=j($a(),1);import{assertNever as ZC,ErrorCategory as Sx,Subject as vx}from"@vkontakte/videoplayer-shared/es2015";var eV=18,yx=!1;try{yx=G.browser.isSafari&&!!G.browser.safariVersion&&G.browser.safariVersion<=eV}catch(s){console.error(s)}var eh=class{constructor(e){this.bufferFull$=new vx;this.error$=new vx;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:Sx.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)};yx&&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:Sx.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)}}},Tx=eh;import{abortable as zi,assertNonNullable as mt,ErrorCategory as wr,fromEvent as qx,getExponentialDelay as dh,isNonNullable as gs,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 bs=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:bs},ki=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 ki),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 ki().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 ki().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 ki().parse(s);return(r=new Gi(t).find("sidx"))==null?void 0:r.timescale},cV=(s,e)=>{let i=new ki().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 ki().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},Ix={validateData:aV,parseInit:dV,getIndexRange:()=>{},parseSegments:nV,parseFeedableSegmentChunk:oV,getChunkEndTime:cV,getServerLatencyTimestamps:uV,getTimescaleFromIndex:lV};var oo=j(wt(),1);import{assertNonNullable as ih,isNonNullable as Px,isNullable as hV}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as pV}from"@vkontakte/videoplayer-shared/es2015";var xx={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"}},Ex=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 xx,a=r?xx[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},Gt=(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=Ex(i);if(!e(r))return;r.type==="master"&&xr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},wx=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=Ex(s);return xr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Gt(o,n):a===17026?t=Gt(o,n):a===17029&&(i=Gt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Ax=[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=Gt(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=Gt(f,p):h===17545?r=Gt(f,p):h===21420&&l===475249515?u=Gt(f,p):h===374648427?xr(f,({tag:g,type:S,value:v})=>g===30321?(d=Gt(v,S)===1,!1):!0):a&&n&&(0,oo.default)(Ax,h)&&(o=!0),!o}),ih(e,"Failed to parse webm Segment start"),ih(t,"Failed to parse webm Segment end"),ih(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=>Px(o.time)&&Px(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=Gt(l,u));break;case 183:break;case 241:n&&(n.position=Gt(l,u));break;default:t&&(0,oo.default)(Ax,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},kx={validateData:wx,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 kx;case"mp4":return Ix}}throw new ReferenceError(`Unsupported mime type ${s}`)};var uh=j(wp(),1),_x=j(nr(),1),Fx=j(Pp(),1),Nx=j(jt(),1),lh=j(fr(),1);import{isNonNullable as IV,isNullable as Vx}from"@vkontakte/videoplayer-shared/es2015";var Rx=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(nx,this.gl.VERTEX_SHADER),i=this.createShader(ox,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 RC,now as Dn,once as LC,Subscription as MC,ValueSubject as qp,isNonNullable as $C,safeStorage as ux,filterChanged as DC}from"@vkontakte/videoplayer-shared/es2015";var ul="stalls_manager_metrics",lx="stalls_manager_abr_params",jp=class{constructor(){this.isSeeked$=new qp(!1);this.isBuffering$=new qp(!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 MC;this.severeStallOccurred$=new qp(!1)}connect(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.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){return E(E({},this.abrParams),this.getStoredData(lx))}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()}updateStoredAbrParams(){let e=[],t=this.getStoredData(ul,"[]");if(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(lx,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=ux.get(e))!=null?i:t)}setStoredData(e,t){ux.set(e,JSON.stringify(t))}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?wi(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(LC()).subscribe(t=>this.providerStartWatchingTimestamp=Dn())),this.subscription.add(this.currentStallDuration$.pipe(DC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(RC(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=jp;import{combine as BC,map as CC,observeElementSize as VC,Subscription as OC,ValueSubject as Hp,noop as _C}from"@vkontakte/videoplayer-shared/es2015";var cl=class{constructor(){this.subscription=new OC;this.pipSize$=new Hp(void 0);this.videoSize$=new Hp(void 0);this.elementSize$=new Hp(void 0);this.pictureInPictureWindowRemoveEventListener=_C}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(VC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(BC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(CC(({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 Ir=class{constructor(e){this.subscription=new HC;this.videoState=new z("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 Ui;this.audioTrackSwitchHistory=new Ui;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 NC(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 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:cx.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(Gp(l=>!!l.length),px()).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(zp(l=>l.to.state!=="none"),dl());this.stallsManager.connect({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(Gp(dx),px()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(zp(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(UC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(Pp(p));let f=[];for(let m of p.representations){let g=OI(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(Ap(h));let p=[];for(let f of h.representations){let m=VI(D(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=_I(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$,jC(this.video,"progress")).pipe(Gp(()=>this.videoTracksMap.size>0)).subscribe(()=>x(this,null,function*(){let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,hx.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});dx(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(Ap(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(Pp(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(zp(({to:l})=>l==="ready"),dl());this.subscription.add(pl(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Qp(["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$,Qp(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=pl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Qp(["init"])).pipe(qC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var A,F,M,H,N,K,P,$,R,w,V,de,Ne;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Fa:_a,t=this.params.tuning.useNewAutoSelectVideoTrack?Bu:Du,i=this.params.tuning.useNewAutoSelectVideoTrack?ti:$u,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(A=r.videoTrack.getState())==null?void 0:A.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,(P=this.audioStreamsMap.get(y))!=null?P:[],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,(w=ue==null?void 0:ue.bitrate)!=null?w:-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,(V=this.audioStreamsMap.get(y))!=null?V:[],{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}),B=(de=this.videoTracksMap.get(k))==null?void 0:de.representation,_=C&&((Ne=this.audioTracksMap.get(C))==null?void 0:Ne.representation);if(B&&_)return[B,_];if(B&&!_&&this.audioTracksMap.size===0)return[B,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:cx.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 Bn=class extends Ir{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 Wp,merge as fx,filter as mx,filterChanged as GC,isNullable as Yp,map as bx,ValueSubject as Kp,isNonNullable as zC}from"@vkontakte/videoplayer-shared/es2015";var Cn=class extends Ir{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 Kp(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(bx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Wp({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(bx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(mx(o=>zC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Wp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:fx(i.playbackRateState$,new Kp(1))}).pipe(mx(({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||Yp(l)||(e=o-l)})).add(Wp({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:fx(i.playbackRateState$,new Kp(1))}).pipe(GC((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||Yp(o)||Yp(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=FI(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as VV,assertNonNullable as OV,debounce as _V,ErrorCategory as zx,filter as Qx,filterChanged as Il,fromEvent as FV,isNonNullable as Wx,map as Sh,merge as xl,observableFrom as vh,once as Yx,Subscription as NV}from"@vkontakte/videoplayer-shared/es2015";var bh=j(Wa(),1);import{abortable as ph,assertNonNullable as ys,combine as Ts,ErrorCategory as Qt,filter as Sl,filterChanged as mo,flattenObject as bo,fromEvent as Mi,getTraceSubscriptionMethod as wV,interval as hh,isNonNullable as go,isNullable as Gx,map as Is,merge as Ar,now as fh,Subject as vl,Subscription as mh,tap as PV,throttle as AV,ValueSubject as Se}from"@vkontakte/videoplayer-shared/es2015";var fl=j(wt(),1),Ss=j(jt(),1),ml=j(Wa(),1);var Nx=j($a(),1);import{assertNever as QC,ErrorCategory as gx,Subject as Sx}from"@vkontakte/videoplayer-shared/es2015";var WC=18,vx=!1;try{vx=G.browser.isSafari&&!!G.browser.safariVersion&&G.browser.safariVersion<=WC}catch(s){console.error(s)}var Xp=class{constructor(e){this.bufferFull$=new Sx;this.error$=new Sx;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:gx.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)};vx&&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:gx.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:QC(t)}}},yx=Xp;import{abortable as Qi,assertNonNullable as mt,ErrorCategory as Li,fromEvent as uh,getExponentialDelay as lh,isNonNullable as gs,isNullable as Xe,now as hl,once as bV,Subject as gV,Subscription as SV,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 xr=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 KC={ftyp:On,moov:_n,mvhd:Fn,moof:Nn,mdat:Un,sidx:xr,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},ki=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=KC[e];return i?new i(t,new s):new bs(t,new s)}};var zi=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 JC=new TextDecoder("ascii"),ZC=s=>JC.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",eV=s=>{let e=new xr(s,new ki),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})},tV=(s,e)=>{let i=new ki().parse(s),r=new zi(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)},iV=s=>{let t=new ki().parse(s),i=new zi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},rV=s=>{var r;let t=new ki().parse(s);return(r=new zi(t).find("sidx"))==null?void 0:r.timescale},sV=(s,e)=>{let i=new ki().parse(s),a=new zi(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},aV=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 ki().parse(s),r=new zi(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},Tx={validateData:ZC,parseInit:aV,getIndexRange:()=>{},parseSegments:eV,parseFeedableSegmentChunk:tV,getChunkEndTime:sV,getServerLatencyTimestamps:iV,getTimescaleFromIndex:rV};var no=j(wt(),1);import{assertNonNullable as Zp,isNonNullable as wx,isNullable as oV}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as nV}from"@vkontakte/videoplayer-shared/es2015";var Ix={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"}},xx=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 Ix,a=r?Ix[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*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}},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)*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 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:nV(e)}},Er=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=xx(i);if(!e(r))return;r.type==="master"&&Er(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Ex=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=xx(s);return Er(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 Px=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],uV=[231,22612,22743,167,171,163,160,175],lV=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return Er(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?Er(f,({tag:g,type:S,value:v})=>g===30321?(d=zt(v,S)===1,!1):!0):a&&n&&(0,no.default)(Px,h)&&(o=!0),!o}),Zp(e,"Failed to parse webm Segment start"),Zp(t,"Failed to parse webm Segment end"),Zp(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}}}},cV=s=>{if(oV(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},dV=(s,e)=>{let t=!1,i=!1,r=o=>wx(o.time)&&wx(o.position),a=[],n;return Er(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)(Px,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}}})},pV=s=>{let e=0,t=!1;try{Er(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,no.default)(uV,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},Ax={validateData:Ex,parseInit:lV,getIndexRange:cV,parseSegments:dV,parseFeedableSegmentChunk:pV};var oo=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Ax;case"mp4":return Tx}}throw new ReferenceError(`Unsupported mime type ${s}`)};var ah=j(Ip(),1),Vx=j(or(),1),Ox=j(xp(),1),_x=j(jt(),1),nh=j(mr(),1);import{isNonNullable as mV,isNullable as Bx}from"@vkontakte/videoplayer-shared/es2015";var kx=s=>{var e;try{let t=hV(),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 hV(){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 sh=j(jt(),1);import{videoSizeToQuality as yV}from"@vkontakte/videoplayer-shared/es2015";var Lx=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Jt(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}},Mx=({id:s,bitrate:e})=>({id:s,bitrate:e}),$x=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Bx=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),ah=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,sh.default)(i.split("."),0),isDefault:r}),nh=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,sh.default)(r.split("."),0)}),oh=s=>"url"in s,ut=s=>s.type==="template",lo=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Dx=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},TV=(s,e)=>{let t=0;return()=>{let i=Date.now();i-t>=e&&(s(),t=i)}},Cx=s=>{let e=!1,t=TV(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}},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 Ox=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},Ri=(s,e)=>{let t=s;t=(0,uh.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,_x.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,uh.default)(t,n,(o,u)=>Vx(a)?o:Vx(u)?a:(0,Fx.default)(a,parseInt(u,10),"0"))}return t},Ux=(s,e)=>{var _,P,U,$,H,F,K,A,B,R,w,V,de,Ne,ue,ee,Ee,we,Pe,Ue,Rt,$t,Qt,si,$i,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,Je;return(Je=(q=fe.textContent)==null?void 0:q.trim())!=null?Je:""}),o=(_=(0,Nx.default)(n,0))!=null?_:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],T=y.reduce((fe,q)=>D(E({},fe),{[q.id]:q.children}),{}),I=y.reduce((fe,q)=>D(E({},fe),{[q.id]:q.getAttribute("duration")}),{});v?S=Ox(v):(0,lh.default)(I).filter(fe=>fe).length&&!u?S=(0,lh.default)(I).reduce((fe,q)=>{var Je;return fe+((Je=Ox(q))!=null?Je:0)},0):m&&(S=parseInt(m,10));let k=0,C=(U=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?U:[];for(let fe of y.map(q=>q.id))for(let q of T[fe]){let Je=($=q.getAttribute("id"))!=null?$:"id"+(k++).toString(10),Bt=(H=q.getAttribute("mimeType"))!=null?H:"",Ki=(F=q.getAttribute("codecs"))!=null?F:"",Xi=(K=q.getAttribute("contentType"))!=null?K:Bt==null?void 0:Bt.split("/")[0],ql=(B=(A=q.getAttribute("profiles"))==null?void 0:A.split(","))!=null?B:[],oa=(w=Rx((R=q.getAttribute("lang"))!=null?R:""))!=null?w:{},ai=(Ne=(de=(V=q.querySelector("Label"))==null?void 0:V.textContent)==null?void 0:de.trim())!=null?Ne: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,bt=Xi,W={id:Je,language:oa.language,isDefault:Gl==="main",label:ai,codecs:Ki,hdr:bt==="video"&&os(Ki),mime:Bt,representations:[]};for(let N of jl){let Le=(Ee=N.getAttribute("lang"))!=null?Ee:void 0,Dt=(Pe=(we=ai!=null?ai:q.getAttribute("label"))!=null?we:N.getAttribute("label"))!=null?Pe:void 0,ni=($t=(Rt=(Ue=N.querySelector("BaseURL"))==null?void 0:Ue.textContent)==null?void 0:Rt.trim())!=null?$t:"",Ze=new URL(ni||o,e).toString(),Me=(Qt=N.getAttribute("mimeType"))!=null?Qt:Bt,oi=($i=(si=N.getAttribute("codecs"))!=null?si:Ki)!=null?$i:"",ui;if(Xi==="text"){let $e=N.getAttribute("id")||"",li=((ws=oa.privateuse)==null?void 0:ws.includes("x-auto"))||$e.includes("_auto"),et=N.querySelector("SegmentTemplate");if(et){let Ct={representationId:(Ps=N.getAttribute("id"))!=null?Ps:void 0,bandwidth:(As=N.getAttribute("bandwidth"))!=null?As:void 0},ci=parseInt((ks=N.getAttribute("bandwidth"))!=null?ks:"",10)/1e3,di=(Ls=parseInt((Rs=et.getAttribute("startNumber"))!=null?Rs:"",10))!=null?Ls:1,gt=parseInt((Ms=et.getAttribute("timescale"))!=null?Ms:"",10),Ji=($s=et.querySelectorAll("SegmentTimeline S"))!=null?$s:[],St=et.getAttribute("media");if(!St)continue;let pi=[],hi=0,fi="",vt=0,Vt=di,se=0;for(let me of Ji){let tt=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 it=tt/gt*1e3,De=se/gt*1e3;for(let ve=0;ve<ce+1;ve++){let Ce=Ri(St,D(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:(se+ve*tt).toString(10)})),yt=(De!=null?De:0)+ve*it,_t=yt+it;Vt++,pi.push({time:{from:yt,to:_t},url:Ce})}se+=(ce+1)*tt,hi+=(ce+1)*it}vt=se/gt*1e3,fi=Ri(St,D(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:se.toString(10)}));let Ot={time:{from:vt,to:1/0},url:fi},Ae={type:"template",baseUrl:Ze,segmentTemplateUrl:St,initUrl:"",totalSegmentsDurationMs:hi,segments:pi,nextSegmentBeyondManifest:Ot,timescale:gt};ui={id:$e,kind:"text",segmentReference:Ae,profiles:[],duration:S,bitrate:ci,mime:"",codecs:"",width:0,height:0,isAuto:li}}else ui={id:$e,isAuto:li,kind:"text",url:Ze}}else{let $e=(Os=(Vs=N.getAttribute("contentType"))!=null?Vs:Me==null?void 0:Me.split("/")[0])!=null?Os:Xi,li=(Fs=(_s=q.getAttribute("profiles"))==null?void 0:_s.split(","))!=null?Fs:[],et=parseInt((Ns=N.getAttribute("width"))!=null?Ns:"",10),Ct=parseInt((Us=N.getAttribute("height"))!=null?Us:"",10),ci=parseInt((qs=N.getAttribute("bandwidth"))!=null?qs:"",10)/1e3,di=(js=N.getAttribute("frameRate"))!=null?js:"",gt=(Hs=N.getAttribute("quality"))!=null?Hs:void 0,Ji=di?qu(di):void 0,St=(Gs=N.getAttribute("id"))!=null?Gs:"id"+(k++).toString(10),pi=$e==="video"?`${Ct}p`:$e==="audio"?`${ci}Kbps`:oi,hi=`${St}@${pi}`,fi=[...C,...ql,...li],vt,Vt=N.querySelector("SegmentBase"),se=(zs=N.querySelector("SegmentTemplate"))!=null?zs:Hl;if(Vt){let Ae=(Ws=(Qs=N.querySelector("SegmentBase Initialization"))==null?void 0:Qs.getAttribute("range"))!=null?Ws:"",[me,tt]=Ae.split("-").map(Ce=>parseInt(Ce,10)),ce={from:me,to:tt},Be=(Ys=N.querySelector("SegmentBase"))==null?void 0:Ys.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:(Ks=N.getAttribute("id"))!=null?Ks:void 0,bandwidth:(Xs=N.getAttribute("bandwidth"))!=null?Xs:void 0},me=parseInt((Js=se.getAttribute("timescale"))!=null?Js:"",10),tt=(Zs=se.getAttribute("initialization"))!=null?Zs:"",ce=se.getAttribute("media"),Be=(ta=parseInt((ea=se.getAttribute("startNumber"))!=null?ea:"",10))!=null?ta:1,it=Ri(tt,Ae);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let De=(ia=se.querySelectorAll("SegmentTimeline S"))!=null?ia:[],ve=[],Ce=0,yt="",_t=0;if(De.length){let mi=Be,be=0;for(let Tt of De){let ye=parseInt((ra=Tt.getAttribute("d"))!=null?ra:"",10),rt=parseInt((sa=Tt.getAttribute("r"))!=null?sa:"",10)||0,bi=parseInt((aa=Tt.getAttribute("t"))!=null?aa:"",10);be=Number.isFinite(bi)?bi:be;let Zi=ye/me*1e3,er=be/me*1e3;for(let gi=0;gi<rt+1;gi++){let Ql=Ri(ce,D(E({},Ae),{segmentNumber:mi.toString(10),segmentTime:(be+gi*ye).toString(10)})),ua=(er!=null?er:0)+gi*Zi,Wl=ua+Zi;mi++,ve.push({time:{from:ua,to:Wl},url:Ql})}be+=(rt+1)*ye,Ce+=(rt+1)*Zi}_t=be/me*1e3,yt=Ri(ce,D(E({},Ae),{segmentNumber:mi.toString(10),segmentTime:be.toString(10)}))}else if(IV(S)){let be=parseInt((na=se.getAttribute("duration"))!=null?na:"",10)/me*1e3,Tt=Math.ceil(S/be),ye=0;for(let rt=1;rt<Tt;rt++){let bi=Ri(ce,D(E({},Ae),{segmentNumber:rt.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:bi}),ye+=be}_t=ye,yt=Ri(ce,D(E({},Ae),{segmentNumber:Tt.toString(10),segmentTime:ye.toString(10)}))}let zl={time:{from:_t,to:1/0},url:yt};vt={type:"template",baseUrl:Ze,segmentTemplateUrl:ce,initUrl:it,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;bt||(bt=Ot),ui={id:hi,kind:Ot,segmentReference:vt,profiles:fi,duration:S,bitrate:ci,mime:Me,codecs:oi,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=oi),W.hdr||(W.hdr=bt==="video"&&os(oi)),W.representations.push(ui)}if(bt){let N=r[bt].find(Le=>Le.id===W.id);if(N&&W.representations.every(Le=>ut(Le.segmentReference)))for(let Le of N.representations){let Dt=W.representations.find(Me=>Me.id===Le.id),ni=Dt==null?void 0:Dt.segmentReference,Ze=Le.segmentReference;Ze.segments.push(...ni.segments),Ze.nextSegmentBeyondManifest=ni.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 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 Tx(this.sourceBuffer),this.sourceBufferBufferedDiff=new fl(this.mediaSource,this.sourceBuffer),this.subscription.add(qx(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();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);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();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,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||!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);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();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(){!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)||gs(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);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=_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,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)&&_e(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Ss.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;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,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||!ut(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>D(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;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(!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=Ri(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&ei&&ei(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ei&&ei(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:h,to:p}},f)=>{let m=h<=i&&p>=i,g=h>i||m||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=i+S||p<=i+S;return(c==="none"||c==="partially_ejected"&&g&&v&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(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*(){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=dh(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())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=dh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),qx(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(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=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(!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=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",oh(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,jx.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=dh(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&&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||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=oh(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=Dx(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 Hx,fromEvent as Gx,merge as kV,now as ho,Subject as zx,ValueSubject as ph,flattenObject as vs,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 ph(void 0);this.lastConnectionReused$=new ph(void 0);this.lastRequestFirstBytes$=new ph(void 0);this.recoverableError$=new zx;this.error$=new zx;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=Qu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Sl);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=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,F,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:Hx(t)}this.requestQuic&&(d=ji(d));let p=this.abortAllController.signal,f;if(n){let A=new le;if(f=kV(Gx(this.abortAllController.signal,"abort"),Gx(n,"abort")).subscribe(()=>{try{A.abort()}catch(B){Sl(B)}}),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch(B){Sl(B)}p=A.signal}let m=ho();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=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(),B={requestStartedAt:m,requestEndedAt:A,duration:A-m};return h.log("endRequest",vs(B)),h.end(),g.arrayBuffer()}let v=g.body;if(o){let A;[v,A]=g.body.tee(),(F=this.throughputEstimator)==null||F.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),M=!1,_=A=>{this.unsubscribeAbortSubscription(f),M=!0,Sl(A)},P=po(p,function(R){return X(this,arguments,function*({done:A,value:B}){if(k===0&&this.lastRequestFirstBytes$.next(ho()-m),p.aborted){this.unsubscribeAbortSubscription(f);return}if(!A&&B){if(T)C.set(B,k),k+=B.byteLength;else{let w=new Uint8Array(C.length+B.length);w.set(C),w.set(B,C.length),C=w,k+=B.byteLength}r==null||r(new DataView(C.buffer),k),yield y==null?void 0:y.read().then(P,_)}})}.bind(this));yield y==null?void 0:y.read().then(P,_),this.unsubscribeAbortSubscription(f);let U=ho(),$={failed:M,requestStartedAt:m,requestEndedAt:U,duration:U-m};return M?(h.error("endRequest",vs($)),h.end(),null):(h.log("endRequest",vs($)),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=>D(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:Hx(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: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(D(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=["timeupdate","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 gh;this.representationSubscription=new gh;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=fh(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:ii.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=fh(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:ii.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Ux(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Uu(e))!=null?n:{id:"ManifestParsing",category:ii.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=D(E({},t),{streams:r});return this.tracer.log("updateManifestEnd",go(a)),a})}.bind(this));this.initRepresentations=fh(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})),ys(this.manifest),ys(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new gh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(ri(p,"error").pipe(yl(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:ii.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=>ri(this.element,p))).pipe(Is(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(ri(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(bo()).subscribe(f=>this.liveStreamEndTimestamp=bh())),this.subscription.add(ri(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=mh(1e3).subscribe(f=>{let m=Vi(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(ri(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),bo()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ds(this.element,1)})),this.representationSubscription.add(Ts({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(Ts({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),Is(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Vi(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(Yx(1e3)).subscribe(g=>x(this,[g],function*({liveLoadBufferLength:f,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=Vi(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,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),_=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(_);let P="none";if(M?P="active_low_latency":this.isLowLatency$.getValue()&&_?(this.bufferManagers.forEach(U=>U.proceedLowLatencyLive()),P="active_low_latency"):v!==0&&C<T?P="live_forward_buffering":C<T+k&&(P="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let U=p-(T+I),$=this.normolizeLiveOffset(Math.trunc(v+U/S)),H=Math.abs($-v),F=0;!f||H<=this.tuning.dashCmafLive.offsetCalculationError?F=v:$>0&&H>this.tuning.dashCmafLive.offsetCalculationError&&(F=$),this.manifestUrlString=Ie(this.manifestUrlString,F,2)}(P==="live_with_target_offset"||P==="live_forward_buffering")&&(p=0,yield this.updateLive())}),f=>{this.error$.next({id:"updateLive",category:ii.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(bo(),Is(({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:ii.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,m)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.readyState)==="open"){f();return}this.tuning.dash.rejectOnSourceOpenTimeout?m(new Error("Timeout reject when wait sourceopen event")):f()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,Sh.default)((0,Sh.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&&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=mh(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ii.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 vl({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=Pi.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"?bh()-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"),this.subscription.add(Ar(...VV.filter(e=>e!=="timeupdate").map(e=>ri(this.element,e)),ri(window,"online"),ri(this.element,"timeupdate").pipe(Yx(300))).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ii.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ri(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(ri(this.element,"waiting").subscribe(()=>{var t;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 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=bh(),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 M=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(M).catch(_=>{this.error$.next({id:"stallIntervalCallback",category:ii.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:_})}),r.liveLastOffset=M}else{let M=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(M),(C=this.audioBufferManager)==null||C.maintain(M),r.position=M}this.tracer.log("stallIntervalCallback",go(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=mh(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ii.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;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),Ye(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(Wx(this.element)||Wx(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 vh,noop as qV}from"@vkontakte/videoplayer-shared/es2015";var xl=class{constructor(){this.subscription=new UV;this.pipSize$=new vh(void 0);this.videoSize$=new vh(void 0);this.elementSize$=new vh(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 El=class extends ll{get abrTuningParams(){return this.abrParams}};var kr=class{constructor(e){this.subscription=new WV;this.videoState=new Q("stopped");this.droppedFramesManager=new ts;this.stallsManager=new El;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 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=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:Kx.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(yh(c=>!!c.length),Jx()).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(Th(c=>c.to.state!=="none"),wl());this.stallsManager.connect({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(yh(Xx),Jx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Th(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(c=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),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(ct(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(ah(m));let g=[];for(let S of m.representations){let v=Mx(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(nh(f));let m=[];for(let g of f.representations){let S=Lx(D(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=$x(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&&Cx(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(yh(()=>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});Xx(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(nh(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(ah(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(Th(({to:c})=>c==="ready"),wl());this.subscription.add(Pl(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ih(["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$,Ih(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Pl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ih(["init"])).pipe(zV(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var M,_,P,U,$,H,F,K,A,B,R,w;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Na:Fa,t=this.params.tuning.useNewAutoSelectVideoTrack?Du:Bu,i=this.params.tuning.useNewAutoSelectVideoTrack?Zt:$u,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(M=r.videoTrack.getState())==null?void 0:M.id,u=Er(this.videoTracksMap.keys(),V=>V.id===o),l=a.currentVideoTrack$.getValue(),d=((U=(P=r.videoStream.getState())!=null?P:u&&((_=this.videoTracksMap.get(u))==null?void 0:_.stream))!=null?U:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Er(this.videoStreamsMap.keys(),V=>V.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=($=r.audioStream.getState())!=null?$:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(S==null?void 0:S.id)&&Er(this.audioStreamsMap.keys(),V=>V.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(v){if(u&&!n){let V=e(u,h,(H=this.audioStreamsMap.get(v))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(F=V==null?void 0:V.bitrate)!=null?F:-1/0)}if(l){let V=e(l,h,(K=this.audioStreamsMap.get(v))!=null?K:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(A=V==null?void 0:V.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,(B=this.audioStreamsMap.get(v))!=null?B:[],{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&&((w=this.audioTracksMap.get(I))==null?void 0:w.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:Kx.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 xh,merge as Zx,filter as eE,filterChanged as YV,isNullable as Eh,map as tE,ValueSubject as wh,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 wh(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(tE(o=>o.to)).subscribe(this.player.isLowLatency$)).add(xh({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(tE(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(eE(o=>KV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(xh({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Zx(i.playbackRateState$,new wh(1))}).pipe(eE(({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(xh({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Zx(i.playbackRateState$,new wh(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||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=Bx(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 rE=j($a(),1);import{assertNever as To,assertNonNullable as iE,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 zt={};var xs=(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 dt(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:Al.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,rE.default)(import("hls.js").then(r=>{e||(zt.Hls=r.default,zt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){iE(zt.Hls,"hls.js not loaded"),this.hls=new zt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){iE(zt.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=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(ct(this.video,e.playbackRate,r.playbackRateState$,i)),a(ht(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(kl(l=>l.to)),this.params.output.playbackState$),this.subscription.add(xs(this.hls,zt.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,zt.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=Jt((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,zt.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,zt.Events.LEVEL_LOADING).pipe(kl(({url:l})=>Re(l))),t.hostname$),a(xs(this.hls,zt.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(Oi(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,zt.Events.LEVEL_SWITCHED).pipe(kl(({level:l})=>n(this.hls.levels[l])));o.pipe(JV(ZV)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Oi(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: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 sE="X-Playback-Duration",Ph=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(sE)?parseInt(e.headers.get(sE),10):void 0});import{assertNever as bO,combine as gO,debounce as SO,ErrorCategory as Ml,filter as vO,filterChanged as yO,isNonNullable as oE,isNullable as $l,map as uE,merge as TO,observableFrom as IO,Subscription as xO,ValueSubject as Rh,VideoQuality as EO}from"@vkontakte/videoplayer-shared/es2015";var kh=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=Jt(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([D(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 Rh([]);this.liveOffset=new mr;this.manifestStartTime$=new Rh(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)=>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 Rh((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=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(ct(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(),uE(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&&oE(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(oE)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(uE(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($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(),Ph(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();Ph(g).then(S=>{$l(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: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 Lh,fromEvent as Mh,isNonNullable as AO,isNullable as kO,map as lE,merge as cE,observableFrom as dE,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 dt(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),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:Lh.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:Lh.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(lE(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(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(lE(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(cE(Mh(o,"addtrack"),Mh(o,"removetrack"),Mh(o,"change"),dE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=cE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,dE(["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:Lh.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var fE=j(nr(),1),$h=j(fr(),1),mE=j(jt(),1);import{assertNever as $O,assertNonNullable as pE,debounce as BO,ErrorCategory as hE,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 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=He(e.container,e.tuning),this.params.output.element$.next(this.video),(0,fE.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,$h.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:hE.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(ct(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;pE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];pE(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:hE.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let h=Zt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,$h.default)(this.trackUrls).map(c=>c.track);if(!r||!a||Kr(e,n[0].quality,(d=(0,mE.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 gE,debounce as HO,merge as SE,observableFrom as GO,Subscription as zO,map as vE,ValueSubject as QO,ErrorCategory as Dh,VideoQuality as WO}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as UO}from"@vkontakte/videoplayer-shared/es2015";var bE=["stun:videostun.mycdn.me:80"],qO=1e3,jO=3,Bh=()=>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=Bh;this.externalStopCallback=Bh;this.externalErrorCallback=Bh;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:bE}]};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:bE,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 gE(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 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),Ge(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Dh.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(SE(this.videoState.stateChangeStarted$.pipe(vE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(vE(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 gE(n.to)}},i)).add(SE(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:Dh.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:Dh.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 Dl,filter as wE,isNonNullable as PE,isNullable as t_,map as i_,merge as r_,once as s_,Subject as Fe,Subscription as AE,ValueSubject as J,flattenObject as kE}from"@vkontakte/videoplayer-shared/es2015";import{Observable as YO,map as yE,Subscription as KO,Subject as XO}from"@vkontakte/videoplayer-shared/es2015";var TE=s=>new YO(e=>{let t=new KO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(yE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(yE(({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 xE,once as EE}from"@vkontakte/videoplayer-shared/es2015";function IE(){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(xE(a=>!!a.type),EE()).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(xE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),EE()).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=IE();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 Es=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 AE;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=ex([...ix(this.params.tuning),...tx(this.params.tuning)],this.params.tuning).filter(l=>PE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Ch.default)(r,l)),...t.filter(l=>(0,Ch.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",kE(a)),this.screenFormatsIterator=new Ao(a);let n=[...Fp(!0),...Fp(!1)];this.chromecastFormatsIterator=new Ao(n.filter(l=>PE(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 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(D(E({},o),{source:u,sourceHls:l})):new Cn(D(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(D(E({},o),{source:u})):new Vn(D(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(D(E({},o),{source:u})):new Io(D(E({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Qi(u),new xo(D(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(D(E({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Qi(u),new eT(D(E({},o),{source:u,config:D(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 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 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 D(E({},e),{url:i(e.url)})}return(0,LE.default)((0,RE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new AE,t=!1,i=0;return e.add(r_(this.providerOutput.error$.pipe(wE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),TE({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(wE(({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=D(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"))}this.tracer.error("providerError",kE(n))})),e}};import{fromEvent as Cl,once as n_,combine as o_,Subscription as ME,ValueSubject as Vh,map as u_,filter as l_,isNonNullable as Vl,now as kt,safeStorage as Oh}from"@vkontakte/videoplayer-shared/es2015";var c_=5e3,$E="one_video_throughput",BE="one_video_rtt",Li=window.navigator.connection,DE=()=>{let s=Li==null?void 0:Li.downlink;if(Vl(s)&&s!==10)return s*1e3},CE=()=>{let s=Li==null?void 0:Li.rtt;if(Vl(s)&&s!==3e3)return s},VE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},_h=class s{constructor(e){this.subscription=new ME;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load($E)||(e.useBrowserEstimation?DE():void 0)||c_,i=(a=(r=s.load(BE))!=null?r:e.useBrowserEstimation?CE():void 0)!=null?a:0;if(this.throughput$=new Vh(t),this.rtt$=new Vh(i),this.rttAdjustedThroughput$=new Vh(VE(t,i,e.rttPenaltyRequestSize)),this.throughput=Pi.getSmoothedValue(t,-1,e),this.rtt=Pi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=DE();u&&this.throughput.next(u);let l=CE();Vl(l)&&this.rtt.next(l)};Li&&"onchange"in Li&&this.subscription.add(Cl(Li,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Oh.set($E,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Oh.set(BE,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})=>VE(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 ME;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=Oh.get(e);if(Vl(t))return(i=parseInt(t,10))!=null?i:void 0}},OE=_h;import{fillWithDefault as d_,VideoQuality as Ol}from"@vkontakte/videoplayer-shared/es2015";var _E={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:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:0,maxTvtToBeCounted:3*60*60,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,rejectOnSourceOpenTimeout:!1,vktvAbrThrottle:null},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},FE=s=>{var e;return D(E({},d_(s,_E)),{configName:[...(e=s.configName)!=null?e:[],..._E.configName]})};import{assertNonNullable as _l,combine as Mi,ErrorCategory as Fl,filter as Y,filterChanged as ae,fromEvent as Nh,isNonNullable as jE,isNullable as S_,Logger as v_,map as re,mapTo as HE,merge as Wi,now as Nl,once as Z,Subject as oe,Subscription as GE,tap as Uh,ValueSubject as O,isHigher as y_,isInvariantQuality as zE,flattenObject as Yi,throttle as qh,getTraceSubscriptionMethod as QE,Tracer as T_,InternalsExposure as I_}from"@vkontakte/videoplayer-shared/es2015";import{merge as p_,map as h_,filter as NE,isNonNullable as f_}from"@vkontakte/videoplayer-shared/es2015";var Fh=({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}),NE(f_)),e.pipe(NE(()=>s.getState().state==="none")));import{assertNonNullable as m_}from"@vkontakte/videoplayer-shared/es2015";var UE=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 qE=(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 GE;this.logger=new v_;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new O(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new O(!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 O(void 0),position$:new O(0),duration$:new O(1/0),muted$:new O(!1),volume$:new O(1),availableVideoStreams$:new O([]),currentVideoStream$:new O(void 0),availableQualities$:new O([]),availableQualitiesFps$:new O({}),currentQuality$:new O(void 0),isAutoQualityEnabled$:new O(!0),autoQualityLimitingAvailable$:new O(!1),autoQualityLimits$:new O({}),predefinedQualityLimitType$:new O("unknown"),availableAudioStreams$:new O([]),currentAudioStream$:new O(void 0),availableAudioTracks$:new O([]),isAudioAvailable$:new O(!0),currentPlaybackRate$:new O(1),currentBuffer$:new O({start:0,end:0}),isBuffering$:new O(!0),isStalled$:new O(!1),isEnded$:new O(!1),isLooped$:new O(!1),isLive$:new O(void 0),isLiveEnded$:new O(null),canChangePlaybackSpeed$:new O(void 0),atLiveEdge$:new O(void 0),atLiveDurationEdge$:new O(void 0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),liveLatency$:new O(void 0),currentFormat$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),throughputEstimation$:new O(void 0),rttEstimation$:new O(void 0),videoBitrate$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),surface$:new O("none"),chromecastState$:new O("NOT_AVAILABLE"),chromecastDeviceName$:new O(void 0),intrinsicVideoSize$:new O(void 0),availableSources$:new O(void 0),is3DVideo$:new O(!1),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(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 O(void 0),tuningConfigName$:new O([]),enableDebugTelemetry$:new O(!1),dumpTelemetry:Py,getCurrentTime$:new O(null)};if(this.initLogs(),this.tuning=FE(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 OE(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,WE.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=Gh(u,["container"]);this.tracer.log("initVideo",Yi(o)),this.domContainer=UE(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"),Nh(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;qE(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 jE(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(D(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(Mi({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(re(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>zE(u)?1:zE(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=>jE(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(Uh(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Mi({hasLiveOffsetByPaused: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(Mi({atLiveEdge:Mi({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Fh({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(),Uh(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(re(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Mi({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(re(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ae(),Uh(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(Fh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Wi(e.providerOutput.endedEvent$.pipe(HE(!0)),e.providerOutput.seekedEvent$.pipe(HE(!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 O(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new O(!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 GE;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=Zt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(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),wy(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Ey(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 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)),_a("codecs",G.video.supportedCodecs)}initTracerSubscription(){let e=QE(this.tracer.log.bind(this.tracer)),t=QE(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(ae()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Mi({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(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(Mi({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(qh(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(ae()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(ae()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(ae()).subscribe(e("canChangePlaybackSpeed"))).add(Mi({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Y(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),qh(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(Mi({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Y(({throughputEstimation:i,rtt:r})=>!!i&&!!r),qh(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(Nh(document,"visibilitychange"),Nh(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 Zte,Observable as eie,Subject as tie,ValueSubject as iie,VideoQuality as rie}from"@vkontakte/videoplayer-shared/es2015";var sie=`@vkontakte/videoplayer-core@${zh}`;export{$o as ChromecastState,Xl as HttpConnectionType,eie as Observable,lt as PlaybackState,Ul as Player,Bo as PredefinedQualityLimits,sie as SDK_VERSION,tie as Subject,Zte as Subscription,Jl as Surface,zh as VERSION,iie as ValueSubject,Si as VideoFormat,rie as VideoQuality,G as clientChecker,Va as isMobile};
|
|
185
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var th=j(jt(),1);import{videoSizeToQuality as fV}from"@vkontakte/videoplayer-shared/es2015";var Rx=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?ei(a):void 0)!=null?u:fV({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Lx=({id:s,bitrate:e})=>({id:s,bitrate:e}),Mx=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),$x=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),ih=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,th.default)(i.split("."),0),isDefault:r}),rh=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,th.default)(r.split("."),0)}),sh=s=>"url"in s,lt=s=>s.type==="template",uo=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Dx=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},wr=(s,e)=>{for(let t of s)if(e(t))return t;return null};var Cx=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},Ri=(s,e)=>{let t=s;t=(0,ah.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Vx.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,ah.default)(t,n,(o,u)=>Bx(a)?o:Bx(u)?a:(0,Ox.default)(a,parseInt(u,10),"0"))}return t},Fx=(s,e)=>{var _,A,F,M,H,N,K,P,$,R,w,V,de,Ne,ue,ee,Ee,we,Pe,Ue,Rt,$t,Yt,ri,Bi,ws,Ps,As,ks,Rs,Ls,Ms,$s,Ds,Bs,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,Je;return(Je=(q=fe.textContent)==null?void 0:q.trim())!=null?Je:""}),o=(_=(0,_x.default)(n,0))!=null?_:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,v=a.getAttribute("mediaPresentationDuration"),y=[...a.getElementsByTagName("Period")],T=y.reduce((fe,q)=>D(E({},fe),{[q.id]:q.children}),{}),I=y.reduce((fe,q)=>D(E({},fe),{[q.id]:q.getAttribute("duration")}),{});v?S=Cx(v):(0,nh.default)(I).filter(fe=>fe).length&&!u?S=(0,nh.default)(I).reduce((fe,q)=>{var Je;return fe+((Je=Cx(q))!=null?Je:0)},0):m&&(S=parseInt(m,10));let k=0,C=(F=(A=a.getAttribute("profiles"))==null?void 0:A.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),Dt=(H=q.getAttribute("mimeType"))!=null?H:"",Xi=(N=q.getAttribute("codecs"))!=null?N:"",Ji=(K=q.getAttribute("contentType"))!=null?K:Dt==null?void 0:Dt.split("/")[0],Fl=($=(P=q.getAttribute("profiles"))==null?void 0:P.split(","))!=null?$:[],oa=(w=kx((R=q.getAttribute("lang"))!=null?R:""))!=null?w:{},si=(Ne=(de=(V=q.querySelector("Label"))==null?void 0:V.textContent)==null?void 0:de.trim())!=null?Ne:void 0,Nl=q.querySelectorAll("Representation"),Ul=q.querySelector("SegmentTemplate"),ql=(ee=(ue=q.querySelector("Role"))==null?void 0:ue.getAttribute("value"))!=null?ee:void 0,bt=Ji,Q={id:Je,language:oa.language,isDefault:ql==="main",label:si,codecs:Xi,hdr:bt==="video"&&os(Xi),mime:Dt,representations:[]};for(let U of Nl){let Le=(Ee=U.getAttribute("lang"))!=null?Ee:void 0,Bt=(Pe=(we=si!=null?si:q.getAttribute("label"))!=null?we:U.getAttribute("label"))!=null?Pe:void 0,ai=($t=(Rt=(Ue=U.querySelector("BaseURL"))==null?void 0:Ue.textContent)==null?void 0:Rt.trim())!=null?$t:"",Ze=new URL(ai||o,e).toString(),Me=(Yt=U.getAttribute("mimeType"))!=null?Yt:Dt,ni=(Bi=(ri=U.getAttribute("codecs"))!=null?ri:Xi)!=null?Bi:"",oi;if(Ji==="text"){let $e=U.getAttribute("id")||"",ui=((ws=oa.privateuse)==null?void 0:ws.includes("x-auto"))||$e.includes("_auto"),et=U.querySelector("SegmentTemplate");if(et){let Ct={representationId:(Ps=U.getAttribute("id"))!=null?Ps:void 0,bandwidth:(As=U.getAttribute("bandwidth"))!=null?As:void 0},li=parseInt((ks=U.getAttribute("bandwidth"))!=null?ks:"",10)/1e3,ci=(Ls=parseInt((Rs=et.getAttribute("startNumber"))!=null?Rs:"",10))!=null?Ls:1,gt=parseInt((Ms=et.getAttribute("timescale"))!=null?Ms:"",10),Zi=($s=et.querySelectorAll("SegmentTimeline S"))!=null?$s:[],St=et.getAttribute("media");if(!St)continue;let di=[],pi=0,hi="",vt=0,Vt=ci,se=0;for(let me of Zi){let tt=parseInt((Ds=me.getAttribute("d"))!=null?Ds:"",10),ce=parseInt((Bs=me.getAttribute("r"))!=null?Bs:"",10)||0,De=parseInt((Cs=me.getAttribute("t"))!=null?Cs:"",10);se=Number.isFinite(De)?De:se;let it=tt/gt*1e3,Be=se/gt*1e3;for(let ve=0;ve<ce+1;ve++){let Ce=Ri(St,D(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:(se+ve*tt).toString(10)})),yt=(Be!=null?Be:0)+ve*it,_t=yt+it;Vt++,di.push({time:{from:yt,to:_t},url:Ce})}se+=(ce+1)*tt,pi+=(ce+1)*it}vt=se/gt*1e3,hi=Ri(St,D(E({},Ct),{segmentNumber:Vt.toString(10),segmentTime:se.toString(10)}));let Ot={time:{from:vt,to:1/0},url:hi},Ae={type:"template",baseUrl:Ze,segmentTemplateUrl:St,initUrl:"",totalSegmentsDurationMs:pi,segments:di,nextSegmentBeyondManifest:Ot,timescale:gt};oi={id:$e,kind:"text",segmentReference:Ae,profiles:[],duration:S,bitrate:li,mime:"",codecs:"",width:0,height:0,isAuto:ui}}else oi={id:$e,isAuto:ui,kind:"text",url:Ze}}else{let $e=(Os=(Vs=U.getAttribute("contentType"))!=null?Vs:Me==null?void 0:Me.split("/")[0])!=null?Os:Ji,ui=(Fs=(_s=q.getAttribute("profiles"))==null?void 0:_s.split(","))!=null?Fs:[],et=parseInt((Ns=U.getAttribute("width"))!=null?Ns:"",10),Ct=parseInt((Us=U.getAttribute("height"))!=null?Us:"",10),li=parseInt((qs=U.getAttribute("bandwidth"))!=null?qs:"",10)/1e3,ci=(js=U.getAttribute("frameRate"))!=null?js:"",gt=(Hs=U.getAttribute("quality"))!=null?Hs:void 0,Zi=ci?qu(ci):void 0,St=(Gs=U.getAttribute("id"))!=null?Gs:"id"+(k++).toString(10),di=$e==="video"?`${Ct}p`:$e==="audio"?`${li}Kbps`:ni,pi=`${St}@${di}`,hi=[...C,...Fl,...ui],vt,Vt=U.querySelector("SegmentBase"),se=(zs=U.querySelector("SegmentTemplate"))!=null?zs:Ul;if(Vt){let Ae=(Ws=(Qs=U.querySelector("SegmentBase Initialization"))==null?void 0:Qs.getAttribute("range"))!=null?Ws:"",[me,tt]=Ae.split("-").map(Ce=>parseInt(Ce,10)),ce={from:me,to:tt},De=(Ys=U.querySelector("SegmentBase"))==null?void 0:Ys.getAttribute("indexRange"),[it,Be]=De?De.split("-").map(Ce=>parseInt(Ce,10)):[],ve=De?{from:it,to:Be}:void 0;vt={type:"byteRange",url:Ze,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),tt=(Zs=se.getAttribute("initialization"))!=null?Zs:"",ce=se.getAttribute("media"),De=(ta=parseInt((ea=se.getAttribute("startNumber"))!=null?ea:"",10))!=null?ta:1,it=Ri(tt,Ae);if(!ce)throw new ReferenceError("No media attribute in SegmentTemplate");let Be=(ia=se.querySelectorAll("SegmentTimeline S"))!=null?ia:[],ve=[],Ce=0,yt="",_t=0;if(Be.length){let fi=De,be=0;for(let Tt of Be){let ye=parseInt((ra=Tt.getAttribute("d"))!=null?ra:"",10),rt=parseInt((sa=Tt.getAttribute("r"))!=null?sa:"",10)||0,mi=parseInt((aa=Tt.getAttribute("t"))!=null?aa:"",10);be=Number.isFinite(mi)?mi:be;let er=ye/me*1e3,tr=be/me*1e3;for(let bi=0;bi<rt+1;bi++){let Hl=Ri(ce,D(E({},Ae),{segmentNumber:fi.toString(10),segmentTime:(be+bi*ye).toString(10)})),ua=(tr!=null?tr:0)+bi*er,Gl=ua+er;fi++,ve.push({time:{from:ua,to:Gl},url:Hl})}be+=(rt+1)*ye,Ce+=(rt+1)*er}_t=be/me*1e3,yt=Ri(ce,D(E({},Ae),{segmentNumber:fi.toString(10),segmentTime:be.toString(10)}))}else if(mV(S)){let be=parseInt((na=se.getAttribute("duration"))!=null?na:"",10)/me*1e3,Tt=Math.ceil(S/be),ye=0;for(let rt=1;rt<Tt;rt++){let mi=Ri(ce,D(E({},Ae),{segmentNumber:rt.toString(10),segmentTime:ye.toString(10)}));ve.push({time:{from:ye,to:ye+be},url:mi}),ye+=be}_t=ye,yt=Ri(ce,D(E({},Ae),{segmentNumber:Tt.toString(10),segmentTime:ye.toString(10)}))}let jl={time:{from:_t,to:1/0},url:yt};vt={type:"template",baseUrl:Ze,segmentTemplateUrl:ce,initUrl:it,totalSegmentsDurationMs:Ce,segments:ve,nextSegmentBeyondManifest:jl,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),oi={id:pi,kind:Ot,segmentReference:vt,profiles:hi,duration:S,bitrate:li,mime:Me,codecs:ni,width:et,height:Ct,fps:Zi,quality:gt}}Q.language||(Q.language=Le),Q.label||(Q.label=Bt),Q.mime||(Q.mime=Me),Q.codecs||(Q.codecs=ni),Q.hdr||(Q.hdr=bt==="video"&&os(ni)),Q.representations.push(oi)}if(bt){let U=r[bt].find(Le=>Le.id===Q.id);if(U&&Q.representations.every(Le=>lt(Le.segmentReference)))for(let Le of U.representations){let Bt=Q.representations.find(Me=>Me.id===Le.id),ai=Bt==null?void 0:Bt.segmentReference,Ze=Le.segmentReference;Ze.segments.push(...ai.segments),Ze.nextSegmentBeyondManifest=ai.nextSegmentBeyondManifest}else r[bt].push(Q)}}return{duration:S,streams:r,baseUrls:n,live:g}};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 gV;this.gaps=[];this.subscription=new SV;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);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 yx(this.sourceBuffer),this.subscription.add(uh(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Li.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Li.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(uh(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Li.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!W(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=Qi(this.destroyAbortController.signal,function(e,t=!1){return X(this,null,function*(){if(!W(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||!W(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 ir(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(!W(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||!W(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 ir(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,ml.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){!W(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);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||!W(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(){!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)||!W(this.mediaSource,this.sourceBuffer)||gs(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);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=_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,fl.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)&&_e(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Ss.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}),i=a.time.to;gs(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,ml.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,ml.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=>D(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;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=Ri(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;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&ii&&ii(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ii&&ii(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){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&&W(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 Qi(o,function(){return X(this,null,function*(){let d=lh(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=hl(),!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())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 Qi(n,function(){return X(this,null,function*(){let u=lh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),uh(window,"online").pipe(bV()).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=hl(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),uo(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,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=hl(),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:Li.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=hl();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:Li.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,fl.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||!W(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||!W(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(!(Xe(this.sourceBuffer)||!W(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:Li.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",sh(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,Nx.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=lh(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&<(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:Li.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||!W(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Xe(e))return!1;let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push(E({},o.time));let u=sh(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,fl.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=Dx(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||!W(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||!W(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||!W(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||!W(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Xe(e)?0:_e(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!W(this.mediaSource,this.sourceBuffer))return;if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));let i={representation:e,from:t.time.from,to:t.time.to};for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=this.sourceBuffer.buffered.start(r)*1e3,n=this.sourceBuffer.buffered.end(r)*1e3;if(!(n<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&n>=t.time.to){i=void 0;break}n>t.time.from&&n<t.time.to&&(i.from=n),a<t.time.to&&a>t.time.from&&(i.to=a)}}i&&i.to-i.from>1&&!this.gaps.some(r=>i&&r.from===i.from&&r.to===i.to)&&this.gaps.push(i)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!W(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:Li.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Xe(this.sourceBuffer)||!W(this.mediaSource,this.sourceBuffer)||Xe(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:Li.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as co,assertNever as Ux,fromEvent as qx,merge as vV,now as po,Subject as jx,ValueSubject as ch,flattenObject as vs,ErrorCategory as ho,SubscriptionRemovable as yV}from"@vkontakte/videoplayer-shared/es2015";var gl=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new ch(void 0);this.lastConnectionReused$=new ch(void 0);this.lastRequestFirstBytes$=new ch(void 0);this.recoverableError$=new jx;this.error$=new jx;this.abortAllController=new le;this.subscription=new yV;this.fetchManifest=co(this.abortAllController.signal,function(e){return X(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Hi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(bl);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 P=new URL(d,location.href);P.searchParams.append("bytes",`${i.from}-${i.to}`),d=P.toString();break}default:Ux(t)}this.requestQuic&&(d=Hi(d));let p=this.abortAllController.signal,f;if(n){let P=new le;if(f=vV(qx(this.abortAllController.signal,"abort"),qx(n,"abort")).subscribe(()=>{try{P.abort()}catch($){bl($)}}),this.abortAllController.signal.aborted||n.aborted)try{P.abort()}catch($){bl($)}p=P.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 P=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:P}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let P=po(),$={requestStartedAt:m,requestEndedAt:P,duration:P-m};return h.log("endRequest",vs($)),h.end(),g.arrayBuffer()}let v=g.body;if(o){let P;[v,P]=g.body.tee(),(N=this.throughputEstimator)==null||N.trackStream(P,u)}let y=v.getReader(),T,I=parseInt((K=g.headers.get("content-length"))!=null?K:"",10);Number.isFinite(I)&&(T=I),!T&&i&&(T=i.to-i.from+1);let k=0,C=T?new Uint8Array(T):new Uint8Array(0),B=!1,_=P=>{this.unsubscribeAbortSubscription(f),B=!0,bl(P)},A=co(p,function(R){return X(this,arguments,function*({done:P,value:$}){if(k===0&&this.lastRequestFirstBytes$.next(po()-m),p.aborted){this.unsubscribeAbortSubscription(f);return}if(!P&&$){if(T)C.set($,k),k+=$.byteLength;else{let w=new Uint8Array(C.length+$.length);w.set(C),w.set($,C.length),C=w,k+=$.byteLength}r==null||r(new DataView(C.buffer),k),yield y==null?void 0:y.read().then(A,_)}})}.bind(this));yield y==null?void 0:y.read().then(A,_),this.unsubscribeAbortSubscription(f);let F=po(),M={failed:B,requestStartedAt:m,requestEndedAt:F,duration:F-m};return B?(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=>D(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:Ux(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))}},bl=s=>{if(!uo(s))throw s};import{isNullable as TV,ValueSubject as IV}from"@vkontakte/videoplayer-shared/es2015";var fo=class s{constructor(e,t){this.currentRepresentation$=new IV(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(!TV(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(D(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 kV=["timeupdate","progress","play","seeked","stalled","waiting"],RV=["timeupdate","progress","loadeddata","playing","seeked"];var yl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new mh;this.representationSubscription=new mh;this.state$=new z("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 vl;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 vl;this.fetcherError$=new vl;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new vl;this.gapWatchdogActive=!1;this.destroyController=new le;this.initManifest=ph(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=ph(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=Fx(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=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=D(E({},t),{streams:r});return this.tracer.log("updateManifestEnd",bo(a)),a})}.bind(this));this.initRepresentations=ph(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 mh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Mi(p,"error").pipe(Sl(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(...RV.map(p=>Mi(this.element,p))).pipe(Is(p=>this.element?_e(this.element.buffered,this.element.currentTime*1e3):0),mo(),PV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ar(Mi(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(mo()).subscribe(f=>this.liveStreamEndTimestamp=fh())),this.subscription.add(Mi(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=hh(1e3).subscribe(f=>{let m=_i(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Mi(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(Sl(({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(Sl(({isLive:f})=>f),mo((f,m)=>m.bufferLength<f.bufferLength),Is(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=_i(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(AV(1e3)).subscribe(g=>x(this,[g],function*({liveLoadBufferLength:f,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,v=_i(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,B=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),_=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(_);let A="none";if(B?A="active_low_latency":this.isLowLatency$.getValue()&&_?(this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),A="active_low_latency"):v!==0&&C<T?A="live_forward_buffering":C<T+k&&(A="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),A==="live_forward_buffering"||A==="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)}(A==="live_with_target_offset"||A==="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),Sl(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,bh.default)((0,bh.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&&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=hh(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 gl({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=Pi.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"?fh()-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"),this.subscription.add(Ar(...kV.map(e=>Mi(this.element,e)),Mi(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Qt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Mi(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(Mi(this.element,"waiting").subscribe(()=>{var t;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 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=fh(),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 B=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(B).catch(_=>{this.error$.next({id:"stallIntervalCallback",category:Qt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:_})}),r.liveLastOffset=B}else{let B=this.element.currentTime*1e3;(k=this.videoBufferManager)==null||k.maintain(B),(C=this.audioBufferManager)==null||C.maintain(B),r.position=B}this.tracer.log("stallIntervalCallback",bo(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=hh(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Qt.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;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),Ye(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(Gx(this.element)||Gx(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=wV(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();this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,r=null,a=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-a<=i&&o.to+a>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r=1/0:(r===null||o.to>r)&&(r=o.to));if(r!==null){let n=r+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,this.tracer.log("jumpGap",bo({isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime,jumpTo:n,resultCurrentTime:this.element.currentTime})))}}};import{combine as LV,map as MV,observeElementSize as $V,Subscription as DV,ValueSubject as gh,noop as BV}from"@vkontakte/videoplayer-shared/es2015";var Tl=class{constructor(){this.subscription=new DV;this.pipSize$=new gh(void 0);this.videoSize$=new gh(void 0);this.elementSize$=new gh(void 0);this.pictureInPictureWindowRemoveEventListener=BV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add($V(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(LV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(MV(({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 NV;this.videoState=new z("stopped");this.droppedFramesManager=new ts;this.stallsManager=new ll;this.elementSizeManager=new Tl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ui;this.audioTrackSwitchHistory=new Ui;this.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 VV(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 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 yl({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:zx.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(Qx(l=>!!l.length),Yx()).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(Sh(l=>l.to.state!=="none"),Il());this.stallsManager.connect({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(Qx(Wx),Yx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Sh(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(OV(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(ih(p));let f=[];for(let m of p.representations){let g=Lx(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(rh(h));let p=[];for(let f of h.representations){let m=Rx(D(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=Mx(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(xl(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,FV(this.video,"progress")).subscribe(()=>x(this,null,function*(){let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:c,audio:h}=this.selectedRepresentations;if(!c)return;let p=wr(this.videoTracksMap.keys(),m=>{var g;return((g=this.videoTracksMap.get(m))==null?void 0:g.representation.id)===c.id});Wx(p)&&(this.stallsManager.lastVideoTrackSelected=p);let f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")yield this.player.initRepresentations(c.id,h==null?void 0:h.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",c.id),h){let m=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.id,m)}}),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(Il()).subscribe(l=>{let d=wr(this.videoTracksMap.entries(),([,{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(rh(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Il()).subscribe(l=>{let d=wr(this.audioTracksMap.entries(),([,{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(ih(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(Sh(({to:l})=>l==="ready"),Il());this.subscription.add(xl(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,vh(["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(xl(o,this.player.state$.stateChangeEnded$,vh(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=xl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,vh(["init"])).pipe(_V(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var B,_,A,F,M,H,N,K,P,$,R,w;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Fa:_a,t=this.params.tuning.useNewAutoSelectVideoTrack?Bu:Du,i=this.params.tuning.useNewAutoSelectVideoTrack?ti:$u,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(B=r.videoTrack.getState())==null?void 0:B.id,u=wr(this.videoTracksMap.keys(),V=>V.id===o),l=a.currentVideoTrack$.getValue(),d=((F=(A=r.videoStream.getState())!=null?A:u&&((_=this.videoTracksMap.get(u))==null?void 0:_.stream))!=null?F:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=wr(this.videoStreamsMap.keys(),V=>V.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)&&wr(this.audioStreamsMap.keys(),V=>V.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(v){if(u&&!n){let V=e(u,h,(H=this.audioStreamsMap.get(v))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(N=V==null?void 0:V.bitrate)!=null?N:-1/0)}if(l){let V=e(l,h,(K=this.audioStreamsMap.get(v))!=null?K:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(P=V==null?void 0:V.bitrate)!=null?P:-1/0)}}let T=u;(n||!T)&&(T=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let I=v&&t(T,h,($=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&&((w=this.audioTracksMap.get(I))==null?void 0:w.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:zx.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 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 yh,merge as Kx,filter as Xx,filterChanged as UV,isNullable as Th,map as Jx,ValueSubject as Ih,isNonNullable as qV}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 Ih(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(Jx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(yh({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Jx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Xx(o=>qV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(yh({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Kx(i.playbackRateState$,new Ih(1))}).pipe(Xx(({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||Th(l)||(e=o-l)})).add(yh({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Kx(i.playbackRateState$,new Ih(1))}).pipe(UV((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||Th(o)||Th(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=$x(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 eE=j($a(),1);import{assertNever as yo,assertNonNullable as Zx,debounce as jV,ErrorCategory as El,filter as HV,isNonNullable as GV,isNullable as zV,map as wl,merge as QV,Observable as WV,observableFrom as YV,Subscription as KV,videoSizeToQuality as XV}from"@vkontakte/videoplayer-shared/es2015";var Wt={};var xs=(s,e)=>new WV(t=>{let i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)}),To=class{constructor(e){this.subscription=new KV;this.videoState=new z("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 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:El.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,eE.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(){Zx(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(){Zx(Wt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:El.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(wl(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:El.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(wl(({levels:l})=>l.reduce((d,c)=>{var v,y;let h=c.name||c.height.toString(10),{width:p,height:f}=c,m=(y=ei((v=c.attrs.QUALITY)!=null?v:""))!=null?y:XV({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(wl(({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(Fi(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(wl(({level:l})=>n(this.hls.levels[l])));o.pipe(HV(GV)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Fi(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(zV(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=QV(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,YV(["init"])).pipe(jV(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:El.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 tE="X-Playback-Duration",xh=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(tE)?parseInt(e.headers.get(tE),10):void 0});import{assertNever as uO,combine as lO,debounce as cO,ErrorCategory as kl,filter as dO,filterChanged as pO,isNonNullable as sE,isNullable as Rl,map as aE,merge as hO,observableFrom as fO,Subscription as mO,ValueSubject as Ph,VideoQuality as bO}from"@vkontakte/videoplayer-shared/es2015";var wh=j(td(),1);import{videoSizeToQuality as JV,getExponentialDelay as ZV}from"@vkontakte/videoplayer-shared/es2015";var eO=s=>{let e=null;if(s.QUALITY&&(e=ei(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=JV({width:t,height:i})}return e!=null?e:null},tO=(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,wh.default)(l[1].split(",").map(v=>v.split("="))),h=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,p=eO(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,wh.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}},iO=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),Eh=0,iE=(r,...a)=>x(void 0,[r,...a],function*(s,e=s,t,i){let o=yield(yield Mt(s,i)).text();Eh+=1;try{let{qualityManifests:u,textTracks:l}=tO(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(Eh<=t.manifestRetryMaxCount)return yield iO(ZV(Eh-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),iE(s,e,t)}return{qualityManifests:[],textTracks:[]}}),Pl=iE;import{isNonNullable as rO,Subscription as sO,throttle as aO,ValueSubject as rE,Subject as nO,ErrorCategory as oO}from"@vkontakte/videoplayer-shared/es2015";var Al=class{constructor(e,t,i,r,a){this.subscription=new sO;this.abortControllers={destroy:new le,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new rE(null);this.getCurrentTime$=new rE(null);this.error$=new nO;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(aO(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(rO(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([D(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:oO.WTF,thrown:t,message:e})}};var Io=class{constructor(e){this.subscription=new mO;this.videoState=new z("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Ph([]);this.liveOffset=new br;this.manifestStartTime$=new Ph(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 uO(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:bO.INVARIANT,url:this.params.source.url};let t=(r,a)=>Pl(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 Al(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:kl.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:kl.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 Ph((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:kl.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(pO(),aE(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&&sE(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(lO({startTime:this.manifestStartTime$.pipe(dO(sE)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(aE(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=hO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,fO(["init"])).pipe(cO(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(Rl(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(),xh(n).then(d=>{var c;if(!Rl(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(Rl(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();xh(g).then(S=>{Rl(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:kl.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 gO,debounce as SO,ErrorCategory as Ah,fromEvent as kh,isNonNullable as vO,isNullable as yO,map as nE,merge as oE,observableFrom as uE,Subscription as TO,ValueSubject as IO,VideoQuality as xO}from"@vkontakte/videoplayer-shared/es2015";var xo=class{constructor(e){this.subscription=new TO;this.videoState=new z("stopped");this.manifests$=new IO([]);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 gO(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:xO.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),Pl(Ie(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ah.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Ah.WTF,message:"HlsProvider internal logic error",thrown:o})},r=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(nE(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&&vO(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(nE(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(oE(kh(o,"addtrack"),kh(o,"removetrack"),kh(o,"change"),uE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=oE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,uE(["init"])).pipe(SO(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(yO(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:Ah.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var dE=j(or(),1),Rh=j(mr(),1),pE=j(jt(),1);import{assertNever as EO,assertNonNullable as lE,debounce as wO,ErrorCategory as cE,isHigherOrEqual as PO,isLowerOrEqual as AO,isNonNullable as kO,merge as RO,observableFrom as LO,Subscription as MO,map as $O}from"@vkontakte/videoplayer-shared/es2015";var Eo=class{constructor(e){this.subscription=new MO;this.videoState=new z("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 EO(e)}};this.params=e,this.video=He(e.container,e.tuning),this.params.output.element$.next(this.video),(0,dE.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,Rh.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:cE.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($O(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&&kO(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=RO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,LO(["init"])).pipe(wO(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;lE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];lE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Hi(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:cE.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=ti(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,Rh.default)(this.trackUrls).map(c=>c.track);if(!r||!a||Kr(e,n[0].quality,(d=(0,pE.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?AO(r,e.max):!0,u=e.min?PO(r,e.min):!0;o&&u||i(e)}};import{assertNever as fE,debounce as VO,merge as mE,observableFrom as OO,Subscription as _O,map as bE,ValueSubject as FO,ErrorCategory as Mh,VideoQuality as NO}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as DO}from"@vkontakte/videoplayer-shared/es2015";var hE=["stun:videostun.mycdn.me:80"],BO=1e3,CO=3,Lh=()=>null,Ll=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=Lh;this.externalStopCallback=Lh;this.externalErrorCallback=Lh;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:hE}]};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:DO.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),BO)}normalizeOptions(e={}){let t={stunServerList:hE,maxRetryNumber:CO,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 z("stopped");this.maxSeekBackTime$=new FO(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 fE(e)}};this.subscription=new _O,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=He(e.container,e.tuning),this.liveStreamClient=new Ll(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:Mh.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(mE(this.videoState.stateChangeStarted$.pipe(bE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(bE(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 fE(n.to)}},i)).add(mE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,OO(["init"])).pipe(VO(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:NO.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:Mh.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:Mh.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 Wi,ErrorCategory as Ml,filter as IE,isNonNullable as xE,isNullable as QO,map as WO,merge as YO,once as KO,Subject as Fe,Subscription as EE,ValueSubject as J,flattenObject as $h}from"@vkontakte/videoplayer-shared/es2015";import{Observable as UO,map as gE,Subscription as qO,Subject as jO}from"@vkontakte/videoplayer-shared/es2015";var SE=s=>new UO(e=>{let t=new qO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(gE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(gE(({type:l})=>l!==void 0)),n=new jO,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 HO,Subscription as GO,combine as zO,filter as yE,once as TE}from"@vkontakte/videoplayer-shared/es2015";function vE(){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 GO;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(yE(a=>!!a.type),TE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){G.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(zO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(yE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),TE()).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=vE();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:HO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ao.errorId} exception`,thrown:e})}};Ao.errorId="VolumeMultiplierManager";var Es=Ao;var XO={chunkDuration:5e3,maxParallelRequests:5},Ro=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 EE;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=ZI([...tx(this.params.tuning),...ex(this.params.tuning)],this.params.tuning).filter(l=>xE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Dh.default)(r,l)),...t.filter(l=>(0,Dh.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",$h(a)),this.screenFormatsIterator=new Po(a);let n=[...Vp(!0),...Vp(!1)];this.chromecastFormatsIterator=new Po(n.filter(l=>xE(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(QO(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Ml.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 Wi(u),this.params.tuning.useNewDashProvider?new So(D(E({},o),{source:u,sourceHls:l})):new Bn(D(E({},o),{source:u,sourceHls:l}))}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Wi(u),this.params.tuning.useNewDashProvider?new vo(D(E({},o),{source:u})):new Cn(D(E({},o),{source:u}))}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Wi(u),G.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new xo(D(E({},o),{source:u})):new To(D(E({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Wi(u),new Io(D(E({},o),{source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Wi(u),new Eo(D(E({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Wi(u),new Zy(D(E({},o),{source:u,config:D(E({},XO),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Wi(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 Wi(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 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 D(E({},e),{url:i(e.url)})}return(0,PE.default)((0,wE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new EE,t=!1,i=0;return e.add(YO(this.providerOutput.error$.pipe(IE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),SE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(WO(r=>({id:`ProviderHangup:${r}`,category:Ml.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(IE(({to:a})=>a==="playing"),KO()).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===Ml.NETWORK,u=r.category===Ml.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=D(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",$h(n)):this.tracer.error("providerError",$h(n))})),e}};import{fromEvent as $l,once as JO,combine as ZO,Subscription as AE,ValueSubject as Bh,map as e_,filter as t_,isNonNullable as Dl,now as kt,safeStorage as Ch}from"@vkontakte/videoplayer-shared/es2015";var i_=5e3,kE="one_video_throughput",RE="one_video_rtt",$i=window.navigator.connection,LE=()=>{let s=$i==null?void 0:$i.downlink;if(Dl(s)&&s!==10)return s*1e3},ME=()=>{let s=$i==null?void 0:$i.rtt;if(Dl(s)&&s!==3e3)return s},$E=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Vh=class s{constructor(e){this.subscription=new AE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(kE)||(e.useBrowserEstimation?LE():void 0)||i_,i=(a=(r=s.load(RE))!=null?r:e.useBrowserEstimation?ME():void 0)!=null?a:0;if(this.throughput$=new Bh(t),this.rtt$=new Bh(i),this.rttAdjustedThroughput$=new Bh($E(t,i,e.rttPenaltyRequestSize)),this.throughput=Pi.getSmoothedValue(t,-1,e),this.rtt=Pi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=LE();u&&this.throughput.next(u);let l=ME();Dl(l)&&this.rtt.next(l)};$i&&"onchange"in $i&&this.subscription.add($l($i,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Ch.set(kE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Ch.set(RE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(ZO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(e_(({throughput:n,rtt:o})=>$E(n,o,e.rttPenaltyRequestSize)),t_(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 AE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add($l(e,"progress").pipe(JO()).subscribe(a=>{t=a.loaded,i=kt()}));break;case 1:case 0:r.add($l(e,"loadstart").subscribe(()=>{t=0,i=kt()}));break}r.add($l(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=Ch.get(e);if(Dl(t))return(i=parseInt(t,10))!=null?i:void 0}},DE=Vh;import{fillWithDefault as r_,VideoQuality as Bl}from"@vkontakte/videoplayer-shared/es2015";var BE={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:Bl.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Bl.Q_720P,trafficSavingLimit:Bl.Q_480P},stallsManager:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:0,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:Bl.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},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},CE=s=>{var e;return D(E({},r_(s,BE)),{configName:[...(e=s.configName)!=null?e:[],...BE.configName]})};import{assertNonNullable as Cl,combine as Di,ErrorCategory as Vl,filter as Y,filterChanged as ae,fromEvent as _h,isNonNullable as FE,isNullable as c_,Logger as d_,map as re,mapTo as NE,merge as Yi,now as Ol,once as Z,Subject as oe,Subscription as UE,tap as Fh,ValueSubject as O,isHigher as p_,isInvariantQuality as qE,flattenObject as Ki,throttle as Nh,getTraceSubscriptionMethod as jE,Tracer as h_,InternalsExposure as f_}from"@vkontakte/videoplayer-shared/es2015";import{merge as s_,map as a_,filter as VE,isNonNullable as n_}from"@vkontakte/videoplayer-shared/es2015";var Oh=({seekState:s,position$:e})=>s_(s.stateChangeEnded$.pipe(a_(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),VE(n_)),e.pipe(VE(()=>s.getState().state==="none")));import{assertNonNullable as o_}from"@vkontakte/videoplayer-shared/es2015";var OE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return o_(e,`Wrong container or containerId {${s.container}}`),e};import{filter as u_,once as l_}from"@vkontakte/videoplayer-shared/es2015";var _E=(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(u_(r=>r.length>0),l_()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var _l=class{constructor(e={configName:[]},t=h_.createRootTracer(!1)){this.subscription=new UE;this.logger=new d_;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new O(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new O(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new z("stopped"),seekState:new z({state:"none"}),volume:new z({volume:1,muted:!1}),videoTrack:new z(void 0),videoStream:new z(void 0),audioStream:new z(void 0),autoVideoTrackSwitching:new z(!0),autoVideoTrackLimits:new z({}),isLooped:new z(!1),isLowLatency:new z(!1),playbackRate:new z(1),externalTextTracks:new z([]),internalTextTracks:new z([]),currentTextTrack:new z(void 0),textTrackCuesSettings:new z({}),cameraOrientation:new z({x:0,y:0})};this.info={playbackState$:new O(void 0),position$:new O(0),duration$:new O(1/0),muted$:new O(!1),volume$:new O(1),availableVideoStreams$:new O([]),currentVideoStream$:new O(void 0),availableQualities$:new O([]),availableQualitiesFps$:new O({}),currentQuality$:new O(void 0),isAutoQualityEnabled$:new O(!0),autoQualityLimitingAvailable$:new O(!1),autoQualityLimits$:new O({}),predefinedQualityLimitType$:new O("unknown"),availableAudioStreams$:new O([]),currentAudioStream$:new O(void 0),availableAudioTracks$:new O([]),isAudioAvailable$:new O(!0),currentPlaybackRate$:new O(1),currentBuffer$:new O({start:0,end:0}),isBuffering$:new O(!0),isStalled$:new O(!1),isEnded$:new O(!1),isLooped$:new O(!1),isLive$:new O(void 0),isLiveEnded$:new O(null),canChangePlaybackSpeed$:new O(void 0),atLiveEdge$:new O(void 0),atLiveDurationEdge$:new O(void 0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),liveLatency$:new O(void 0),currentFormat$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),throughputEstimation$:new O(void 0),rttEstimation$:new O(void 0),videoBitrate$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),surface$:new O("none"),chromecastState$:new O("NOT_AVAILABLE"),chromecastDeviceName$:new O(void 0),intrinsicVideoSize$:new O(void 0),availableSources$:new O(void 0),is3DVideo$:new O(!1),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(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 O(void 0),tuningConfigName$:new O([]),enableDebugTelemetry$:new O(!1),dumpTelemetry:wy,getCurrentTime$:new O(null)};if(this.initLogs(),this.tuning=CE(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 DE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f_("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,HE.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:Vl.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=jh(u,["container"]);this.tracer.log("initVideo",Ki(o)),this.domContainer=OE(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"),_h(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(()=>{Cl(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",Ki(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;Cl(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",Ki(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;_E(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(c_(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return FE(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(Yi(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(Zd(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Y(({from:e})=>e==="stopped"),Z()).subscribe(()=>{this.initedAt=Ol(),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",Ki(n)),n.state==="requested"?this.desiredState.seekState.setState(D(E({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Vl.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",Ki(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(Di({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:p_(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=>FE(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(Fh(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(Di({hasLiveOffsetByPaused:Yi(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(Di({atLiveEdge:Di({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Oh({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(),Fh(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(re(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Di({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(),Fh(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(Oh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Yi(e.providerOutput.endedEvent$.pipe(NE(!0)),e.providerOutput.seekedEvent$.pipe(NE(!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:Vl.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:Ol()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Z(),re(()=>Ol()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Z(),re(()=>Ol()-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 O(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new O(!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=Yi(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(Yi(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(Yi(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 UE;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=ti(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(Yi(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;Cl(this.providerContainer),Cl(e),Ey(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>xy(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 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)),Oa("codecs",G.video.supportedCodecs)}initTracerSubscription(){let e=jE(this.tracer.log.bind(this.tracer)),t=jE(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(Di({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(Di({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(Nh(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(Di({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Y(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Nh(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(Di({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Y(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Nh(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:Vl.DOM,message:String(r)})})});this.subscription.add(Yi(_h(document,"visibilitychange"),_h(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",Ki({quality:t,availableTracks:Ki(e),track:Ki(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 _te,Observable as Fte,Subject as Nte,ValueSubject as Ute,VideoQuality as qte}from"@vkontakte/videoplayer-shared/es2015";var jte=`@vkontakte/videoplayer-core@${Hh}`;export{Mo as ChromecastState,Wl as HttpConnectionType,Fte as Observable,ct as PlaybackState,_l as Player,$o as PredefinedQualityLimits,jte as SDK_VERSION,Nte as Subject,_te as Subscription,Yl as Surface,Hh as VERSION,Ute as ValueSubject,gi as VideoFormat,qte as VideoQuality,G as clientChecker,Va as isMobile};
|