@vkontakte/videoplayer-core 2.0.150-dev.f4d0e2c9.0 → 2.0.151-dev.0ce40db4.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 +37 -37
- package/es2015.esm.js +37 -37
- package/es2018.cjs +31 -31
- package/es2018.esm.js +36 -36
- package/es2024.cjs +33 -33
- package/es2024.esm.js +32 -32
- package/esnext.cjs +33 -33
- package/esnext.esm.js +32 -32
- package/evergreen.esm.js +42 -42
- package/package.json +2 -2
- package/types/index.d.ts +1 -0
- package/types/player/Player.d.ts +3 -1
- package/types/player/types.d.ts +21 -0
- package/types/providers/DashProvider/lib/fetcher.d.ts +20 -1
- package/types/providers/DashProvider/lib/player.d.ts +3 -1
- package/types/providers/DashProviderVirtual/lib/buffer/types.d.ts +2 -1
- package/types/providers/DashProviderVirtual/lib/buffer/virtualBuffer/baseVirtualBufferManager.d.ts +3 -2
- package/types/providers/DashProviderVirtual/lib/fetcher.d.ts +20 -1
- package/types/providers/DashProviderVirtual/lib/player/basePlayer.d.ts +4 -2
- package/types/providers/types.d.ts +3 -1
- package/types/providers/utils/videoStreamRepresentaionsFilter.d.ts +4 -0
- package/types/utils/tuningConfig.d.ts +5 -0
package/es2018.esm.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
* Tue,
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.151-dev.0ce40db4.0
|
|
3
|
+
* Tue, 03 Feb 2026 17:23:08 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-151/doc/
|
|
5
5
|
*/
|
|
6
|
-
var Pw=Object.create;var ph=Object.defineProperty;var Aw=Object.getOwnPropertyDescriptor;var kw=Object.getOwnPropertyNames;var Rw=Object.getPrototypeOf,$w=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Mw=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of kw(e))!$w.call(a,r)&&r!==t&&ph(a,r,{get:()=>e[r],enumerable:!(i=Aw(e,r))||i.enumerable});return a};var _=(a,e,t)=>(t=a!=null?Pw(Rw(a)):{},Mw(e||!a||!a.__esModule?ph(t,"default",{value:a,enumerable:!0}):t,a));var ne=b(($u,mh)=>{"use strict";var Jr=function(a){return a&&a.Math===Math&&a};mh.exports=Jr(typeof globalThis=="object"&&globalThis)||Jr(typeof window=="object"&&window)||Jr(typeof self=="object"&&self)||Jr(typeof global=="object"&&global)||Jr(typeof $u=="object"&&$u)||function(){return this}()||Function("return this")()});var me=b((CO,fh)=>{"use strict";fh.exports=function(a){try{return!!a()}catch(e){return!0}}});var Zr=b((LO,bh)=>{"use strict";var Cw=me();bh.exports=!Cw(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Mu=b((DO,yh)=>{"use strict";var Lw=Zr(),Sh=Function.prototype,gh=Sh.apply,vh=Sh.call;yh.exports=typeof Reflect=="object"&&Reflect.apply||(Lw?vh.bind(gh):function(){return vh.apply(gh,arguments)})});var fe=b((BO,Eh)=>{"use strict";var Th=Zr(),Ih=Function.prototype,Cu=Ih.call,Dw=Th&&Ih.bind.bind(Cu,Cu);Eh.exports=Th?Dw:function(a){return function(){return Cu.apply(a,arguments)}}});var vi=b((VO,xh)=>{"use strict";var wh=fe(),Bw=wh({}.toString),Vw=wh("".slice);xh.exports=function(a){return Vw(Bw(a),8,-1)}});var Lu=b((_O,Ph)=>{"use strict";var _w=vi(),Ow=fe();Ph.exports=function(a){if(_w(a)==="Function")return Ow(a)}});var oe=b((OO,Ah)=>{"use strict";var Du=typeof document=="object"&&document.all;Ah.exports=typeof Du=="undefined"&&Du!==void 0?function(a){return typeof a=="function"||a===Du}:function(a){return typeof a=="function"}});var qe=b((NO,kh)=>{"use strict";var Nw=me();kh.exports=!Nw(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ue=b((FO,Rh)=>{"use strict";var Fw=Zr(),dn=Function.prototype.call;Rh.exports=Fw?dn.bind(dn):function(){return dn.apply(dn,arguments)}});var Bu=b(Ch=>{"use strict";var $h={}.propertyIsEnumerable,Mh=Object.getOwnPropertyDescriptor,qw=Mh&&!$h.call({1:2},1);Ch.f=qw?function(e){var t=Mh(this,e);return!!t&&t.enumerable}:$h});var ea=b((UO,Lh)=>{"use strict";Lh.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Bh=b((jO,Dh)=>{"use strict";var Uw=fe(),jw=me(),Hw=vi(),Vu=Object,Qw=Uw("".split);Dh.exports=jw(function(){return!Vu("z").propertyIsEnumerable(0)})?function(a){return Hw(a)==="String"?Qw(a,""):Vu(a)}:Vu});var ta=b((HO,Vh)=>{"use strict";Vh.exports=function(a){return a==null}});var Qt=b((QO,_h)=>{"use strict";var Ww=ta(),zw=TypeError;_h.exports=function(a){if(Ww(a))throw new zw("Can't call method on "+a);return a}});var Si=b((WO,Oh)=>{"use strict";var Gw=Bh(),Yw=Qt();Oh.exports=function(a){return Gw(Yw(a))}});var Le=b((zO,Nh)=>{"use strict";var Kw=oe();Nh.exports=function(a){return typeof a=="object"?a!==null:Kw(a)}});var yi=b((GO,Fh)=>{"use strict";Fh.exports={}});var Pt=b((YO,Uh)=>{"use strict";var _u=yi(),Ou=ne(),Xw=oe(),qh=function(a){return Xw(a)?a:void 0};Uh.exports=function(a,e){return arguments.length<2?qh(_u[a])||qh(Ou[a]):_u[a]&&_u[a][e]||Ou[a]&&Ou[a][e]}});var ia=b((KO,jh)=>{"use strict";var Jw=fe();jh.exports=Jw({}.isPrototypeOf)});var Ti=b((XO,Wh)=>{"use strict";var Zw=ne(),Hh=Zw.navigator,Qh=Hh&&Hh.userAgent;Wh.exports=Qh?String(Qh):""});var Fu=b((JO,Jh)=>{"use strict";var Xh=ne(),Nu=Ti(),zh=Xh.process,Gh=Xh.Deno,Yh=zh&&zh.versions||Gh&&Gh.version,Kh=Yh&&Yh.v8,rt,pn;Kh&&(rt=Kh.split("."),pn=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!pn&&Nu&&(rt=Nu.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=Nu.match(/Chrome\/(\d+)/),rt&&(pn=+rt[1])));Jh.exports=pn});var qu=b((ZO,em)=>{"use strict";var Zh=Fu(),ex=me(),tx=ne(),ix=tx.String;em.exports=!!Object.getOwnPropertySymbols&&!ex(function(){var a=Symbol("symbol detection");return!ix(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Zh&&Zh<41})});var Uu=b((eN,tm)=>{"use strict";var rx=qu();tm.exports=rx&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ju=b((tN,im)=>{"use strict";var ax=Pt(),sx=oe(),nx=ia(),ox=Uu(),ux=Object;im.exports=ox?function(a){return typeof a=="symbol"}:function(a){var e=ax("Symbol");return sx(e)&&nx(e.prototype,ux(a))}});var ra=b((iN,rm)=>{"use strict";var lx=String;rm.exports=function(a){try{return lx(a)}catch(e){return"Object"}}});var mt=b((rN,am)=>{"use strict";var cx=oe(),dx=ra(),px=TypeError;am.exports=function(a){if(cx(a))return a;throw new px(dx(a)+" is not a function")}});var aa=b((aN,sm)=>{"use strict";var hx=mt(),mx=ta();sm.exports=function(a,e){var t=a[e];return mx(t)?void 0:hx(t)}});var om=b((sN,nm)=>{"use strict";var Hu=Ue(),Qu=oe(),Wu=Le(),fx=TypeError;nm.exports=function(a,e){var t,i;if(e==="string"&&Qu(t=a.toString)&&!Wu(i=Hu(t,a))||Qu(t=a.valueOf)&&!Wu(i=Hu(t,a))||e!=="string"&&Qu(t=a.toString)&&!Wu(i=Hu(t,a)))return i;throw new fx("Can't convert object to primitive value")}});var at=b((nN,um)=>{"use strict";um.exports=!0});var dm=b((oN,cm)=>{"use strict";var lm=ne(),bx=Object.defineProperty;cm.exports=function(a,e){try{bx(lm,a,{value:e,configurable:!0,writable:!0})}catch(t){lm[a]=e}return e}});var sa=b((uN,mm)=>{"use strict";var gx=at(),vx=ne(),Sx=dm(),pm="__core-js_shared__",hm=mm.exports=vx[pm]||Sx(pm,{});(hm.versions||(hm.versions=[])).push({version:"3.43.0",mode:gx?"pure":"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var zu=b((lN,bm)=>{"use strict";var fm=sa();bm.exports=function(a,e){return fm[a]||(fm[a]=e||{})}});var ir=b((cN,gm)=>{"use strict";var yx=Qt(),Tx=Object;gm.exports=function(a){return Tx(yx(a))}});var st=b((dN,vm)=>{"use strict";var Ix=fe(),Ex=ir(),wx=Ix({}.hasOwnProperty);vm.exports=Object.hasOwn||function(e,t){return wx(Ex(e),t)}});var Gu=b((pN,Sm)=>{"use strict";var xx=fe(),Px=0,Ax=Math.random(),kx=xx(1.1.toString);Sm.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+kx(++Px+Ax,36)}});var Ie=b((hN,Tm)=>{"use strict";var Rx=ne(),$x=zu(),ym=st(),Mx=Gu(),Cx=qu(),Lx=Uu(),rr=Rx.Symbol,Yu=$x("wks"),Dx=Lx?rr.for||rr:rr&&rr.withoutSetter||Mx;Tm.exports=function(a){return ym(Yu,a)||(Yu[a]=Cx&&ym(rr,a)?rr[a]:Dx("Symbol."+a)),Yu[a]}});var xm=b((mN,wm)=>{"use strict";var Bx=Ue(),Im=Le(),Em=ju(),Vx=aa(),_x=om(),Ox=Ie(),Nx=TypeError,Fx=Ox("toPrimitive");wm.exports=function(a,e){if(!Im(a)||Em(a))return a;var t=Vx(a,Fx),i;if(t){if(e===void 0&&(e="default"),i=Bx(t,a,e),!Im(i)||Em(i))return i;throw new Nx("Can't convert object to primitive value")}return e===void 0&&(e="number"),_x(a,e)}});var Ku=b((fN,Pm)=>{"use strict";var qx=xm(),Ux=ju();Pm.exports=function(a){var e=qx(a,"string");return Ux(e)?e:e+""}});var hn=b((bN,km)=>{"use strict";var jx=ne(),Am=Le(),Xu=jx.document,Hx=Am(Xu)&&Am(Xu.createElement);km.exports=function(a){return Hx?Xu.createElement(a):{}}});var Ju=b((gN,Rm)=>{"use strict";var Qx=qe(),Wx=me(),zx=hn();Rm.exports=!Qx&&!Wx(function(){return Object.defineProperty(zx("div"),"a",{get:function(){return 7}}).a!==7})});var Cm=b(Mm=>{"use strict";var Gx=qe(),Yx=Ue(),Kx=Bu(),Xx=ea(),Jx=Si(),Zx=Ku(),eP=st(),tP=Ju(),$m=Object.getOwnPropertyDescriptor;Mm.f=Gx?$m:function(e,t){if(e=Jx(e),t=Zx(t),tP)try{return $m(e,t)}catch(i){}if(eP(e,t))return Xx(!Yx(Kx.f,e,t),e[t])}});var Zu=b((SN,Lm)=>{"use strict";var iP=me(),rP=oe(),aP=/#|\.prototype\./,na=function(a,e){var t=nP[sP(a)];return t===uP?!0:t===oP?!1:rP(e)?iP(e):!!e},sP=na.normalize=function(a){return String(a).replace(aP,".").toLowerCase()},nP=na.data={},oP=na.NATIVE="N",uP=na.POLYFILL="P";Lm.exports=na});var ar=b((yN,Bm)=>{"use strict";var Dm=Lu(),lP=mt(),cP=Zr(),dP=Dm(Dm.bind);Bm.exports=function(a,e){return lP(a),e===void 0?a:cP?dP(a,e):function(){return a.apply(e,arguments)}}});var el=b((TN,Vm)=>{"use strict";var pP=qe(),hP=me();Vm.exports=pP&&hP(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ft=b((IN,_m)=>{"use strict";var mP=Le(),fP=String,bP=TypeError;_m.exports=function(a){if(mP(a))return a;throw new bP(fP(a)+" is not an object")}});var Ii=b(Nm=>{"use strict";var gP=qe(),vP=Ju(),SP=el(),mn=ft(),Om=Ku(),yP=TypeError,tl=Object.defineProperty,TP=Object.getOwnPropertyDescriptor,il="enumerable",rl="configurable",al="writable";Nm.f=gP?SP?function(e,t,i){if(mn(e),t=Om(t),mn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&al in i&&!i[al]){var r=TP(e,t);r&&r[al]&&(e[t]=i.value,i={configurable:rl in i?i[rl]:r[rl],enumerable:il in i?i[il]:r[il],writable:!1})}return tl(e,t,i)}:tl:function(e,t,i){if(mn(e),t=Om(t),mn(i),vP)try{return tl(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new yP("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var sr=b((wN,Fm)=>{"use strict";var IP=qe(),EP=Ii(),wP=ea();Fm.exports=IP?function(a,e,t){return EP.f(a,e,wP(1,t))}:function(a,e,t){return a[e]=t,a}});var ce=b((xN,Um)=>{"use strict";var oa=ne(),xP=Mu(),PP=Lu(),AP=oe(),kP=Cm().f,RP=Zu(),nr=yi(),$P=ar(),or=sr(),qm=st();sa();var MP=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return xP(a,this,arguments)};return e.prototype=a.prototype,e};Um.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?oa:r?oa[t]:oa[t]&&oa[t].prototype,o=i?nr:nr[t]||or(nr,t,{})[t],u=o.prototype,l,d,c,p,h,m,f,v,g;for(p in e)l=RP(i?p:t+(r?".":"#")+p,a.forced),d=!l&&n&&qm(n,p),m=o[p],d&&(a.dontCallGetSet?(g=kP(n,p),f=g&&g.value):f=n[p]),h=d&&f?f:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&d?v=$P(h,oa):a.wrap&&d?v=MP(h):s&&AP(h)?v=PP(h):v=h,(a.sham||h&&h.sham||m&&m.sham)&&or(v,"sham",!0),or(o,p,v),s&&(c=t+"Prototype",qm(nr,c)||or(nr,c,{}),or(nr[c],p,h),a.real&&u&&(l||!u[p])&&or(u,p,h)))}});var fn=b((PN,Hm)=>{"use strict";var CP=zu(),LP=Gu(),jm=CP("keys");Hm.exports=function(a){return jm[a]||(jm[a]=LP(a))}});var Wm=b((AN,Qm)=>{"use strict";var DP=me();Qm.exports=!DP(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var bn=b((kN,Gm)=>{"use strict";var BP=st(),VP=oe(),_P=ir(),OP=fn(),NP=Wm(),zm=OP("IE_PROTO"),sl=Object,FP=sl.prototype;Gm.exports=NP?sl.getPrototypeOf:function(a){var e=_P(a);if(BP(e,zm))return e[zm];var t=e.constructor;return VP(t)&&e instanceof t?t.prototype:e instanceof sl?FP:null}});var Km=b((RN,Ym)=>{"use strict";var qP=Math.ceil,UP=Math.floor;Ym.exports=Math.trunc||function(e){var t=+e;return(t>0?UP:qP)(t)}});var ua=b(($N,Xm)=>{"use strict";var jP=Km();Xm.exports=function(a){var e=+a;return e!==e||e===0?0:jP(e)}});var Zm=b((MN,Jm)=>{"use strict";var HP=ua(),QP=Math.max,WP=Math.min;Jm.exports=function(a,e){var t=HP(a);return t<0?QP(t+e,0):WP(t,e)}});var nl=b((CN,ef)=>{"use strict";var zP=ua(),GP=Math.min;ef.exports=function(a){var e=zP(a);return e>0?GP(e,9007199254740991):0}});var ur=b((LN,tf)=>{"use strict";var YP=nl();tf.exports=function(a){return YP(a.length)}});var ol=b((DN,af)=>{"use strict";var KP=Si(),XP=Zm(),JP=ur(),rf=function(a){return function(e,t,i){var r=KP(e),s=JP(r);if(s===0)return!a&&-1;var n=XP(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};af.exports={includes:rf(!0),indexOf:rf(!1)}});var gn=b((BN,sf)=>{"use strict";sf.exports={}});var uf=b((VN,of)=>{"use strict";var ZP=fe(),ul=st(),eA=Si(),tA=ol().indexOf,iA=gn(),nf=ZP([].push);of.exports=function(a,e){var t=eA(a),i=0,r=[],s;for(s in t)!ul(iA,s)&&ul(t,s)&&nf(r,s);for(;e.length>i;)ul(t,s=e[i++])&&(~tA(r,s)||nf(r,s));return r}});var ll=b((_N,lf)=>{"use strict";lf.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var cl=b((ON,cf)=>{"use strict";var rA=uf(),aA=ll();cf.exports=Object.keys||function(e){return rA(e,aA)}});var dl=b((NN,ff)=>{"use strict";var pf=qe(),sA=me(),hf=fe(),nA=bn(),oA=cl(),uA=Si(),lA=Bu().f,mf=hf(lA),cA=hf([].push),dA=pf&&sA(function(){var a=Object.create(null);return a[2]=2,!mf(a,2)}),df=function(a){return function(e){for(var t=uA(e),i=oA(t),r=dA&&nA(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!pf||(r?u in t:mf(t,u)))&&cA(o,a?[u,t[u]]:t[u]);return o}};ff.exports={entries:df(!0),values:df(!1)}});var bf=b(()=>{"use strict";var pA=ce(),hA=dl().values;pA({target:"Object",stat:!0},{values:function(e){return hA(e)}})});var vf=b((UN,gf)=>{"use strict";bf();var mA=yi();gf.exports=mA.Object.values});var yf=b((jN,Sf)=>{"use strict";var fA=vf();Sf.exports=fA});var Ei=b((HN,Tf)=>{"use strict";var bA=yf();Tf.exports=bA});var la=b((QN,If)=>{"use strict";If.exports=function(){}});var Ef=b(()=>{"use strict";var gA=ce(),vA=ol().includes,SA=me(),yA=la(),TA=SA(function(){return!Array(1).includes()});gA({target:"Array",proto:!0,forced:TA},{includes:function(e){return vA(this,e,arguments.length>1?arguments[1]:void 0)}});yA("includes")});var Wt=b((GN,wf)=>{"use strict";var IA=Pt();wf.exports=IA});var Pf=b((YN,xf)=>{"use strict";Ef();var EA=Wt();xf.exports=EA("Array","includes")});var kf=b((KN,Af)=>{"use strict";var wA=Pf();Af.exports=wA});var De=b((XN,Rf)=>{"use strict";var xA=kf();Rf.exports=xA});var ib=b(()=>{"use strict";var lk=ce(),ck=dl().entries;lk({target:"Object",stat:!0},{entries:function(e){return ck(e)}})});var ab=b((Xq,rb)=>{"use strict";ib();var dk=yi();rb.exports=dk.Object.entries});var nb=b((Jq,sb)=>{"use strict";var pk=ab();sb.exports=pk});var zt=b((Zq,ob)=>{"use strict";var hk=nb();ob.exports=hk});var Pi=b((eU,ub)=>{"use strict";ub.exports={}});var db=b((tU,cb)=>{"use strict";var mk=ne(),fk=oe(),lb=mk.WeakMap;cb.exports=fk(lb)&&/native code/.test(String(lb))});var Rl=b((iU,mb)=>{"use strict";var bk=db(),hb=ne(),gk=Le(),vk=sr(),Pl=st(),Al=sa(),Sk=fn(),yk=gn(),pb="Object already initialized",kl=hb.TypeError,Tk=hb.WeakMap,$n,ma,Mn,Ik=function(a){return Mn(a)?ma(a):$n(a,{})},Ek=function(a){return function(e){var t;if(!gk(e)||(t=ma(e)).type!==a)throw new kl("Incompatible receiver, "+a+" required");return t}};bk||Al.state?(nt=Al.state||(Al.state=new Tk),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,$n=function(a,e){if(nt.has(a))throw new kl(pb);return e.facade=a,nt.set(a,e),e},ma=function(a){return nt.get(a)||{}},Mn=function(a){return nt.has(a)}):(Ai=Sk("state"),yk[Ai]=!0,$n=function(a,e){if(Pl(a,Ai))throw new kl(pb);return e.facade=a,vk(a,Ai,e),e},ma=function(a){return Pl(a,Ai)?a[Ai]:{}},Mn=function(a){return Pl(a,Ai)});var nt,Ai;mb.exports={set:$n,get:ma,has:Mn,enforce:Ik,getterFor:Ek}});var Cl=b((rU,bb)=>{"use strict";var $l=qe(),wk=st(),fb=Function.prototype,xk=$l&&Object.getOwnPropertyDescriptor,Ml=wk(fb,"name"),Pk=Ml&&function(){}.name==="something",Ak=Ml&&(!$l||$l&&xk(fb,"name").configurable);bb.exports={EXISTS:Ml,PROPER:Pk,CONFIGURABLE:Ak}});var vb=b(gb=>{"use strict";var kk=qe(),Rk=el(),$k=Ii(),Mk=ft(),Ck=Si(),Lk=cl();gb.f=kk&&!Rk?Object.defineProperties:function(e,t){Mk(e);for(var i=Ck(t),r=Lk(t),s=r.length,n=0,o;s>n;)$k.f(e,o=r[n++],i[o]);return e}});var Ll=b((sU,Sb)=>{"use strict";var Dk=Pt();Sb.exports=Dk("document","documentElement")});var _l=b((nU,Pb)=>{"use strict";var Bk=ft(),Vk=vb(),yb=ll(),_k=gn(),Ok=Ll(),Nk=hn(),Fk=fn(),Tb=">",Ib="<",Bl="prototype",Vl="script",wb=Fk("IE_PROTO"),Dl=function(){},xb=function(a){return Ib+Vl+Tb+a+Ib+"/"+Vl+Tb},Eb=function(a){a.write(xb("")),a.close();var e=a.parentWindow.Object;return a=null,e},qk=function(){var a=Nk("iframe"),e="java"+Vl+":",t;return a.style.display="none",Ok.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(xb("document.F=Object")),t.close(),t.F},Cn,Ln=function(){try{Cn=new ActiveXObject("htmlfile")}catch(e){}Ln=typeof document!="undefined"?document.domain&&Cn?Eb(Cn):qk():Eb(Cn);for(var a=yb.length;a--;)delete Ln[Bl][yb[a]];return Ln()};_k[wb]=!0;Pb.exports=Object.create||function(e,t){var i;return e!==null?(Dl[Bl]=Bk(e),i=new Dl,Dl[Bl]=null,i[wb]=e):i=Ln(),t===void 0?i:Vk.f(i,t)}});var pr=b((oU,Ab)=>{"use strict";var Uk=sr();Ab.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:Uk(a,e,t),a}});var ql=b((uU,$b)=>{"use strict";var jk=me(),Hk=oe(),Qk=Le(),Wk=_l(),kb=bn(),zk=pr(),Gk=Ie(),Yk=at(),Fl=Gk("iterator"),Rb=!1,kt,Ol,Nl;[].keys&&(Nl=[].keys(),"next"in Nl?(Ol=kb(kb(Nl)),Ol!==Object.prototype&&(kt=Ol)):Rb=!0);var Kk=!Qk(kt)||jk(function(){var a={};return kt[Fl].call(a)!==a});Kk?kt={}:Yk&&(kt=Wk(kt));Hk(kt[Fl])||zk(kt,Fl,function(){return this});$b.exports={IteratorPrototype:kt,BUGGY_SAFARI_ITERATORS:Rb}});var Dn=b((lU,Cb)=>{"use strict";var Xk=Ie(),Jk=Xk("toStringTag"),Mb={};Mb[Jk]="z";Cb.exports=String(Mb)==="[object z]"});var fa=b((cU,Lb)=>{"use strict";var Zk=Dn(),eR=oe(),Bn=vi(),tR=Ie(),iR=tR("toStringTag"),rR=Object,aR=Bn(function(){return arguments}())==="Arguments",sR=function(a,e){try{return a[e]}catch(t){}};Lb.exports=Zk?Bn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=sR(e=rR(a),iR))=="string"?t:aR?Bn(e):(i=Bn(e))==="Object"&&eR(e.callee)?"Arguments":i}});var Bb=b((dU,Db)=>{"use strict";var nR=Dn(),oR=fa();Db.exports=nR?{}.toString:function(){return"[object "+oR(this)+"]"}});var ba=b((pU,_b)=>{"use strict";var uR=Dn(),lR=Ii().f,cR=sr(),dR=st(),pR=Bb(),hR=Ie(),Vb=hR("toStringTag");_b.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(dR(r,Vb)||lR(r,Vb,{configurable:!0,value:e}),i&&!uR&&cR(r,"toString",pR))}});var Nb=b((hU,Ob)=>{"use strict";var mR=ql().IteratorPrototype,fR=_l(),bR=ea(),gR=ba(),vR=Pi(),SR=function(){return this};Ob.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=fR(mR,{next:bR(+!i,t)}),gR(a,r,!1,!0),vR[r]=SR,a}});var qb=b((mU,Fb)=>{"use strict";var yR=fe(),TR=mt();Fb.exports=function(a,e,t){try{return yR(TR(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var jb=b((fU,Ub)=>{"use strict";var IR=Le();Ub.exports=function(a){return IR(a)||a===null}});var Qb=b((bU,Hb)=>{"use strict";var ER=jb(),wR=String,xR=TypeError;Hb.exports=function(a){if(ER(a))return a;throw new xR("Can't set "+wR(a)+" as a prototype")}});var Ul=b((gU,Wb)=>{"use strict";var PR=qb(),AR=Le(),kR=Qt(),RR=Qb();Wb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=PR(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return kR(r),RR(s),AR(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var rg=b((vU,ig)=>{"use strict";var $R=ce(),MR=Ue(),Vn=at(),eg=Cl(),CR=oe(),LR=Nb(),zb=bn(),Gb=Ul(),DR=ba(),BR=sr(),jl=pr(),VR=Ie(),Yb=Pi(),tg=ql(),_R=eg.PROPER,OR=eg.CONFIGURABLE,Kb=tg.IteratorPrototype,_n=tg.BUGGY_SAFARI_ITERATORS,ga=VR("iterator"),Xb="keys",va="values",Jb="entries",Zb=function(){return this};ig.exports=function(a,e,t,i,r,s,n){LR(t,e,i);var o=function(g){if(g===r&&p)return p;if(!_n&&g&&g in d)return d[g];switch(g){case Xb:return function(){return new t(this,g)};case va:return function(){return new t(this,g)};case Jb:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[ga]||d["@@iterator"]||r&&d[r],p=!_n&&c||o(r),h=e==="Array"&&d.entries||c,m,f,v;if(h&&(m=zb(h.call(new a)),m!==Object.prototype&&m.next&&(!Vn&&zb(m)!==Kb&&(Gb?Gb(m,Kb):CR(m[ga])||jl(m,ga,Zb)),DR(m,u,!0,!0),Vn&&(Yb[u]=Zb))),_R&&r===va&&c&&c.name!==va&&(!Vn&&OR?BR(d,"name",va):(l=!0,p=function(){return MR(c,this)})),r)if(f={values:o(va),keys:s?p:o(Xb),entries:o(Jb)},n)for(v in f)(_n||l||!(v in d))&&jl(d,v,f[v]);else $R({target:e,proto:!0,forced:_n||l},f);return(!Vn||n)&&d[ga]!==p&&jl(d,ga,p,{name:r}),Yb[e]=p,f}});var sg=b((SU,ag)=>{"use strict";ag.exports=function(a,e){return{value:a,done:e}}});var Ql=b((yU,cg)=>{"use strict";var NR=Si(),Hl=la(),ng=Pi(),ug=Rl(),FR=Ii().f,qR=rg(),On=sg(),UR=at(),jR=qe(),lg="Array Iterator",HR=ug.set,QR=ug.getterFor(lg);cg.exports=qR(Array,"Array",function(a,e){HR(this,{type:lg,target:NR(a),index:0,kind:e})},function(){var a=QR(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,On(void 0,!0);switch(a.kind){case"keys":return On(t,!1);case"values":return On(e[t],!1)}return On([t,e[t]],!1)},"values");var og=ng.Arguments=ng.Array;Hl("keys");Hl("values");Hl("entries");if(!UR&&jR&&og.name!=="values")try{FR(og,"name",{value:"values"})}catch(a){}});var pg=b((TU,dg)=>{"use strict";var WR=Ie(),zR=Pi(),GR=WR("iterator"),YR=Array.prototype;dg.exports=function(a){return a!==void 0&&(zR.Array===a||YR[GR]===a)}});var Wl=b((IU,mg)=>{"use strict";var KR=fa(),hg=aa(),XR=ta(),JR=Pi(),ZR=Ie(),e$=ZR("iterator");mg.exports=function(a){if(!XR(a))return hg(a,e$)||hg(a,"@@iterator")||JR[KR(a)]}});var bg=b((EU,fg)=>{"use strict";var t$=Ue(),i$=mt(),r$=ft(),a$=ra(),s$=Wl(),n$=TypeError;fg.exports=function(a,e){var t=arguments.length<2?s$(a):e;if(i$(t))return r$(t$(t,a));throw new n$(a$(a)+" is not iterable")}});var Sg=b((wU,vg)=>{"use strict";var o$=Ue(),gg=ft(),u$=aa();vg.exports=function(a,e,t){var i,r;gg(a);try{if(i=u$(a,"return"),!i){if(e==="throw")throw t;return t}i=o$(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return gg(i),t}});var Fn=b((xU,Eg)=>{"use strict";var l$=ar(),c$=Ue(),d$=ft(),p$=ra(),h$=pg(),m$=ur(),yg=ia(),f$=bg(),b$=Wl(),Tg=Sg(),g$=TypeError,Nn=function(a,e){this.stopped=a,this.result=e},Ig=Nn.prototype;Eg.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=l$(e,i),l,d,c,p,h,m,f,v=function(S){return l&&Tg(l,"normal"),new Nn(!0,S)},g=function(S){return r?(d$(S),o?u(S[0],S[1],v):u(S[0],S[1])):o?u(S,v):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(d=b$(a),!d)throw new g$(p$(a)+" is not iterable");if(h$(d)){for(c=0,p=m$(a);p>c;c++)if(h=g(a[c]),h&&yg(Ig,h))return h;return new Nn(!1)}l=f$(a,d)}for(m=s?a.next:l.next;!(f=c$(m,l)).done;){try{h=g(f.value)}catch(S){Tg(l,"throw",S)}if(typeof h=="object"&&h&&yg(Ig,h))return h}return new Nn(!1)}});var xg=b((PU,wg)=>{"use strict";var v$=qe(),S$=Ii(),y$=ea();wg.exports=function(a,e,t){v$?S$.f(a,e,y$(0,t)):a[e]=t}});var Pg=b(()=>{"use strict";var T$=ce(),I$=Fn(),E$=xg();T$({target:"Object",stat:!0},{fromEntries:function(e){var t={};return I$(e,function(i,r){E$(t,i,r)},{AS_ENTRIES:!0}),t}})});var kg=b((RU,Ag)=>{"use strict";Ql();Pg();var w$=yi();Ag.exports=w$.Object.fromEntries});var $g=b(($U,Rg)=>{"use strict";Rg.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 Cg=b(()=>{"use strict";Ql();var x$=$g(),P$=ne(),A$=ba(),Mg=Pi();for(qn in x$)A$(P$[qn],qn),Mg[qn]=Mg.Array;var qn});var Dg=b((LU,Lg)=>{"use strict";var k$=kg();Cg();Lg.exports=k$});var zl=b((DU,Bg)=>{"use strict";var R$=Dg();Bg.exports=R$});var Vg=b(()=>{"use strict"});var Gl=b((_U,_g)=>{"use strict";var Sa=ne(),$$=Ti(),M$=vi(),Un=function(a){return $$.slice(0,a.length)===a};_g.exports=function(){return Un("Bun/")?"BUN":Un("Cloudflare-Workers")?"CLOUDFLARE":Un("Deno/")?"DENO":Un("Node.js/")?"NODE":Sa.Bun&&typeof Bun.version=="string"?"BUN":Sa.Deno&&typeof Deno.version=="object"?"DENO":M$(Sa.process)==="process"?"NODE":Sa.window&&Sa.document?"BROWSER":"REST"}()});var jn=b((OU,Og)=>{"use strict";var C$=Gl();Og.exports=C$==="NODE"});var Fg=b((NU,Ng)=>{"use strict";var L$=Ii();Ng.exports=function(a,e,t){return L$.f(a,e,t)}});var jg=b((FU,Ug)=>{"use strict";var D$=Pt(),B$=Fg(),V$=Ie(),_$=qe(),qg=V$("species");Ug.exports=function(a){var e=D$(a);_$&&e&&!e[qg]&&B$(e,qg,{configurable:!0,get:function(){return this}})}});var Qg=b((qU,Hg)=>{"use strict";var O$=ia(),N$=TypeError;Hg.exports=function(a,e){if(O$(e,a))return a;throw new N$("Incorrect invocation")}});var Kl=b((UU,Wg)=>{"use strict";var F$=fe(),q$=oe(),Yl=sa(),U$=F$(Function.toString);q$(Yl.inspectSource)||(Yl.inspectSource=function(a){return U$(a)});Wg.exports=Yl.inspectSource});var Jl=b((jU,Xg)=>{"use strict";var j$=fe(),H$=me(),zg=oe(),Q$=fa(),W$=Pt(),z$=Kl(),Gg=function(){},Yg=W$("Reflect","construct"),Xl=/^\s*(?:class|function)\b/,G$=j$(Xl.exec),Y$=!Xl.test(Gg),ya=function(e){if(!zg(e))return!1;try{return Yg(Gg,[],e),!0}catch(t){return!1}},Kg=function(e){if(!zg(e))return!1;switch(Q$(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Y$||!!G$(Xl,z$(e))}catch(t){return!0}};Kg.sham=!0;Xg.exports=!Yg||H$(function(){var a;return ya(ya.call)||!ya(Object)||!ya(function(){a=!0})||a})?Kg:ya});var Zg=b((HU,Jg)=>{"use strict";var K$=Jl(),X$=ra(),J$=TypeError;Jg.exports=function(a){if(K$(a))return a;throw new J$(X$(a)+" is not a constructor")}});var Zl=b((QU,tv)=>{"use strict";var ev=ft(),Z$=Zg(),eM=ta(),tM=Ie(),iM=tM("species");tv.exports=function(a,e){var t=ev(a).constructor,i;return t===void 0||eM(i=ev(t)[iM])?e:Z$(i)}});var rv=b((WU,iv)=>{"use strict";var rM=fe();iv.exports=rM([].slice)});var sv=b((zU,av)=>{"use strict";var aM=TypeError;av.exports=function(a,e){if(a<e)throw new aM("Not enough arguments");return a}});var ec=b((GU,nv)=>{"use strict";var sM=Ti();nv.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(sM)});var lc=b((YU,fv)=>{"use strict";var He=ne(),nM=Mu(),oM=ar(),ov=oe(),uM=st(),mv=me(),uv=Ll(),lM=rv(),lv=hn(),cM=sv(),dM=ec(),pM=jn(),nc=He.setImmediate,oc=He.clearImmediate,hM=He.process,tc=He.Dispatch,mM=He.Function,cv=He.MessageChannel,fM=He.String,ic=0,Ta={},dv="onreadystatechange",Ia,ki,rc,ac;mv(function(){Ia=He.location});var uc=function(a){if(uM(Ta,a)){var e=Ta[a];delete Ta[a],e()}},sc=function(a){return function(){uc(a)}},pv=function(a){uc(a.data)},hv=function(a){He.postMessage(fM(a),Ia.protocol+"//"+Ia.host)};(!nc||!oc)&&(nc=function(e){cM(arguments.length,1);var t=ov(e)?e:mM(e),i=lM(arguments,1);return Ta[++ic]=function(){nM(t,void 0,i)},ki(ic),ic},oc=function(e){delete Ta[e]},pM?ki=function(a){hM.nextTick(sc(a))}:tc&&tc.now?ki=function(a){tc.now(sc(a))}:cv&&!dM?(rc=new cv,ac=rc.port2,rc.port1.onmessage=pv,ki=oM(ac.postMessage,ac)):He.addEventListener&&ov(He.postMessage)&&!He.importScripts&&Ia&&Ia.protocol!=="file:"&&!mv(hv)?(ki=hv,He.addEventListener("message",pv,!1)):dv in lv("script")?ki=function(a){uv.appendChild(lv("script"))[dv]=function(){uv.removeChild(this),uc(a)}}:ki=function(a){setTimeout(sc(a),0)});fv.exports={set:nc,clear:oc}});var vv=b((KU,gv)=>{"use strict";var bv=ne(),bM=qe(),gM=Object.getOwnPropertyDescriptor;gv.exports=function(a){if(!bM)return bv[a];var e=gM(bv,a);return e&&e.value}});var cc=b((XU,yv)=>{"use strict";var Sv=function(){this.head=null,this.tail=null};Sv.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};yv.exports=Sv});var Iv=b((JU,Tv)=>{"use strict";var vM=Ti();Tv.exports=/ipad|iphone|ipod/i.test(vM)&&typeof Pebble!="undefined"});var wv=b((ZU,Ev)=>{"use strict";var SM=Ti();Ev.exports=/web0s(?!.*chrome)/i.test(SM)});var Mv=b((e1,$v)=>{"use strict";var mr=ne(),yM=vv(),xv=ar(),dc=lc().set,TM=cc(),IM=ec(),EM=Iv(),wM=wv(),pc=jn(),Pv=mr.MutationObserver||mr.WebKitMutationObserver,Av=mr.document,kv=mr.process,Hn=mr.Promise,fc=yM("queueMicrotask"),hr,hc,mc,Qn,Rv;fc||(Ea=new TM,wa=function(){var a,e;for(pc&&(a=kv.domain)&&a.exit();e=Ea.get();)try{e()}catch(t){throw Ea.head&&hr(),t}a&&a.enter()},!IM&&!pc&&!wM&&Pv&&Av?(hc=!0,mc=Av.createTextNode(""),new Pv(wa).observe(mc,{characterData:!0}),hr=function(){mc.data=hc=!hc}):!EM&&Hn&&Hn.resolve?(Qn=Hn.resolve(void 0),Qn.constructor=Hn,Rv=xv(Qn.then,Qn),hr=function(){Rv(wa)}):pc?hr=function(){kv.nextTick(wa)}:(dc=xv(dc,mr),hr=function(){dc(wa)}),fc=function(a){Ea.head||hr(),Ea.add(a)});var Ea,wa;$v.exports=fc});var Lv=b((t1,Cv)=>{"use strict";Cv.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Wn=b((i1,Dv)=>{"use strict";Dv.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ri=b((r1,Bv)=>{"use strict";var xM=ne();Bv.exports=xM.Promise});var fr=b((a1,Nv)=>{"use strict";var PM=ne(),xa=Ri(),AM=oe(),kM=Zu(),RM=Kl(),$M=Ie(),Vv=Gl(),MM=at(),bc=Fu(),_v=xa&&xa.prototype,CM=$M("species"),gc=!1,Ov=AM(PM.PromiseRejectionEvent),LM=kM("Promise",function(){var a=RM(xa),e=a!==String(xa);if(!e&&bc===66||MM&&!(_v.catch&&_v.finally))return!0;if(!bc||bc<51||!/native code/.test(a)){var t=new xa(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[CM]=i,gc=t.then(function(){})instanceof i,!gc)return!0}return!e&&(Vv==="BROWSER"||Vv==="DENO")&&!Ov});Nv.exports={CONSTRUCTOR:LM,REJECTION_EVENT:Ov,SUBCLASSING:gc}});var br=b((s1,qv)=>{"use strict";var Fv=mt(),DM=TypeError,BM=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new DM("Bad Promise constructor");e=i,t=r}),this.resolve=Fv(e),this.reject=Fv(t)};qv.exports.f=function(a){return new BM(a)}});var oS=b(()=>{"use strict";var VM=ce(),_M=at(),Kn=jn(),Gt=ne(),OM=yi(),yr=Ue(),Uv=pr(),jv=Ul(),NM=ba(),FM=jg(),qM=mt(),Yn=oe(),UM=Le(),jM=Qg(),HM=Zl(),Gv=lc().set,Ic=Mv(),QM=Lv(),WM=Wn(),zM=cc(),Yv=Rl(),Xn=Ri(),Ec=fr(),Kv=br(),Jn="Promise",Xv=Ec.CONSTRUCTOR,GM=Ec.REJECTION_EVENT,YM=Ec.SUBCLASSING,vc=Yv.getterFor(Jn),KM=Yv.set,gr=Xn&&Xn.prototype,$i=Xn,zn=gr,Jv=Gt.TypeError,Sc=Gt.document,wc=Gt.process,yc=Kv.f,XM=yc,JM=!!(Sc&&Sc.createEvent&&Gt.dispatchEvent),Zv="unhandledrejection",ZM="rejectionhandled",Hv=0,eS=1,eC=2,xc=1,tS=2,Gn,Qv,iS,Wv,rS=function(a){var e;return UM(a)&&Yn(e=a.then)?e:!1},aS=function(a,e){var t=e.value,i=e.state===eS,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{r?(i||(e.rejection===tS&&iC(e),e.rejection=xc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new Jv("Promise-chain cycle")):(l=rS(u))?yr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},sS=function(a,e){a.notified||(a.notified=!0,Ic(function(){for(var t=a.reactions,i;i=t.get();)aS(i,a);a.notified=!1,e&&!a.rejection&&tC(a)}))},nS=function(a,e,t){var i,r;JM?(i=Sc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Gt.dispatchEvent(i)):i={promise:e,reason:t},!GM&&(r=Gt["on"+a])?r(i):a===Zv&&QM("Unhandled promise rejection",t)},tC=function(a){yr(Gv,Gt,function(){var e=a.facade,t=a.value,i=zv(a),r;if(i&&(r=WM(function(){Kn?wc.emit("unhandledRejection",t,e):nS(Zv,e,t)}),a.rejection=Kn||zv(a)?tS:xc,r.error))throw r.value})},zv=function(a){return a.rejection!==xc&&!a.parent},iC=function(a){yr(Gv,Gt,function(){var e=a.facade;Kn?wc.emit("rejectionHandled",e):nS(ZM,e,a.value)})},vr=function(a,e,t){return function(i){a(e,i,t)}},Sr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=eC,sS(a,!0))},Tc=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Jv("Promise can't be resolved itself");var i=rS(e);i?Ic(function(){var r={done:!1};try{yr(i,e,vr(Tc,r,a),vr(Sr,r,a))}catch(s){Sr(r,s,a)}}):(a.value=e,a.state=eS,sS(a,!1))}catch(r){Sr({done:!1},r,a)}}};if(Xv&&($i=function(e){jM(this,zn),qM(e),yr(Gn,this);var t=vc(this);try{e(vr(Tc,t),vr(Sr,t))}catch(i){Sr(t,i)}},zn=$i.prototype,Gn=function(e){KM(this,{type:Jn,done:!1,notified:!1,parent:!1,reactions:new zM,rejection:!1,state:Hv,value:null})},Gn.prototype=Uv(zn,"then",function(e,t){var i=vc(this),r=yc(HM(this,$i));return i.parent=!0,r.ok=Yn(e)?e:!0,r.fail=Yn(t)&&t,r.domain=Kn?wc.domain:void 0,i.state===Hv?i.reactions.add(r):Ic(function(){aS(r,i)}),r.promise}),Qv=function(){var a=new Gn,e=vc(a);this.promise=a,this.resolve=vr(Tc,e),this.reject=vr(Sr,e)},Kv.f=yc=function(a){return a===$i||a===iS?new Qv(a):XM(a)},!_M&&Yn(Xn)&&gr!==Object.prototype)){Wv=gr.then,YM||Uv(gr,"then",function(e,t){var i=this;return new $i(function(r,s){yr(Wv,i,r,s)}).then(e,t)},{unsafe:!0});try{delete gr.constructor}catch(a){}jv&&jv(gr,zn)}VM({global:!0,constructor:!0,wrap:!0,forced:Xv},{Promise:$i});iS=OM.Promise;NM($i,Jn,!1,!0);FM(Jn)});var pS=b((u1,dS)=>{"use strict";var rC=Ie(),lS=rC("iterator"),cS=!1;try{uS=0,Pc={next:function(){return{done:!!uS++}},return:function(){cS=!0}},Pc[lS]=function(){return this},Array.from(Pc,function(){throw 2})}catch(a){}var uS,Pc;dS.exports=function(a,e){try{if(!e&&!cS)return!1}catch(r){return!1}var t=!1;try{var i={};i[lS]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Ac=b((l1,hS)=>{"use strict";var aC=Ri(),sC=pS(),nC=fr().CONSTRUCTOR;hS.exports=nC||!sC(function(a){aC.all(a).then(void 0,function(){})})});var mS=b(()=>{"use strict";var oC=ce(),uC=Ue(),lC=mt(),cC=br(),dC=Wn(),pC=Fn(),hC=Ac();oC({target:"Promise",stat:!0,forced:hC},{all:function(e){var t=this,i=cC.f(t),r=i.resolve,s=i.reject,n=dC(function(){var o=lC(t.resolve),u=[],l=0,d=1;pC(e,function(c){var p=l++,h=!1;d++,uC(o,t,c).then(function(m){h||(h=!0,u[p]=m,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var bS=b(()=>{"use strict";var mC=ce(),fC=at(),bC=fr().CONSTRUCTOR,Rc=Ri(),gC=Pt(),vC=oe(),SC=pr(),fS=Rc&&Rc.prototype;mC({target:"Promise",proto:!0,forced:bC,real:!0},{catch:function(a){return this.then(void 0,a)}});!fC&&vC(Rc)&&(kc=gC("Promise").prototype.catch,fS.catch!==kc&&SC(fS,"catch",kc,{unsafe:!0}));var kc});var gS=b(()=>{"use strict";var yC=ce(),TC=Ue(),IC=mt(),EC=br(),wC=Wn(),xC=Fn(),PC=Ac();yC({target:"Promise",stat:!0,forced:PC},{race:function(e){var t=this,i=EC.f(t),r=i.reject,s=wC(function(){var n=IC(t.resolve);xC(e,function(o){TC(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var vS=b(()=>{"use strict";var AC=ce(),kC=br(),RC=fr().CONSTRUCTOR;AC({target:"Promise",stat:!0,forced:RC},{reject:function(e){var t=kC.f(this),i=t.reject;return i(e),t.promise}})});var $c=b((v1,SS)=>{"use strict";var $C=ft(),MC=Le(),CC=br();SS.exports=function(a,e){if($C(a),MC(e)&&e.constructor===a)return e;var t=CC.f(a),i=t.resolve;return i(e),t.promise}});var IS=b(()=>{"use strict";var LC=ce(),DC=Pt(),yS=at(),BC=Ri(),TS=fr().CONSTRUCTOR,VC=$c(),_C=DC("Promise"),OC=yS&&!TS;LC({target:"Promise",stat:!0,forced:yS||TS},{resolve:function(e){return VC(OC&&this===_C?BC:this,e)}})});var ES=b(()=>{"use strict";oS();mS();bS();gS();vS();IS()});var AS=b(()=>{"use strict";var NC=ce(),FC=at(),Zn=Ri(),qC=me(),xS=Pt(),PS=oe(),UC=Zl(),wS=$c(),jC=pr(),Cc=Zn&&Zn.prototype,HC=!!Zn&&qC(function(){Cc.finally.call({then:function(){}},function(){})});NC({target:"Promise",proto:!0,real:!0,forced:HC},{finally:function(a){var e=UC(this,xS("Promise")),t=PS(a);return this.then(t?function(i){return wS(e,a()).then(function(){return i})}:a,t?function(i){return wS(e,a()).then(function(){throw i})}:a)}});!FC&&PS(Zn)&&(Mc=xS("Promise").prototype.finally,Cc.finally!==Mc&&jC(Cc,"finally",Mc,{unsafe:!0}));var Mc});var RS=b((x1,kS)=>{"use strict";Vg();ES();AS();var QC=Wt();kS.exports=QC("Promise","finally")});var MS=b((P1,$S)=>{"use strict";var WC=RS();$S.exports=WC});var Lc=b((A1,CS)=>{"use strict";var zC=MS();CS.exports=zC});var XS=b(()=>{"use strict";var IL=ce(),EL=ir(),wL=ur(),xL=ua(),PL=la();IL({target:"Array",proto:!0},{at:function(e){var t=EL(this),i=wL(t),r=xL(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});PL("at")});var ZS=b((kj,JS)=>{"use strict";XS();var AL=Wt();JS.exports=AL("Array","at")});var ty=b((Rj,ey)=>{"use strict";var kL=ZS();ey.exports=kL});var Ke=b(($j,iy)=>{"use strict";var RL=ty();iy.exports=RL});var pd=b((QQ,Ky)=>{"use strict";var DD=vi();Ky.exports=Array.isArray||function(e){return DD(e)==="Array"}});var Jy=b((WQ,Xy)=>{"use strict";var BD=TypeError,VD=9007199254740991;Xy.exports=function(a){if(a>VD)throw BD("Maximum allowed index exceeded");return a}});var tT=b((zQ,eT)=>{"use strict";var _D=pd(),OD=ur(),ND=Jy(),FD=ar(),Zy=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,d=n?FD(n,o):!1,c,p;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&_D(c)?(p=OD(c),u=Zy(a,e,c,p,u,s-1)-1):(ND(u+1),a[u]=c),u++),l++;return u};eT.exports=Zy});var sT=b((GQ,aT)=>{"use strict";var iT=pd(),qD=Jl(),UD=Le(),jD=Ie(),HD=jD("species"),rT=Array;aT.exports=function(a){var e;return iT(a)&&(e=a.constructor,qD(e)&&(e===rT||iT(e.prototype))?e=void 0:UD(e)&&(e=e[HD],e===null&&(e=void 0))),e===void 0?rT:e}});var oT=b((YQ,nT)=>{"use strict";var QD=sT();nT.exports=function(a,e){return new(QD(a))(e===0?0:e)}});var uT=b(()=>{"use strict";var WD=ce(),zD=tT(),GD=mt(),YD=ir(),KD=ur(),XD=oT();WD({target:"Array",proto:!0},{flatMap:function(e){var t=YD(this),i=KD(t),r;return GD(e),r=XD(t,0),r.length=zD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var lT=b(()=>{"use strict";var JD=la();JD("flatMap")});var dT=b((eW,cT)=>{"use strict";uT();lT();var ZD=Wt();cT.exports=ZD("Array","flatMap")});var hT=b((tW,pT)=>{"use strict";var eB=dT();pT.exports=eB});var ja=b((iW,mT)=>{"use strict";var tB=hT();mT.exports=tB});var Qa=b((SW,vT)=>{"use strict";var rB=fa(),aB=String;vT.exports=function(a){if(rB(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return aB(a)}});var md=b((yW,ST)=>{"use strict";ST.exports=`
|
|
7
|
-
\v\f\r \u2028\u2029\uFEFF`});var IT=b((TW,TT)=>{"use strict";var sB=fe(),nB=Qt(),oB=Qa(),bd=md(),yT=sB("".replace),uB=RegExp("^["+bd+"]+"),lB=RegExp("(^|[^"+bd+"])["+bd+"]+$"),fd=function(a){return function(e){var t=oB(nB(e));return a&1&&(t=yT(t,uB,"")),a&2&&(t=yT(t,lB,"$1")),t}};TT.exports={start:fd(1),end:fd(2),trim:fd(3)}});var PT=b((IW,xT)=>{"use strict";var cB=Cl().PROPER,dB=me(),ET=md(),wT="
";xT.exports=function(a){return dB(function(){return!!ET[a]()||wT[a]()!==wT||cB&&ET[a].name!==a})}});var gd=b((EW,AT)=>{"use strict";var pB=IT().start,hB=PT();AT.exports=hB("trimStart")?function(){return pB(this)}:"".trimStart});var RT=b(()=>{"use strict";var mB=ce(),kT=gd();mB({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==kT},{trimLeft:kT})});var MT=b(()=>{"use strict";RT();var fB=ce(),$T=gd();fB({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==$T},{trimStart:$T})});var LT=b((kW,CT)=>{"use strict";MT();var bB=Wt();CT.exports=bB("String","trimLeft")});var BT=b((RW,DT)=>{"use strict";var gB=LT();DT.exports=gB});var _T=b(($W,VT)=>{"use strict";var vB=BT();VT.exports=vB});var qT=b(()=>{"use strict"});var UT=b(()=>{"use strict"});var HT=b((hz,jT)=>{"use strict";var IB=Le(),EB=vi(),wB=Ie(),xB=wB("match");jT.exports=function(a){var e;return IB(a)&&((e=a[xB])!==void 0?!!e:EB(a)==="RegExp")}});var zT=b((mz,WT)=>{"use strict";var PB=ne(),AB=me(),QT=PB.RegExp,kB=!AB(function(){var a=!0;try{QT(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(QT.prototype,"flags").get.call(e);return o!==i||t!==i});WT.exports={correct:kB}});var YT=b((fz,GT)=>{"use strict";var RB=ft();GT.exports=function(){var a=RB(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var JT=b((bz,XT)=>{"use strict";var $B=Ue(),MB=st(),CB=ia(),KT=zT(),LB=YT(),DB=RegExp.prototype;XT.exports=KT.correct?function(a){return a.flags}:function(a){return!KT.correct&&CB(DB,a)&&!MB(a,"flags")?$B(LB,a):a.flags}});var eI=b((gz,ZT)=>{"use strict";var Id=fe(),BB=ir(),VB=Math.floor,yd=Id("".charAt),_B=Id("".replace),Td=Id("".slice),OB=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,NB=/\$([$&'`]|\d{1,2})/g;ZT.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=NB;return r!==void 0&&(r=BB(r),u=OB),_B(s,u,function(l,d){var c;switch(yd(d,0)){case"$":return"$";case"&":return a;case"`":return Td(e,0,t);case"'":return Td(e,n);case"<":c=r[Td(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=VB(p/10);return h===0?l:h<=o?i[h-1]===void 0?yd(d,1):i[h-1]+yd(d,1):l}c=i[p-1]}return c===void 0?"":c})}});var rI=b(()=>{"use strict";var FB=ce(),qB=Ue(),wd=fe(),tI=Qt(),UB=oe(),jB=Le(),HB=HT(),Cr=Qa(),QB=aa(),WB=JT(),zB=eI(),GB=Ie(),YB=at(),KB=GB("replace"),XB=TypeError,Ed=wd("".indexOf),JB=wd("".replace),iI=wd("".slice),ZB=Math.max;FB({target:"String",proto:!0},{replaceAll:function(e,t){var i=tI(this),r,s,n,o,u,l,d,c,p,h,m=0,f="";if(jB(e)){if(r=HB(e),r&&(s=Cr(tI(WB(e))),!~Ed(s,"g")))throw new XB("`.replaceAll` does not allow non-global regexes");if(n=QB(e,KB),n)return qB(n,e,i,t);if(YB&&r)return JB(Cr(i),e,t)}for(o=Cr(i),u=Cr(e),l=UB(t),l||(t=Cr(t)),d=u.length,c=ZB(1,d),p=Ed(o,u);p!==-1;)h=l?Cr(t(u,p,o)):zB(u,o,p,[],void 0,t),f+=iI(o,m,p)+h,m=p+d,p=p+c>o.length?-1:Ed(o,u,p+c);return m<o.length&&(f+=iI(o,m)),f}})});var sI=b((yz,aI)=>{"use strict";qT();UT();rI();var e0=Wt();aI.exports=e0("String","replaceAll")});var oI=b((Tz,nI)=>{"use strict";var t0=sI();nI.exports=t0});var lI=b((Iz,uI)=>{"use strict";var i0=oI();uI.exports=i0});var dI=b((Ez,cI)=>{"use strict";var r0=ua(),a0=Qa(),s0=Qt(),n0=RangeError;cI.exports=function(e){var t=a0(s0(this)),i="",r=r0(e);if(r<0||r===1/0)throw new n0("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var bI=b((wz,fI)=>{"use strict";var mI=fe(),o0=nl(),pI=Qa(),u0=dI(),l0=Qt(),c0=mI(u0),d0=mI("".slice),p0=Math.ceil,hI=function(a){return function(e,t,i){var r=pI(l0(e)),s=o0(t),n=r.length,o=i===void 0?" ":pI(i),u,l;return s<=n||o===""?r:(u=s-n,l=c0(o,p0(u/o.length)),l.length>u&&(l=d0(l,0,u)),a?r+l:l+r)}};fI.exports={start:hI(!1),end:hI(!0)}});var vI=b((xz,gI)=>{"use strict";var h0=Ti();gI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(h0)});var SI=b(()=>{"use strict";var m0=ce(),f0=bI().start,b0=vI();m0({target:"String",proto:!0,forced:b0},{padStart:function(e){return f0(this,e,arguments.length>1?arguments[1]:void 0)}})});var TI=b((kz,yI)=>{"use strict";SI();var g0=Wt();yI.exports=g0("String","padStart")});var EI=b((Rz,II)=>{"use strict";var v0=TI();II.exports=v0});var xI=b(($z,wI)=>{"use strict";var S0=EI();wI.exports=S0});var hh="2.0.150-dev.f4d0e2c9.0";var Pe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Pe||{}),xt=(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_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(xt||{});var Xr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Xr||{}),ku=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ku||{});var Ru=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ru||{}),cn=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(cn||{});var Ap=_(Ei(),1),vw=_(De(),1);import{assertNever as Bf,assertNonNullable as PA,isNonNullable as vn,ValueSubject as pl,Subject as AA,Subscription as kA,merge as RA,observableFrom as $A,fromEvent as Mf,map as Cf,tap as Lf,filterChanged as MA,isNullable as hl,ErrorCategory as Df}from"@vkontakte/videoplayer-shared/es2018";var $f=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Sn=class{constructor(e){this.connection$=new pl(void 0);this.castState$=new pl("NOT_AVAILABLE");this.errorEvent$=new AA;this.realCastState$=new pl("NOT_AVAILABLE");this.subscription=new kA;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=vn((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||$f("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Df.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){vn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();hl(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();hl(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(Mf(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Bf(r.sessionState)}})).add(RA(Mf(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Lf(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Cf(r=>r.castState)),$A([i.getCastState()])).pipe(MA(),Cf(CA),Lf(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=vn(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();PA(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(hl(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?vn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Df.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},CA=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Bf(a)}};import{assertNonNullable as Sl,combine as yl,debounce as Tl,ErrorCategory as XA,filter as cr,filterChanged as Kf,isNonNullable as Il,isNullable as Xf,map as JA,Subscription as ZA,ValueSubject as El}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as LA,assertNonNullable as wi,ErrorCategory as DA,getHighestQuality as BA,isNonNullable as _f}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as Vf}from"@vkontakte/videoplayer-shared/es2018";var Ee=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Vf(t)}return a},yn=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:Vf(e)}};var In=a=>{var c;let{source:e,format:t,meta:i,output:r}=a,s,n,o;switch(t){case"MPEG":{let p=e[t];wi(p);let h=BA(Object.keys(p));wi(h);let m=p[h];wi(m),s=m,n="video/mp4",o=Tn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let p=e[t];wi(p),s=p.url,n="application/x-mpegurl",o=Tn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let p=e[t];wi(p),s=p.url,n="application/dash+xml",o=Tn();break}case"DASH_LIVE_CMAF":{let p=e[t];wi(p),s=p.url,n="application/dash+xml",o=Of();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let p=e[t];wi(p),s=Ee(p.url),n="application/x-mpegurl",o=Of();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let p="Unsupported format for Chromecast",h=new Error(p);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:DA.VIDEO_PIPELINE,message:p,thrown:h}),h}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return LA(t)}let u=VA((c=i.videoId)!=null?c:s,n);u.contentUrl=s,u.streamType=o,u.metadata=_A();let{title:l,subtitle:d}=i;return _f(l)&&(u.metadata.title=l),_f(d)&&(u.metadata.subtitle=d),u};function Tn(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.BUFFERED)!=null?i:"BUFFERED"}function Of(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.LIVE)!=null?i:"LIVE"}function VA(a,e){var t,i;return(i=(t=chrome.cast)==null?void 0:t.media)!=null&&i.MediaInfo?new chrome.cast.media.MediaInfo(a,e):{contentId:a,contentType:e,metadata:{title:"",subtitle:""},streamType:Tn()}}function _A(){var a,e;return(e=(a=chrome.cast)==null?void 0:a.media)!=null&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var A=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var En=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};import{assertNever as Yf}from"@vkontakte/videoplayer-shared/es2018";import{isBrowserWindow as GA,ValueSubject as YA}from"@vkontakte/videoplayer-shared/es2018";var Nf=_(De(),1);import{getWindow as OA}from"@vkontakte/videoplayer-shared/es2018";var wn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Nf.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=OA().navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Ff=_(De(),1);import{getWindow as ml,isBrowserWindow as fl}from"@vkontakte/videoplayer-shared/es2018";var xi=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var xn=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||(0,Ff.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||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.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=ml();if(!fl(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=xi()}catch(i){console.error("DeviceChecker: calling isMobile error - ",i)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let e=ml();if(!fl(e))return;let{userAgentData:t}=e.navigator;if(t!=null&&t.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}}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,s=/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||s||o||n||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r.length>0,o=r.length>1,u="Unknown",l="Unknown";if(n){let d=r[0];typeof d=="number"?d<s.length&&s[d]!==void 0&&(u=s[d]):u=d}if(o){let d=r[1];typeof d=="number"?d<s.length&&s[d]!==void 0&&(l=s[d]):d!==void 0&&(l=d)}else s[2]!==void 0?l=s[2]:s[1]!==void 0&&n&&typeof r[0]=="string"&&(l=s[1]);u=this.normalizeOSName(u),l=this.normalizeOSVersion(l,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:l||"Unknown",full:l&&l!=="Unknown"?`${u} ${l}`:u};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r[0],o=r[1],u=typeof n=="number"?s[n]!==void 0?this.normalizeVendorName(s[n]):"Unknown":this.normalizeVendorName(n),l="Unknown";typeof o=="number"?l=s[o]!==void 0?s[o]:"Unknown":o!==void 0?l=o:s[1]!==void 0?l=s[1]:s[0]!==void 0&&(l=s[0]),l=this.normalizeModelName(l,u),this.details.vendor=u,this.details.model=l;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{let e=ml();if(!fl(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t!=null&&t[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};import{getWindow as qf,isBrowserWindow as NA}from"@vkontakte/videoplayer-shared/es2018";var Pn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in qf()}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 s;let e=qf();if(!NA(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r!=null?r:0,this._isHdr=!!((s=e.matchMedia("(dynamic-range: high)"))!=null&&s.matches),this._colorDepth=i.colorDepth}catch(n){console.error(n)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(n){console.error(n)}}};import{getWindow as bl,isBrowserWindow as Hf}from"@vkontakte/videoplayer-shared/es2018";var je=()=>window.ManagedMediaSource||window.MediaSource,lr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Uf=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},An=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var jf,FA=(jf=bl().document)==null?void 0:jf.createElement("video"),qA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',UA='video/mp4; codecs="hev1.1.6.L93.B0"',Qf='video/webm; codecs="vp09.00.10.08"',Wf='video/webm; codecs="av01.0.00M.08"',jA='audio/mp4; codecs="mp4a.40.2"',HA='audio/webm; codecs="opus"',zf,QA=async()=>{let a=bl();if(!Hf(a))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Wf}}),a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Qf}})]);zf={DASH_WEBM_AV1:t,DASH_WEBM:i}};QA().catch(a=>{console.log(FA),console.error(a)});var kn=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 zf}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var i,r,s,n,o,u,l,d,c,p,h,m,f,v,g,S,T,y,w,R;let e=bl();if(!Hf(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:lr(),mse:Uf(),hls:!!((r=(i=this._video).canPlayType)!=null&&r.call(i,"application/x-mpegurl")||(n=(s=this._video).canPlayType)!=null&&n.call(s,"vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/mp4")),webm:!!((d=(l=this._video).canPlayType)!=null&&d.call(l,"video/webm")),cmaf:!0};let L=!!((p=(c=je())==null?void 0:c.isTypeSupported)!=null&&p.call(c,qA)),$=!!((m=(h=je())==null?void 0:h.isTypeSupported)!=null&&m.call(h,UA)),D=!!((v=(f=je())==null?void 0:f.isTypeSupported)!=null&&v.call(f,jA));this._codecs={h264:L,h265:$,vp9:!!((S=(g=je())==null?void 0:g.isTypeSupported)!=null&&S.call(g,Qf)),av1:!!((y=(T=je())==null?void 0:T.isTypeSupported)!=null&&y.call(T,Wf)),aac:D,opus:!!((R=(w=je())==null?void 0:w.isTypeSupported)!=null&&R.call(w,HA)),mpeg:(L||$)&&D},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(L){console.error(L)}try{this.destroyVideoElement()}catch(L){console.error("Error destroying video element:",L)}}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}};import{getWindow as WA,isBrowserWindow as zA}from"@vkontakte/videoplayer-shared/es2018";var Gf="audio/mpeg",Rn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var i,r,s,n;let e=WA();if(!zA(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!((r=(i=this._audio).canPlayType)!=null&&r.call(i,Gf))},this._codecs={mp3:!!((n=(s=je())==null?void 0:s.isTypeSupported)!=null&&n.call(s,Gf))}}catch(o){console.error(o)}try{this.destroyAudioElement()}catch(o){console.error("Error destroying audio element:",o)}}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}};var gl=class{constructor(){this.isInited$=new YA(!1);this._displayChecker=new Pn,this._deviceChecker=new xn(this._displayChecker),this._browserChecker=new wn,this._videoChecker=new kn(this._deviceChecker,this._browserChecker),this._audioChecker=new Rn,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}async detect(){GA()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},B=new gl;var vl=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=B.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Yf(o)}})},ca=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":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 Yf(a)}},KA=a=>{let t=Object.keys(a).filter(i=>!ca(i));return vl(t).length>0};var da=class{constructor(e){this.subscription=new ZA;this.sessionId$=new El(null);this.mediaSessionId$=new El(null);this.contentId$=new El(null);this.isMobile=xi();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{var s,n,o;if(Xf(e))return;this.media=e,this.mediaSessionId$.next((s=e.mediaSessionId)!=null?s:null);let t=(n=e.media)==null?void 0:n.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=(o=e.media)==null?void 0:o.duration;Il(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(Il(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let l=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!l?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new En(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ca(e.format)),this.subscribe()}subscribe(){let e=r=>{var s;this.params.output.error$.next({category:XA.WTF,id:"ChromecastPresentationApiProvider",message:(s=r==null?void 0:r.message)!=null?s:"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(cr(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(cr(Il),Kf(),Tl(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(Kf(),JA(Boolean));this.subscription.add(yl({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(cr(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=yl({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(cr(({mediaLoaded:r})=>r),Tl(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(cr(({mediaLoaded:r,playbackState:{from:s,to:n}})=>!r&&s==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(yl({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(Tl(30)),mediaLoaded:t}).pipe(cr(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:s,volume:n}=r.to;this.setVolume(n,s)},e))}handleMessage(e){var t,i,r,s,n,o;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let u=(i=(t=e.message)==null?void 0:t.media)==null?void 0:i[0];this.syncMediaState(u);let l=(r=e.message)==null?void 0:r.receiver.volume;this.syncVolumeState(l)}break;case"v2_message":{switch((s=e.message)==null?void 0:s.type){case"MEDIA_STATUS":{let u=(o=(n=e.message)==null?void 0:n.status)==null?void 0:o[0];this.syncMediaState(u);break}}break}}}loadMedia(){var o;let e=In(this.params),t=(o=this.media)==null?void 0:o.currentTime,i=this.params.desiredState.seekState.getState(),r=t!=null?t:i.state!=="none"?i.position/1e3:0,n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();Sl(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Sl(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Sl(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":A(this.params.desiredState.playbackState,"paused");break;case"PLAYING":A(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),A(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):A(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if(Xf(e))return;let{level:t,muted:i}=e,r={muted:i!=null?i:!1,volume:t!=null?t:0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let s=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,s+=`, volume passed to state machine: ${r.volume}`),this.log({message:s}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};import{assertNonNullable as ek,ErrorCategory as wl,filter as tk,Subject as ik,Subscription as xl,tap as rk,ValueSubject as dr,fromEvent as pa}from"@vkontakte/videoplayer-shared/es2018";var Jf=a=>({castDevice:{friendlyName:a},remotePlayer:{},remotePlayerController:{},session:{}}),Zf=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var ha=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new dr(null);this.sessionId$=new dr(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new xl;this.subscriptionEvents=new xl;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new dr(!1);this.presentationConnection$=new dr(null);this.message$=new dr(null);this.friendlyName$=new dr(null);this.errorEvent$=new ik;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(pa(r,"change").subscribe(()=>{s()})),s()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){var e;this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let t=this.presentationRequest$.getValue();ek(t,"connect with null presentationRequest");let i=await t.start();this.handleConnection(i)}catch(t){switch(t==null?void 0:t.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:wl.WTF,id:"ChromecastPresentationApiConnector",message:(e=t==null?void 0:t.message)!=null?e:"connect error",thrown:t});break}}}subscribe(){this.subscription.add(pa(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe(rk(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),tk(e=>!!e)).subscribe(e=>{let t=pa(e,"message").subscribe(s=>{let n=JSON.parse(s.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(n),this.message$.next(n))}),i=pa(e,"connect").subscribe(()=>{this.send("client_connect")}),r=pa(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:wl.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:s});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();(t==null?void 0:t.state)==="connected"&&(t==null||t.send(e))}catch(t){this.errorEvent$.next({category:wl.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){var t;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":((t=e.message)==null?void 0:t.action)==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||Zf()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new xl}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};import{ValueSubject as eb,Subject as ak,map as sk,Subscription as nk,combine as ok,filterChanged as tb,assertNonNullable as uk}from"@vkontakte/videoplayer-shared/es2018";var At=class a{constructor(e){this.subscription=new nk;this.connection$=new eb(void 0);this.castState$=new eb("NOT_AVAILABLE");this.errorEvent$=new ak;let t=a.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new ha({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){uk(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=ok({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(tb())});this.subscription.add(e.pipe(sk(({connection:t,friendlyName:i})=>!!(t&&i)),tb()).subscribe(t=>{var r,s;let i=(s=(r=this.chromecastConnector)==null?void 0:r.friendlyName$.getValue())!=null?s:"";this.connection$.next(t?Jf(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){var e;this.log({message:"connect"}),(e=this.chromecastConnector)==null||e.connect()}disconnect(){var e;this.log({message:"disconnect"}),(e=this.chromecastConnector)==null||e.disconnect()}async stopMedia(){var e;this.log({message:"stopMedia"}),(e=this.chromecastConnector)==null||e.stopMedia()}toggleConnection(){var t;let e=!!((t=this.chromecastConnector)!=null&&t.presentationConnection$.getValue());this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){var e;this.log({message:"destroy"}),(e=this.chromecastConnector)==null||e.destroy(),this.subscription.unsubscribe()}};var fp=_(De(),1),bp=_(zt(),1),JE=_(zl(),1);var OS=_(Lc(),1);import{isNonNullable as GC,Subject as eo,merge as LS}from"@vkontakte/videoplayer-shared/es2018";var j=class{constructor(e){this.transitionStarted$=new eo;this.transitionEnded$=new eo;this.transitionUpdated$=new eo;this.forceChanged$=new eo;this.stateChangeStarted$=LS(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=LS(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||GC(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 Pa,debounce as DS,ErrorCategory as YC,fromEvent as Mi,map as BS,merge as VS,observableFrom as KC,Subject as XC,Subscription as Dc,timeout as JC}from"@vkontakte/videoplayer-shared/es2018";var ZC=5,eL=5,tL=500,_S=7e3,Aa=class{constructor(e){this.subscription=new Dc;this.loadMediaTimeoutSubscription=new Dc;this.videoState=new j("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Pa(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:Pa(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:Pa(e)}break}default:Pa(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(ca(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 Dc;this.subscription.add(e),this.subscription.add(VS(this.videoState.stateChangeStarted$.pipe(BS(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(BS(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new XC;e.add(r.pipe(DS(tL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>ZC)&&r.next(o),s=o})),e.add(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<eL&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Pa(n)}}),t(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(Mi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=VS(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,KC(["init"])).pipe(DS(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"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(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=In(this.params),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"),A(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),A(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(JC(_S).subscribe(()=>s(`timeout(${_S})`)))});(0,OS.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:YC.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Zc=_(De(),1);import{clearVideoElement as FS,getWindow as rL}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as iL}from"@vkontakte/videoplayer-shared/es2018";var NS=a=>{try{a.pause(),a.playbackRate=0,iL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as aL,Subscription as sL}from"@vkontakte/videoplayer-shared/es2018";var Bc=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)}},to=rL(),Vc=to.WeakMap?new to.WeakMap:new Bc,_c=to.WeakMap?new to.WeakMap:new Map,nL=(a,e=20)=>{let t=0;return aL(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Be=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?FS(i):(i=document.createElement("video"),a.appendChild(i)),Vc.set(i,r);let s=new sL;return s.add(nL(i,e)),_c.set(i,s),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},Ve=a=>{let e=_c.get(a);e==null||e.unsubscribe(),_c.delete(a);let t=Vc.get(a);Vc.delete(a),t?FS(a):NS(a)};var Nc=_(Ei(),1);import{assertNonNullable as Ra,isNonNullable as vt,isNullable as lL,fromEvent as Tr,merge as qS,observableFrom as US,filterChanged as jS,map as $a,Subject as HS,Subscription as cL,ValueSubject as dL,ErrorCategory as pL}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Oc,isNullable as oL,Subscription as uL}from"@vkontakte/videoplayer-shared/es2018";var io=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=oL(r),l=new uL;return r&&l.add(r.subscribe(d=>{let c=a.getState();i(d,c)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),l},gt=(a,e,t)=>io(e,()=>a.loop,i=>{Oc(i)&&(a.loop=i)},{onError:t}),_e=(a,e,t,i)=>io(e,()=>({muted:a.muted,volume:a.volume}),r=>{Oc(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ge=(a,e,t,i)=>io(e,()=>a.playbackRate,r=>{Oc(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),ka=io;var hL=a=>["__",a.language,a.label].join("|"),mL=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Fc=class a{constructor(e){this.available$=new HS;this.current$=new dL(void 0);this.error$=new HS;this.subscription=new cL;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=s=>{this.error$.next({id:"TextTracksManager",category:pL.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ka(t.internalTextTracks,()=>(0,Nc.default)(this.internalTracks),s=>{vt(s)&&this.setInternal(s)},{equal:(s,n)=>vt(s)&&vt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($a(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ka(t.externalTextTracks,()=>(0,Nc.default)(this.externalTracks),s=>{vt(s)&&this.setExternal(s)},{equal:(s,n)=>vt(s)&&vt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($a(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ka(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(ka(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ra(this.video);let{textTracks:e}=this.video;this.subscription.add(Tr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(qS(Tr(e,"addtrack"),Tr(e,"removetrack"),US(["init"])).pipe($a(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),jS((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(qS(Tr(e,"change"),US(["init"])).pipe($a(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),$a(i=>i&&this.htmlTextTrackToITextTrack(i).id),jS()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(Tr(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,d,c,p,h;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(c=o.target)==null?void 0:c.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Tr(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;vt(t.align)&&(r.align=t.align),vt(t.position)&&(r.position=t.position),vt(t.size)&&(r.size=t.size),vt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ra(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:hL(e),s=this.externalTracks.has(r),n=(l=s?(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 s?{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:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Ra(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(lL(e)||!mL(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){Ra(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){Ra(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)}},Ye=Fc;var Ci=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 QS=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},qc=a=>{let e=QS(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},WS=a=>{let e=QS(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ae,map as St,merge as ro,filterChanged as GS,isNonNullable as YS,Subject as bL,filter as Uc,mapTo as jc,combine as gL,once as vL,shareReplay as ke,throttle as SL,ErrorCategory as yL,ValueSubject as KS,Subscription as TL}from"@vkontakte/videoplayer-shared/es2018";var fL=3,zS=(a,e,t=fL)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Oe=a=>{let e=k=>Ae(a,k).pipe(jc(void 0),ke(1)),t=new TL,i=()=>t.unsubscribe(),r=ro(Ae(a,"progress"),Ae(a,"timeupdate")).pipe(St(()=>zS(a.buffered,a.currentTime)),ke(1)),s=B.browser.isSafari?gL({play:e("play").pipe(vL()),playing:e("playing")}).pipe(jc(void 0),ke(1)):e("playing"),n=Ae(a,"volumechange").pipe(St(()=>({muted:a.muted,volume:a.volume})),ke(1)),o=Ae(a,"ratechange").pipe(St(()=>a.playbackRate),ke(1)),u=Ae(a,"error").pipe(Uc(()=>!!(a.error||a.played.length)),St(()=>{var V;let k=a.error;return{id:k?`MediaError#${k.code}`:"HtmlVideoError",category:yL.VIDEO_PIPELINE,message:k?k.message:"Error event from HTML video element",thrown:(V=a.error)!=null?V:void 0}}),ke(1)),l=Ae(a,"timeupdate").pipe(St(()=>a.currentTime),ke(1)),d=["waiting","seeking","seeked","timeupdate"],c=new bL,p=.3,h;t.add(ro(...d.map(k=>Ae(a,k))).subscribe(k=>{let V=a.currentTime;a.loop&&YS(h)&&YS(V)&&h>=a.duration-p&&V<=p&&c.next(h),h=V}));let m=e("pause").pipe(Uc(()=>!a.error&&h!==a.duration),ke(1)),f=Ae(a,"enterpictureinpicture").pipe(ke(1)),v=Ae(a,"leavepictureinpicture").pipe(ke(1)),g=new KS(WS(a));t.add(f.subscribe(()=>g.next(!0))),t.add(v.subscribe(()=>g.next(!1)));let S=new KS(qc(a)),T=Ae(a,"fullscreenchange").pipe(ke(1));t.add(T.pipe(St(()=>qc(a))).subscribe(S));let y=.1,w=1e3,R=Ae(a,"timeupdate").pipe(St(k=>a.duration-a.currentTime<y),GS(),ke(1)),L=ro(R.pipe(Uc(k=>!a.loop&&k)),Ae(a,"ended")).pipe(SL(w),jc(void 0),ke(1)),D=ro(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(k=>Ae(a,k)),R.pipe(St(k=>({type:k?"ended":"unknown"})))).pipe(St(k=>B.browser.isFirefox&&k.type==="ended"?a.readyState<2:a.readyState<3),GS(),ke(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:L,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$:Ae(a,"durationchange").pipe(St(()=>a.duration),ke(1)),isBuffering$:D,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:v,destroy:i}};import{VideoQuality as Yt}from"@vkontakte/videoplayer-shared/es2018";var Kt=a=>{switch(a){case"mobile":return Yt.Q_144P;case"lowest":return Yt.Q_240P;case"low":return Yt.Q_360P;case"sd":case"medium":return Yt.Q_480P;case"hd":case"high":return Yt.Q_720P;case"fullhd":case"full":return Yt.Q_1080P;case"quadhd":case"quad":return Yt.Q_1440P;case"ultrahd":case"ultra":return Yt.Q_2160P}};var $e=_(Ke(),1),Qc=_(De(),1),Di=_(zt(),1);import{isNonNullable as X,isNullable as oo,now as hy,isHigher as uo,isHigherOrEqual as Li,isInvariantQuality as lo,isLowerOrEqual as Er,videoSizeToQuality as my,assertNotEmptyArray as co,assertNonNullable as fy}from"@vkontakte/videoplayer-shared/es2018";var Hc=!1,Rt={},ry=a=>{Hc=a},ay=()=>{Rt={}},sy=a=>{a(Rt)},Ma=(a,e)=>{var t;Hc&&(Rt.meta=(t=Rt.meta)!=null?t:{},Rt.meta[a]=e)},Re=class{constructor(e){this.name=e}next(e){var i,r;if(!Hc)return;Rt.series=(i=Rt.series)!=null?i:{};let t=(r=Rt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Rt.series[this.name]=t}};import{isHigher as $L,isHigherOrEqual as Vj,isLower as ny,isLowerOrEqual as _j,isNonNullable as ao,isNullable as ML,videoHeightToQuality as so}from"@vkontakte/videoplayer-shared/es2018";function oy(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Ir(a,e,t){return ML(a)||ao(a.min)&&ao(a.max)&&ny(a.max,a.min)||ao(a.min)&&e&&$L(a.min,e)||ao(a.max)&&t&&ny(a.max,t)}function uy({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Ir({max:a!=null&&a.max?so(a.max):void 0,min:a!=null&&a.min?so(a.min):void 0},e?so(e):void 0,t?so(t):void 0)}var by=new Re("best_bitrate"),po=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var wr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Xt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=hy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ho='Assertion "ABR Tracks is empty array" failed',no=new WeakMap,ly=new WeakMap,cy=new WeakMap,Ca=(a,e,t,i)=>{var u;let r=[...e].sort(wr(1)),s=[...t].sort(wr(1)),n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,$e.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,$e.default)(s,-1);return o&&(0,Qc.default)(n,o)?o:n.length?(0,$e.default)(n,-1):(0,$e.default)(s,0)},La=(a,e,t,i)=>{var u;let r=no.get(e);r||(r=[...e].sort(wr(1)),no.set(e,r));let s=no.get(t);s||(s=[...t].sort(wr(1)),no.set(t,s));let n=cy.get(a);n||(n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),cy.set(a,n));let o=(u=(0,$e.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,$e.default)(s,-1);return o&&(0,Qc.default)(n,o)?o:n.length?(0,$e.default)(n,-1):(0,$e.default)(s,0)},dy=a=>"quality"in a,mo=(a,e,t,i)=>{var n;let r=X((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&X(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&hy()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=dy(o)?"video":"audio",l=dy(o)?o.quality:o.bitrate;return e({message:`
|
|
8
|
-
[last ${u} selected] ${
|
|
9
|
-
`}),o}return i==null||i.recordSwitch(t),t},
|
|
6
|
+
var Mw=Object.create;var bh=Object.defineProperty;var $w=Object.getOwnPropertyDescriptor;var Cw=Object.getOwnPropertyNames;var Dw=Object.getPrototypeOf,Lw=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Bw=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Cw(e))!Lw.call(a,r)&&r!==t&&bh(a,r,{get:()=>e[r],enumerable:!(i=$w(e,r))||i.enumerable});return a};var _=(a,e,t)=>(t=a!=null?Mw(Dw(a)):{},Bw(e||!a||!a.__esModule?bh(t,"default",{value:a,enumerable:!0}):t,a));var ne=b((Vu,vh)=>{"use strict";var ia=function(a){return a&&a.Math===Math&&a};vh.exports=ia(typeof globalThis=="object"&&globalThis)||ia(typeof window=="object"&&window)||ia(typeof self=="object"&&self)||ia(typeof global=="object"&&global)||ia(typeof Vu=="object"&&Vu)||function(){return this}()||Function("return this")()});var fe=b((LO,Sh)=>{"use strict";Sh.exports=function(a){try{return!!a()}catch(e){return!0}}});var ra=b((BO,yh)=>{"use strict";var Vw=fe();yh.exports=!Vw(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var _u=b((VO,wh)=>{"use strict";var _w=ra(),Eh=Function.prototype,Th=Eh.apply,Ih=Eh.call;wh.exports=typeof Reflect=="object"&&Reflect.apply||(_w?Ih.bind(Th):function(){return Ih.apply(Th,arguments)})});var me=b((_O,kh)=>{"use strict";var xh=ra(),Ph=Function.prototype,Ou=Ph.call,Ow=xh&&Ph.bind.bind(Ou,Ou);kh.exports=xh?Ow:function(a){return function(){return Ou.apply(a,arguments)}}});var vi=b((OO,Rh)=>{"use strict";var Ah=me(),Nw=Ah({}.toString),Fw=Ah("".slice);Rh.exports=function(a){return Fw(Nw(a),8,-1)}});var Nu=b((NO,Mh)=>{"use strict";var qw=vi(),Uw=me();Mh.exports=function(a){if(qw(a)==="Function")return Uw(a)}});var oe=b((FO,$h)=>{"use strict";var Fu=typeof document=="object"&&document.all;$h.exports=typeof Fu=="undefined"&&Fu!==void 0?function(a){return typeof a=="function"||a===Fu}:function(a){return typeof a=="function"}});var qe=b((qO,Ch)=>{"use strict";var Hw=fe();Ch.exports=!Hw(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ue=b((UO,Dh)=>{"use strict";var jw=ra(),mn=Function.prototype.call;Dh.exports=jw?mn.bind(mn):function(){return mn.apply(mn,arguments)}});var qu=b(Vh=>{"use strict";var Lh={}.propertyIsEnumerable,Bh=Object.getOwnPropertyDescriptor,Qw=Bh&&!Lh.call({1:2},1);Vh.f=Qw?function(e){var t=Bh(this,e);return!!t&&t.enumerable}:Lh});var aa=b((jO,_h)=>{"use strict";_h.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Nh=b((QO,Oh)=>{"use strict";var Ww=me(),zw=fe(),Gw=vi(),Uu=Object,Yw=Ww("".split);Oh.exports=zw(function(){return!Uu("z").propertyIsEnumerable(0)})?function(a){return Gw(a)==="String"?Yw(a,""):Uu(a)}:Uu});var sa=b((WO,Fh)=>{"use strict";Fh.exports=function(a){return a==null}});var Qt=b((zO,qh)=>{"use strict";var Kw=sa(),Xw=TypeError;qh.exports=function(a){if(Kw(a))throw new Xw("Can't call method on "+a);return a}});var Si=b((GO,Uh)=>{"use strict";var Jw=Nh(),Zw=Qt();Uh.exports=function(a){return Jw(Zw(a))}});var De=b((YO,Hh)=>{"use strict";var ex=oe();Hh.exports=function(a){return typeof a=="object"?a!==null:ex(a)}});var yi=b((KO,jh)=>{"use strict";jh.exports={}});var Pt=b((XO,Wh)=>{"use strict";var Hu=yi(),ju=ne(),tx=oe(),Qh=function(a){return tx(a)?a:void 0};Wh.exports=function(a,e){return arguments.length<2?Qh(Hu[a])||Qh(ju[a]):Hu[a]&&Hu[a][e]||ju[a]&&ju[a][e]}});var na=b((JO,zh)=>{"use strict";var ix=me();zh.exports=ix({}.isPrototypeOf)});var Ti=b((ZO,Kh)=>{"use strict";var rx=ne(),Gh=rx.navigator,Yh=Gh&&Gh.userAgent;Kh.exports=Yh?String(Yh):""});var Wu=b((eN,rf)=>{"use strict";var tf=ne(),Qu=Ti(),Xh=tf.process,Jh=tf.Deno,Zh=Xh&&Xh.versions||Jh&&Jh.version,ef=Zh&&Zh.v8,rt,bn;ef&&(rt=ef.split("."),bn=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!bn&&Qu&&(rt=Qu.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=Qu.match(/Chrome\/(\d+)/),rt&&(bn=+rt[1])));rf.exports=bn});var zu=b((tN,sf)=>{"use strict";var af=Wu(),ax=fe(),sx=ne(),nx=sx.String;sf.exports=!!Object.getOwnPropertySymbols&&!ax(function(){var a=Symbol("symbol detection");return!nx(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&af&&af<41})});var Gu=b((iN,nf)=>{"use strict";var ox=zu();nf.exports=ox&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Yu=b((rN,of)=>{"use strict";var ux=Pt(),cx=oe(),lx=na(),dx=Gu(),px=Object;of.exports=dx?function(a){return typeof a=="symbol"}:function(a){var e=ux("Symbol");return cx(e)&&lx(e.prototype,px(a))}});var oa=b((aN,uf)=>{"use strict";var hx=String;uf.exports=function(a){try{return hx(a)}catch(e){return"Object"}}});var ft=b((sN,cf)=>{"use strict";var fx=oe(),mx=oa(),bx=TypeError;cf.exports=function(a){if(fx(a))return a;throw new bx(mx(a)+" is not a function")}});var ua=b((nN,lf)=>{"use strict";var gx=ft(),vx=sa();lf.exports=function(a,e){var t=a[e];return vx(t)?void 0:gx(t)}});var pf=b((oN,df)=>{"use strict";var Ku=Ue(),Xu=oe(),Ju=De(),Sx=TypeError;df.exports=function(a,e){var t,i;if(e==="string"&&Xu(t=a.toString)&&!Ju(i=Ku(t,a))||Xu(t=a.valueOf)&&!Ju(i=Ku(t,a))||e!=="string"&&Xu(t=a.toString)&&!Ju(i=Ku(t,a)))return i;throw new Sx("Can't convert object to primitive value")}});var at=b((uN,hf)=>{"use strict";hf.exports=!0});var bf=b((cN,mf)=>{"use strict";var ff=ne(),yx=Object.defineProperty;mf.exports=function(a,e){try{yx(ff,a,{value:e,configurable:!0,writable:!0})}catch(t){ff[a]=e}return e}});var ca=b((lN,Sf)=>{"use strict";var Tx=at(),Ix=ne(),Ex=bf(),gf="__core-js_shared__",vf=Sf.exports=Ix[gf]||Ex(gf,{});(vf.versions||(vf.versions=[])).push({version:"3.43.0",mode:Tx?"pure":"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Zu=b((dN,Tf)=>{"use strict";var yf=ca();Tf.exports=function(a,e){return yf[a]||(yf[a]=e||{})}});var ar=b((pN,If)=>{"use strict";var wx=Qt(),xx=Object;If.exports=function(a){return xx(wx(a))}});var st=b((hN,Ef)=>{"use strict";var Px=me(),kx=ar(),Ax=Px({}.hasOwnProperty);Ef.exports=Object.hasOwn||function(e,t){return Ax(kx(e),t)}});var ec=b((fN,wf)=>{"use strict";var Rx=me(),Mx=0,$x=Math.random(),Cx=Rx(1.1.toString);wf.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Cx(++Mx+$x,36)}});var Ie=b((mN,Pf)=>{"use strict";var Dx=ne(),Lx=Zu(),xf=st(),Bx=ec(),Vx=zu(),_x=Gu(),sr=Dx.Symbol,tc=Lx("wks"),Ox=_x?sr.for||sr:sr&&sr.withoutSetter||Bx;Pf.exports=function(a){return xf(tc,a)||(tc[a]=Vx&&xf(sr,a)?sr[a]:Ox("Symbol."+a)),tc[a]}});var Mf=b((bN,Rf)=>{"use strict";var Nx=Ue(),kf=De(),Af=Yu(),Fx=ua(),qx=pf(),Ux=Ie(),Hx=TypeError,jx=Ux("toPrimitive");Rf.exports=function(a,e){if(!kf(a)||Af(a))return a;var t=Fx(a,jx),i;if(t){if(e===void 0&&(e="default"),i=Nx(t,a,e),!kf(i)||Af(i))return i;throw new Hx("Can't convert object to primitive value")}return e===void 0&&(e="number"),qx(a,e)}});var ic=b((gN,$f)=>{"use strict";var Qx=Mf(),Wx=Yu();$f.exports=function(a){var e=Qx(a,"string");return Wx(e)?e:e+""}});var gn=b((vN,Df)=>{"use strict";var zx=ne(),Cf=De(),rc=zx.document,Gx=Cf(rc)&&Cf(rc.createElement);Df.exports=function(a){return Gx?rc.createElement(a):{}}});var ac=b((SN,Lf)=>{"use strict";var Yx=qe(),Kx=fe(),Xx=gn();Lf.exports=!Yx&&!Kx(function(){return Object.defineProperty(Xx("div"),"a",{get:function(){return 7}}).a!==7})});var _f=b(Vf=>{"use strict";var Jx=qe(),Zx=Ue(),eP=qu(),tP=aa(),iP=Si(),rP=ic(),aP=st(),sP=ac(),Bf=Object.getOwnPropertyDescriptor;Vf.f=Jx?Bf:function(e,t){if(e=iP(e),t=rP(t),sP)try{return Bf(e,t)}catch(i){}if(aP(e,t))return tP(!Zx(eP.f,e,t),e[t])}});var sc=b((TN,Of)=>{"use strict";var nP=fe(),oP=oe(),uP=/#|\.prototype\./,la=function(a,e){var t=lP[cP(a)];return t===pP?!0:t===dP?!1:oP(e)?nP(e):!!e},cP=la.normalize=function(a){return String(a).replace(uP,".").toLowerCase()},lP=la.data={},dP=la.NATIVE="N",pP=la.POLYFILL="P";Of.exports=la});var nr=b((IN,Ff)=>{"use strict";var Nf=Nu(),hP=ft(),fP=ra(),mP=Nf(Nf.bind);Ff.exports=function(a,e){return hP(a),e===void 0?a:fP?mP(a,e):function(){return a.apply(e,arguments)}}});var nc=b((EN,qf)=>{"use strict";var bP=qe(),gP=fe();qf.exports=bP&&gP(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var mt=b((wN,Uf)=>{"use strict";var vP=De(),SP=String,yP=TypeError;Uf.exports=function(a){if(vP(a))return a;throw new yP(SP(a)+" is not an object")}});var Ii=b(jf=>{"use strict";var TP=qe(),IP=ac(),EP=nc(),vn=mt(),Hf=ic(),wP=TypeError,oc=Object.defineProperty,xP=Object.getOwnPropertyDescriptor,uc="enumerable",cc="configurable",lc="writable";jf.f=TP?EP?function(e,t,i){if(vn(e),t=Hf(t),vn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&lc in i&&!i[lc]){var r=xP(e,t);r&&r[lc]&&(e[t]=i.value,i={configurable:cc in i?i[cc]:r[cc],enumerable:uc in i?i[uc]:r[uc],writable:!1})}return oc(e,t,i)}:oc:function(e,t,i){if(vn(e),t=Hf(t),vn(i),IP)try{return oc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new wP("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var or=b((PN,Qf)=>{"use strict";var PP=qe(),kP=Ii(),AP=aa();Qf.exports=PP?function(a,e,t){return kP.f(a,e,AP(1,t))}:function(a,e,t){return a[e]=t,a}});var le=b((kN,zf)=>{"use strict";var da=ne(),RP=_u(),MP=Nu(),$P=oe(),CP=_f().f,DP=sc(),ur=yi(),LP=nr(),cr=or(),Wf=st();ca();var BP=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return RP(a,this,arguments)};return e.prototype=a.prototype,e};zf.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?da:r?da[t]:da[t]&&da[t].prototype,o=i?ur:ur[t]||cr(ur,t,{})[t],u=o.prototype,c,d,l,p,h,f,m,v,g;for(p in e)c=DP(i?p:t+(r?".":"#")+p,a.forced),d=!c&&n&&Wf(n,p),f=o[p],d&&(a.dontCallGetSet?(g=CP(n,p),m=g&&g.value):m=n[p]),h=d&&m?m:e[p],!(!c&&!s&&typeof f==typeof h)&&(a.bind&&d?v=LP(h,da):a.wrap&&d?v=BP(h):s&&$P(h)?v=MP(h):v=h,(a.sham||h&&h.sham||f&&f.sham)&&cr(v,"sham",!0),cr(o,p,v),s&&(l=t+"Prototype",Wf(ur,l)||cr(ur,l,{}),cr(ur[l],p,h),a.real&&u&&(c||!u[p])&&cr(u,p,h)))}});var Sn=b((AN,Yf)=>{"use strict";var VP=Zu(),_P=ec(),Gf=VP("keys");Yf.exports=function(a){return Gf[a]||(Gf[a]=_P(a))}});var Xf=b((RN,Kf)=>{"use strict";var OP=fe();Kf.exports=!OP(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var yn=b((MN,Zf)=>{"use strict";var NP=st(),FP=oe(),qP=ar(),UP=Sn(),HP=Xf(),Jf=UP("IE_PROTO"),dc=Object,jP=dc.prototype;Zf.exports=HP?dc.getPrototypeOf:function(a){var e=qP(a);if(NP(e,Jf))return e[Jf];var t=e.constructor;return FP(t)&&e instanceof t?t.prototype:e instanceof dc?jP:null}});var tm=b(($N,em)=>{"use strict";var QP=Math.ceil,WP=Math.floor;em.exports=Math.trunc||function(e){var t=+e;return(t>0?WP:QP)(t)}});var pa=b((CN,im)=>{"use strict";var zP=tm();im.exports=function(a){var e=+a;return e!==e||e===0?0:zP(e)}});var am=b((DN,rm)=>{"use strict";var GP=pa(),YP=Math.max,KP=Math.min;rm.exports=function(a,e){var t=GP(a);return t<0?YP(t+e,0):KP(t,e)}});var pc=b((LN,sm)=>{"use strict";var XP=pa(),JP=Math.min;sm.exports=function(a){var e=XP(a);return e>0?JP(e,9007199254740991):0}});var lr=b((BN,nm)=>{"use strict";var ZP=pc();nm.exports=function(a){return ZP(a.length)}});var hc=b((VN,um)=>{"use strict";var ek=Si(),tk=am(),ik=lr(),om=function(a){return function(e,t,i){var r=ek(e),s=ik(r);if(s===0)return!a&&-1;var n=tk(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};um.exports={includes:om(!0),indexOf:om(!1)}});var Tn=b((_N,cm)=>{"use strict";cm.exports={}});var pm=b((ON,dm)=>{"use strict";var rk=me(),fc=st(),ak=Si(),sk=hc().indexOf,nk=Tn(),lm=rk([].push);dm.exports=function(a,e){var t=ak(a),i=0,r=[],s;for(s in t)!fc(nk,s)&&fc(t,s)&&lm(r,s);for(;e.length>i;)fc(t,s=e[i++])&&(~sk(r,s)||lm(r,s));return r}});var mc=b((NN,hm)=>{"use strict";hm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var bc=b((FN,fm)=>{"use strict";var ok=pm(),uk=mc();fm.exports=Object.keys||function(e){return ok(e,uk)}});var gc=b((qN,Sm)=>{"use strict";var bm=qe(),ck=fe(),gm=me(),lk=yn(),dk=bc(),pk=Si(),hk=qu().f,vm=gm(hk),fk=gm([].push),mk=bm&&ck(function(){var a=Object.create(null);return a[2]=2,!vm(a,2)}),mm=function(a){return function(e){for(var t=pk(e),i=dk(t),r=mk&&lk(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!bm||(r?u in t:vm(t,u)))&&fk(o,a?[u,t[u]]:t[u]);return o}};Sm.exports={entries:mm(!0),values:mm(!1)}});var ym=b(()=>{"use strict";var bk=le(),gk=gc().values;bk({target:"Object",stat:!0},{values:function(e){return gk(e)}})});var Im=b((jN,Tm)=>{"use strict";ym();var vk=yi();Tm.exports=vk.Object.values});var wm=b((QN,Em)=>{"use strict";var Sk=Im();Em.exports=Sk});var Ei=b((WN,xm)=>{"use strict";var yk=wm();xm.exports=yk});var ha=b((zN,Pm)=>{"use strict";Pm.exports=function(){}});var km=b(()=>{"use strict";var Tk=le(),Ik=hc().includes,Ek=fe(),wk=ha(),xk=Ek(function(){return!Array(1).includes()});Tk({target:"Array",proto:!0,forced:xk},{includes:function(e){return Ik(this,e,arguments.length>1?arguments[1]:void 0)}});wk("includes")});var Wt=b((KN,Am)=>{"use strict";var Pk=Pt();Am.exports=Pk});var Mm=b((XN,Rm)=>{"use strict";km();var kk=Wt();Rm.exports=kk("Array","includes")});var Cm=b((JN,$m)=>{"use strict";var Ak=Mm();$m.exports=Ak});var Le=b((ZN,Dm)=>{"use strict";var Rk=Cm();Dm.exports=Rk});var nb=b(()=>{"use strict";var hA=le(),fA=gc().entries;hA({target:"Object",stat:!0},{entries:function(e){return fA(e)}})});var ub=b((Zq,ob)=>{"use strict";nb();var mA=yi();ob.exports=mA.Object.entries});var lb=b((eU,cb)=>{"use strict";var bA=ub();cb.exports=bA});var zt=b((tU,db)=>{"use strict";var gA=lb();db.exports=gA});var Pi=b((iU,pb)=>{"use strict";pb.exports={}});var mb=b((rU,fb)=>{"use strict";var vA=ne(),SA=oe(),hb=vA.WeakMap;fb.exports=SA(hb)&&/native code/.test(String(hb))});var Bc=b((aU,vb)=>{"use strict";var yA=mb(),gb=ne(),TA=De(),IA=or(),Cc=st(),Dc=ca(),EA=Sn(),wA=Tn(),bb="Object already initialized",Lc=gb.TypeError,xA=gb.WeakMap,Ln,va,Bn,PA=function(a){return Bn(a)?va(a):Ln(a,{})},kA=function(a){return function(e){var t;if(!TA(e)||(t=va(e)).type!==a)throw new Lc("Incompatible receiver, "+a+" required");return t}};yA||Dc.state?(nt=Dc.state||(Dc.state=new xA),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,Ln=function(a,e){if(nt.has(a))throw new Lc(bb);return e.facade=a,nt.set(a,e),e},va=function(a){return nt.get(a)||{}},Bn=function(a){return nt.has(a)}):(ki=EA("state"),wA[ki]=!0,Ln=function(a,e){if(Cc(a,ki))throw new Lc(bb);return e.facade=a,IA(a,ki,e),e},va=function(a){return Cc(a,ki)?a[ki]:{}},Bn=function(a){return Cc(a,ki)});var nt,ki;vb.exports={set:Ln,get:va,has:Bn,enforce:PA,getterFor:kA}});var Oc=b((sU,yb)=>{"use strict";var Vc=qe(),AA=st(),Sb=Function.prototype,RA=Vc&&Object.getOwnPropertyDescriptor,_c=AA(Sb,"name"),MA=_c&&function(){}.name==="something",$A=_c&&(!Vc||Vc&&RA(Sb,"name").configurable);yb.exports={EXISTS:_c,PROPER:MA,CONFIGURABLE:$A}});var Ib=b(Tb=>{"use strict";var CA=qe(),DA=nc(),LA=Ii(),BA=mt(),VA=Si(),_A=bc();Tb.f=CA&&!DA?Object.defineProperties:function(e,t){BA(e);for(var i=VA(t),r=_A(t),s=r.length,n=0,o;s>n;)LA.f(e,o=r[n++],i[o]);return e}});var Nc=b((oU,Eb)=>{"use strict";var OA=Pt();Eb.exports=OA("document","documentElement")});var Hc=b((uU,Mb)=>{"use strict";var NA=mt(),FA=Ib(),wb=mc(),qA=Tn(),UA=Nc(),HA=gn(),jA=Sn(),xb=">",Pb="<",qc="prototype",Uc="script",Ab=jA("IE_PROTO"),Fc=function(){},Rb=function(a){return Pb+Uc+xb+a+Pb+"/"+Uc+xb},kb=function(a){a.write(Rb("")),a.close();var e=a.parentWindow.Object;return a=null,e},QA=function(){var a=HA("iframe"),e="java"+Uc+":",t;return a.style.display="none",UA.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Rb("document.F=Object")),t.close(),t.F},Vn,_n=function(){try{Vn=new ActiveXObject("htmlfile")}catch(e){}_n=typeof document!="undefined"?document.domain&&Vn?kb(Vn):QA():kb(Vn);for(var a=wb.length;a--;)delete _n[qc][wb[a]];return _n()};qA[Ab]=!0;Mb.exports=Object.create||function(e,t){var i;return e!==null?(Fc[qc]=NA(e),i=new Fc,Fc[qc]=null,i[Ab]=e):i=_n(),t===void 0?i:FA.f(i,t)}});var fr=b((cU,$b)=>{"use strict";var WA=or();$b.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:WA(a,e,t),a}});var zc=b((lU,Lb)=>{"use strict";var zA=fe(),GA=oe(),YA=De(),KA=Hc(),Cb=yn(),XA=fr(),JA=Ie(),ZA=at(),Wc=JA("iterator"),Db=!1,At,jc,Qc;[].keys&&(Qc=[].keys(),"next"in Qc?(jc=Cb(Cb(Qc)),jc!==Object.prototype&&(At=jc)):Db=!0);var eR=!YA(At)||zA(function(){var a={};return At[Wc].call(a)!==a});eR?At={}:ZA&&(At=KA(At));GA(At[Wc])||XA(At,Wc,function(){return this});Lb.exports={IteratorPrototype:At,BUGGY_SAFARI_ITERATORS:Db}});var On=b((dU,Vb)=>{"use strict";var tR=Ie(),iR=tR("toStringTag"),Bb={};Bb[iR]="z";Vb.exports=String(Bb)==="[object z]"});var Sa=b((pU,_b)=>{"use strict";var rR=On(),aR=oe(),Nn=vi(),sR=Ie(),nR=sR("toStringTag"),oR=Object,uR=Nn(function(){return arguments}())==="Arguments",cR=function(a,e){try{return a[e]}catch(t){}};_b.exports=rR?Nn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=cR(e=oR(a),nR))=="string"?t:uR?Nn(e):(i=Nn(e))==="Object"&&aR(e.callee)?"Arguments":i}});var Nb=b((hU,Ob)=>{"use strict";var lR=On(),dR=Sa();Ob.exports=lR?{}.toString:function(){return"[object "+dR(this)+"]"}});var ya=b((fU,qb)=>{"use strict";var pR=On(),hR=Ii().f,fR=or(),mR=st(),bR=Nb(),gR=Ie(),Fb=gR("toStringTag");qb.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(mR(r,Fb)||hR(r,Fb,{configurable:!0,value:e}),i&&!pR&&fR(r,"toString",bR))}});var Hb=b((mU,Ub)=>{"use strict";var vR=zc().IteratorPrototype,SR=Hc(),yR=aa(),TR=ya(),IR=Pi(),ER=function(){return this};Ub.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=SR(vR,{next:yR(+!i,t)}),TR(a,r,!1,!0),IR[r]=ER,a}});var Qb=b((bU,jb)=>{"use strict";var wR=me(),xR=ft();jb.exports=function(a,e,t){try{return wR(xR(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var zb=b((gU,Wb)=>{"use strict";var PR=De();Wb.exports=function(a){return PR(a)||a===null}});var Yb=b((vU,Gb)=>{"use strict";var kR=zb(),AR=String,RR=TypeError;Gb.exports=function(a){if(kR(a))return a;throw new RR("Can't set "+AR(a)+" as a prototype")}});var Gc=b((SU,Kb)=>{"use strict";var MR=Qb(),$R=De(),CR=Qt(),DR=Yb();Kb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=MR(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return CR(r),DR(s),$R(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var og=b((yU,ng)=>{"use strict";var LR=le(),BR=Ue(),Fn=at(),ag=Oc(),VR=oe(),_R=Hb(),Xb=yn(),Jb=Gc(),OR=ya(),NR=or(),Yc=fr(),FR=Ie(),Zb=Pi(),sg=zc(),qR=ag.PROPER,UR=ag.CONFIGURABLE,eg=sg.IteratorPrototype,qn=sg.BUGGY_SAFARI_ITERATORS,Ta=FR("iterator"),tg="keys",Ia="values",ig="entries",rg=function(){return this};ng.exports=function(a,e,t,i,r,s,n){_R(t,e,i);var o=function(g){if(g===r&&p)return p;if(!qn&&g&&g in d)return d[g];switch(g){case tg:return function(){return new t(this,g)};case Ia:return function(){return new t(this,g)};case ig:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",c=!1,d=a.prototype,l=d[Ta]||d["@@iterator"]||r&&d[r],p=!qn&&l||o(r),h=e==="Array"&&d.entries||l,f,m,v;if(h&&(f=Xb(h.call(new a)),f!==Object.prototype&&f.next&&(!Fn&&Xb(f)!==eg&&(Jb?Jb(f,eg):VR(f[Ta])||Yc(f,Ta,rg)),OR(f,u,!0,!0),Fn&&(Zb[u]=rg))),qR&&r===Ia&&l&&l.name!==Ia&&(!Fn&&UR?NR(d,"name",Ia):(c=!0,p=function(){return BR(l,this)})),r)if(m={values:o(Ia),keys:s?p:o(tg),entries:o(ig)},n)for(v in m)(qn||c||!(v in d))&&Yc(d,v,m[v]);else LR({target:e,proto:!0,forced:qn||c},m);return(!Fn||n)&&d[Ta]!==p&&Yc(d,Ta,p,{name:r}),Zb[e]=p,m}});var cg=b((TU,ug)=>{"use strict";ug.exports=function(a,e){return{value:a,done:e}}});var Xc=b((IU,fg)=>{"use strict";var HR=Si(),Kc=ha(),lg=Pi(),pg=Bc(),jR=Ii().f,QR=og(),Un=cg(),WR=at(),zR=qe(),hg="Array Iterator",GR=pg.set,YR=pg.getterFor(hg);fg.exports=QR(Array,"Array",function(a,e){GR(this,{type:hg,target:HR(a),index:0,kind:e})},function(){var a=YR(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,Un(void 0,!0);switch(a.kind){case"keys":return Un(t,!1);case"values":return Un(e[t],!1)}return Un([t,e[t]],!1)},"values");var dg=lg.Arguments=lg.Array;Kc("keys");Kc("values");Kc("entries");if(!WR&&zR&&dg.name!=="values")try{jR(dg,"name",{value:"values"})}catch(a){}});var bg=b((EU,mg)=>{"use strict";var KR=Ie(),XR=Pi(),JR=KR("iterator"),ZR=Array.prototype;mg.exports=function(a){return a!==void 0&&(XR.Array===a||ZR[JR]===a)}});var Jc=b((wU,vg)=>{"use strict";var eM=Sa(),gg=ua(),tM=sa(),iM=Pi(),rM=Ie(),aM=rM("iterator");vg.exports=function(a){if(!tM(a))return gg(a,aM)||gg(a,"@@iterator")||iM[eM(a)]}});var yg=b((xU,Sg)=>{"use strict";var sM=Ue(),nM=ft(),oM=mt(),uM=oa(),cM=Jc(),lM=TypeError;Sg.exports=function(a,e){var t=arguments.length<2?cM(a):e;if(nM(t))return oM(sM(t,a));throw new lM(uM(a)+" is not iterable")}});var Eg=b((PU,Ig)=>{"use strict";var dM=Ue(),Tg=mt(),pM=ua();Ig.exports=function(a,e,t){var i,r;Tg(a);try{if(i=pM(a,"return"),!i){if(e==="throw")throw t;return t}i=dM(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Tg(i),t}});var jn=b((kU,kg)=>{"use strict";var hM=nr(),fM=Ue(),mM=mt(),bM=oa(),gM=bg(),vM=lr(),wg=na(),SM=yg(),yM=Jc(),xg=Eg(),TM=TypeError,Hn=function(a,e){this.stopped=a,this.result=e},Pg=Hn.prototype;kg.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=hM(e,i),c,d,l,p,h,f,m,v=function(S){return c&&xg(c,"normal"),new Hn(!0,S)},g=function(S){return r?(mM(S),o?u(S[0],S[1],v):u(S[0],S[1])):o?u(S,v):u(S)};if(s)c=a.iterator;else if(n)c=a;else{if(d=yM(a),!d)throw new TM(bM(a)+" is not iterable");if(gM(d)){for(l=0,p=vM(a);p>l;l++)if(h=g(a[l]),h&&wg(Pg,h))return h;return new Hn(!1)}c=SM(a,d)}for(f=s?a.next:c.next;!(m=fM(f,c)).done;){try{h=g(m.value)}catch(S){xg(c,"throw",S)}if(typeof h=="object"&&h&&wg(Pg,h))return h}return new Hn(!1)}});var Rg=b((AU,Ag)=>{"use strict";var IM=qe(),EM=Ii(),wM=aa();Ag.exports=function(a,e,t){IM?EM.f(a,e,wM(0,t)):a[e]=t}});var Mg=b(()=>{"use strict";var xM=le(),PM=jn(),kM=Rg();xM({target:"Object",stat:!0},{fromEntries:function(e){var t={};return PM(e,function(i,r){kM(t,i,r)},{AS_ENTRIES:!0}),t}})});var Cg=b(($U,$g)=>{"use strict";Xc();Mg();var AM=yi();$g.exports=AM.Object.fromEntries});var Lg=b((CU,Dg)=>{"use strict";Dg.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Vg=b(()=>{"use strict";Xc();var RM=Lg(),MM=ne(),$M=ya(),Bg=Pi();for(Qn in RM)$M(MM[Qn],Qn),Bg[Qn]=Bg.Array;var Qn});var Og=b((BU,_g)=>{"use strict";var CM=Cg();Vg();_g.exports=CM});var Zc=b((VU,Ng)=>{"use strict";var DM=Og();Ng.exports=DM});var Fg=b(()=>{"use strict"});var el=b((NU,qg)=>{"use strict";var Ea=ne(),LM=Ti(),BM=vi(),Wn=function(a){return LM.slice(0,a.length)===a};qg.exports=function(){return Wn("Bun/")?"BUN":Wn("Cloudflare-Workers")?"CLOUDFLARE":Wn("Deno/")?"DENO":Wn("Node.js/")?"NODE":Ea.Bun&&typeof Bun.version=="string"?"BUN":Ea.Deno&&typeof Deno.version=="object"?"DENO":BM(Ea.process)==="process"?"NODE":Ea.window&&Ea.document?"BROWSER":"REST"}()});var zn=b((FU,Ug)=>{"use strict";var VM=el();Ug.exports=VM==="NODE"});var jg=b((qU,Hg)=>{"use strict";var _M=Ii();Hg.exports=function(a,e,t){return _M.f(a,e,t)}});var zg=b((UU,Wg)=>{"use strict";var OM=Pt(),NM=jg(),FM=Ie(),qM=qe(),Qg=FM("species");Wg.exports=function(a){var e=OM(a);qM&&e&&!e[Qg]&&NM(e,Qg,{configurable:!0,get:function(){return this}})}});var Yg=b((HU,Gg)=>{"use strict";var UM=na(),HM=TypeError;Gg.exports=function(a,e){if(UM(e,a))return a;throw new HM("Incorrect invocation")}});var il=b((jU,Kg)=>{"use strict";var jM=me(),QM=oe(),tl=ca(),WM=jM(Function.toString);QM(tl.inspectSource)||(tl.inspectSource=function(a){return WM(a)});Kg.exports=tl.inspectSource});var al=b((QU,tv)=>{"use strict";var zM=me(),GM=fe(),Xg=oe(),YM=Sa(),KM=Pt(),XM=il(),Jg=function(){},Zg=KM("Reflect","construct"),rl=/^\s*(?:class|function)\b/,JM=zM(rl.exec),ZM=!rl.test(Jg),wa=function(e){if(!Xg(e))return!1;try{return Zg(Jg,[],e),!0}catch(t){return!1}},ev=function(e){if(!Xg(e))return!1;switch(YM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return ZM||!!JM(rl,XM(e))}catch(t){return!0}};ev.sham=!0;tv.exports=!Zg||GM(function(){var a;return wa(wa.call)||!wa(Object)||!wa(function(){a=!0})||a})?ev:wa});var rv=b((WU,iv)=>{"use strict";var e$=al(),t$=oa(),i$=TypeError;iv.exports=function(a){if(e$(a))return a;throw new i$(t$(a)+" is not a constructor")}});var sl=b((zU,sv)=>{"use strict";var av=mt(),r$=rv(),a$=sa(),s$=Ie(),n$=s$("species");sv.exports=function(a,e){var t=av(a).constructor,i;return t===void 0||a$(i=av(t)[n$])?e:r$(i)}});var ov=b((GU,nv)=>{"use strict";var o$=me();nv.exports=o$([].slice)});var cv=b((YU,uv)=>{"use strict";var u$=TypeError;uv.exports=function(a,e){if(a<e)throw new u$("Not enough arguments");return a}});var nl=b((KU,lv)=>{"use strict";var c$=Ti();lv.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(c$)});var ml=b((XU,Sv)=>{"use strict";var je=ne(),l$=_u(),d$=nr(),dv=oe(),p$=st(),vv=fe(),pv=Nc(),h$=ov(),hv=gn(),f$=cv(),m$=nl(),b$=zn(),pl=je.setImmediate,hl=je.clearImmediate,g$=je.process,ol=je.Dispatch,v$=je.Function,fv=je.MessageChannel,S$=je.String,ul=0,xa={},mv="onreadystatechange",Pa,Ai,cl,ll;vv(function(){Pa=je.location});var fl=function(a){if(p$(xa,a)){var e=xa[a];delete xa[a],e()}},dl=function(a){return function(){fl(a)}},bv=function(a){fl(a.data)},gv=function(a){je.postMessage(S$(a),Pa.protocol+"//"+Pa.host)};(!pl||!hl)&&(pl=function(e){f$(arguments.length,1);var t=dv(e)?e:v$(e),i=h$(arguments,1);return xa[++ul]=function(){l$(t,void 0,i)},Ai(ul),ul},hl=function(e){delete xa[e]},b$?Ai=function(a){g$.nextTick(dl(a))}:ol&&ol.now?Ai=function(a){ol.now(dl(a))}:fv&&!m$?(cl=new fv,ll=cl.port2,cl.port1.onmessage=bv,Ai=d$(ll.postMessage,ll)):je.addEventListener&&dv(je.postMessage)&&!je.importScripts&&Pa&&Pa.protocol!=="file:"&&!vv(gv)?(Ai=gv,je.addEventListener("message",bv,!1)):mv in hv("script")?Ai=function(a){pv.appendChild(hv("script"))[mv]=function(){pv.removeChild(this),fl(a)}}:Ai=function(a){setTimeout(dl(a),0)});Sv.exports={set:pl,clear:hl}});var Iv=b((JU,Tv)=>{"use strict";var yv=ne(),y$=qe(),T$=Object.getOwnPropertyDescriptor;Tv.exports=function(a){if(!y$)return yv[a];var e=T$(yv,a);return e&&e.value}});var bl=b((ZU,wv)=>{"use strict";var Ev=function(){this.head=null,this.tail=null};Ev.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};wv.exports=Ev});var Pv=b((e1,xv)=>{"use strict";var I$=Ti();xv.exports=/ipad|iphone|ipod/i.test(I$)&&typeof Pebble!="undefined"});var Av=b((t1,kv)=>{"use strict";var E$=Ti();kv.exports=/web0s(?!.*chrome)/i.test(E$)});var Bv=b((i1,Lv)=>{"use strict";var br=ne(),w$=Iv(),Rv=nr(),gl=ml().set,x$=bl(),P$=nl(),k$=Pv(),A$=Av(),vl=zn(),Mv=br.MutationObserver||br.WebKitMutationObserver,$v=br.document,Cv=br.process,Gn=br.Promise,Tl=w$("queueMicrotask"),mr,Sl,yl,Yn,Dv;Tl||(ka=new x$,Aa=function(){var a,e;for(vl&&(a=Cv.domain)&&a.exit();e=ka.get();)try{e()}catch(t){throw ka.head&&mr(),t}a&&a.enter()},!P$&&!vl&&!A$&&Mv&&$v?(Sl=!0,yl=$v.createTextNode(""),new Mv(Aa).observe(yl,{characterData:!0}),mr=function(){yl.data=Sl=!Sl}):!k$&&Gn&&Gn.resolve?(Yn=Gn.resolve(void 0),Yn.constructor=Gn,Dv=Rv(Yn.then,Yn),mr=function(){Dv(Aa)}):vl?mr=function(){Cv.nextTick(Aa)}:(gl=Rv(gl,br),mr=function(){gl(Aa)}),Tl=function(a){ka.head||mr(),ka.add(a)});var ka,Aa;Lv.exports=Tl});var _v=b((r1,Vv)=>{"use strict";Vv.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Kn=b((a1,Ov)=>{"use strict";Ov.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ri=b((s1,Nv)=>{"use strict";var R$=ne();Nv.exports=R$.Promise});var gr=b((n1,Hv)=>{"use strict";var M$=ne(),Ra=Ri(),$$=oe(),C$=sc(),D$=il(),L$=Ie(),Fv=el(),B$=at(),Il=Wu(),qv=Ra&&Ra.prototype,V$=L$("species"),El=!1,Uv=$$(M$.PromiseRejectionEvent),_$=C$("Promise",function(){var a=D$(Ra),e=a!==String(Ra);if(!e&&Il===66||B$&&!(qv.catch&&qv.finally))return!0;if(!Il||Il<51||!/native code/.test(a)){var t=new Ra(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[V$]=i,El=t.then(function(){})instanceof i,!El)return!0}return!e&&(Fv==="BROWSER"||Fv==="DENO")&&!Uv});Hv.exports={CONSTRUCTOR:_$,REJECTION_EVENT:Uv,SUBCLASSING:El}});var vr=b((o1,Qv)=>{"use strict";var jv=ft(),O$=TypeError,N$=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new O$("Bad Promise constructor");e=i,t=r}),this.resolve=jv(e),this.reject=jv(t)};Qv.exports.f=function(a){return new N$(a)}});var dS=b(()=>{"use strict";var F$=le(),q$=at(),eo=zn(),Gt=ne(),U$=yi(),Ir=Ue(),Wv=fr(),zv=Gc(),H$=ya(),j$=zg(),Q$=ft(),Zn=oe(),W$=De(),z$=Yg(),G$=sl(),Jv=ml().set,Al=Bv(),Y$=_v(),K$=Kn(),X$=bl(),Zv=Bc(),to=Ri(),Rl=gr(),eS=vr(),io="Promise",tS=Rl.CONSTRUCTOR,J$=Rl.REJECTION_EVENT,Z$=Rl.SUBCLASSING,wl=Zv.getterFor(io),eC=Zv.set,Sr=to&&to.prototype,Mi=to,Xn=Sr,iS=Gt.TypeError,xl=Gt.document,Ml=Gt.process,Pl=eS.f,tC=Pl,iC=!!(xl&&xl.createEvent&&Gt.dispatchEvent),rS="unhandledrejection",rC="rejectionhandled",Gv=0,aS=1,aC=2,$l=1,sS=2,Jn,Yv,nS,Kv,oS=function(a){var e;return W$(a)&&Zn(e=a.then)?e:!1},uS=function(a,e){var t=e.value,i=e.state===aS,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,c,d;try{r?(i||(e.rejection===sS&&nC(e),e.rejection=$l),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new iS("Promise-chain cycle")):(c=oS(u))?Ir(c,u,s,n):s(u)):n(t)}catch(l){o&&!d&&o.exit(),n(l)}},cS=function(a,e){a.notified||(a.notified=!0,Al(function(){for(var t=a.reactions,i;i=t.get();)uS(i,a);a.notified=!1,e&&!a.rejection&&sC(a)}))},lS=function(a,e,t){var i,r;iC?(i=xl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Gt.dispatchEvent(i)):i={promise:e,reason:t},!J$&&(r=Gt["on"+a])?r(i):a===rS&&Y$("Unhandled promise rejection",t)},sC=function(a){Ir(Jv,Gt,function(){var e=a.facade,t=a.value,i=Xv(a),r;if(i&&(r=K$(function(){eo?Ml.emit("unhandledRejection",t,e):lS(rS,e,t)}),a.rejection=eo||Xv(a)?sS:$l,r.error))throw r.value})},Xv=function(a){return a.rejection!==$l&&!a.parent},nC=function(a){Ir(Jv,Gt,function(){var e=a.facade;eo?Ml.emit("rejectionHandled",e):lS(rC,e,a.value)})},yr=function(a,e,t){return function(i){a(e,i,t)}},Tr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=aC,cS(a,!0))},kl=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new iS("Promise can't be resolved itself");var i=oS(e);i?Al(function(){var r={done:!1};try{Ir(i,e,yr(kl,r,a),yr(Tr,r,a))}catch(s){Tr(r,s,a)}}):(a.value=e,a.state=aS,cS(a,!1))}catch(r){Tr({done:!1},r,a)}}};if(tS&&(Mi=function(e){z$(this,Xn),Q$(e),Ir(Jn,this);var t=wl(this);try{e(yr(kl,t),yr(Tr,t))}catch(i){Tr(t,i)}},Xn=Mi.prototype,Jn=function(e){eC(this,{type:io,done:!1,notified:!1,parent:!1,reactions:new X$,rejection:!1,state:Gv,value:null})},Jn.prototype=Wv(Xn,"then",function(e,t){var i=wl(this),r=Pl(G$(this,Mi));return i.parent=!0,r.ok=Zn(e)?e:!0,r.fail=Zn(t)&&t,r.domain=eo?Ml.domain:void 0,i.state===Gv?i.reactions.add(r):Al(function(){uS(r,i)}),r.promise}),Yv=function(){var a=new Jn,e=wl(a);this.promise=a,this.resolve=yr(kl,e),this.reject=yr(Tr,e)},eS.f=Pl=function(a){return a===Mi||a===nS?new Yv(a):tC(a)},!q$&&Zn(to)&&Sr!==Object.prototype)){Kv=Sr.then,Z$||Wv(Sr,"then",function(e,t){var i=this;return new Mi(function(r,s){Ir(Kv,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Sr.constructor}catch(a){}zv&&zv(Sr,Xn)}F$({global:!0,constructor:!0,wrap:!0,forced:tS},{Promise:Mi});nS=U$.Promise;H$(Mi,io,!1,!0);j$(io)});var bS=b((l1,mS)=>{"use strict";var oC=Ie(),hS=oC("iterator"),fS=!1;try{pS=0,Cl={next:function(){return{done:!!pS++}},return:function(){fS=!0}},Cl[hS]=function(){return this},Array.from(Cl,function(){throw 2})}catch(a){}var pS,Cl;mS.exports=function(a,e){try{if(!e&&!fS)return!1}catch(r){return!1}var t=!1;try{var i={};i[hS]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Dl=b((d1,gS)=>{"use strict";var uC=Ri(),cC=bS(),lC=gr().CONSTRUCTOR;gS.exports=lC||!cC(function(a){uC.all(a).then(void 0,function(){})})});var vS=b(()=>{"use strict";var dC=le(),pC=Ue(),hC=ft(),fC=vr(),mC=Kn(),bC=jn(),gC=Dl();dC({target:"Promise",stat:!0,forced:gC},{all:function(e){var t=this,i=fC.f(t),r=i.resolve,s=i.reject,n=mC(function(){var o=hC(t.resolve),u=[],c=0,d=1;bC(e,function(l){var p=c++,h=!1;d++,pC(o,t,l).then(function(f){h||(h=!0,u[p]=f,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var yS=b(()=>{"use strict";var vC=le(),SC=at(),yC=gr().CONSTRUCTOR,Bl=Ri(),TC=Pt(),IC=oe(),EC=fr(),SS=Bl&&Bl.prototype;vC({target:"Promise",proto:!0,forced:yC,real:!0},{catch:function(a){return this.then(void 0,a)}});!SC&&IC(Bl)&&(Ll=TC("Promise").prototype.catch,SS.catch!==Ll&&EC(SS,"catch",Ll,{unsafe:!0}));var Ll});var TS=b(()=>{"use strict";var wC=le(),xC=Ue(),PC=ft(),kC=vr(),AC=Kn(),RC=jn(),MC=Dl();wC({target:"Promise",stat:!0,forced:MC},{race:function(e){var t=this,i=kC.f(t),r=i.reject,s=AC(function(){var n=PC(t.resolve);RC(e,function(o){xC(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var IS=b(()=>{"use strict";var $C=le(),CC=vr(),DC=gr().CONSTRUCTOR;$C({target:"Promise",stat:!0,forced:DC},{reject:function(e){var t=CC.f(this),i=t.reject;return i(e),t.promise}})});var Vl=b((y1,ES)=>{"use strict";var LC=mt(),BC=De(),VC=vr();ES.exports=function(a,e){if(LC(a),BC(e)&&e.constructor===a)return e;var t=VC.f(a),i=t.resolve;return i(e),t.promise}});var PS=b(()=>{"use strict";var _C=le(),OC=Pt(),wS=at(),NC=Ri(),xS=gr().CONSTRUCTOR,FC=Vl(),qC=OC("Promise"),UC=wS&&!xS;_C({target:"Promise",stat:!0,forced:wS||xS},{resolve:function(e){return FC(UC&&this===qC?NC:this,e)}})});var kS=b(()=>{"use strict";dS();vS();yS();TS();IS();PS()});var $S=b(()=>{"use strict";var HC=le(),jC=at(),ro=Ri(),QC=fe(),RS=Pt(),MS=oe(),WC=sl(),AS=Vl(),zC=fr(),Ol=ro&&ro.prototype,GC=!!ro&&QC(function(){Ol.finally.call({then:function(){}},function(){})});HC({target:"Promise",proto:!0,real:!0,forced:GC},{finally:function(a){var e=WC(this,RS("Promise")),t=MS(a);return this.then(t?function(i){return AS(e,a()).then(function(){return i})}:a,t?function(i){return AS(e,a()).then(function(){throw i})}:a)}});!jC&&MS(ro)&&(_l=RS("Promise").prototype.finally,Ol.finally!==_l&&zC(Ol,"finally",_l,{unsafe:!0}));var _l});var DS=b((k1,CS)=>{"use strict";Fg();kS();$S();var YC=Wt();CS.exports=YC("Promise","finally")});var BS=b((A1,LS)=>{"use strict";var KC=DS();LS.exports=KC});var Nl=b((R1,VS)=>{"use strict";var XC=BS();VS.exports=XC});var ty=b(()=>{"use strict";var PD=le(),kD=ar(),AD=lr(),RD=pa(),MD=ha();PD({target:"Array",proto:!0},{at:function(e){var t=kD(this),i=AD(t),r=RD(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});MD("at")});var ry=b((MH,iy)=>{"use strict";ty();var $D=Wt();iy.exports=$D("Array","at")});var sy=b(($H,ay)=>{"use strict";var CD=ry();ay.exports=CD});var Ke=b((CH,ny)=>{"use strict";var DD=sy();ny.exports=DD});var vd=b((zQ,Zy)=>{"use strict";var _L=vi();Zy.exports=Array.isArray||function(e){return _L(e)==="Array"}});var tT=b((GQ,eT)=>{"use strict";var OL=TypeError,NL=9007199254740991;eT.exports=function(a){if(a>NL)throw OL("Maximum allowed index exceeded");return a}});var aT=b((YQ,rT)=>{"use strict";var FL=vd(),qL=lr(),UL=tT(),HL=nr(),iT=function(a,e,t,i,r,s,n,o){for(var u=r,c=0,d=n?HL(n,o):!1,l,p;c<i;)c in t&&(l=d?d(t[c],c,e):t[c],s>0&&FL(l)?(p=qL(l),u=iT(a,e,l,p,u,s-1)-1):(UL(u+1),a[u]=l),u++),c++;return u};rT.exports=iT});var uT=b((KQ,oT)=>{"use strict";var sT=vd(),jL=al(),QL=De(),WL=Ie(),zL=WL("species"),nT=Array;oT.exports=function(a){var e;return sT(a)&&(e=a.constructor,jL(e)&&(e===nT||sT(e.prototype))?e=void 0:QL(e)&&(e=e[zL],e===null&&(e=void 0))),e===void 0?nT:e}});var lT=b((XQ,cT)=>{"use strict";var GL=uT();cT.exports=function(a,e){return new(GL(a))(e===0?0:e)}});var dT=b(()=>{"use strict";var YL=le(),KL=aT(),XL=ft(),JL=ar(),ZL=lr(),e0=lT();YL({target:"Array",proto:!0},{flatMap:function(e){var t=JL(this),i=ZL(t),r;return XL(e),r=e0(t,0),r.length=KL(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var pT=b(()=>{"use strict";var t0=ha();t0("flatMap")});var fT=b((iW,hT)=>{"use strict";dT();pT();var i0=Wt();hT.exports=i0("Array","flatMap")});var bT=b((rW,mT)=>{"use strict";var r0=fT();mT.exports=r0});var za=b((aW,gT)=>{"use strict";var a0=bT();gT.exports=a0});var Ya=b((TW,TT)=>{"use strict";var n0=Sa(),o0=String;TT.exports=function(a){if(n0(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return o0(a)}});var yd=b((IW,IT)=>{"use strict";IT.exports=`
|
|
7
|
+
\v\f\r \u2028\u2029\uFEFF`});var xT=b((EW,wT)=>{"use strict";var u0=me(),c0=Qt(),l0=Ya(),Id=yd(),ET=u0("".replace),d0=RegExp("^["+Id+"]+"),p0=RegExp("(^|[^"+Id+"])["+Id+"]+$"),Td=function(a){return function(e){var t=l0(c0(e));return a&1&&(t=ET(t,d0,"")),a&2&&(t=ET(t,p0,"$1")),t}};wT.exports={start:Td(1),end:Td(2),trim:Td(3)}});var RT=b((wW,AT)=>{"use strict";var h0=Oc().PROPER,f0=fe(),PT=yd(),kT="
";AT.exports=function(a){return f0(function(){return!!PT[a]()||kT[a]()!==kT||h0&&PT[a].name!==a})}});var Ed=b((xW,MT)=>{"use strict";var m0=xT().start,b0=RT();MT.exports=b0("trimStart")?function(){return m0(this)}:"".trimStart});var CT=b(()=>{"use strict";var g0=le(),$T=Ed();g0({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==$T},{trimLeft:$T})});var LT=b(()=>{"use strict";CT();var v0=le(),DT=Ed();v0({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==DT},{trimStart:DT})});var VT=b((MW,BT)=>{"use strict";LT();var S0=Wt();BT.exports=S0("String","trimLeft")});var OT=b(($W,_T)=>{"use strict";var y0=VT();_T.exports=y0});var FT=b((CW,NT)=>{"use strict";var T0=OT();NT.exports=T0});var jT=b(()=>{"use strict"});var QT=b(()=>{"use strict"});var zT=b((mz,WT)=>{"use strict";var w0=De(),x0=vi(),P0=Ie(),k0=P0("match");WT.exports=function(a){var e;return w0(a)&&((e=a[k0])!==void 0?!!e:x0(a)==="RegExp")}});var KT=b((bz,YT)=>{"use strict";var A0=ne(),R0=fe(),GT=A0.RegExp,M0=!R0(function(){var a=!0;try{GT(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,c){Object.defineProperty(e,u,{get:function(){return t+=c,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(GT.prototype,"flags").get.call(e);return o!==i||t!==i});YT.exports={correct:M0}});var JT=b((gz,XT)=>{"use strict";var $0=mt();XT.exports=function(){var a=$0(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var tI=b((vz,eI)=>{"use strict";var C0=Ue(),D0=st(),L0=na(),ZT=KT(),B0=JT(),V0=RegExp.prototype;eI.exports=ZT.correct?function(a){return a.flags}:function(a){return!ZT.correct&&L0(V0,a)&&!D0(a,"flags")?C0(B0,a):a.flags}});var rI=b((Sz,iI)=>{"use strict";var kd=me(),_0=ar(),O0=Math.floor,xd=kd("".charAt),N0=kd("".replace),Pd=kd("".slice),F0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,q0=/\$([$&'`]|\d{1,2})/g;iI.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=q0;return r!==void 0&&(r=_0(r),u=F0),N0(s,u,function(c,d){var l;switch(xd(d,0)){case"$":return"$";case"&":return a;case"`":return Pd(e,0,t);case"'":return Pd(e,n);case"<":l=r[Pd(d,1,-1)];break;default:var p=+d;if(p===0)return c;if(p>o){var h=O0(p/10);return h===0?c:h<=o?i[h-1]===void 0?xd(d,1):i[h-1]+xd(d,1):c}l=i[p-1]}return l===void 0?"":l})}});var nI=b(()=>{"use strict";var U0=le(),H0=Ue(),Rd=me(),aI=Qt(),j0=oe(),Q0=De(),W0=zT(),Br=Ya(),z0=ua(),G0=tI(),Y0=rI(),K0=Ie(),X0=at(),J0=K0("replace"),Z0=TypeError,Ad=Rd("".indexOf),eB=Rd("".replace),sI=Rd("".slice),tB=Math.max;U0({target:"String",proto:!0},{replaceAll:function(e,t){var i=aI(this),r,s,n,o,u,c,d,l,p,h,f=0,m="";if(Q0(e)){if(r=W0(e),r&&(s=Br(aI(G0(e))),!~Ad(s,"g")))throw new Z0("`.replaceAll` does not allow non-global regexes");if(n=z0(e,J0),n)return H0(n,e,i,t);if(X0&&r)return eB(Br(i),e,t)}for(o=Br(i),u=Br(e),c=j0(t),c||(t=Br(t)),d=u.length,l=tB(1,d),p=Ad(o,u);p!==-1;)h=c?Br(t(u,p,o)):Y0(u,o,p,[],void 0,t),m+=sI(o,f,p)+h,f=p+d,p=p+l>o.length?-1:Ad(o,u,p+l);return f<o.length&&(m+=sI(o,f)),m}})});var uI=b((Iz,oI)=>{"use strict";jT();QT();nI();var iB=Wt();oI.exports=iB("String","replaceAll")});var lI=b((Ez,cI)=>{"use strict";var rB=uI();cI.exports=rB});var pI=b((wz,dI)=>{"use strict";var aB=lI();dI.exports=aB});var fI=b((xz,hI)=>{"use strict";var sB=pa(),nB=Ya(),oB=Qt(),uB=RangeError;hI.exports=function(e){var t=nB(oB(this)),i="",r=sB(e);if(r<0||r===1/0)throw new uB("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var SI=b((Pz,vI)=>{"use strict";var gI=me(),cB=pc(),mI=Ya(),lB=fI(),dB=Qt(),pB=gI(lB),hB=gI("".slice),fB=Math.ceil,bI=function(a){return function(e,t,i){var r=mI(dB(e)),s=cB(t),n=r.length,o=i===void 0?" ":mI(i),u,c;return s<=n||o===""?r:(u=s-n,c=pB(o,fB(u/o.length)),c.length>u&&(c=hB(c,0,u)),a?r+c:c+r)}};vI.exports={start:bI(!1),end:bI(!0)}});var TI=b((kz,yI)=>{"use strict";var mB=Ti();yI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(mB)});var II=b(()=>{"use strict";var bB=le(),gB=SI().start,vB=TI();bB({target:"String",proto:!0,forced:vB},{padStart:function(e){return gB(this,e,arguments.length>1?arguments[1]:void 0)}})});var wI=b((Mz,EI)=>{"use strict";II();var SB=Wt();EI.exports=SB("String","padStart")});var PI=b(($z,xI)=>{"use strict";var yB=wI();xI.exports=yB});var AI=b((Cz,kI)=>{"use strict";var TB=PI();kI.exports=TB});var gh="2.0.151-dev.0ce40db4.0";var Pe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Pe||{}),xt=(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_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(xt||{});var ta=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(ta||{}),Lu=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Lu||{});var Bu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Bu||{}),fn=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(fn||{});var $p=_(Ei(),1),Iw=_(Le(),1);import{assertNever as Nm,assertNonNullable as Mk,isNonNullable as In,ValueSubject as vc,Subject as $k,Subscription as Ck,merge as Dk,observableFrom as Lk,fromEvent as Bm,map as Vm,tap as _m,filterChanged as Bk,isNullable as Sc,ErrorCategory as Om}from"@vkontakte/videoplayer-shared/es2018";var Lm=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var En=class{constructor(e){this.connection$=new vc(void 0);this.castState$=new vc("NOT_AVAILABLE");this.errorEvent$=new $k;this.realCastState$=new vc("NOT_AVAILABLE");this.subscription=new Ck;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=In((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Lm("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Om.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){In(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Sc(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Sc(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(Bm(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Nm(r.sessionState)}})).add(Dk(Bm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(_m(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Vm(r=>r.castState)),Lk([i.getCastState()])).pipe(Bk(),Vm(Vk),_m(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=In(this.connection$.getValue());if(s&&!n){let c=i.getCurrentSession();Mk(c);let d=c.getCastDevice(),l=(u=(o=c.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Sc(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?In(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Om.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Vk=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Nm(a)}};import{assertNonNullable as xc,combine as Pc,debounce as kc,ErrorCategory as tA,filter as pr,filterChanged as eb,isNonNullable as Ac,isNullable as tb,map as iA,Subscription as rA,ValueSubject as Rc}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as _k,assertNonNullable as wi,ErrorCategory as Ok,getHighestQuality as Nk,isNonNullable as qm}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as Fm}from"@vkontakte/videoplayer-shared/es2018";var Ee=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Fm(t)}return a},wn=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:Fm(e)}};var Pn=a=>{var l;let{source:e,format:t,meta:i,output:r}=a,s,n,o;switch(t){case"MPEG":{let p=e[t];wi(p);let h=Nk(Object.keys(p));wi(h);let f=p[h];wi(f),s=f,n="video/mp4",o=xn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let p=e[t];wi(p),s=p.url,n="application/x-mpegurl",o=xn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let p=e[t];wi(p),s=p.url,n="application/dash+xml",o=xn();break}case"DASH_LIVE_CMAF":{let p=e[t];wi(p),s=p.url,n="application/dash+xml",o=Um();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let p=e[t];wi(p),s=Ee(p.url),n="application/x-mpegurl",o=Um();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let p="Unsupported format for Chromecast",h=new Error(p);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Ok.VIDEO_PIPELINE,message:p,thrown:h}),h}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return _k(t)}let u=Fk((l=i.videoId)!=null?l:s,n);u.contentUrl=s,u.streamType=o,u.metadata=qk();let{title:c,subtitle:d}=i;return qm(c)&&(u.metadata.title=c),qm(d)&&(u.metadata.subtitle=d),u};function xn(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.BUFFERED)!=null?i:"BUFFERED"}function Um(){var a,e,t,i;return(i=(t=(e=(a=chrome.cast)==null?void 0:a.media)==null?void 0:e.StreamType)==null?void 0:t.LIVE)!=null?i:"LIVE"}function Fk(a,e){var t,i;return(i=(t=chrome.cast)==null?void 0:t.media)!=null&&i.MediaInfo?new chrome.cast.media.MediaInfo(a,e):{contentId:a,contentType:e,metadata:{title:"",subtitle:""},streamType:xn()}}function qk(){var a,e;return(e=(a=chrome.cast)==null?void 0:a.media)!=null&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var k=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var kn=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};import{assertNever as Zm}from"@vkontakte/videoplayer-shared/es2018";import{isBrowserWindow as Jk,ValueSubject as Zk}from"@vkontakte/videoplayer-shared/es2018";var Hm=_(Le(),1);import{getWindow as Uk}from"@vkontakte/videoplayer-shared/es2018";var An=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Hm.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/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,c=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||c||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=Uk().navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var jm=_(Le(),1);import{getWindow as yc,isBrowserWindow as Tc}from"@vkontakte/videoplayer-shared/es2018";var xi=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Rn=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||(0,jm.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||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.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=yc();if(!Tc(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=xi()}catch(i){console.error("DeviceChecker: calling isMobile error - ",i)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let e=yc();if(!Tc(e))return;let{userAgentData:t}=e.navigator;if(t!=null&&t.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}}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,s=/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||s||o||n||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r.length>0,o=r.length>1,u="Unknown",c="Unknown";if(n){let d=r[0];typeof d=="number"?d<s.length&&s[d]!==void 0&&(u=s[d]):u=d}if(o){let d=r[1];typeof d=="number"?d<s.length&&s[d]!==void 0&&(c=s[d]):d!==void 0&&(c=d)}else s[2]!==void 0?c=s[2]:s[1]!==void 0&&n&&typeof r[0]=="string"&&(c=s[1]);u=this.normalizeOSName(u),c=this.normalizeOSVersion(c,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:c||"Unknown",full:c&&c!=="Unknown"?`${u} ${c}`:u};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let s=e.match(i);if(s){let n=r[0],o=r[1],u=typeof n=="number"?s[n]!==void 0?this.normalizeVendorName(s[n]):"Unknown":this.normalizeVendorName(n),c="Unknown";typeof o=="number"?c=s[o]!==void 0?s[o]:"Unknown":o!==void 0?c=o:s[1]!==void 0?c=s[1]:s[0]!==void 0&&(c=s[0]),c=this.normalizeModelName(c,u),this.details.vendor=u,this.details.model=c;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{let e=yc();if(!Tc(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t!=null&&t[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};import{getWindow as Qm,isBrowserWindow as Hk}from"@vkontakte/videoplayer-shared/es2018";var Mn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in Qm()}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 s;let e=Qm();if(!Hk(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r!=null?r:0,this._isHdr=!!((s=e.matchMedia("(dynamic-range: high)"))!=null&&s.matches),this._colorDepth=i.colorDepth}catch(n){console.error(n)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(n){console.error(n)}}};import{getWindow as Ic,isBrowserWindow as Gm}from"@vkontakte/videoplayer-shared/es2018";var He=()=>window.ManagedMediaSource||window.MediaSource,dr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Wm=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},$n=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var zm,jk=(zm=Ic().document)==null?void 0:zm.createElement("video"),Qk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Wk='video/mp4; codecs="hev1.1.6.L93.B0"',Ym='video/webm; codecs="vp09.00.10.08"',Km='video/webm; codecs="av01.0.00M.08"',zk='audio/mp4; codecs="mp4a.40.2"',Gk='audio/webm; codecs="opus"',Xm,Yk=async()=>{let a=Ic();if(!Gm(a))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Km}}),a.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Ym}})]);Xm={DASH_WEBM_AV1:t,DASH_WEBM:i}};Yk().catch(a=>{console.log(jk),console.error(a)});var Cn=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 Xm}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var i,r,s,n,o,u,c,d,l,p,h,f,m,v,g,S,T,y,x,R;let e=Ic();if(!Gm(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:dr(),mse:Wm(),hls:!!((r=(i=this._video).canPlayType)!=null&&r.call(i,"application/x-mpegurl")||(n=(s=this._video).canPlayType)!=null&&n.call(s,"vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/mp4")),webm:!!((d=(c=this._video).canPlayType)!=null&&d.call(c,"video/webm")),cmaf:!0};let D=!!((p=(l=He())==null?void 0:l.isTypeSupported)!=null&&p.call(l,Qk)),M=!!((f=(h=He())==null?void 0:h.isTypeSupported)!=null&&f.call(h,Wk)),L=!!((v=(m=He())==null?void 0:m.isTypeSupported)!=null&&v.call(m,zk));this._codecs={h264:D,h265:M,vp9:!!((S=(g=He())==null?void 0:g.isTypeSupported)!=null&&S.call(g,Ym)),av1:!!((y=(T=He())==null?void 0:T.isTypeSupported)!=null&&y.call(T,Km)),aac:L,opus:!!((R=(x=He())==null?void 0:x.isTypeSupported)!=null&&R.call(x,Gk)),mpeg:(D||M)&&L},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(D){console.error(D)}try{this.destroyVideoElement()}catch(D){console.error("Error destroying video element:",D)}}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}};import{getWindow as Kk,isBrowserWindow as Xk}from"@vkontakte/videoplayer-shared/es2018";var Jm="audio/mpeg",Dn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var i,r,s,n;let e=Kk();if(!Xk(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!((r=(i=this._audio).canPlayType)!=null&&r.call(i,Jm))},this._codecs={mp3:!!((n=(s=He())==null?void 0:s.isTypeSupported)!=null&&n.call(s,Jm))}}catch(o){console.error(o)}try{this.destroyAudioElement()}catch(o){console.error("Error destroying audio element:",o)}}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}};var Ec=class{constructor(){this.isInited$=new Zk(!1);this._displayChecker=new Mn,this._deviceChecker=new Rn(this._displayChecker),this._browserChecker=new An,this._videoChecker=new Cn(this._deviceChecker,this._browserChecker),this._audioChecker=new Dn,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}async detect(){Jk()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},V=new Ec;var wc=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=V.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Zm(o)}})},fa=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":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 Zm(a)}},eA=a=>{let t=Object.keys(a).filter(i=>!fa(i));return wc(t).length>0};var ma=class{constructor(e){this.subscription=new rA;this.sessionId$=new Rc(null);this.mediaSessionId$=new Rc(null);this.contentId$=new Rc(null);this.isMobile=xi();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{var s,n,o;if(tb(e))return;this.media=e,this.mediaSessionId$.next((s=e.mediaSessionId)!=null?s:null);let t=(n=e.media)==null?void 0:n.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=(o=e.media)==null?void 0:o.duration;Ac(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(Ac(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let c=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!c?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new kn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(fa(e.format)),this.subscribe()}subscribe(){let e=r=>{var s;this.params.output.error$.next({category:tA.WTF,id:"ChromecastPresentationApiProvider",message:(s=r==null?void 0:r.message)!=null?s:"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(pr(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(pr(Ac),eb(),kc(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(eb(),iA(Boolean));this.subscription.add(Pc({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(pr(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=Pc({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(pr(({mediaLoaded:r})=>r),kc(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(pr(({mediaLoaded:r,playbackState:{from:s,to:n}})=>!r&&s==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(Pc({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(kc(30)),mediaLoaded:t}).pipe(pr(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:s,volume:n}=r.to;this.setVolume(n,s)},e))}handleMessage(e){var t,i,r,s,n,o;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let u=(i=(t=e.message)==null?void 0:t.media)==null?void 0:i[0];this.syncMediaState(u);let c=(r=e.message)==null?void 0:r.receiver.volume;this.syncVolumeState(c)}break;case"v2_message":{switch((s=e.message)==null?void 0:s.type){case"MEDIA_STATUS":{let u=(o=(n=e.message)==null?void 0:n.status)==null?void 0:o[0];this.syncMediaState(u);break}}break}}}loadMedia(){var o;let e=Pn(this.params),t=(o=this.media)==null?void 0:o.currentTime,i=this.params.desiredState.seekState.getState(),r=t!=null?t:i.state!=="none"?i.position/1e3:0,n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();xc(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();xc(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();xc(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":k(this.params.desiredState.playbackState,"paused");break;case"PLAYING":k(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),k(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):k(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if(tb(e))return;let{level:t,muted:i}=e,r={muted:i!=null?i:!1,volume:t!=null?t:0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let s=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,s+=`, volume passed to state machine: ${r.volume}`),this.log({message:s}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};import{assertNonNullable as aA,ErrorCategory as Mc,filter as sA,Subject as nA,Subscription as $c,tap as oA,ValueSubject as hr,fromEvent as ba}from"@vkontakte/videoplayer-shared/es2018";var ib=a=>({castDevice:{friendlyName:a},remotePlayer:{},remotePlayerController:{},session:{}}),rb=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var ga=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new hr(null);this.sessionId$=new hr(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new $c;this.subscriptionEvents=new $c;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new hr(!1);this.presentationConnection$=new hr(null);this.message$=new hr(null);this.friendlyName$=new hr(null);this.errorEvent$=new nA;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let s=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(ba(r,"change").subscribe(()=>{s()})),s()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){var e;this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let t=this.presentationRequest$.getValue();aA(t,"connect with null presentationRequest");let i=await t.start();this.handleConnection(i)}catch(t){switch(t==null?void 0:t.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:Mc.WTF,id:"ChromecastPresentationApiConnector",message:(e=t==null?void 0:t.message)!=null?e:"connect error",thrown:t});break}}}subscribe(){this.subscription.add(ba(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe(oA(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),sA(e=>!!e)).subscribe(e=>{let t=ba(e,"message").subscribe(s=>{let n=JSON.parse(s.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${s.data}`}),this.handleMessage(n),this.message$.next(n))}),i=ba(e,"connect").subscribe(()=>{this.send("client_connect")}),r=ba(e,"close").subscribe(s=>{switch(s.reason){case"error":this.errorEvent$.next({category:Mc.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:s});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();(t==null?void 0:t.state)==="connected"&&(t==null||t.send(e))}catch(t){this.errorEvent$.next({category:Mc.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){var t;switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":((t=e.message)==null?void 0:t.action)==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||rb()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new $c}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};import{ValueSubject as ab,Subject as uA,map as cA,Subscription as lA,combine as dA,filterChanged as sb,assertNonNullable as pA}from"@vkontakte/videoplayer-shared/es2018";var kt=class a{constructor(e){this.subscription=new lA;this.connection$=new ab(void 0);this.castState$=new ab("NOT_AVAILABLE");this.errorEvent$=new uA;let t=a.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new ga({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){pA(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=dA({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(sb())});this.subscription.add(e.pipe(cA(({connection:t,friendlyName:i})=>!!(t&&i)),sb()).subscribe(t=>{var r,s;let i=(s=(r=this.chromecastConnector)==null?void 0:r.friendlyName$.getValue())!=null?s:"";this.connection$.next(t?ib(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){var e;this.log({message:"connect"}),(e=this.chromecastConnector)==null||e.connect()}disconnect(){var e;this.log({message:"disconnect"}),(e=this.chromecastConnector)==null||e.disconnect()}async stopMedia(){var e;this.log({message:"stopMedia"}),(e=this.chromecastConnector)==null||e.stopMedia()}toggleConnection(){var t;let e=!!((t=this.chromecastConnector)!=null&&t.presentationConnection$.getValue());this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){var e;this.log({message:"destroy"}),(e=this.chromecastConnector)==null||e.destroy(),this.subscription.unsubscribe()}};var Sp=_(Le(),1),yp=_(zt(),1),iw=_(Zc(),1);var US=_(Nl(),1);import{isNonNullable as JC,Subject as ao,merge as _S}from"@vkontakte/videoplayer-shared/es2018";var H=class{constructor(e){this.transitionStarted$=new ao;this.transitionEnded$=new ao;this.transitionUpdated$=new ao;this.forceChanged$=new ao;this.stateChangeStarted$=_S(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=_S(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||JC(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 Ma,debounce as OS,ErrorCategory as ZC,fromEvent as $i,map as NS,merge as FS,observableFrom as eD,Subject as tD,Subscription as Fl,timeout as iD}from"@vkontakte/videoplayer-shared/es2018";var rD=5,aD=5,sD=500,qS=7e3,$a=class{constructor(e){this.subscription=new Fl;this.loadMediaTimeoutSubscription=new Fl;this.videoState=new H("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Ma(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:Ma(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:Ma(e)}break}default:Ma(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(fa(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 Fl;this.subscription.add(e),this.subscription.add(FS(this.videoState.stateChangeStarted$.pipe(NS(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(NS(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new tD;e.add(r.pipe(OS(sD)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>rD)&&r.next(o),s=o})),e.add($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<aD&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Ma(n)}}),t($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t($i(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=FS(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,eD(["init"])).pipe(OS(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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(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=Pn(this.params),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"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(iD(qS).subscribe(()=>s(`timeout(${qS})`)))});(0,US.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:ZC.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var sd=_(Le(),1);import{clearVideoElement as jS,getWindow as oD}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as nD}from"@vkontakte/videoplayer-shared/es2018";var HS=a=>{try{a.pause(),a.playbackRate=0,nD(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as uD,Subscription as cD}from"@vkontakte/videoplayer-shared/es2018";var ql=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)}},so=oD(),Ul=so.WeakMap?new so.WeakMap:new ql,Hl=so.WeakMap?new so.WeakMap:new Map,lD=(a,e=20)=>{let t=0;return uD(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Be=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?jS(i):(i=document.createElement("video"),a.appendChild(i)),Ul.set(i,r);let s=new cD;return s.add(lD(i,e)),Hl.set(i,s),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},Ve=a=>{let e=Hl.get(a);e==null||e.unsubscribe(),Hl.delete(a);let t=Ul.get(a);Ul.delete(a),t?jS(a):HS(a)};var Ql=_(Ei(),1);import{assertNonNullable as Da,isNonNullable as vt,isNullable as hD,fromEvent as Er,merge as QS,observableFrom as WS,filterChanged as zS,map as La,Subject as GS,Subscription as fD,ValueSubject as mD,ErrorCategory as bD}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as jl,isNullable as dD,Subscription as pD}from"@vkontakte/videoplayer-shared/es2018";var no=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=dD(r),c=new pD;return r&&c.add(r.subscribe(d=>{let l=a.getState();i(d,l)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),c.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),c},gt=(a,e,t)=>no(e,()=>a.loop,i=>{jl(i)&&(a.loop=i)},{onError:t}),_e=(a,e,t,i)=>no(e,()=>({muted:a.muted,volume:a.volume}),r=>{jl(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ge=(a,e,t,i)=>no(e,()=>a.playbackRate,r=>{jl(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Ca=no;var gD=a=>["__",a.language,a.label].join("|"),vD=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Wl=class a{constructor(e){this.available$=new GS;this.current$=new mD(void 0);this.error$=new GS;this.subscription=new fD;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=s=>{this.error$.next({id:"TextTracksManager",category:bD.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ca(t.internalTextTracks,()=>(0,Ql.default)(this.internalTracks),s=>{vt(s)&&this.setInternal(s)},{equal:(s,n)=>vt(s)&&vt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(La(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ca(t.externalTextTracks,()=>(0,Ql.default)(this.externalTracks),s=>{vt(s)&&this.setExternal(s)},{equal:(s,n)=>vt(s)&&vt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(La(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ca(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Ca(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Da(this.video);let{textTracks:e}=this.video;this.subscription.add(Er(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(QS(Er(e,"addtrack"),Er(e,"removetrack"),WS(["init"])).pipe(La(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),zS((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(QS(Er(e,"change"),WS(["init"])).pipe(La(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),La(i=>i&&this.htmlTextTrackToITextTrack(i).id),zS()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(Er(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var c,d,l,p,h;let u=(d=(c=o.target)==null?void 0:c.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(l=o.target)==null?void 0:l.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Er(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;vt(t.align)&&(r.align=t.align),vt(t.position)&&(r.position=t.position),vt(t.size)&&(r.size=t.size),vt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Da(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,c,d,l;let{language:t,label:i}=e,r=e.id?e.id:gD(e),s=this.externalTracks.has(r),n=(c=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?c:r.includes("auto");return s?{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:(l=this.internalTracks.get(r))==null?void 0:l.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Da(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(hD(e)||!vD(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)}},Ye=Wl;var Ci=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 YS=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},zl=a=>{let e=YS(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},KS=a=>{let e=YS(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as ke,map as St,merge as oo,filterChanged as JS,isNonNullable as ZS,Subject as yD,filter as Gl,mapTo as Yl,combine as TD,once as ID,shareReplay as Ae,throttle as ED,ErrorCategory as wD,ValueSubject as ey,Subscription as xD}from"@vkontakte/videoplayer-shared/es2018";var SD=3,XS=(a,e,t=SD)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Oe=a=>{let e=A=>ke(a,A).pipe(Yl(void 0),Ae(1)),t=new xD,i=()=>t.unsubscribe(),r=oo(ke(a,"progress"),ke(a,"timeupdate")).pipe(St(()=>XS(a.buffered,a.currentTime)),Ae(1)),s=V.browser.isSafari?TD({play:e("play").pipe(ID()),playing:e("playing")}).pipe(Yl(void 0),Ae(1)):e("playing"),n=ke(a,"volumechange").pipe(St(()=>({muted:a.muted,volume:a.volume})),Ae(1)),o=ke(a,"ratechange").pipe(St(()=>a.playbackRate),Ae(1)),u=ke(a,"error").pipe(Gl(()=>!!(a.error||a.played.length)),St(()=>{var B;let A=a.error;return{id:A?`MediaError#${A.code}`:"HtmlVideoError",category:wD.VIDEO_PIPELINE,message:A?A.message:"Error event from HTML video element",thrown:(B=a.error)!=null?B:void 0}}),Ae(1)),c=ke(a,"timeupdate").pipe(St(()=>a.currentTime),Ae(1)),d=["waiting","seeking","seeked","timeupdate"],l=new yD,p=.3,h;t.add(oo(...d.map(A=>ke(a,A))).subscribe(A=>{let B=a.currentTime;a.loop&&ZS(h)&&ZS(B)&&h>=a.duration-p&&B<=p&&l.next(h),h=B}));let f=e("pause").pipe(Gl(()=>!a.error&&h!==a.duration),Ae(1)),m=ke(a,"enterpictureinpicture").pipe(Ae(1)),v=ke(a,"leavepictureinpicture").pipe(Ae(1)),g=new ey(KS(a));t.add(m.subscribe(()=>g.next(!0))),t.add(v.subscribe(()=>g.next(!1)));let S=new ey(zl(a)),T=ke(a,"fullscreenchange").pipe(Ae(1));t.add(T.pipe(St(()=>zl(a))).subscribe(S));let y=.1,x=1e3,R=ke(a,"timeupdate").pipe(St(A=>a.duration-a.currentTime<y),JS(),Ae(1)),D=oo(R.pipe(Gl(A=>!a.loop&&A)),ke(a,"ended")).pipe(ED(x),Yl(void 0),Ae(1)),L=oo(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>ke(a,A)),R.pipe(St(A=>({type:A?"ended":"unknown"})))).pipe(St(A=>V.browser.isFirefox&&A.type==="ended"?a.readyState<2:a.readyState<3),JS(),Ae(1));return{playing$:s,pause$:f,canplay$:e("canplay"),ended$:D,looped$:l,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:ke(a,"durationchange").pipe(St(()=>a.duration),Ae(1)),isBuffering$:L,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S,enterPip$:m,leavePip$:v,destroy:i}};import{VideoQuality as Yt}from"@vkontakte/videoplayer-shared/es2018";var Kt=a=>{switch(a){case"mobile":return Yt.Q_144P;case"lowest":return Yt.Q_240P;case"low":return Yt.Q_360P;case"sd":case"medium":return Yt.Q_480P;case"hd":case"high":return Yt.Q_720P;case"fullhd":case"full":return Yt.Q_1080P;case"quadhd":case"quad":return Yt.Q_1440P;case"ultrahd":case"ultra":return Yt.Q_2160P}};var Me=_(Ke(),1),Xl=_(Le(),1),Li=_(zt(),1);import{isNonNullable as X,isNullable as po,now as gy,isHigher as ho,isHigherOrEqual as Di,isInvariantQuality as fo,isLowerOrEqual as xr,videoSizeToQuality as vy,assertNotEmptyArray as mo,assertNonNullable as Sy}from"@vkontakte/videoplayer-shared/es2018";var Kl=!1,Rt={},oy=a=>{Kl=a},uy=()=>{Rt={}},cy=a=>{a(Rt)},Ba=(a,e)=>{var t;Kl&&(Rt.meta=(t=Rt.meta)!=null?t:{},Rt.meta[a]=e)},Re=class{constructor(e){this.name=e}next(e){var i,r;if(!Kl)return;Rt.series=(i=Rt.series)!=null?i:{};let t=(r=Rt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Rt.series[this.name]=t}};import{isHigher as LD,isHigherOrEqual as OH,isLower as ly,isLowerOrEqual as NH,isNonNullable as uo,isNullable as BD,videoHeightToQuality as co}from"@vkontakte/videoplayer-shared/es2018";function dy(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function wr(a,e,t){return BD(a)||uo(a.min)&&uo(a.max)&&ly(a.max,a.min)||uo(a.min)&&e&&LD(a.min,e)||uo(a.max)&&t&&ly(a.max,t)}function py({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return wr({max:a!=null&&a.max?co(a.max):void 0,min:a!=null&&a.min?co(a.min):void 0},e?co(e):void 0,t?co(t):void 0)}var yy=new Re("best_bitrate"),bo=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Pr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Xt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=gy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},go='Assertion "ABR Tracks is empty array" failed',lo=new WeakMap,hy=new WeakMap,fy=new WeakMap,Va=(a,e,t,i)=>{var u;let r=[...e].sort(Pr(1)),s=[...t].sort(Pr(1)),n=s.filter(c=>X(c.bitrate)&&X(a.bitrate)?a.bitrate/c.bitrate>i:!0),o=(u=(0,Me.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Me.default)(s,-1);return o&&(0,Xl.default)(n,o)?o:n.length?(0,Me.default)(n,-1):(0,Me.default)(s,0)},_a=(a,e,t,i)=>{var u;let r=lo.get(e);r||(r=[...e].sort(Pr(1)),lo.set(e,r));let s=lo.get(t);s||(s=[...t].sort(Pr(1)),lo.set(t,s));let n=fy.get(a);n||(n=s.filter(c=>X(c.bitrate)&&X(a.bitrate)?a.bitrate/c.bitrate>i:!0),fy.set(a,n));let o=(u=(0,Me.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Me.default)(s,-1);return o&&(0,Xl.default)(n,o)?o:n.length?(0,Me.default)(n,-1):(0,Me.default)(s,0)},my=a=>"quality"in a,vo=(a,e,t,i)=>{var n;let r=X((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&X(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&gy()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=my(o)?"video":"audio",c=my(o)?o.quality:o.bitrate;return e({message:`
|
|
8
|
+
[last ${u} selected] ${c}
|
|
9
|
+
`}),o}return i==null||i.recordSwitch(t),t},VD=(a,e)=>Math.log(e)/Math.log(a),Ty=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&V.display.pixelRatio){let s=V.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,c=0]=a.pixelRatioLogCoefficients,d=VD(n,o*s+u)+c;Number.isFinite(d)&&(r*=d)}}return X(t==null?void 0:t.min)&&Di(t.min,a.highQualityLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},by=new WeakMap,yt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f,panelSize:m})=>{var U,G,j,E,P;mo(a,go);let{containerSizeFactor:v,containerSizeLimit:g}=Ty({container:e,tuning:i,limits:r,panelSize:m}),S=i.considerPlaybackRate&&X(o)?o:1,T=by.get(a);T||(T=a.filter(I=>!fo(I.quality)).sort((I,w)=>ho(I.quality,w.quality)?-1:1),by.set(a,T));let y=(U=(0,Me.default)(T,-1))==null?void 0:U.quality,x=(G=(0,Me.default)(T,0))==null?void 0:G.quality,R=wr(r,x,y),D=S*bo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),M={},L=null;for(let I of T){let w=!0;if(g)if(I.size)w=I.size.width<=g.width&&I.size.height<=g.height;else{let Fe=g&&vy(g);w=Fe?xr(I.quality,Fe):!0}if(!w){M[I.quality]="FitsContainer";continue}let N=h||t,O=X(N)&&isFinite(N)&&X(I.bitrate)?N-s>=I.bitrate*D:!0,lt=(r==null?void 0:r.min)===I.quality;if(!O&&!lt){M[I.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!fo(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&ho(I.quality,u.quality)){M[I.quality]="Buffer";continue}if(!!l&&Di(I.quality,l)&&!lt){M[I.quality]="DroppedFramesLimit";continue}if(!!p&&Di(I.quality,p)&&!lt){M[I.quality]="StallsLimit";continue}let ye=R||(po(r==null?void 0:r.max)||xr(I.quality,r.max))&&(po(r==null?void 0:r.min)||Di(I.quality,r.min)),Te=X(d)&&!d?xr(I.quality,i.backgroundVideoQualityLimit):!0;if(!ye||!Te){M[I.quality]="FitsQualityLimits";continue}L||(L=I)}L&&L.bitrate&&yy.next(L.bitrate);let A=(j=L!=null?L:(0,Me.default)(T,-1))!=null?j:a[0],B=c==null?void 0:c.last,$=vo(i,f,A,c);return X(c)&&$.quality!==(B==null?void 0:B.quality)&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${a.map(I=>{var
|
|
12
|
+
${a.map(I=>{var w,N;return`{ id: ${I.id}, quality: ${I.quality}, bitrate: ${I.bitrate}, size: ${(w=I.size)==null?void 0:w.width}:${(N=I.size)==null?void 0:N.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,Li.default)(i!=null?i:{}).map(([I,w])=>`${I}: ${w}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
@@ -25,28 +25,28 @@ var Pw=Object.create;var ph=Object.defineProperty;var Aw=Object.getOwnPropertyDe
|
|
|
25
25
|
playbackRate: ${o},
|
|
26
26
|
playbackRateFactor: ${S},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${D},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
|
-
droppedVideoMaxQualityLimit: ${
|
|
30
|
+
droppedVideoMaxQualityLimit: ${l},
|
|
31
31
|
stallsVideoMaxQualityLimit: ${p},
|
|
32
32
|
limitsAreInvalid: ${R},
|
|
33
33
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
34
34
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,Li.default)(M).map(([I,w])=>`${I}: ${w}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`})
|
|
40
|
+
[best video track] ${L==null?void 0:L.quality}
|
|
41
|
+
[selected video track] ${$==null?void 0:$.quality}
|
|
42
|
+
`}),$},So=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:c,visible:d,droppedVideoMaxQualityLimit:l,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f,panelSize:m})=>{var G,j,E,P,I;mo(a,go);let{containerSizeFactor:v,containerSizeLimit:g}=Ty({container:e,tuning:i,limits:r,panelSize:m}),S=i.considerPlaybackRate&&X(o)?o:1,T=a.filter(w=>!fo(w.quality)).sort((w,N)=>ho(w.quality,N.quality)?-1:1),y=(G=(0,Me.default)(T,-1))==null?void 0:G.quality,x=(j=(0,Me.default)(T,0))==null?void 0:j.quality,R=wr(r,x,y),D=S*bo(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),M={},A=T.filter(w=>{let N=!0;if(g)if(w.size)N=w.size.width<=g.width&&w.size.height<=g.height;else{let It=g&&vy(g);N=It?xr(w.quality,It):!0}if(!N)return M[w.quality]="FitsContainer",!1;let O=h||t,lt=X(O)&&isFinite(O)&&X(w.bitrate)?O-s>=w.bitrate*D:!0,dt=(r==null?void 0:r.min)===w.quality;if(!lt&&!dt)return M[w.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!fo(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&ho(w.quality,u.quality))return M[w.quality]="Buffer",!1;if(!!l&&Di(w.quality,l)&&!dt)return M[w.quality]="DroppedFramesLimit",!1;if(!!p&&Di(w.quality,p)&&!dt)return M[w.quality]="StallsLimit",!1;let Te=R||(po(r==null?void 0:r.max)||xr(w.quality,r.max))&&(po(r==null?void 0:r.min)||Di(w.quality,r.min)),Fe=X(d)&&!d?xr(w.quality,i.backgroundVideoQualityLimit):!0;return!Te||!Fe?(M[w.quality]="FitsQualityLimits",!1):!0})[0];A&&A.bitrate&&yy.next(A.bitrate);let B=(E=A!=null?A:(0,Me.default)(T,-1))!=null?E:a[0],$=c==null?void 0:c.last,U=vo(i,f,B,c);return X(c)&&U.quality!==($==null?void 0:$.quality)&&f({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
|
-
${a.map(
|
|
45
|
+
${a.map(w=>{var N,O;return`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate}, size: ${(N=w.size)==null?void 0:N.width}:${(O=w.size)==null?void 0:O.height} }`}).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,Li.default)(i!=null?i:{}).map(([w,N])=>`${w}: ${N}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
@@ -58,33 +58,33 @@ var Pw=Object.create;var ph=Object.defineProperty;var Aw=Object.getOwnPropertyDe
|
|
|
58
58
|
playbackRate: ${o},
|
|
59
59
|
playbackRateFactor: ${S},
|
|
60
60
|
forwardBufferHealth: ${n},
|
|
61
|
-
bitrateFactor: ${
|
|
61
|
+
bitrateFactor: ${D},
|
|
62
62
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
|
-
droppedVideoMaxQualityLimit: ${
|
|
63
|
+
droppedVideoMaxQualityLimit: ${l},
|
|
64
64
|
stallsVideoMaxQualityLimit: ${p},
|
|
65
65
|
limitsAreInvalid: ${R},
|
|
66
66
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
67
67
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
68
68
|
|
|
69
69
|
[limited video tracks]
|
|
70
|
-
${(0,
|
|
70
|
+
${(0,Li.default)(M).map(([w,N])=>`${w}: ${N}`).join(`
|
|
71
71
|
`)||"All tracks are available"}
|
|
72
72
|
|
|
73
|
-
[best video track] ${
|
|
74
|
-
[selected video track] ${
|
|
75
|
-
`}),
|
|
73
|
+
[best video track] ${A==null?void 0:A.quality}
|
|
74
|
+
[selected video track] ${U==null?void 0:U.quality}
|
|
75
|
+
`}),U},yo=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:c})=>{mo(t,go);let d=r.considerPlaybackRate&&X(s)?s:1,l=[...t].sort(Pr(-1)),p=a.bitrate;Sy(p);let h=d*bo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Va(a,e,t,r.minVideoAudioRatio),v=c||i;X(v)&&isFinite(v)&&(f=l.find(T=>X(T.bitrate)&&X(m==null?void 0:m.bitrate)?v-p>=T.bitrate*h&&T.bitrate>=m.bitrate:!1)),f||(f=m);let g=o==null?void 0:o.last,S=f&&vo(r,u,f,o);return X(o)&&(S==null?void 0:S.bitrate)!==(g==null?void 0:g.bitrate)&&u({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
78
|
${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
|
|
79
79
|
`)}
|
|
80
80
|
|
|
81
81
|
[tuning]
|
|
82
|
-
${(0,
|
|
82
|
+
${(0,Li.default)(r!=null?r:{}).map(([T,y])=>`${T}: ${y}`).join(`
|
|
83
83
|
`)}
|
|
84
84
|
|
|
85
85
|
[limit params]
|
|
86
86
|
estimatedThroughput: ${i},
|
|
87
|
-
stallsPredictedThroughput: ${
|
|
87
|
+
stallsPredictedThroughput: ${c},
|
|
88
88
|
reserve: ${p},
|
|
89
89
|
playbackRate: ${s},
|
|
90
90
|
playbackRateFactor: ${d},
|
|
@@ -93,19 +93,19 @@ var Pw=Object.create;var ph=Object.defineProperty;var Aw=Object.getOwnPropertyDe
|
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
95
|
[selected audio track] ${S==null?void 0:S.id}
|
|
96
|
-
`}),S},
|
|
96
|
+
`}),S},To=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:c})=>{mo(t,go);let d=r.considerPlaybackRate&&X(s)?s:1,l=hy.get(t);l||(l=[...t].sort(Pr(-1)),hy.set(t,l));let p=a.bitrate;Sy(p);let h=d*bo(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=_a(a,e,t,r.minVideoAudioRatio),v=c||i;X(v)&&isFinite(v)&&(f=l.find(T=>X(T.bitrate)&&X(m==null?void 0:m.bitrate)?v-p>=T.bitrate*h&&T.bitrate>=m.bitrate:!1)),f||(f=m);let g=o==null?void 0:o.last,S=f&&vo(r,u,f,o);return X(o)&&(S==null?void 0:S.bitrate)!==(g==null?void 0:g.bitrate)&&u({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
99
|
${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
|
|
100
100
|
`)}
|
|
101
101
|
|
|
102
102
|
[tuning]
|
|
103
|
-
${(0,
|
|
103
|
+
${(0,Li.default)(r!=null?r:{}).map(([T,y])=>`${T}: ${y}`).join(`
|
|
104
104
|
`)}
|
|
105
105
|
|
|
106
106
|
[limit params]
|
|
107
107
|
estimatedThroughput: ${i},
|
|
108
|
-
stallsPredictedThroughput: ${
|
|
108
|
+
stallsPredictedThroughput: ${c},
|
|
109
109
|
reserve: ${p},
|
|
110
110
|
playbackRate: ${s},
|
|
111
111
|
playbackRateFactor: ${d},
|
|
@@ -114,7 +114,7 @@ var Pw=Object.create;var ph=Object.defineProperty;var Aw=Object.getOwnPropertyDe
|
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
116
|
[selected audio track] ${S==null?void 0:S.id}
|
|
117
|
-
`}),S};var we=a=>new URL(a).hostname;import{assertNever as My,assertNonNullable as Cy,combine as rD,debounce as aD,ErrorCategory as Ly,filter as Dy,filterChanged as sD,isNonNullable as Xc,map as To,merge as By,observableFrom as nD,once as oD,Subscription as uD,ValueSubject as Jc,videoQualityToHeight as Vy,videoSizeToQuality as lD}from"@vkontakte/videoplayer-shared/es2018";var Ay=_(Ke(),1);var Sy=_(De(),1),vy=a=>{if(a instanceof DOMException&&(0,Sy.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Ne=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!vy(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return vy(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as So,isNullable as NL,assertNonNullable as Va}from"@vkontakte/videoplayer-shared/es2018";var Ty=_(Ei(),1);import{isNonNullable as yy,assertNonNullable as vo,now as LL}from"@vkontakte/videoplayer-shared/es2018";function be(){return LL()}function Wc(a){return be()-a}function zc(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Iy(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function xr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",m=7e3,f=2e3,v=()=>{if(u)return;vo(d);let M=Wc(d),q;if(M<f){q=f-M,setTimeout(v,q);return}f*=2,f>m&&(f=m),n&&n.abort(),n=new r,R()},g=M=>(s=M,V),S=M=>(c=M,V),T=()=>(h="json",V),y=()=>{if(!u){if(--l>=0){v(),i&&i();return}u=!0,c&&c(),t&&t()}},w=M=>(p=M,V),R=()=>{d=be(),n=new r,n.open("get",a);let M=0,q,G=0,H=()=>(vo(d),Math.max(d,Math.max(q||0,G||0)));if(s&&n.addEventListener("progress",E=>{let P=be();s.updateChunk&&E.loaded>M&&(s.updateChunk(H(),E.loaded-M),M=E.loaded,q=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;vo(n);let E=n.status;if(E>=200&&E<300){let{response:P,responseType:I}=n,x=P==null?void 0:P.byteLength;if(typeof x=="number"&&s){let F=x-M;F&&s.updateChunk&&s.updateChunk(H(),F)}I==="json"&&(!P||!(0,Ty.default)(P).length)?y():(c&&c(),e(P))}else y()}),n.addEventListener("error",()=>{y()}),p){let E=()=>{vo(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(G=be(),n.removeEventListener("readystatechange",E))};n.addEventListener("readystatechange",E)}return n.responseType=h,n.send(),V},V={withBitrateReporting:g,withParallel:w,withJSONResponse:T,withRetryCount:M=>(l=M,V),withRetryInterval:(M,q)=>(yy(M)&&(f=M),yy(q)&&(m=q),V),withTimeout:M=>(o=M,V),withFinally:S,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return V}var Da=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ey=_(Ei(),1);var Ba=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=be(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=be()-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=xr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=be()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=be();if(Object.keys(this.activeRequests).length>=e)return!1;let 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,Ey.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as FL}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as wy}from"@vkontakte/videoplayer-shared/es2018";var ee=(a,e)=>wy(a)&&wy(e)&&a.readyState==="open"&&DL(a,e);function DL(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var Py=_(zt(),1);import{getWindow as BL,safeStorage as VL}from"@vkontakte/videoplayer-shared/es2018";var Gc=class{constructor(e,t,i,r){this.tag=e;this.time=t;this.data=i;this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:""}`}toDevNullEntry(){var t;let e=(0,Py.default)(this.data).map(([i,r])=>`${i}:${r}`).join(",");return{key:this.tag,strings:[e,(t=this.stack)!=null?t:""],numbers:[this.time]}}},_L=(a,e="warn")=>{let t=BL(),i=[];function r(s,n=!1){var l,d,c;let o=(c=(d=(l=t.performance)==null?void 0:l.timing)==null?void 0:d.navigationStart)!=null?c:0,u=new Gc(a,Math.round((Date.now()-o)/1e3),s,n?new Error().stack:void 0);i.push(u),e&&t.console[e](u.toString())}return r.reset=()=>{i=[]},r.drain=()=>{let s=i;return i=[],s},r},xy,N=_L("vp_dash_live_debug",(xy=VL.get("vp_dev_null_console_method"))!=null?xy:!1);var yo=1e4,Yc=3;var qL=6e4,UL=10,jL=1,HL=500,_a=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 FL,this.chunkRateEstimator=new Da(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=zc(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&(N({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",N({m:"ldp.catchUp.2"}),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()?(N({m:"ldp.play.1"}),this._playVideoElement()):(N({m:"ldp.play.2"}),this._notifyBuffering(!0))):(N({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,N({m:"startPlay",url:e.jidxUrl}),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=zc(e),N({m:"ldp.reinit",url: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;N({m:"iv"}),e.addEventListener("error",()=>{var r,s,n,o;!!e.error&&!this.destroyed&&(N({m:"iv.err",e:((r=e.error)==null?void 0:r.code)+":"+((s=e.error)==null?void 0:s.message)}),t(`Video element error: ${(n=e.error)==null?void 0:n.code}, details: ${(o=e.error)==null?void 0:o.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),N({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(B.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!uy({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Ay.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||So(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){var o;let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(N({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),(o=this.mediaSource)==null||o.addEventListener("sourceclose",u=>{N({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{N({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Iy(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({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 Ba(Yc,yo,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let y=s&&(!d||d===this.rep);return y||t("Not running!"),y},p=(y,w,R)=>{u&&u.abort(),u=xr(this.urlResolver.resolve(y,!1),w,R,()=>this._retryCallback()).withTimeout(yo).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Yc).withFinally(()=>{u=null}).send()},h=(y,w,R)=>{Va(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),w,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=y=>{let w=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${w}=>${y}`),i.playbackRate=y)},f=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let R=be()-1e4,L=0;for(let D=0;D<this.bufferStates.length;D++){let k=this.bufferStates[D];y=Math.min(y,k.buf),k.ts<R&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${y} drop=${L} jitter=${this.sourceJitter}`);let $=y-jL;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?m(1.15):$>1?m(1.1):$>.3?m(1.05):m(1)}},g=y=>{let w,R=()=>w&&w.start?w.start.length:0,L=E=>w.start[E]/1e3,$=E=>w.dur[E]/1e3,D=E=>w.fragIndex+E,k=(E,P)=>({chunkIdx:D(E),startTS:L(E),dur:$(E),discontinuity:P}),V=()=>{let E=0;if(w&&w.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,I=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,x=P;this.sourceJitter>1&&(x+=this.sourceJitter-1);let F=w.dur.length-1;for(;F>=0&&(x-=w.dur[F],!(x<=0));--F);E=Math.min(F,w.dur.length-1-I),E=Math.max(E,0)}return k(E,!0)},M=E=>{let P=R();if(!(P<=0)){if(So(E)){for(let I=0;I<P;I++)if(L(I)>E)return k(I)}return V()}},q=E=>{let P=R(),I=E?E.chunkIdx+1:0,x=I-w.fragIndex;if(!(P<=0)){if(!E||x<0||x-P>UL)return t(`Resync: offset=${x} bChunks=${P} chunk=`+JSON.stringify(E)),V();if(!(x>=P))return k(I-w.fragIndex,!1)}},G=(E,P,I)=>{l&&l.abort(),l=xr(this.urlResolver.resolve(E,!0,this.lowLatency),P,I,()=>this._retryCallback()).withTimeout(yo).withRetryCount(Yc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(E,P)=>{G(y,I=>{if(!c())return;w=I;let x=!!w.lowLatency;x!==this.lowLatency&&f(x);let F=0;for(let O=0;O<w.dur.length;++O)F+=w.dur[O];F>0&&(Va(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(F/w.dur.length)),r({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,E(M(P))},()=>this._handleNetworkError())},nextChunk:q}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Va(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:y=>{let{videoElement:w,logger:R}=this.params,L=g(e.jidxUrl),$,D,k,V,M=0,q,G,H,E=()=>{q&&(clearTimeout(q),q=void 0);let Y=Math.max(HL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=M+Y,ye=be(),Te=Math.min(1e4,Se-ye);M=ye;let Fe=()=>{l||c()&&L.seek(()=>{c()&&(M=be(),P(),E())})};Te>0?q=window.setTimeout(()=>{this.paused?E():Fe()},Te):Fe()},P=()=>{let Y;for(;Y=L.nextChunk(V);)V=Y,ct(Y);let Se=L.nextChunk(k);if(Se){if(k&&Se.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?E():(S(),N({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}O(Se)}else E()},I=(Y,Se)=>{if(!c()||!this.sourceBuffer){N({m:"ab.0",c:[!c(),!this.sourceBuffer]});return}let ye,Te,Fe,It=Et=>{N({m:"ldp.postpone",t:Et}),window.setTimeout(()=>{c()&&I(Y,Se)},Et)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),N({m:"ldp.ab.1"}),It(100);else{let Et=be(),di=w.currentTime;!this.paused&&w.buffered.length>1&&G===di&&Et-H>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),G!==di&&(G=di,H=Et);let Gi=this._getBufferSizeSec();if(Gi>30)N({m:"ldp.ab.3"}),R(`Buffered ${Gi} seconds; delaying appendBuffer`),It(2e3);else try{if(this.params.config.useInvalidBufferFix&&ee(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(N({m:"ldp.ab.5"}),this.bufferStates.push({ts:Et,buf:Gi}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(N({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(Yi){if(N({m:"ldp.ab.err",e:Yi.name}),Yi.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Fe=this.sourceBuffer.buffered.length,Fe!==0&&(ye=this.sourceBuffer.buffered.start(0),Te=di,Te-ye>4&&this.sourceBuffer.remove(ye,Te-3)),It(1e3);else throw Yi}}},x=()=>{D&&$&&(R([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(k)]),I(D,function(){D=null,P()}))},F=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),O=Y=>{c()&&h(F(Y),(Se,ye)=>{if(c()){if(ye/=1e3,D=Se,k=Y,n=Y.startTS,ye){let Te=Math.min(10,Y.dur/ye);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Te:Te}x()}},()=>this._handleNetworkError())},ct=Y=>{c()&&(Va(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(F(Y),!1)))},dt=Y=>{c()&&(e.cachedHeader=Y,I(Y,()=>{$=!0,x()}))};s=!0,L.seek(Y=>{if(c()){if(M=be(),!Y){E();return}V=Y,!NL(y)||Y.startTS>y?O(Y):(k=Y,P())}},y),e.cachedHeader?dt(e.cachedHeader):p(e.headerUrl,dt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),So(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,Va(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return So(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,h)=>{let m=be();if(this.chunkRateEstimator.addInterval(p,m,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Wc(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=s.updateChunk(c,p);return h&&l(),h},notifySwitch:c=>{let p=be();c<o&&(n=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=xr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(yo).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;Ne(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{N({m:"ldp.pve.1"}),t||(N({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{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=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},qL))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var $y=_(zt(),1);import{debounce as QL,filter as ky,fromEvent as WL,interval as zL,isHigher as GL,isInvariantQuality as YL,isLower as KL,merge as XL,Subject as Ry,Subscription as JL}from"@vkontakte/videoplayer-shared/es2018";var Kc=class{constructor(){this.onDroopedVideoFramesLimit$=new Ry;this.subscription=new JL;this.playing=!1;this.tracks=[];this.forceChecker$=new Ry;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&&!YL(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&GL(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(WL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=zL(this.droppedFramesChecker.checkTime).pipe(ky(()=>this.playing),ky(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(QL(this.droppedFramesChecker.checkTime)),i=XL(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,$y.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>KL(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Pr=Kc;import{map as ZL,Observable as eD}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as tD}from"@vkontakte/videoplayer-shared/es2018";var Oa=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var iD=(a,e)=>new eD(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Oa()))},{...i,...e});r.observe(a);let s=tD(document,"visibilitychange").pipe(ZL(n=>!document.hidden||Oa())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Xe=iD;var cD=["paused","playing","ready"],dD=["paused","playing","ready"],Na=class{constructor(e){this.subscription=new uD;this.videoState=new j("stopped");this.representations$=new Jc([]);this.droppedFramesManager=new Pr;this.maxSeekBackTime$=new Jc(1/0);this.zeroTime$=new Jc(void 0);this.liveOffset=new Ci;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Ly.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=Kt(u.name))!=null?i:lD(u.video),c=u.bitrate/1e3,p={...u.video};if(!d)continue;let h={id:l,quality:d,bitrate:c,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Xc(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Zc.default)(dD,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Zc.default)(cD,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){N({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&(N({m:"dlp.sync.2"}),this.dash.catchUp()),N({m:"dlp.sync.3"}),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(Ee(this.params.source.url,u))}return;default:return My(e)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Ly.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(By(this.videoState.stateChangeStarted$.pipe(To(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(To(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{N({m:"dlp.s.1",t:s+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Be(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(we(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=Oe(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(To(r=>r.map(({track:s})=>s)),Dy(r=>!!r.length),oD()).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(),To(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(rD({zeroTime:this.zeroTime$.pipe(Dy(Xc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(gt(this.video,this.params.desiredState.isLooped,t)).add(_e(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ge(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Xe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Vy(r),min:s&&Vy(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),N({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&(N({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":N({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":N({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return My(r.to)}},t)).add(By(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,nD(["init"])).pipe(aD(0)).subscribe(this.syncPlayback,t))}destroy(){N({m:"dlp.destroy"}),this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ve(this.video)}createLiveDashPlayer(){let e=new _a({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount,useInvalidBufferFix:this.params.tuning.useInvalidBufferFix||!1},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,p,h,m;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=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Xc(t)?t:yt(e.map(({track:f})=>f),{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}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let f=(m=e.find(({track:v})=>v.id===s))==null?void 0:m.representation;Cy(f,"Representations missing"),this.dash.startPlay(f,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Cy(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),N({m:"dlp.seek",p:e,no:n,url:this.params.source.url}),this.dash.reinit(Ee(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var _y=Na;import{filterChanged as wV}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as AD,assertNonNullable as kD,debounce as RD,ErrorCategory as zy,filter as ud,filterChanged as ld,fromEvent as $D,isNonNullable as Gy,isNullable as MD,map as cd,merge as ko,observableFrom as dd,once as Yy,Subscription as CD,throttle as LD}from"@vkontakte/videoplayer-shared/es2018";var ed=_(Ke(),1);import{videoSizeToQuality as pD}from"@vkontakte/videoplayer-shared/es2018";var Oy=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:pD({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Ny=({id:a,bitrate:e})=>({id:a,bitrate:e}),Fy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e});var td=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,ed.default)(i.split("."),0),isDefault:r}),Io=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,ed.default)(r.split("."),0)});var Me=a=>a.type==="template";var Eo=class{constructor(e,t){this.fov=e,this.orientation=t}};var wo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...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*(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 qy=`attribute vec2 a_vertex;
|
|
117
|
+
`}),S};var we=a=>new URL(a).hostname;import{assertNever as Ly,assertNonNullable as By,combine as nL,debounce as oL,ErrorCategory as Vy,filter as _y,filterChanged as uL,isNonNullable as rd,map as xo,merge as Oy,observableFrom as cL,once as lL,Subscription as dL,ValueSubject as ad,videoQualityToHeight as Ny,videoSizeToQuality as pL}from"@vkontakte/videoplayer-shared/es2018";var My=_(Ke(),1);var Ey=_(Le(),1),Iy=a=>{if(a instanceof DOMException&&(0,Ey.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Ne=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!Iy(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return Iy(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Eo,isNullable as UD,assertNonNullable as Fa}from"@vkontakte/videoplayer-shared/es2018";var xy=_(Ei(),1);import{isNonNullable as wy,assertNonNullable as Io,now as _D}from"@vkontakte/videoplayer-shared/es2018";function be(){return _D()}function Jl(a){return be()-a}function Zl(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let c=n.indexOf("?")>-1?"&":"?";return u&&(n+=c+"lowLat=1",c="&"),o&&(n+=c+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Py(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function kr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,c=0,d,l,p=!1,h="arraybuffer",f=7e3,m=2e3,v=()=>{if(u)return;Io(d);let $=Jl(d),U;if($<m){U=m-$,setTimeout(v,U);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,R()},g=$=>(s=$,B),S=$=>(l=$,B),T=()=>(h="json",B),y=()=>{if(!u){if(--c>=0){v(),i&&i();return}u=!0,l&&l(),t&&t()}},x=$=>(p=$,B),R=()=>{d=be(),n=new r,n.open("get",a);let $=0,U,G=0,j=()=>(Io(d),Math.max(d,Math.max(U||0,G||0)));if(s&&n.addEventListener("progress",E=>{let P=be();s.updateChunk&&E.loaded>$&&(s.updateChunk(j(),E.loaded-$),$=E.loaded,U=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;Io(n);let E=n.status;if(E>=200&&E<300){let{response:P,responseType:I}=n,w=P==null?void 0:P.byteLength;if(typeof w=="number"&&s){let N=w-$;N&&s.updateChunk&&s.updateChunk(j(),N)}I==="json"&&(!P||!(0,xy.default)(P).length)?y():(l&&l(),e(P))}else y()}),n.addEventListener("error",()=>{y()}),p){let E=()=>{Io(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(G=be(),n.removeEventListener("readystatechange",E))};n.addEventListener("readystatechange",E)}return n.responseType=h,n.send(),B},B={withBitrateReporting:g,withParallel:x,withJSONResponse:T,withRetryCount:$=>(c=$,B),withRetryInterval:($,U)=>(wy($)&&(m=$),wy(U)&&(f=U),B),withTimeout:$=>(o=$,B),withFinally:S,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,l&&l()}};return B}var Oa=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var ky=_(Ei(),1);var Na=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=be(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=be()-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=kr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=be()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=be();if(Object.keys(this.activeRequests).length>=e)return!1;let 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,ky.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as HD}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Ay}from"@vkontakte/videoplayer-shared/es2018";var te=(a,e)=>Ay(a)&&Ay(e)&&a.readyState==="open"&&OD(a,e);function OD(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var Ry=_(zt(),1);import{getWindow as ND}from"@vkontakte/videoplayer-shared/es2018";var ed=class{constructor(e,t,i,r){this.tag=e;this.time=t;this.data=i;this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:""}`}toDevNullEntry(){var t;let e=(0,Ry.default)(this.data).map(([i,r])=>`${i}:${r}`).join(",");return{key:this.tag,strings:[e,(t=this.stack)!=null?t:""],numbers:[this.time]}}},FD=(a,e="warn")=>{let t=ND(),i=[];function r(s,n=!1){var c,d,l;let o=(l=(d=(c=t.performance)==null?void 0:c.timing)==null?void 0:d.navigationStart)!=null?l:0,u=new ed(a,Math.round((Date.now()-o)/1e3),s,n?new Error().stack:void 0);i.push(u),e&&t.console[e](u.toString())}return r.reset=()=>{i=[]},r.drain=()=>{let s=i;return i=[],s},r},F=FD("vp_dash_live_debug",!1);var wo=1e4,td=3;var jD=6e4,QD=10,WD=1,zD=500,qa=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 HD,this.chunkRateEstimator=new Oa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Zl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&(F({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",F({m:"ldp.catchUp.2"}),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()?(F({m:"ldp.play.1"}),this._playVideoElement()):(F({m:"ldp.play.2"}),this._notifyBuffering(!0))):(F({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,F({m:"startPlay",url:e.jidxUrl}),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=Zl(e),F({m:"ldp.reinit",url: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;F({m:"iv"}),e.addEventListener("error",()=>{var r,s,n,o;!!e.error&&!this.destroyed&&(F({m:"iv.err",e:((r=e.error)==null?void 0:r.code)+":"+((s=e.error)==null?void 0:s.message)}),t(`Video element error: ${(n=e.error)==null?void 0:n.code}, details: ${(o=e.error)==null?void 0:o.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),F({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(V.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:c}=this.autoQualityLimits||{};!py({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,My.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||c&&s.video.height<c)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Eo(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){var o;let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(F({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),(o=this.mediaSource)==null||o.addEventListener("sourceclose",u=>{F({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{F({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Py(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({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 Na(td,wo,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,c=null,d=!1,l=()=>{let y=s&&(!d||d===this.rep);return y||t("Not running!"),y},p=(y,x,R)=>{u&&u.abort(),u=kr(this.urlResolver.resolve(y,!1),x,R,()=>this._retryCallback()).withTimeout(wo).withBitrateReporting(this.bitrateSwitcher).withRetryCount(td).withFinally(()=>{u=null}).send()},h=(y,x,R)=>{Fa(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),x,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let x=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${x}=>${y}`),i.playbackRate=y)},m=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=be()-1e4,D=0;for(let L=0;L<this.bufferStates.length;L++){let A=this.bufferStates[L];y=Math.min(y,A.buf),A.ts<R&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${y} drop=${D} jitter=${this.sourceJitter}`);let M=y-WD;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)}},g=y=>{let x,R=()=>x&&x.start?x.start.length:0,D=E=>x.start[E]/1e3,M=E=>x.dur[E]/1e3,L=E=>x.fragIndex+E,A=(E,P)=>({chunkIdx:L(E),startTS:D(E),dur:M(E),discontinuity:P}),B=()=>{let E=0;if(x&&x.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,I=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,w=P;this.sourceJitter>1&&(w+=this.sourceJitter-1);let N=x.dur.length-1;for(;N>=0&&(w-=x.dur[N],!(w<=0));--N);E=Math.min(N,x.dur.length-1-I),E=Math.max(E,0)}return A(E,!0)},$=E=>{let P=R();if(!(P<=0)){if(Eo(E)){for(let I=0;I<P;I++)if(D(I)>E)return A(I)}return B()}},U=E=>{let P=R(),I=E?E.chunkIdx+1:0,w=I-x.fragIndex;if(!(P<=0)){if(!E||w<0||w-P>QD)return t(`Resync: offset=${w} bChunks=${P} chunk=`+JSON.stringify(E)),B();if(!(w>=P))return A(I-x.fragIndex,!1)}},G=(E,P,I)=>{c&&c.abort(),c=kr(this.urlResolver.resolve(E,!0,this.lowLatency),P,I,()=>this._retryCallback()).withTimeout(wo).withRetryCount(td).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(E,P)=>{G(y,I=>{if(!l())return;x=I;let w=!!x.lowLatency;w!==this.lowLatency&&m(w);let N=0;for(let O=0;O<x.dur.length;++O)N+=x.dur[O];N>0&&(Fa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(N/x.dur.length)),r({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,E($(P))},()=>this._handleNetworkError())},nextChunk:U}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),c&&c.abort(),Fa(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:y=>{let{videoElement:x,logger:R}=this.params,D=g(e.jidxUrl),M,L,A,B,$=0,U,G,j,E=()=>{U&&(clearTimeout(U),U=void 0);let K=Math.max(zD,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=$+K,ye=be(),Te=Math.min(1e4,Se-ye);$=ye;let Fe=()=>{c||l()&&D.seek(()=>{l()&&($=be(),P(),E())})};Te>0?U=window.setTimeout(()=>{this.paused?E():Fe()},Te):Fe()},P=()=>{let K;for(;K=D.nextChunk(B);)B=K,lt(K);let Se=D.nextChunk(A);if(Se){if(A&&Se.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?E():(S(),F({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}O(Se)}else E()},I=(K,Se)=>{if(!l()||!this.sourceBuffer){F({m:"ab.0",c:[!l(),!this.sourceBuffer]});return}let ye,Te,Fe,It=Et=>{F({m:"ldp.postpone",t:Et}),window.setTimeout(()=>{l()&&I(K,Se)},Et)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),F({m:"ldp.ab.1"}),It(100);else{let Et=be(),di=x.currentTime;!this.paused&&x.buffered.length>1&&G===di&&Et-j>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),G!==di&&(G=di,j=Et);let Ki=this._getBufferSizeSec();if(Ki>30)F({m:"ldp.ab.3"}),R(`Buffered ${Ki} seconds; delaying appendBuffer`),It(2e3);else try{if(this.params.config.useInvalidBufferFix&&te(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(F({m:"ldp.ab.5"}),this.bufferStates.push({ts:Et,buf:Ki}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(F({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(Xi){if(F({m:"ldp.ab.err",e:Xi.name}),Xi.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Fe=this.sourceBuffer.buffered.length,Fe!==0&&(ye=this.sourceBuffer.buffered.start(0),Te=di,Te-ye>4&&this.sourceBuffer.remove(ye,Te-3)),It(1e3);else throw Xi}}},w=()=>{L&&M&&(R([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(A)]),I(L,function(){L=null,P()}))},N=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),O=K=>{l()&&h(N(K),(Se,ye)=>{if(l()){if(ye/=1e3,L=Se,A=K,n=K.startTS,ye){let Te=Math.min(10,K.dur/ye);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Te:Te}w()}},()=>this._handleNetworkError())},lt=K=>{l()&&(Fa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(N(K),!1)))},dt=K=>{l()&&(e.cachedHeader=K,I(K,()=>{M=!0,w()}))};s=!0,D.seek(K=>{if(l()){if($=be(),!K){E();return}B=K,!UD(y)||K.startTS>y?O(K):(A=K,P())}},y),e.cachedHeader?dt(e.cachedHeader):p(e.headerUrl,dt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Eo(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Fa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Eo(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=l=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&l<this.bitrate&&(h=this._getBufferSizeSec(),f=l/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(l)}`);return}p=this._selectQuality(l),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${l}`)},s={updateChunk:(p,h)=>{let f=be();if(this.chunkRateEstimator.addInterval(p,f,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,c=()=>{let l=s.get();if(l&&o&&this.autoQuality){if(u&&l>o&&Jl(n)<3e4)return;i(l)}u=this.autoQuality};return{updateChunk:(l,p)=>{let h=s.updateChunk(l,p);return h&&c(),h},notifySwitch:l=>{let p=be();l<o&&(n=p),o=l}}}_fetchManifest(e,t,i){this.manifestRequest=kr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(wo).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;Ne(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{F({m:"ldp.pve.1"}),t||(F({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,c)=>{var d,l;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((l=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&l.call(d,u.codecs))&&(u.index=c,o.push(u))}),o.sort(function(u,c){return u.video&&c.video?c.video.height-u.video.height:c.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},jD))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Dy=_(zt(),1);import{debounce as GD,filter as $y,fromEvent as YD,interval as KD,isHigher as XD,isInvariantQuality as JD,isLower as ZD,merge as eL,Subject as Cy,Subscription as tL}from"@vkontakte/videoplayer-shared/es2018";var id=class{constructor(){this.onDroopedVideoFramesLimit$=new Cy;this.subscription=new tL;this.playing=!1;this.tracks=[];this.forceChecker$=new Cy;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,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&XD(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(YD(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=KD(this.droppedFramesChecker.checkTime).pipe($y(()=>this.playing),$y(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(GD(this.droppedFramesChecker.checkTime)),i=eL(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,Dy.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>ZD(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Ar=id;import{map as iL,Observable as rL}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as aL}from"@vkontakte/videoplayer-shared/es2018";var Ua=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var sL=(a,e)=>new rL(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ua()))},{...i,...e});r.observe(a);let s=aL(document,"visibilitychange").pipe(iL(n=>!document.hidden||Ua())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Xe=sL;var hL=["paused","playing","ready"],fL=["paused","playing","ready"],Ha=class{constructor(e){this.subscription=new dL;this.videoState=new H("stopped");this.representations$=new ad([]);this.droppedFramesManager=new Ar;this.maxSeekBackTime$=new ad(1/0);this.zeroTime$=new ad(void 0);this.liveOffset=new Ci;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Vy.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let c=(t=u.name)!=null?t:u.index.toString(10),d=(i=Kt(u.name))!=null?i:pL(u.video),l=u.bitrate/1e3,p={...u.video};if(!d)continue;let h={id:c,quality:d,bitrate:l,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),rd(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,sd.default)(fL,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,sd.default)(hL,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ee(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){F({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&(F({m:"dlp.sync.2"}),this.dash.catchUp()),F({m:"dlp.sync.3"}),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(Ee(this.params.source.url,u))}return;default:return Ly(e)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Vy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Oy(this.videoState.stateChangeStarted$.pipe(xo(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(xo(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{F({m:"dlp.s.1",t:s+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Be(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(we(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=Oe(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(xo(r=>r.map(({track:s})=>s)),_y(r=>!!r.length),lL()).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(uL(),xo(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(nL({zeroTime:this.zeroTime$.pipe(_y(rd)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(gt(this.video,this.params.desiredState.isLooped,t)).add(_e(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ge(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Xe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Ny(r),min:s&&Ny(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),F({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&(F({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":F({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":F({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return Ly(r.to)}},t)).add(Oy(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,cL(["init"])).pipe(oL(0)).subscribe(this.syncPlayback,t))}destroy(){F({m:"dlp.destroy"}),this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ve(this.video)}createLiveDashPlayer(){let e=new qa({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount,useInvalidBufferFix:this.params.tuning.useInvalidBufferFix||!1},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var c,d,l,p,h,f;let e=this.representations$.getValue(),t=(d=(c=this.params.desiredState.videoTrack.getTransition())==null?void 0:c.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(p=(l=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:l.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&rd(t)?t:yt(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}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let m=(f=e.find(({track:v})=>v.id===s))==null?void 0:f.representation;By(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;By(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),F({m:"dlp.seek",p:e,no:n,url:this.params.source.url}),this.dash.reinit(Ee(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Fy=Ha;import{filter as wV,filterChanged as xV,isNonNullable as PV}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as ML,assertNonNullable as $L,debounce as CL,ErrorCategory as Ky,filter as md,filterChanged as $o,fromEvent as DL,isNonNullable as Xy,isNullable as LL,map as bd,merge as Co,observableFrom as gd,once as Jy,Subscription as BL,throttle as VL}from"@vkontakte/videoplayer-shared/es2018";var nd=_(Ke(),1);import{videoSizeToQuality as mL}from"@vkontakte/videoplayer-shared/es2018";var qy=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:mL({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Uy=({id:a,bitrate:e})=>({id:a,bitrate:e}),Hy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e});var od=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,nd.default)(i.split("."),0),isDefault:r}),ud=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,nd.default)(r.split("."),0)});var $e=a=>a.type==="template";var Po=class{constructor(e,t){this.fov=e,this.orientation=t}};var ko=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...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*(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 jy=`attribute vec2 a_vertex;
|
|
118
118
|
attribute vec2 a_texel;
|
|
119
119
|
|
|
120
120
|
varying vec2 v_texel;
|
|
@@ -125,7 +125,7 @@ void main(void) {
|
|
|
125
125
|
// save texel vector to pass to fragment shader
|
|
126
126
|
v_texel = a_texel;
|
|
127
127
|
}
|
|
128
|
-
`;var
|
|
128
|
+
`;var Qy=`#ifdef GL_ES
|
|
129
129
|
precision highp float;
|
|
130
130
|
precision highp int;
|
|
131
131
|
#else
|
|
@@ -168,17 +168,17 @@ void main(void) {
|
|
|
168
168
|
// sample using new coordinates
|
|
169
169
|
gl_FragColor = texture2D(u_texture, tc);
|
|
170
170
|
}
|
|
171
|
-
`;var Ar=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 Eo(this.params.fov,this.params.orientation),this.cameraRotationManager=new wo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(qy,this.gl.VERTEX_SHADER),i=this.createShader(Uy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,p=t+r;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as fD,now as qa,once as bD,Subscription as gD,ValueSubject as rd,isNonNullable as vD,safeStorage as ad,filterChanged as SD}from"@vkontakte/videoplayer-shared/es2018";var $t=(a,e,t)=>t*e+(1-t)*a,id=(a,e)=>a.reduce((t,i)=>t+i,0)/e,jy=(a,e,t,i)=>{let r=0,s=t,n=id(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var xo="stalls_manager_metrics",sd="stalls_manager_abr_params",Hy="stalls_manager_default_tuning_abr_params",nd=class{constructor(){this.isSeeked$=new rd(!1);this.isBuffering$=new rd(!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 gD;this.severeStallOccurred$=new rd(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(sd):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=qa(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(qa()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Hy)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(sd),this.setStoredData(Hy,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(xo,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(xo,[]),this.setStoredData(sd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o}=this.tuning,u=n*Math.min(t/o,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>s&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){var i;return JSON.parse((i=ad.get(e))!=null?i:t)}setStoredData(e,t){ad.set(e,JSON.stringify(t))}removeStoredData(e){ad.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(xo,"[]"),r=t/e,s=i.length?$t(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(xo,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(bD()).subscribe(t=>this.providerStartWatchingTimestamp=qa())),this.subscription.add(this.currentStallDuration$.pipe(SD()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(fD(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=qa(),c=r&&this.currentStallsCount>=r,p=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,vD(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&qa()-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},s)),this.lastStallDuration=t}))}},Po=nd;import{combine as yD,map as TD,observeElementSize as ID,Subscription as ED,ValueSubject as od,noop as wD}from"@vkontakte/videoplayer-shared/es2018";var Ao=class{constructor(){this.subscription=new ED;this.pipSize$=new od(void 0);this.videoSize$=new od(void 0);this.elementSize$=new od(void 0);this.pictureInPictureWindowRemoveEventListener=wD}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(ID(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(yD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(TD(({videoSize:r,inPip:s,pipSize:n})=>s?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()}};import{filter as Qy,map as xD,once as Wy}from"@vkontakte/videoplayer-shared/es2018";var Jt=({subscription:a,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!B.browser.isSafari)return;let r=0,s=!1;a.add(e.volume.stateChangeStarted$.pipe(xD(()=>{let n=e.volume.getTransition(),o=t.getValue();return!o||!n?!1:!n.to.muted&&o.muted}),Qy(n=>!!n),Wy()).subscribe(()=>{r=performance.now(),s=!0})),a.add(i.playbackRateState$.pipe(Qy(()=>s),Wy()).subscribe(()=>{let n=t.getValue(),o=e.playbackRate.getState();n&&o!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=o)}))};var Ua=class{constructor(e){this.subscription=new CD;this.videoState=new j("stopped");this.observableVideo=null;this.droppedFramesManager=new Pr;this.stallsManager=new Po;this.elementSizeManager=new Ao;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return AD(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Ar(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Be(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(we(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=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;MD(this.observableVideo)&&(this.observableVideo=Oe(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:zy.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ud(c=>!!c.length),Yy()).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(cd(c=>c.to.state!=="none"),ld());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.currentBuffer$,e.currentBuffer$),s(this.player.lastRequestFirstBytes$.pipe(ud(Gy),Yy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(cd(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(gt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Jt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Ge(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Xe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),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 p=this.player.getStreams(),h=this.player.getCodecs();if(kD(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let v of p.audio){f.push(td(v));let g=[];for(let S of v.representations){let T=Ny(S);g.push(T),this.audioTracksMap.set(T,{stream:v,representation:S})}this.audioStreamsMap.set(v,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of p.video){m.push(Io(f));let v=[];for(let g of f.representations){let S=Oy({...g,streamId:f.id});S&&(v.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,v)}this.params.output.availableVideoStreams$.next(m);for(let f of p.text)for(let v of f.representations){let g=Fy(f,v);this.textTracksMap.set(g,{stream:f,representation:v})}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),h!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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 o=ko(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$,$D(this.video,"progress")).pipe(ud(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(LD(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition(),h=t.autoVideoTrackSwitching.getState();if(c!=="manifest_ready"&&c!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let m=this.selectVideoAudioRepresentations();if(!m)return;let[f,v]=m,g=[...this.videoTracksMap.keys()].find(T=>{var y;return((y=this.videoTracksMap.get(T))==null?void 0:y.representation.id)===f.id});Gy(g)&&(this.stallsManager.lastVideoTrackSelected=g);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready"?await this.player.initRepresentations(f.id,v==null?void 0:v.id,this.params.sourceHls):(await this.player.switchRepresentation("video",f.id,h),v&&await this.player.switchRepresentation("audio",v.id,h))},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.currentAudioRepresentation$.pipe(ld()).subscribe(c=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:v}])=>v.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(td(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.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(cd(({to:c})=>c==="ready"),ld());this.subscription.add(ko(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,dd(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(ko(l,this.player.state$.stateChangeEnded$,dd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=ko(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dd(["init"])).pipe(RD(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var $,D,k,V,M,q,G,H,E,P,I,x,F;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?La:Ca,t=this.params.tuning.useNewAutoSelectVideoTrack?go:bo,i=this.params.tuning.useNewAutoSelectVideoTrack?yt:fo,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=($=r.videoTrack.getState())==null?void 0:$.id,u=[...this.videoTracksMap.keys()].find(({id:O})=>O===o),l=s.currentVideoTrack$.getValue(),d=((V=(k=r.videoStream.getState())!=null?k:u&&((D=this.videoTracksMap.get(u))==null?void 0:D.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=[...this.videoStreamsMap.keys()].find(({id:O})=>O===d.id),p=c&&this.videoStreamsMap.get(c);if(!p)return;let h=this.player.bufferLength$.getValue(),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 f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,v=Math.min(h/Math.min(m,f||1/0),1),g=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(q=[...this.audioStreamsMap.keys()].find(({id:O})=>O===(g==null?void 0:g.id)))!=null?q:this.audioStreamsMap.keys().next().value,T=0;if(S){if(u&&!n){let O=e(u,p,(G=this.audioStreamsMap.get(S))!=null?G:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(H=O==null?void 0:O.bitrate)!=null?H:-1/0)}if(l){let O=e(l,p,(E=this.audioStreamsMap.get(S))!=null?E:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(P=O==null?void 0:O.bitrate)!=null?P:-1/0)}}let y=u;(n||!y)&&(y=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:v,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 w=S&&t(y,p,(I=this.audioStreamsMap.get(S))!=null?I:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),R=(x=this.videoTracksMap.get(y))==null?void 0:x.representation,L=w&&((F=this.audioTracksMap.get(w))==null?void 0:F.representation);if(R&&L)return[R,L];if(R&&!L&&this.audioTracksMap.size===0)return[R,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:zy.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),Ve(this.video),this.tracer.end()}};var jd=_(ja(),1);var{NativeAbortSignal:rW,NativeAbortController:aW}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function fT(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function bT(a){if(a===void 0)if(typeof document=="undefined")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var Ro=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Rr=class extends Ro{constructor(){super(),this.listeners||Ro.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)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new Bi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Bi;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},Bi=class{constructor(){Object.defineProperty(this,"signal",{value:new Rr,writable:!0,configurable:!0})}abort(e){let t=bT(e),i=fT(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Bi.prototype[Symbol.toStringTag]="AbortController",Rr.prototype[Symbol.toStringTag]="AbortSignal");function $o(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function hd(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!$o({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(h){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var de=typeof globalThis=="object"&&globalThis||typeof window=="object"&&window;var iB=()=>"fetch"in de,Ha=iB()&&$o({fetch:de.fetch,Request:de.Request,AbortController:de.AbortController}),gT=Ha?hd({fetch:de.fetch,Request:de.Request,AbortController:de.AbortController}):void 0,Je=Ha?gT.fetch:de.fetch,bW=Ha?gT.Request:de.Request,te=Ha?Bi:de.AbortController,gW=Ha?Rr:de.AbortSignal;var uE=_(De(),1);var OT=_(_T(),1);import{ErrorCategory as Wa}from"@vkontakte/videoplayer-shared/es2018";var Mo=a=>{if(!a)return{id:"EmptyResponse",category:Wa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Wa.NETWORK,message:`UV Error ${a}`};let e=(0,OT.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Wa.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Wa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Wa.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as sE,assertNonNullable as Lt,ErrorCategory as qi,filter as Nd,filterChanged as hV,flattenObject as Go,fromEvent as Ui,getTraceSubscriptionMethod as mV,getWindow as xs,interval as fV,isNonNullable as ri,isNullable as Ps,map as Fd,merge as As,now as bV,Subject as ai,Subscription as nE,SubscriptionRemovable as gV,ValueSubject as re}from"@vkontakte/videoplayer-shared/es2018";var Zt=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Co=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as za,assertNever as NT,ErrorCategory as Ga,flattenObject as $r,fromEvent as FT,getWindow as SB,merge as yB,now as Ya,Subject as Mr,Subscription as TB,ValueSubject as vd}from"@vkontakte/videoplayer-shared/es2018";var ot=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Lo=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Bo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Mr;this.manifestReceived=new Mr;this.firstBytesRequested=new Mr;this.firstBytesReceived=new Mr;this.lastConnectionType$=new vd(void 0);this.lastConnectionReused$=new vd(void 0);this.lastRequestFirstBytes$=new vd(void 0);this.recoverableError$=new Mr;this.error$=new Mr;this.abortAllController=new te;this.subscription=new TB;this.fetchManifest=za(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Lo(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Do);return r?(t.log("success",$r({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",$r({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=za(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var q,G,H;let d=e,c=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(d,SB().location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),d=E.toString();break}default:NT(t)}this.requestQuic&&(d=Zt(d));let h=this.abortAllController.signal,m;if(n){let E=new te;if(m=yB(FT(this.abortAllController.signal,"abort"),FT(n,"abort")).subscribe(()=>{try{E.abort()}catch(P){Do(P)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(P){Do(P)}h=E.signal}let f=0,v=Ya();p.log("startRequest",$r({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.firstBytesRequested.next();let g=yield this.doFetch(d,{priority:s,headers:c,signal:h}),S=Ya();if(!g)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((q=this.throughputEstimator)==null||q.addRawRtt(S-v),!g.ok||!g.body){m==null||m.unsubscribe();let E=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:E}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){m==null||m.unsubscribe();let E=Ya(),P={requestStartedAt:v,requestEndedAt:E,duration:E-v};return p.log("endRequest",$r(P)),p.end(),g.arrayBuffer()}let T=g.body;if(o){let E;[T,E]=g.body.tee(),(G=this.throughputEstimator)==null||G.trackStream(E,u)}let y=T.getReader(),w,R=parseInt((H=g.headers.get("content-length"))!=null?H:"",10);Number.isFinite(R)&&(w=R),!w&&i&&(w=i.to-i.from+1);let L=w?new Uint8Array(w):new Uint8Array(0),$=!1,D=E=>{m==null||m.unsubscribe(),$=!0,Do(E)},k=za(h,async function*({done:E,value:P}){if(f===0&&(this.lastRequestFirstBytes$.next(Ya()-v),this.firstBytesReceived.next()),h.aborted){m==null||m.unsubscribe();return}if(!E&&P){if(l&&w)L.set(P,f),f+=P.byteLength;else{let I=new Uint8Array(L.length+P.length);I.set(L),I.set(P,L.length),L=I,f+=P.byteLength}r==null||r(new DataView(L.buffer),f),yield y==null?void 0:y.read().then(k,D)}}.bind(this));yield y==null?void 0:y.read().then(k,D),m==null||m.unsubscribe();let V=Ya(),M={failed:$,requestStartedAt:v,requestEndedAt:V,duration:V-v};return $?(p.error("endRequest",$r(M)),p.end(),null):(p.log("endRequest",$r(M)),p.end(),L.buffer)}.bind(this));this.fetchByteRangeRepresentation=za(this.abortAllController.signal,async function*(e,t,i){var g;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),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 p=new DataView(c,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(g=e.indexRange)!=null?g:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(c,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;f=new DataView(S)}let v=t.parseSegments(f,h,m).map(S=>({networkStatus:"none",bufferStatus:"none",status:"none",time:S.time,byte:S.byte}));return{initMetadata:h,initDataView:new DataView(c),segments:v}}.bind(this));this.fetchTemplateRepresentation=za(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});if(!r)return null;let s=e.segments.map(n=>({...n,networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:s}}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Co(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=this.fetchTemplateRepresentation(e,i))!=null?n:null;default:NT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Je(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ga.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ga.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ga.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ga.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ga.FATAL})}}},Do=a=>{if(!ot(a))throw a};var Pd=_(lI(),1),MI=_(zt(),1),CI=_(xI(),1),LI=_(Ke(),1),Ad=_(Ei(),1);var PI=_(De(),1),xd=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,PI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as T0,isNullable as RI}from"@vkontakte/videoplayer-shared/es2018";var AI=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var kI=a=>{var e;try{let t=y0(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=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:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function y0(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
171
|
+
`;var Rr=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 Po(this.params.fov,this.params.orientation),this.cameraRotationManager=new ko(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(jy,this.gl.VERTEX_SHADER),i=this.createShader(Qy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,c=e+i,d=t+r,l=e-i,p=t+r;return[s,n,o,u,c,d,l,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as vL,now as Qa,once as SL,Subscription as yL,ValueSubject as ld,isNonNullable as TL,safeStorage as dd,filterChanged as IL}from"@vkontakte/videoplayer-shared/es2018";var Mt=(a,e,t)=>t*e+(1-t)*a,cd=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Wy=(a,e,t,i)=>{let r=0,s=t,n=cd(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var Ao="stalls_manager_metrics",pd="stalls_manager_abr_params",zy="stalls_manager_default_tuning_abr_params",hd=class{constructor(){this.isSeeked$=new ld(!1);this.isBuffering$=new ld(!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 yL;this.severeStallOccurred$=new ld(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(pd):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Qa(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Qa()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(zy)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(pd),this.setStoredData(zy,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ao,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Ao,[]),this.setStoredData(pd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o}=this.tuning,u=n*Math.min(t/o,1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){var i;return JSON.parse((i=dd.get(e))!=null?i:t)}setStoredData(e,t){dd.set(e,JSON.stringify(t))}removeStoredData(e){dd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ao,"[]"),r=t/e,s=i.length?Mt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ao,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(SL()).subscribe(t=>this.providerStartWatchingTimestamp=Qa())),this.subscription.add(this.currentStallDuration$.pipe(IL()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(vL(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=Qa(),l=r&&this.currentStallsCount>=r,p=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-c>=i+o&&t>=i;(l||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,TL(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Qa()-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},s)),this.lastStallDuration=t}))}},Ro=hd;import{combine as EL,map as wL,observeElementSize as xL,Subscription as PL,ValueSubject as fd,noop as kL}from"@vkontakte/videoplayer-shared/es2018";var Mo=class{constructor(){this.subscription=new PL;this.pipSize$=new fd(void 0);this.videoSize$=new fd(void 0);this.elementSize$=new fd(void 0);this.pictureInPictureWindowRemoveEventListener=kL}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(xL(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(EL({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(wL(({videoSize:r,inPip:s,pipSize:n})=>s?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()}};import{filter as Gy,map as AL,once as Yy}from"@vkontakte/videoplayer-shared/es2018";var Jt=({subscription:a,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!V.browser.isSafari)return;let r=0,s=!1;a.add(e.volume.stateChangeStarted$.pipe(AL(()=>{let n=e.volume.getTransition(),o=t.getValue();return!o||!n?!1:!n.to.muted&&o.muted}),Gy(n=>!!n),Yy()).subscribe(()=>{r=performance.now(),s=!0})),a.add(i.playbackRateState$.pipe(Gy(()=>s),Yy()).subscribe(()=>{let n=t.getValue(),o=e.playbackRate.getState();n&&o!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=o)}))};var Wa=class{constructor(e){this.subscription=new BL;this.videoState=new H("stopped");this.observableVideo=null;this.droppedFramesManager=new Ar;this.stallsManager=new Ro;this.elementSizeManager=new Mo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return ML(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Rr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Be(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(we(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=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;LL(this.observableVideo)&&(this.observableVideo=Oe(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Ky.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(md(l=>!!l.length),Jy()).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(bd(l=>l.to.state!=="none"),$o());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),s(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),s(this.player.isLive$,e.isLive$),s(this.player.currentBuffer$,e.currentBuffer$),s(this.player.lastRequestFirstBytes$.pipe(md(Xy),Jy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(bd(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(gt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Jt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Ge(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Xe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),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 p=this.player.getStreams(),h=this.player.getCodecs();if($L(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let v of p.audio){m.push(od(v));let g=[];for(let S of v.representations){let T=Uy(S);g.push(T),this.audioTracksMap.set(T,{stream:v,representation:S})}this.audioStreamsMap.set(v,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of p.video){f.push(ud(m));let v=[];for(let g of m.representations){let S=qy({...g,streamId:m.id});S&&(v.push(S),this.videoTracksMap.set(S,{stream:m,representation:g}))}this.videoStreamsMap.set(m,v)}this.params.output.availableVideoStreams$.next(f);for(let m of p.text)for(let v of m.representations){let g=Hy(m,v);this.textTracksMap.set(g,{stream:m,representation:v})}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),h!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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));let o=Co(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$,DL(this.video,"progress")).pipe(md(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(VL(u))),this.subscription.add(o.subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition(),h=t.autoVideoTrackSwitching.getState();if(l!=="manifest_ready"&&l!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let f=this.selectVideoAudioRepresentations();if(!f)return;let[m,v]=f,g=[...this.videoTracksMap.keys()].find(T=>{var y;return((y=this.videoTracksMap.get(T))==null?void 0:y.representation.id)===m.id});Xy(g)&&(this.stallsManager.lastVideoTrackSelected=g);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();S&&this.params.output.autoVideoTrackLimits$.next(S.to),l==="manifest_ready"?await this.player.initRepresentations(m.id,v==null?void 0:v.id,this.params.sourceHls):(await this.player.switchRepresentation("video",m.id,h),v&&await this.player.switchRepresentation("audio",v.id,h))},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($o()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===l);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=p,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(ud(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe($o()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:v}])=>v.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=p,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(od(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var p,h;if(l!=null&&l.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.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 c=t.playbackState.stateChangeStarted$.pipe(bd(({to:l})=>l==="ready"),$o());this.subscription.add(Co(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,gd(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(Co(c,this.player.state$.stateChangeEnded$,gd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Co(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,gd(["init"])).pipe(CL(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var M,L,A,B,$,U,G,j,E,P,I,w,N;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?_a:Va,t=this.params.tuning.useNewAutoSelectVideoTrack?To:yo,i=this.params.tuning.useNewAutoSelectVideoTrack?yt:So,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(M=r.videoTrack.getState())==null?void 0:M.id,u=[...this.videoTracksMap.keys()].find(({id:O})=>O===o),c=s.currentVideoTrack$.getValue(),d=((B=(A=r.videoStream.getState())!=null?A:u&&((L=this.videoTracksMap.get(u))==null?void 0:L.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:O})=>O===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let h=this.player.bufferLength$.getValue(),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,v=Math.min(h/Math.min(f,m||1/0),1),g=($=r.audioStream.getState())!=null?$:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(U=[...this.audioStreamsMap.keys()].find(({id:O})=>O===(g==null?void 0:g.id)))!=null?U:this.audioStreamsMap.keys().next().value,T=0;if(S){if(u&&!n){let O=e(u,p,(G=this.audioStreamsMap.get(S))!=null?G:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(j=O==null?void 0:O.bitrate)!=null?j:-1/0)}if(c){let O=e(c,p,(E=this.audioStreamsMap.get(S))!=null?E:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(P=O==null?void 0:O.bitrate)!=null?P:-1/0)}}let y=u;(n||!y)&&(y=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:v,current:c,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 x=S&&t(y,p,(I=this.audioStreamsMap.get(S))!=null?I:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),R=(w=this.videoTracksMap.get(y))==null?void 0:w.representation,D=x&&((N=this.audioTracksMap.get(x))==null?void 0:N.representation);if(R&&D)return[R,D];if(R&&!D&&this.audioTracksMap.size===0)return[R,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ky.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),Ve(this.video),this.tracer.end()}};var Gd=_(za(),1);var{NativeAbortSignal:sW,NativeAbortController:nW}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function vT(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function ST(a){if(a===void 0)if(typeof document=="undefined")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var Do=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},$r=class extends Do{constructor(){super(),this.listeners||Do.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)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new Bi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Bi;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},Bi=class{constructor(){Object.defineProperty(this,"signal",{value:new $r,writable:!0,configurable:!0})}abort(e){let t=ST(e),i=vT(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Bi.prototype[Symbol.toStringTag]="AbortController",$r.prototype[Symbol.toStringTag]="AbortSignal");function Lo(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Sd(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Lo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(c,d){let l;d&&d.signal&&(l=d.signal,delete d.signal);let p=new t(c,d);return l&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:l}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,c)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:c?c.signal:void 0;if(d){let l;try{l=new DOMException("Aborted","AbortError")}catch(h){l=new Error("Aborted"),l.name="AbortError"}if(d.aborted)return Promise.reject(l);let p=new Promise((h,f)=>{d.addEventListener("abort",()=>f(l),{once:!0})});return c&&c.signal&&delete c.signal,Promise.race([p,n(u,c)])}return n(u,c)},Request:s}}var de=typeof globalThis=="object"&&globalThis||typeof window=="object"&&window;var s0=()=>"fetch"in de,Ga=s0()&&Lo({fetch:de.fetch,Request:de.Request,AbortController:de.AbortController}),yT=Ga?Sd({fetch:de.fetch,Request:de.Request,AbortController:de.AbortController}):void 0,Je=Ga?yT.fetch:de.fetch,vW=Ga?yT.Request:de.Request,ie=Ga?Bi:de.AbortController,SW=Ga?$r:de.AbortSignal;var pE=_(Le(),1);var qT=_(FT(),1);import{ErrorCategory as Ka}from"@vkontakte/videoplayer-shared/es2018";var Bo=a=>{if(!a)return{id:"EmptyResponse",category:Ka.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ka.NETWORK,message:`UV Error ${a}`};let e=(0,qT.default)(a).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(a,"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"}};import{abortable as uE,assertNonNullable as Dt,ErrorCategory as Ui,filter as jd,filterChanged as fV,flattenObject as eu,fromEvent as Hi,getTraceSubscriptionMethod as mV,getWindow as Rs,interval as cE,isNonNullable as ri,isNullable as Ms,map as Qd,merge as $s,now as bV,Subject as ai,Subscription as lE,SubscriptionRemovable as gV,ValueSubject as Z}from"@vkontakte/videoplayer-shared/es2018";var Zt=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Vo=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as Xa,assertNever as UT,ErrorCategory as Cr,flattenObject as Dr,fromEvent as HT,getWindow as Ja,merge as I0,now as Vi,Subject as Lr,Subscription as E0,ValueSubject as Za}from"@vkontakte/videoplayer-shared/es2018";var ot=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var _o=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var No=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Lr;this.manifestReceived=new Lr;this.firstBytesRequested=new Lr;this.firstBytesReceived=new Lr;this.lastConnectionType$=new Za(void 0);this.lastConnectionReused$=new Za(void 0);this.lastRequestFirstBytes$=new Za(void 0);this.lastConnectionMetrics$=new Za(void 0);this.lastDownloadMetrics$=new Za(void 0);this.recoverableError$=new Lr;this.error$=new Lr;this.abortAllController=new ie;this.subscription=new E0;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=Xa(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=_o(i)),this.trackRequestStart(i,performance.now());let r=Vi();this.manifestRequested.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Oo);if(s){let n=Vi();t.log("success",Dr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(s.headers);let o=s.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=await s.text();if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let d=n-r,p=u/(d/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",Dr({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=Xa(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1}={}){var U,G,j;let d=e,l=new Headers,p=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(d,Ja().location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),d=E.toString();break}default:UT(t)}this.requestQuic&&(d=Zt(d));let h=this.abortAllController.signal,f;if(n){let E=new ie;if(f=I0(HT(this.abortAllController.signal,"abort"),HT(n,"abort")).subscribe(()=>{try{E.abort()}catch(P){Oo(P)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(P){Oo(P)}h=E.signal}let m=0,v=Vi();p.log("startRequest",Dr({url:d,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:v})),this.trackRequestStart(d,performance.now()),this.firstBytesRequested.next();let g=yield this.doFetch(d,{priority:s,headers:l,signal:h}),S=Vi();if(!g)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((U=this.throughputEstimator)==null||U.addRawRtt(S-v),!g.ok||!g.body){f==null||f.unsubscribe();let E=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:E}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){f==null||f.unsubscribe();let E=Vi(),P={requestStartedAt:v,requestEndedAt:E,duration:E-v};return p.log("endRequest",Dr(P)),p.end(),g.arrayBuffer()}let T=g.body;if(o){let E;[T,E]=g.body.tee(),(G=this.throughputEstimator)==null||G.trackStream(E,u)}let y=T.getReader(),x,R=parseInt((j=g.headers.get("content-length"))!=null?j:"",10);Number.isFinite(R)&&(x=R),!x&&i&&(x=i.to-i.from+1);let D=x?new Uint8Array(x):new Uint8Array(0),M=!1,L=E=>{f==null||f.unsubscribe(),M=!0,Oo(E)},A=Xa(h,async function*({done:E,value:P}){if(m===0&&(this.lastRequestFirstBytes$.next(Vi()-v),this.firstBytesReceived.next()),h.aborted){f==null||f.unsubscribe();return}if(!E&&P){if(c&&x)D.set(P,m),m+=P.byteLength;else{let I=new Uint8Array(D.length+P.length);I.set(D),I.set(P,D.length),D=I,m+=P.byteLength}r==null||r(new DataView(D.buffer),m),yield y==null?void 0:y.read().then(A,L)}}.bind(this));yield y==null?void 0:y.read().then(A,L),f==null||f.unsubscribe();let B=Vi(),$={failed:M,requestStartedAt:v,requestEndedAt:B,duration:B-v};if(M)return p.error("endRequest",Dr($)),p.end(),null;if(m>0){let E=B-v,I=m/(E/1e3)*8/1024,w={bytes:m,speed:I,url:e};this.lastDownloadMetrics$.next(w)}return p.log("endRequest",Dr($)),p.end(),D.buffer}.bind(this));this.fetchByteRangeRepresentation=Xa(this.abortAllController.signal,async function*(e,t,i){var g;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,r),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!l)return null;let p=new DataView(l,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(g=e.indexRange)!=null?g:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(l,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;m=new DataView(S)}let v=t.parseSegments(m,h,f).map(S=>({networkStatus:"none",bufferStatus:"none",status:"none",time:S.time,byte:S.byte}));return{initMetadata:h,initDataView:new DataView(l),segments:v}}.bind(this));this.fetchTemplateRepresentation=Xa(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});if(!r)return null;let s=e.segments.map(n=>({...n,networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:s}}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s,Ja().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=Vo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new(Ja()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in Ja().navigator))return"unknown";let e=Ja().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,s=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(s=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=s),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,s),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),s=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(s===o&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch(t){this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:Cr.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=this.fetchTemplateRepresentation(e,i))!=null?n:null;default:UT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),this.tracer.end()}async doFetch(e,t){let i=await Je(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Cr.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Cr.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Cr.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Cr.FATAL,httpCode:i.status,UVBackendErrorCode:r});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Cr.FATAL,httpCode:i.status,UVBackendErrorCode:r})}}},Oo=a=>{if(!ot(a))throw a};var $d=_(pI(),1),LI=_(zt(),1),BI=_(AI(),1),VI=_(Ke(),1),Cd=_(Ei(),1);var RI=_(Le(),1),Md=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,RI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as EB,isNullable as CI}from"@vkontakte/videoplayer-shared/es2018";var MI=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var $I=a=>{var e;try{let t=IB(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(c=>{s[c[0]]=c.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:s,variants:n};return Object.keys(o).forEach(u=>{let c=o[u];(typeof c=="undefined"||c==="")&&delete o[u]}),o}return null}catch(t){return null}};function IB(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
172
172
|
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
173
173
|
(-(?<script>[a-z]{4}))?
|
|
174
174
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
175
175
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
176
176
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
177
177
|
(?:-(?<privateuse>(?:${e})))?
|
|
178
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var $I=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ut=(a,e)=>{let t=a;t=(0,Pd.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,MI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Pd.default)(t,n,(o,u)=>RI(s)?o:RI(u)?s:(0,CI.default)(s,parseInt(u,10),"0"))}return t},Oo=(a,e)=>{var D,k,V,M,q,G,H,E,P,I,x,F,O,ct,dt,Y,Se,ye,Te,Fe,It,Et,di,Gi,Yi,kp,Rp,$p,Mp,Cp,Lp,Dp,Bp,Vp,_p,Op,Np,Fp,qp,Up,jp,Hp,Qp,Wp,zp,Gp,Yp,Kp,Xp,Jp,Zp,eh,th,ih,rh,ah,sh,nh,oh,uh,lh;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(et=>{var Z,pi;return(pi=(Z=et.textContent)==null?void 0:Z.trim())!=null?pi:""}),o=(D=(0,LI.default)(n,0))!=null?D:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],p=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let g,S=s.getAttribute("mediaPresentationDuration"),T=[...s.getElementsByTagName("Period")],y=T.reduce((et,Z)=>({...et,[Z.id]:Z.children}),{}),w=T.reduce((et,Z)=>({...et,[Z.id]:Z.getAttribute("duration")}),{});S?g=$I(S):(0,Ad.default)(w).filter(et=>et).length&&!u?g=(0,Ad.default)(w).reduce((et,Z)=>{var pi;return et+((pi=$I(Z))!=null?pi:0)},0):f&&(g=parseInt(f,10));let R=0,L=(V=(k=s.getAttribute("profiles"))==null?void 0:k.split(","))!=null?V:[];for(let et of T.map(Z=>Z.id))for(let Z of y[et]){let pi=(M=Z.getAttribute("id"))!=null?M:"id"+(R++).toString(10),Wr=(q=Z.getAttribute("mimeType"))!=null?q:"",Eu=(G=Z.getAttribute("codecs"))!=null?G:"",wu=(H=Z.getAttribute("contentType"))!=null?H:Wr==null?void 0:Wr.split("/")[0],Sw=(P=(E=Z.getAttribute("profiles"))==null?void 0:E.split(","))!=null?P:[],ch=(x=kI((I=Z.getAttribute("lang"))!=null?I:""))!=null?x:{},Ys=(ct=(O=(F=Z.querySelector("Label"))==null?void 0:F.textContent)==null?void 0:O.trim())!=null?ct:void 0,yw=Z.querySelectorAll("Representation"),Tw=Z.querySelector("SegmentTemplate"),Iw=(Y=(dt=Z.querySelector("Role"))==null?void 0:dt.getAttribute("value"))!=null?Y:void 0,Ki=wu,ue={id:pi,language:ch.language,isDefault:Iw==="main",label:Ys,codecs:Eu,hdr:Ki==="video"&&xd(Eu),mime:Wr,representations:[]};for(let J of yw){let Nt=(Se=J.getAttribute("lang"))!=null?Se:void 0,Ks=(Te=(ye=Ys!=null?Ys:Z.getAttribute("label"))!=null?ye:J.getAttribute("label"))!=null?Te:void 0,Xs=(Et=(It=(Fe=J.querySelector("BaseURL"))==null?void 0:Fe.textContent)==null?void 0:It.trim())!=null?Et:"",hi=new URL(Xs||o,e).toString(),Ft=(di=J.getAttribute("mimeType"))!=null?di:Wr,Js=(Yi=(Gi=J.getAttribute("codecs"))!=null?Gi:Eu)!=null?Yi:"",Zs;if(wu==="text"){let qt=J.getAttribute("id")||"",en=((kp=ch.privateuse)==null?void 0:kp.includes("x-auto"))||qt.includes("_auto"),mi=J.querySelector("SegmentTemplate");if(mi){let zr={representationId:(Rp=J.getAttribute("id"))!=null?Rp:void 0,bandwidth:($p=J.getAttribute("bandwidth"))!=null?$p:void 0},tn=parseInt((Mp=J.getAttribute("bandwidth"))!=null?Mp:"",10)/1e3,rn=(Lp=parseInt((Cp=mi.getAttribute("startNumber"))!=null?Cp:"",10))!=null?Lp:1,Xi=parseInt((Dp=mi.getAttribute("timescale"))!=null?Dp:"",10),xu=(Bp=mi.querySelectorAll("SegmentTimeline S"))!=null?Bp:[],Ji=mi.getAttribute("media");if(!Ji)continue;let an=[],sn=0,nn="",Zi=0,Gr=rn,xe=0;for(let tt of xu){let fi=parseInt((Vp=tt.getAttribute("d"))!=null?Vp:"",10),ze=parseInt((_p=tt.getAttribute("r"))!=null?_p:"",10)||0,Ut=parseInt((Op=tt.getAttribute("t"))!=null?Op:"",10);xe=Number.isFinite(Ut)?Ut:xe;let bi=fi/Xi*1e3,jt=xe/Xi*1e3;for(let pt=0;pt<ze+1;pt++){let Ht=ut(Ji,{...zr,segmentNumber:Gr.toString(10),segmentTime:(xe+pt*fi).toString(10)}),er=(jt!=null?jt:0)+pt*bi,Kr=er+bi;Gr++,an.push({time:{from:er,to:Kr},url:Ht})}xe+=(ze+1)*fi,sn+=(ze+1)*bi}Zi=xe/Xi*1e3,nn=ut(Ji,{...zr,segmentNumber:Gr.toString(10),segmentTime:xe.toString(10)});let Yr={time:{from:Zi,to:1/0},url:nn},wt={type:"template",baseUrl:hi,segmentTemplateUrl:Ji,initUrl:"",totalSegmentsDurationMs:sn,segments:an,nextSegmentBeyondManifest:Yr,timescale:Xi};Zs={id:qt,kind:"text",segmentReference:wt,profiles:[],duration:g,bitrate:tn,mime:"",codecs:"",width:0,height:0,isAuto:en}}else Zs={id:qt,isAuto:en,kind:"text",url:hi}}else{let qt=(Fp=(Np=J.getAttribute("contentType"))!=null?Np:Ft==null?void 0:Ft.split("/")[0])!=null?Fp:wu,en=(Up=(qp=Z.getAttribute("profiles"))==null?void 0:qp.split(","))!=null?Up:[],mi=parseInt((jp=J.getAttribute("width"))!=null?jp:"",10),zr=parseInt((Hp=J.getAttribute("height"))!=null?Hp:"",10),tn=parseInt((Qp=J.getAttribute("bandwidth"))!=null?Qp:"",10)/1e3,rn=(Wp=J.getAttribute("frameRate"))!=null?Wp:"",Xi=(zp=J.getAttribute("quality"))!=null?zp:void 0,xu=rn?AI(rn):void 0,Ji=(Gp=J.getAttribute("id"))!=null?Gp:"id"+(R++).toString(10),an=qt==="video"?`${zr}p`:qt==="audio"?`${tn}Kbps`:Js,sn=`${Ji}@${an}`,nn=[...L,...Sw,...en],Zi,Gr=J.querySelector("SegmentBase"),xe=(Yp=J.querySelector("SegmentTemplate"))!=null?Yp:Tw;if(Gr){let wt=(Xp=(Kp=J.querySelector("SegmentBase Initialization"))==null?void 0:Kp.getAttribute("range"))!=null?Xp:"",[tt,fi]=wt.split("-").map(Ht=>parseInt(Ht,10)),ze={from:tt,to:fi},Ut=(Jp=J.querySelector("SegmentBase"))==null?void 0:Jp.getAttribute("indexRange"),[bi,jt]=Ut?Ut.split("-").map(Ht=>parseInt(Ht,10)):[],pt=Ut?{from:bi,to:jt}:void 0;Zi={type:"byteRange",url:hi,initRange:ze,indexRange:pt}}else if(xe){let wt={representationId:(Zp=J.getAttribute("id"))!=null?Zp:void 0,bandwidth:(eh=J.getAttribute("bandwidth"))!=null?eh:void 0},tt=parseInt((th=xe.getAttribute("timescale"))!=null?th:"",10),fi=(ih=xe.getAttribute("initialization"))!=null?ih:"",ze=xe.getAttribute("media"),Ut=(ah=parseInt((rh=xe.getAttribute("startNumber"))!=null?rh:"",10))!=null?ah:1,bi=ut(fi,wt);if(!ze)throw new ReferenceError("No media attribute in SegmentTemplate");let jt=(sh=xe.querySelectorAll("SegmentTimeline S"))!=null?sh:[],pt=[],Ht=0,er="",Kr=0;if(jt.length){let on=Ut,it=0;for(let tr of jt){let ht=parseInt((nh=tr.getAttribute("d"))!=null?nh:"",10),gi=parseInt((oh=tr.getAttribute("r"))!=null?oh:"",10)||0,un=parseInt((uh=tr.getAttribute("t"))!=null?uh:"",10);it=Number.isFinite(un)?un:it;let Pu=ht/tt*1e3,Au=it/tt*1e3;for(let ln=0;ln<gi+1;ln++){let ww=ut(ze,{...wt,segmentNumber:on.toString(10),segmentTime:(it+ln*ht).toString(10)}),dh=(Au!=null?Au:0)+ln*Pu,xw=dh+Pu;on++,pt.push({time:{from:dh,to:xw},url:ww})}it+=(gi+1)*ht,Ht+=(gi+1)*Pu}Kr=it/tt*1e3,er=ut(ze,{...wt,segmentNumber:on.toString(10),segmentTime:it.toString(10)})}else if(T0(g)){let it=parseInt((lh=xe.getAttribute("duration"))!=null?lh:"",10)/tt*1e3,tr=Math.ceil(g/it),ht=0;for(let gi=1;gi<tr;gi++){let un=ut(ze,{...wt,segmentNumber:gi.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+it},url:un}),ht+=it}Kr=ht,er=ut(ze,{...wt,segmentNumber:tr.toString(10),segmentTime:ht.toString(10)})}let Ew={time:{from:Kr,to:1/0},url:er};Zi={type:"template",baseUrl:hi,segmentTemplateUrl:ze,initUrl:bi,totalSegmentsDurationMs:Ht,segments:pt,nextSegmentBeyondManifest:Ew,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!qt||!Ft)continue;let Yr={video:"video",audio:"audio",text:"text"}[qt];if(!Yr)continue;Ki||(Ki=Yr),Zs={id:sn,kind:Yr,segmentReference:Zi,profiles:nn,duration:g,bitrate:tn,mime:Ft,codecs:Js,width:mi,height:zr,fps:xu,quality:Xi}}ue.language||(ue.language=Nt),ue.label||(ue.label=Ks),ue.mime||(ue.mime=Ft),ue.codecs||(ue.codecs=Js),ue.hdr||(ue.hdr=Ki==="video"&&xd(Js)),ue.representations.push(Zs)}if(Ki){let J=r[Ki].find(Nt=>Nt.id===ue.id);if(J&&ue.representations.every(Nt=>Nt.segmentReference.type==="template"))for(let Nt of J.representations){let Ks=ue.representations.find(Ft=>Ft.id===Nt.id);if(!Ks)continue;let Xs=Ks.segmentReference,hi=Nt.segmentReference;hi.segments.push(...Xs.segments),hi.nextSegmentBeyondManifest=Xs.nextSegmentBeyondManifest}else r[Ki].push(ue)}}return{duration:g,streams:r,baseUrls:n,live:v}};var Fo=_(Ke(),1),kd=_(De(),1);import{assertNever as qo}from"@vkontakte/videoplayer-shared/es2018";var No=a=>{let{webmDecodingInfo:e}=B.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){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:qo(a)}},DI=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...No(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(B.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...No(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...No(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...No(a),...s,"HLS","HLS_ONDEMAND"];default:qo(e)}if(B.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:qo(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},BI=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=B.device.isMac&&B.browser.isSafari;if(B.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:qo(a)}else B.video.nativeHlsSupported&&!u&&!B.browser.isChromiumBased?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Rd=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Uo=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Fo.default)(t.value.split("."),0)}for(let t of a){let i=(0,Fo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Fo.default)(e.value.split("."),0)},jo=a=>{let e=a.map(i=>Lr(i)),{codecs:t}=B.video;return x0().filter(i=>{if((0,kd.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},Ho=a=>{let e=a.map(i=>Lr(i)),{codecs:t}=B.video;return P0().filter(i=>{if((0,kd.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Lr=a=>a.split(".")[0].replace("0",""),x0=()=>["av1","vp9","hev1","avc1"],P0=()=>["opus","mp4a"];var YI=_(Ke(),1);var A0=(a,e={})=>{let i=e.timeout||1,r=performance.now();return de.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},k0=a=>de.clearTimeout(a),VI=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),_I=!VI(de.requestIdleCallback)||!VI(de.cancelIdleCallback),Vi=_I?A0:de.requestIdleCallback,_i=_I?k0:de.cancelIdleCallback;import{abortable as Bd,assertNonNullable as Tt,ErrorCategory as Y0,fromEvent as K0,getExponentialDelay as X0,getWindow as GI,isHigher as J0,isNonNullable as le,isNullable as ge,once as Z0,Subject as eV,Subscription as tV,ValueSubject as Is}from"@vkontakte/videoplayer-shared/es2018";var OI=_(Ke(),1);var Qo=a=>a.valid,W=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===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}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 Dr=class extends W{};import{assertNever as R0}from"@vkontakte/videoplayer-shared/es2018";var Ka=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:R0(e)}}};var Xa=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var Ja=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ie=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Za=class extends ie{constructor(e,t){super(e,t),this.valid&&(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 es=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ts=class extends W{constructor(e,t){super(e,t),this.data=this.content}};var Oi=class extends ie{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var is=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var rs=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var as=class extends ie{constructor(e,t){if(super(e,t),!this.valid)return;switch(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 ss=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var ns=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var os=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var us=class extends ie{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 ls=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cs=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ds=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var ps=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var hs=class extends ie{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 ms=class extends ie{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 fs=class extends ie{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 bs=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var gs=class extends ie{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var vs=class extends W{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var M0={ftyp:Xa,moov:Ja,mvhd:Za,moof:es,mdat:ts,sidx:Oi,trak:is,mdia:os,mfhd:ds,tkhd:us,traf:ps,tfhd:hs,tfdt:ms,trun:fs,minf:ls,sv3d:rs,st3d:as,prhd:ss,proj:cs,equi:ns,uuid:Ka,stbl:bs,stsd:gs,avc1:vs,unknown:Dr},Mt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!Qo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=M0[e];return i?new i(t,new a):new Dr(t,new a)}};var ei=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;Qo(t)&&((s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var L0=new TextDecoder("ascii"),D0=a=>L0.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",B0=a=>{let e=new Oi(a,new Mt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},V0=(a,e)=>{let i=new Mt().parse(a),r=new ei(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,c)},_0=a=>{let t=new Mt().parse(a),i=new ei(t),r={},s=i.findAll("uuid"),n=(0,OI.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},O0=a=>{var r;let t=new Mt().parse(a);return(r=new ei(t).find("sidx"))==null?void 0:r.timescale},N0=(a,e)=>{let i=new Mt().parse(a),s=new ei(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},F0=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Mt().parse(a),r=new ei(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},NI={validateData:D0,parseInit:F0,getIndexRange:()=>{},parseSegments:B0,parseFeedableSegmentChunk:V0,getChunkEndTime:N0,getServerLatencyTimestamps:_0,getTimescaleFromIndex:O0};var ys=_(De(),1);import{assertNonNullable as $d,isNonNullable as jI,isNullable as U0}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as q0}from"@vkontakte/videoplayer-shared/es2018";var FI={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"}},qI=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ss(a,t),r=i in FI,s=r?FI[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,d=Ss(u),c=l*2**((o-1)*8)+d,p=t+o,h;return p+c>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},Ss=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},lt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ss(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:q0(e)}},Ni=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=qI(i);if(!e(r))return;r.type==="master"&&Ni(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},UI=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=qI(a);return Ni(r.value,({tag:s,type:n,value:o})=>(s===17143?e=lt(o,n):s===17026?t=lt(o,n):s===17029&&(i=lt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var HI=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],j0=[231,22612,22743,167,171,163,160,175],H0=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return Ni(a,({tag:p,type:h,value:m,valueSize:f})=>{if(p===21419){let v=lt(m,h);l=Ss(v)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+f):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=lt(m,h):p===17545?r=lt(m,h):p===21420&&l===475249515?u=lt(m,h):p===374648427?Ni(m,({tag:v,type:g,value:S})=>v===30321?(d=lt(S,g)===1,!1):!0):s&&n&&(0,ys.default)(HI,p)&&(o=!0),!o}),$d(e,"Failed to parse webm Segment start"),$d(t,"Failed to parse webm Segment end"),$d(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}}}},Q0=a=>{if(U0(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},W0=(a,e)=>{let t=!1,i=!1,r=o=>jI(o.time)&&jI(o.position),s=[],n;return Ni(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=lt(l,u));break;case 183:break;case 241:n&&(n.position=lt(l,u));break;default:t&&(0,ys.default)(HI,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[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}}})},z0=a=>{let e=0,t=!1;try{Ni(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ys.default)(j0,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,ys.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},QI={validateData:UI,parseInit:H0,getIndexRange:Q0,parseSegments:W0,parseFeedableSegmentChunk:z0};var Fi=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return QI;case"mp4":return NI}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Md=_(Ke(),1);import{videoSizeToQuality as G0}from"@vkontakte/videoplayer-shared/es2018";var ti=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:G0({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Ts=({id:a,bitrate:e})=>({id:a,bitrate:e}),WI=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),zI=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Cd=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Md.default)(i.split("."),0),isDefault:r}),Ld=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Md.default)(r.split("."),0)}),Dd=a=>"url"in a,Qe=a=>a.type==="template";var Br=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,manifest:o}){this.error$=new eV;this.playingRepresentation$=new Is(void 0);this.playingRepresentationInit$=new Is(void 0);this.currentSegmentLength$=new Is(0);this.onLastSegment$=new Is(!1);this.fullyBuffered$=new Is(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new te;this.downloadAbortController=new te;this.subscription=new tV;this.startWith=Bd(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Tt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=Fi(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Tt(i,"No init buffer for starting representation"),Tt(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)}.bind(this));this.switchTo=Bd(this.destroyAbortController.signal,async function*(e,t=!0){var c;if(ge(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);Tt(r,`No such representation ${e}`),Tt(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),n=this.segments.get(r.id);Tt(s,"No init buffer for switching representation"),Tt(n,"No segments for switching representation");let o=(c=this.getCurrentPosition())!=null?c:0,u=p=>p.segment.networkStatus!=="downloaded"||p.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,l=p=>{let h=this.representations.get(p.representationId);return Tt(h,"No itemRepresentation for previous track before switch"),p.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(h,r)},d=p=>t?u(p)&&l(p):u(p);this.bufferPlaybackQueue.filter(d).forEach(p=>p.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(p=>!d(p)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=Bd(this.downloadAbortController.signal,async function*(){let e=X0(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=GI();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add(K0(i,"online").pipe(Z0()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));var u;this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=n,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=(u=o==null?void 0:o.baseUrls)!=null?u:[],this.representations=new Map(i.map(l=>[l.id,l]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){ge(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return le(t)&&le(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){var s,n;let t=(n=(s=this.downloadingRepresentationId)!=null?s:this.playingRepresentationId)!=null?n:"",i=this.segments.get(t),r=i==null?void 0:i.find(o=>o.time.from<=e&&o.time.to>=e);return r==null?void 0:r.time.from}getRepresentationInitialTime(){var t;if(ge(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return((t=e==null?void 0:e[0].time.from)!=null?t:0)/1e3}calculateDurationFromSegments(){var t;if(ge(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,YI.default)(e,-1))==null?void 0:t.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=GI();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.__polyfill_cancelIdleCallback_l6350iae348i)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_l6350iae348i(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=ti(e),s=ti(t);i=le(r)&&le(s)&&J0(s.quality,r.quality)}else if(this.kind==="audio"){let r=Ts(e),s=Ts(t);i=le(r==null?void 0:r.bitrate)&&le(s==null?void 0:s.bitrate)&&s.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new te,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,this.maintainNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,Vi(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),s;this.initData.has(e.id)&&this.segments.has(e.id)?s=Promise.resolve():le(r)?s=r:s=this.loadInit(e,t,i),await s}async loadInit(e,t="auto",i=!1){var r;try{let s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s);this.initDataPromises.set(e.id,n);let{initMetadata:o,initDataView:u,segments:l}=(r=await n)!=null?r:{};if(this.initDataPromises.delete(e.id),ge(u)||ge(l))return;o&&this.parsedInitData.set(e.id,o);let d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d),this.segments.set(e.id,l),this.failedDownloads=0}catch(s){i&&this.error$.next({id:"LoadInits",category:Y0.WTF,message:"loadInit threw",thrown:s})}}async maintainNativeBuffer(){var o;let e=this.getCurrentPosition();if(ge(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(u=>this.withinInterval(e,u.segment.time)),i=this.bufferPlaybackQueue.find(u=>u.segment.bufferStatus!=="fed"),r=this.initData.get((o=i==null?void 0:i.representationId)!=null?o:""),s=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;le(r)&&le(i)&&le(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),le(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,n):await this.appendSegmentPartially(i,n)),le(s)&&this.withinRemoveInterval(e,s.segment.time)&&await this.removeSegment(s,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){Tt(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(ge(t)||ge(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(n=>e>=n.time.from&&e<n.time.to);le(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let s=this.selectItemsToLoad();await this.loadItems(s,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){var r;let t=this.segments.get((r=this.downloadingRepresentationId)!=null?r:"");if(ge(t)||t.length===0)return;let i=t[(t==null?void 0:t.length)-1];ge(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){Tt(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;le(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&s>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;s-=u-o,r++}return n}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return le(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return le(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return le(e)?e-i>t:!1}async appendSegmentFully(e,t){if(ge(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if(ge(e.segment.data)||ge(e.segment.loadedBytes)||ge(e.segment.feedingBytes)||ge(e.segment.fedBytes)||ge(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),s=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;s!=null&&s.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=s.byteLength,await this.nativeBufferManager.append(s,t)&&(e.segment.fedBytes+=s.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,s=(r-i)/4;await this.nativeBufferManager.remove(0,r-s,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||le(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let s=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)le(o.size)&&s>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())le(o.size)&&s>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size)}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())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as iV,isNonNullable as rV,isNullable as KI,now as XI}from"@vkontakte/videoplayer-shared/es2018";var Wo=class extends Br{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(s,{...n,priority:i}),this.lastDataObtainedTimestampMs=XI(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),ot(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,s=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=s);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(Me(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=XI(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:s?s.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:iV.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:s,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||KI(o)||KI(r)||n.aborted))for(let u of e){let{segment:l}=u,d=l.byte.from-r,c=l.byte.to-r,p=c-d+1,h=d<s,m=c<=s;l.size=p,h&&(l.networkStatus==="downloading"&&l.bufferStatus==="none"&&m?(l.data=new DataView(t.buffer,t.byteOffset+d,p),this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u),l.loadedBytes=Math.min(p,s-d),await this.onDownloadItem(u)):rV(l.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&l.networkStatus==="downloading"&&(l.loadedBytes=Math.min(p,s-d),m&&(this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u)),l.loadedBytes>l.feedingBytes&&(l.data=new DataView(t.buffer,t.byteOffset+d,l.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(Me(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as aV,isNullable as Vd,now as JI}from"@vkontakte/videoplayer-shared/es2018";var Vr=class extends Br{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(s,{...n,priority:i});if(this.lastDataObtainedTimestampMs=JI(),Vd(o))return;let u=e[0],l=new DataView(o);u.segment.size=l.byteLength,u.segment.loadedBytes=l.byteLength,u.segment.data=l,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),ot(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(n,o)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=JI(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:aV.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!Me(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:s}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||Vd(u)||Vd(o.feedingBytes)||o.networkStatus!=="downloading"||s.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(n)))}updateRepresentationBaseUrl(e,t){if(!Me(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var _d=_(ja(),1),eE=_(Ke(),1);import{assertNonNullable as sV,ErrorCategory as nV,isNullable as Ct,ValueSubject as ZI}from"@vkontakte/videoplayer-shared/es2018";var zo=class extends Vr{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new ZI(0);this.currentLowLatencySegmentLength$=new ZI(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=s.isActiveLowLatency}updateManifest(t){var r,s,n;if(!t||[...this.segments.values()].every(o=>!o.length))return;let i=(0,_d.default)(t.streams[this.kind],o=>o.representations);for(let o of i){if(Ct(o)||!Me(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,networkStatus:"none",bufferStatus:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(s=(0,eE.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>c>=h.time.from+l&&c<=h.time.to+l);if(p===-1){let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...d,...h])}this.representations.set(o.id,o)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;sV(t);let i=this.segments.get(t);if(i!=null&&i.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t==null?void 0:t.streams[this.kind],r=(0,_d.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if(Ct(r))return;let s=this.segments.get(r.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}getRepresentationInitialTime(){var r;if(Ct(this.playingRepresentationId))return 0;let t=(r=this.representations.get(this.playingRepresentationId))==null?void 0:r.segmentReference;return Ct(t)||!Me(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),Ct(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:s,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);s&&n&&this.currentLiveSegmentServerLatency$.next(n-s),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){var n;let i=t.segment.data,r=(n=this.representations.get(t.representationId))==null?void 0:n.segmentReference;if(Ct(t.segment.data)||Ct(r)||!Me(r))return;let s=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:o}=r;t.segment.time.to=s.getChunkEndTime(i,o)}}updateLowLatencyLive(t){var r;let i=0;for(let s of this.representations.values()){let n=s.segmentReference;if(!Me(n))return;let o=(r=this.segments.get(s.id))!=null?r:[],u=o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.from));if(u!=null&&u.isCurrentLowLatency&&(u.time.to=t.segment.time.to,i=u.time.to-u.time.from,u.isCurrentLowLatency=!1),!!!o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let d=Math.round(t.segment.time.to*n.timescale/1e3).toString(10),c=ut(n.segmentTemplateUrl,{segmentTime:d});o.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:c,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){var s;try{let n=this.tuning.dash.useFetchPriorityHints?i:"auto",o=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,n);this.initDataPromises.set(t.id,o);let{initMetadata:u,initDataView:l,segments:d}=(s=await o)!=null?s:{};if(this.initDataPromises.delete(t.id),Ct(l)||Ct(d))return;u&&this.parsedInitData.set(t.id,u);let c=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,c);let p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(t.id,p),this.failedDownloads=0}catch(n){r&&this.error$.next({id:"LoadInits",category:nV.WTF,message:"loadInit threw",thrown:n})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[],n=0,o=i.length-1;do s.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[s[0]]:s}};var Es=class{static getBufferManager(e,t,i,r){var s;return(s=r.manifest)!=null&&s.live?new zo(e,t,i,r):Me(i[0].segmentReference)?new Vr(e,t,i,r):new Wo(e,t,i,r)}};import{ErrorCategory as lV,fromEvent as cV,isNullable as _r,Subject as dV,Subscription as pV}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as oV,ErrorCategory as tE,Subject as iE}from"@vkontakte/videoplayer-shared/es2018";var uV=18,rE=!1;try{rE=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=uV}catch(a){console.error(a)}var Od=class{constructor(e,t=!1){this.bufferFull$=new iE;this.error$=new iE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!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.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:tE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};rE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!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.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:tE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:oV(t)}}},aE=Od;var ii=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var ws=class{constructor(e){this.error$=new dV;this.subscription=new pV;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new aE(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add(cV(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:lV.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if(_r(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&(i=await this.sourceBufferTaskQueue.remove(r.from,r.to,e));return i}warmUpMediaSource(){!_r(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(_r(this.sourceBuffer)||!ee(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return _r(this.sourceBuffer)||!ee(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||_r(e)?0:ii(this.sourceBuffer.buffered,e)}async abortBuffer(e){return _r(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){var e;if(this.subscription.unsubscribe(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null}};var vV=["timeupdate","progress","play","seeked","stalled","waiting"],oE=["timeupdate","progress","loadeddata","playing","seeked"],Yo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new nE;this.subscriptionRemovable=new gV;this.representationSubscription=new nE;this.forceEnded$=new ai;this.destroyController=new te;this.state$=new j("none");this.currentVideoRepresentation$=new re(void 0);this.currentVideoRepresentationInit$=new re(void 0);this.currentAudioRepresentation$=new re(void 0);this.currentVideoSegmentLength$=new re(0);this.currentAudioSegmentLength$=new re(0);this.error$=new ai;this.manifestRequested=new ai;this.manifestReceived=new ai;this.firstBytesRequested=new ai;this.firstBytesReceived=new ai;this.lastConnectionType$=new re(void 0);this.lastConnectionReused$=new re(void 0);this.lastRequestFirstBytes$=new re(void 0);this.currentLiveTextRepresentation$=new re(null);this.isLive$=new re(!1);this.isActiveLive$=new re(!1);this.isLowLatency$=new re(!1);this.liveDuration$=new re(0);this.liveSeekableDuration$=new re(0);this.liveAvailabilityStartTime$=new re(0);this.liveStreamStatus$=new re(void 0);this.currentBuffer$=new re({from:0,to:0});this.bufferLength$=new re(0);this.nativeBufferLength$=new re(0);this.liveLatency$=new re(void 0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.currentStallDuration$=new re(0);this.videoLastDataObtainedTimestamp$=new re(0);this.fetcherRecoverableError$=new ai;this.fetcherError$=new ai;this.initRepresentations=sE(this.destroyController.signal,async function*(e,t,i){var s;this.tracer.log("initRepresentationsStart",Go({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={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};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),Lt(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?(s=this.audioBufferManager)==null?void 0:s.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=sE(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Ps(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:qi.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Bo({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.initTracerSubscription()}async initManifest(e,t,i){var r;this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:qi.PARSER,message:"No playable video representations"})}initBuffer(){var t,i;Lt(this.element),this.state$.setState("running"),this.subscription.add(As(...vV.map(r=>Ui(this.element,r)),Ui(xs(),"online")).subscribe(()=>this.tick(),r=>this.error$.next({id:"DashVKPlayer",category:qi.WTF,message:"Internal logic error",thrown:r})));let e=[...(i=(t=this.source)==null?void 0:t.activeSourceBuffers)!=null?i:[]];this.subscription.add(As(...e.map(r=>Ui(r,"updateend"))).subscribe(r=>this.reinitDecoderIfNeeded())),this.subscription.add(Ui(this.element,"waiting").subscribe(r=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=fV(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),s=>this.error$.next({id:"StallWatchdogCallback",category:qi.NETWORK,message:"Can't restore DASH after stall.",thrown:s})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}async seek(e,t=!1){var r,s,n,o;Lt(this.element),Lt(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await((o=this.audioBufferManager)==null?void 0:o.seek(i)),this.tracer.log("seek",Go({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){ri(this.element)&&ri(this.source)&&ri(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(i=>i.warmUpMediaSource())}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}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),this.nativeBufferManagers.forEach(r=>r.destroy()),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&xs().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),ri(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){var e;return((e=this.source)==null?void 0:e.readyState)!=="open"}async reinitDecoderIfNeeded(e=!1){var r,s;let t=(s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[];if(Ps(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(n=>i>=n.from&&i<=n.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){Lt(this.element),Lt(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",Go(i))}isStallExceeded(e){var p,h,m,f,v,g,S,T;let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=bV(),s=100,n=(h=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?h:0;this.videoLastDataObtainedTimestamp$.next(n);let o=(f=(m=this.audioBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?f:0,u=(g=(v=this.videoBufferManager)==null?void 0:v.getForwardPlaybackBufferDuration())!=null?g:0,l=(T=(S=this.audioBufferManager)==null?void 0:S.getForwardPlaybackBufferDuration())!=null?T:0,d=ri(this.videoBufferManager)&&u<s&&r-n>i,c=ri(this.audioBufferManager)&&l<s&&r-o>i;return(d||c)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Ps(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",Go(i)),i}parseManifest(e){var t;try{return Oo(e!=null?e:"",this.manifestUrlString)}catch(i){let r=(t=Mo(e))!=null?t:{id:"ManifestParsing",category:qi.PARSER,message:"Failed to parse MPD manifest",thrown:i};this.error$.next(r)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,l)=>{var d,c,p,h;return!!((c=(d=this.element)==null?void 0:d.canPlayType)!=null&&c.call(d,u)&&((h=(p=je())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${l}"`))||o==="text")},r,s;for(let o of["video","audio"]){let l=e.streams[o].filter(({mime:c,codecs:p})=>i(o,c,p));t[o]=l;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:p})=>p);o==="audio"&&(s=Ho(c),d=s[0]),o==="video"&&(r=jo(c),this.forceVideoCodec&&(0,uE.default)(r,this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[o]=l.filter(({codecs:p})=>Lr(p)===d))}else{let c=new Set(l.map(({codecs:p})=>p));d=Uo(c),d&&(t[o]=l.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let c=this.tuning.preferHDR,p=t.video.some(m=>m.hdr),h=t.video.some(m=>!m.hdr);B.display.isHDR&&c&&p?t.video=t.video.filter(m=>m.hdr):h&&(t.video=t.video.filter(m=>!m.hdr))}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:s}),n}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){Lt(this.manifest),Lt(this.element);let s=l=>{this.representationSubscription.add(Ui(l,"error").pipe(Nd(d=>{var c;return!!((c=this.element)!=null&&c.played.length)})).subscribe(d=>{this.error$.next({id:"VideoSource",category:qi.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=An();let n=xs().document,o=n.createElement("source");if(s(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),lr())if(r){let l=n.createElement("source");s(l),l.type="application/x-mpegurl",l.src=r.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((l,d)=>[...l,...d.representations],[]);if(this.videoNativeBufferManager=new ws(this.source),this.videoBufferManager=Es.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],ri(i)){this.audioNativeBufferManager=new ws(this.source);let l=this.manifest.streams.audio.reduce((d,c)=>[...d,...c.representations],[]);this.audioBufferManager=Es.getBufferManager("audio",this.audioNativeBufferManager,l,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}async waitStreamToOpen(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;await new Promise(t=>{var i;e&&(this.timeoutSourceOpenId=xs().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:qi.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(i=this.source)==null||i.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&xs().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(As(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),Lt(this.videoBufferManager),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.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add(As(...oE.map(e=>Ui(this.element,e))).pipe(Fd(e=>{var t;return(t=this.videoBufferManager)==null?void 0:t.getPlaybackBufferState()}),Nd(ri),Fd(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(As(...oE.map(e=>Ui(this.element,e))).pipe(Fd(e=>{var t,i,r,s;return Math.max((i=(t=this.videoBufferManager)==null?void 0:t.getForwardPlaybackBufferDuration())!=null?i:0,(s=(r=this.audioBufferManager)==null?void 0:r.getForwardPlaybackBufferDuration())!=null?s:0)}),hV()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(Nd(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=mV(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){var r,s,n;if(Ps(this.element)||Ps(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=((s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[]).find(o=>e>=o.from&&e<=o.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await((n=this.audioBufferManager)==null?void 0:n.maintain(e))}};import{assertNonNullable as Ko,combine as SV,ErrorCategory as yV,filter as qd,filterChanged as TV,fromEvent as IV,isNonNullable as EV,map as Ud,merge as ks}from"@vkontakte/videoplayer-shared/es2018";var Xo=class extends Yo{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){var t;Ko(this.manifest),Ko(this.source);let e=[(t=this.manifest.duration)!=null?t:0,...(0,jd.default)((0,jd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],i=>i.representations),i=>{let r=[];return i.duration&&r.push(i.duration),Me(i.segmentReference)&&i.segmentReference.totalSegmentsDurationMs&&r.push(i.segmentReference.totalSegmentsDurationMs),r})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){var i,r;Ko(this.element);let t=this.element.currentTime*1e3;await Promise.all([(i=this.videoBufferManager)==null?void 0:i.maintain(t),(r=this.audioBufferManager)==null?void 0:r.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){Ko(this.element);let e=ks(IV(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(qd(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(ks(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=ks(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe(Ud(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=ks(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe(Ud(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=SV({allBuffersFull:e,someBufferEnded:t}).pipe(TV(),Ud(({allBuffersFull:s,someBufferEnded:n})=>s&&n),qd(s=>s)),r=()=>{var s;try{(s=this.source)==null||s.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:yV.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}};this.representationSubscription.add(ks(this.forceEnded$,i).pipe(qd(s=>EV(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var Or=class extends Ua{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe(wV()).subscribe(s=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:c}])=>c.id===s);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,l=this.params.desiredState.videoStream.getTransition();l&&l.to&&l.to.id===u.id&&this.params.desiredState.videoStream.setState(l.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(Io(u));let d=this.player.calculateDurationFromSegments();d&&this.params.output.duration$.next(d/1e3)},r))}getPlayer(){return new Xo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{assertNever as KV,assertNonNullable as XV,combine as JV,debounce as ZV,ErrorCategory as yE,filter as tp,filterChanged as _s,fromEvent as e_,isNonNullable as TE,isNullable as t_,map as Os,merge as Ns,observableFrom as lu,once as IE,Subscription as i_,throttle as r_}from"@vkontakte/videoplayer-shared/es2018";var SE=_(De(),1),Zd=_(ja(),1);var si=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as Kd,assertNonNullable as qr,combine as Ur,ErrorCategory as Ze,filter as nu,filterChanged as Ds,flattenObject as Bs,fromEvent as Bt,getTraceSubscriptionMethod as OV,interval as Xd,isNonNullable as Vs,isNullable as gE,map as jr,merge as Wi,now as Jd,Subject as Vt,Subscription as vE,SubscriptionRemovable as NV,tap as FV,throttle as qV,ValueSubject as ae}from"@vkontakte/videoplayer-shared/es2018";var Zo=_(De(),1),Hi=_(Ke(),1),eu=_(ja(),1);var hE=_(Lc(),1);import{assertNever as xV,ErrorCategory as lE,Subject as cE}from"@vkontakte/videoplayer-shared/es2018";var PV=18,dE=!1;try{dE=B.browser.isSafari&&!!B.browser.safariVersion&&B.browser.safariVersion<=PV}catch(a){console.error(a)}var Hd=class{constructor(e,t=!1){this.bufferFull$=new cE;this.error$=new cE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!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.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:lE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};dE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!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.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:lE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:xV(t)}}},pE=Hd;var Qd=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as ni,assertNonNullable as Ce,ErrorCategory as Dt,fromEvent as Wd,getExponentialDelay as zd,isHigher as AV,isNonNullable as oi,isNullable as pe,now as Jo,once as kV,Subject as RV,Subscription as $V,ValueSubject as ji}from"@vkontakte/videoplayer-shared/es2018";var Rs=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ji(0);this.currentLowLatencySegmentLength$=new ji(0);this.currentSegmentLength$=new ji(0);this.onLastSegment$=new ji(!1);this.fullyBuffered$=new ji(!1);this.playingRepresentation$=new ji(void 0);this.playingRepresentationInit$=new ji(void 0);this.error$=new RV;this.gaps=[];this.subscription=new $V;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new te;this.switchAbortController=new te;this.destroyAbortController=new te;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=ni(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ce(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new pE(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(Wd(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Wd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Dt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ee(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Qd(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),s=this.parsedInitData.get(t.id);Ce(i,"No init buffer for starting representation"),Ce(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=ni(this.destroyAbortController.signal,async function*(e,t=!1){if(!ee(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ce(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(pe(s)||pe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ce(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ee(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();oi(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=ni(this.destroyAbortController.signal,async function*(e,t=!1){if(!ee(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ce(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(pe(s)||pe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ce(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ee(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();oi(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=ni(this.destroyAbortController.signal,async function*(e){var u;let t=(0,eu.default)(e,l=>l.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let l of this.representations.keys()){let d=t.find(h=>h.id===l);d&&this.representations.set(l,d);let c=this.representations.get(l);if(!c||!Qe(c.segmentReference)){this.isSeekingLive=!1;return}let p=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,p)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);Ce(r,`Representation not found by id ${i}`);let s=this.segments.get(i);Ce(s,"No segments for starting representation");let n=this.initData.get(i);if(Ce(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.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){!ee(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new te,ni(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Ce(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(pe(o)||pe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Ce(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ee(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();oi(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(){!pe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new te,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var p;if(pe(e)||pe(this.downloadingRepresentationId)||pe(this.playingRepresentationId)||pe(this.sourceBuffer)||!ee(this.mediaSource,this.sourceBuffer)||oi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(Ce(t,`No such representation ${this.downloadingRepresentationId}`),Ce(i,`No such representation ${this.playingRepresentationId}`),pe(r)||pe(s))return;let n=r.find(h=>e>=h.time.from&&e<h.time.to);oi(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=this.getForwardBufferDuration(e),m=ti(i),f=ti(t),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&oi(m)&&oi(f)&&AV(m.quality,f.quality),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(v||g?o+=Math.min(h,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=(p=[...this.segments.entries()].map(([y,w])=>{let R=w.find(L=>e>=L.time.from&&e<L.time.to);return{representationId:y,status:R==null?void 0:R.status}}).find(y=>y.status==="fed"))==null?void 0:p.representationId;T&&(this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Qd(this.sourceBuffer.buffered)>=this.bufferLimit){let h=this.getForwardBufferDuration(e),m=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,h<m).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Zo.default)(d,n))h="high";else{let m=(0,Hi.default)(d,0);m&&m.time.from-n.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(d,t,h).catch(m=>{this.handleAsyncError(m,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,Hi.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;oi(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=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,eu.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,s;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,eu.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!Qe(n.segmentReference))return;let o=n.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),u=100,l=(i=this.segments.get(n.id))!=null?i:[],d=(s=(r=(0,Hi.default)(l,-1))==null?void 0:r.time.to)!=null?s:0,c=o==null?void 0:o.findIndex(p=>d>=p.time.from+u&&d<=p.time.to+u);if(c===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=o.slice(c+1);this.segments.set(n.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ce(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,Hi.default)(e,-1))==null?void 0:t.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Qe(s))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*s.timescale/1e3).toString(10),d=ut(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let 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&&_i&&_i(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&_i&&_i(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=this.getForwardBufferDuration(i),s=e.findIndex(({status:p,time:{from:h,to:m}},f)=>{let v=h<=i&&m>=i,g=h>i||v||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+S||r<S&&m-h>=S||m<=i+S;return(p==="none"||p==="partially_ejected"&&g&&T&&this.sourceBuffer&&ee(this.mediaSource,this.sourceBuffer)&&!(si(this.sourceBuffer.buffered,h)&&si(this.sourceBuffer.buffered,m)))&&g&&T});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=d||u<=c);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){Qe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ni(o,async function*(){let d=zd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Jo(),!d)return;let c=new DataView(d),p=Fi(t.mime);if(!isFinite(r.segment.time.to)){let f=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(c,f)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),ot(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())Qe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ni(n,async function*(){let u=zd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Wd(window,"online").pipe(kV()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Jo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ot(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Qe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Hi.default)(e,0).byte.from,to:(0,Hi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Jo(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Dt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Qe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Jo();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Dt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Zo.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!ee(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Fi(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!ee(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)continue;if(s.aborted){await n();continue}let d=l.byte.from-i,c=l.byte.to-i,p=c-d+1,h=d<r,m=c<=r;if(!h)continue;let f=Fi(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?v:f.parseFeedableSegmentChunk(v);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(pe(this.sourceBuffer)||!ee(this.mediaSource,this.sourceBuffer))){!this.isLive&&B.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(si(this.sourceBuffer.buffered,e.segment.time.from,100)&&si(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Dt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Dd(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Vi(()=>(0,hE.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?ni(this.destroyAbortController.signal,async function*(){let u=zd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Fi(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async u=>{if(!u)return;let{init:l,dataView:d,segments:c}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let h=c;this.isLive&&Qe(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,u=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Dt.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!ee(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||pe(e))return!1;let r=[],s=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:p}=u[d],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,p):l.push(u[d])}return l},o=u=>{var d;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Dd(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=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 p of this.segments.values())for(let h of p)(0,Zo.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!ee(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||!ee(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||!ee(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||pe(e)?0:ii(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ee(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let o=s.start(n)*1e3,u=s.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!ee(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.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}),this.gapDetectionIdleCallback=Vi(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:Dt.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(pe(this.sourceBuffer)||!ee(this.mediaSource,this.sourceBuffer)||pe(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(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:Dt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as $s,assertNever as mE,fromEvent as fE,merge as MV,now as Ms,Subject as Nr,ValueSubject as Gd,flattenObject as Fr,ErrorCategory as Cs,SubscriptionRemovable as CV}from"@vkontakte/videoplayer-shared/es2018";var iu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new Nr;this.firstBytesManifest$=new Nr;this.firstBytesRequested$=new Nr;this.firstBytesReceived$=new Nr;this.lastConnectionType$=new Gd(void 0);this.lastConnectionReused$=new Gd(void 0);this.lastRequestFirstBytes$=new Gd(void 0);this.recoverableError$=new Nr;this.error$=new Nr;this.abortAllController=new te;this.subscription=new CV;this.fetchManifest=$s(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Lo(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(tu);return r?(t.log("success",Fr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",Fr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=$s(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1,ignoreNetworkErrors:d=!1}={}){var G,H,E;let c=e,p=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let P=new URL(c,location.href);P.searchParams.append("bytes",`${i.from}-${i.to}`),c=P.toString();break}default:mE(t)}this.requestQuic&&(c=Zt(c));let m=this.abortAllController.signal,f;if(n){let P=new te;if(f=MV(fE(this.abortAllController.signal,"abort"),fE(n,"abort")).subscribe(()=>{try{P.abort()}catch(I){tu(I)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{P.abort()}catch(I){tu(I)}m=P.signal}let v=0,g=Ms();h.log("startRequest",Fr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested$.next();let S=yield this.doFetch(c,{priority:s,headers:p,signal:m},{ignoreNetworkErrors:d}),T=Ms();if(!S)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(f),null;if((G=this.throughputEstimator)==null||G.addRawRtt(T-g),!S.ok||!S.body){this.unsubscribeAbortSubscription(f);let P=`Fetch error ${S.status}: ${S.statusText}`;return h.error("error",{message:P}),h.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let P=Ms(),I={requestStartedAt:g,requestEndedAt:P,duration:P-g};return h.log("endRequest",Fr(I)),h.end(),S.arrayBuffer()}let y=S.body;if(o){let P;[y,P]=S.body.tee(),(H=this.throughputEstimator)==null||H.trackStream(P,u)}let w=y.getReader(),R,L=parseInt((E=S.headers.get("content-length"))!=null?E:"",10);Number.isFinite(L)&&(R=L),!R&&i&&(R=i.to-i.from+1);let $=R?new Uint8Array(R):new Uint8Array(0),D=!1,k=P=>{this.unsubscribeAbortSubscription(f),D=!0,tu(P)},V=$s(m,async function*({done:P,value:I}){if(v===0&&(this.lastRequestFirstBytes$.next(Ms()-g),this.firstBytesReceived$.next()),m.aborted){this.unsubscribeAbortSubscription(f);return}if(!P&&I){if(l&&R)$.set(I,v),v+=I.byteLength;else{let x=new Uint8Array($.length+I.length);x.set($),x.set(I,$.length),$=x,v+=I.byteLength}r==null||r(new DataView($.buffer),v),yield w==null?void 0:w.read().then(V,k)}}.bind(this));yield w==null?void 0:w.read().then(V,k),this.unsubscribeAbortSubscription(f);let M=Ms(),q={failed:D,requestStartedAt:g,requestEndedAt:M,duration:M-g};return D?(h.error("endRequest",Fr(q)),h.end(),null):(h.log("endRequest",Fr(q)),h.end(),$.buffer)}.bind(this));this.fetchByteRangeRepresentation=$s(this.abortAllController.signal,async function*(e,t,i){var g;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!c)return null;let p=new DataView(c,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(g=e.indexRange)!=null?g:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(c,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,measureThroughput:!1});if(!S)return null;f=new DataView(S)}let v=t.parseSegments(f,h,m);return{init:h,dataView:new DataView(c),segments:v}}.bind(this));this.fetchTemplateRepresentation=$s(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...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=s}onHeadersReceived(e){let{type:t,reused:i}=Co(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:mE(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await Je(e,t);if(r.ok)return r;if(i!=null&&i.ignoreNetworkErrors)return;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Cs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Cs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Cs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Cs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:Cs.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},tu=a=>{if(!ot(a))throw a};import{isNullable as LV,ValueSubject as bE}from"@vkontakte/videoplayer-shared/es2018";var ui=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 bE(e.initial),this.debounced$=new bE(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Re(`raw_${t}`),this.smoothedSeries$=new Re(`smoothed_${t}`),this.reportedSeries$=new Re(`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+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(LV(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 ru=class extends ui{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=$t(this.slow,e,this.params.emaAlphaSlow),this.fast=$t(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var au=class extends ui{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=id(this.pastMeasures,this.takenMeasures);this.emaSmoothed=$t(this.emaSmoothed,e,this.params.emaAlpha);let i=jy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var su=class extends ui{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?$t(this.smoothed,t,this.params.emaAlpha):t}};var Qi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new ru({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new au({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 su({initial:e,label:"liveEdgeDelay",...t})}};var Yd=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as DV,ValueSubject as BV}from"@vkontakte/videoplayer-shared/es2018";var Ls=class a{constructor(e,t){this.currentRepresentation$=new BV(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(!DV(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(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({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.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=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Qe(t.segmentReference))}};var UV=["timeupdate","progress","play","seeked","stalled","waiting"],jV=["timeupdate","progress","loadeddata","playing","seeked"];var ou=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new vE;this.subscriptionRemovable=new NV;this.representationSubscription=new vE;this.state$=new j("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentAudioRepresentation$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new Vt;this.manifestRequested$=new Vt;this.firstBytesManifest$=new Vt;this.manifestReceived$=new Vt;this.firstBytesRequested$=new Vt;this.firstBytesReceived$=new Vt;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.currentLiveTextRepresentation$=new ae(null);this.isLive$=new ae(!1);this.isActiveLive$=new ae(!1);this.isLowLatency$=new ae(!1);this.liveDuration$=new ae(0);this.liveSeekableDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(0);this.liveStreamStatus$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLatency$=new ae(void 0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.currentStallDuration$=new ae(0);this.videoLastDataObtainedTimestamp$=new ae(0);this.fetcherRecoverableError$=new Vt;this.fetcherError$=new Vt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Vt;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new te;this.initManifest=Kd(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ee(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:Ze.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Kd(this.destroyController.signal,async function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(d=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ze.NETWORK,message:"Failed to load manifest",thrown:d})});if(!e)return null;let t=null;try{t=Oo(e!=null?e:"",this.manifestUrlString),this.manifestReceived$.next()}catch(d){let c=(u=Mo(e))!=null?u:{id:"ManifestParsing",category:Ze.PARSER,message:"Failed to parse MPD manifest",thrown:d};this.error$.next(c)}if(!t)return null;let i=(d,c,p)=>{var h,m,f,v;return!!((m=(h=this.element)==null?void 0:h.canPlayType)!=null&&m.call(h,c)&&((v=(f=je())==null?void 0:f.isTypeSupported)!=null&&v.call(f,`${c}; codecs="${p}"`))||d==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:d,latestSegmentPublishTime:c,streamIsUnpublished:p,streamIsAlive:h}=t.live,m=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*m),this.liveDuration$.next((c-d)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let f="active";if(h||(f=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(f),h&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let v=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(v).catch(g=>{this.error$.next({id:"updateManifest",category:Ze.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:g})})}}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let d of["video","audio"]){let p=t.streams[d].filter(({mime:m,codecs:f})=>i(d,m,f));r[d]=p;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let m=p.map(({codecs:f})=>f);d==="audio"&&(n=Ho(m),h=n[0]),d==="video"&&(s=jo(m),this.forceVideoCodec&&(0,SE.default)(s,this.forceVideoCodec)?h=this.forceVideoCodec:h=s[0]),h&&(r[d]=p.filter(({codecs:f})=>Lr(f)===h))}else{let m=new Set(p.map(({codecs:f})=>f));h=Uo(m),h&&(r[d]=p.filter(({codecs:f})=>f.startsWith(h)))}if(d==="video"){let m=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),v=r.video.some(g=>!g.hdr);B.display.isHDR&&m&&f?r.video=r.video.filter(g=>g.hdr):v&&(r.video=r.video.filter(g=>!g.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",Bs(o)),o}.bind(this));this.initRepresentations=Kd(this.destroyController.signal,async function*(e,t,i){var c;this.tracer.log("initRepresentationsStart",Bs({initialVideo:e,initialAudio:t,sourceHls:i})),qr(this.manifest),qr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Bt(p,"error").pipe(nu(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Ze.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=An();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),lr())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,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Rs("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Vs(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Rs("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(Ls.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ls(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Wi(...jV.map(p=>Bt(this.element,p))).pipe(jr(p=>this.element?ii(this.element.buffered,this.element.currentTime*1e3):0),Ds(),FV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Wi(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ds()).subscribe(h=>this.liveStreamEndTimestamp=Jd())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:h}=this.tuning.dash;this.livePauseWatchdogSubscription=Xd(h).subscribe(m=>{let f=yn(this.manifestUrlString,2);this.manifestUrlString=Ee(this.manifestUrlString,f+h,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Bt(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(Ur({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(jr(({isActiveLive:h,isLowLatency:m})=>h&&m),Ds()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Yd(this.element,1)})),this.representationSubscription.add(Ur({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(nu(({bufferLength:h,isActiveLive:m,isLowLatency:f})=>m&&f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Ur({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(nu(({isLive:h})=>h),Ds((h,m)=>m.bufferLength<h.bufferLength),jr(({rtt:h,bufferLength:m,segmentServerLatency:f})=>{let v=yn(this.manifestUrlString,2);return(h/2+m+f+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ur({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:f})=>{if(!f||!m)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-v;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(T)>g&&(y=1+Math.sign(T)*S),Yd(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var f,v;let m=0;if(h){let g=((v=(f=this.element)==null?void 0:f.currentTime)!=null?v:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var y,w;return(w=(y=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?w:g}))-g}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Ur({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(qV(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,v=yn(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,w=isFinite(h)?h:m,R=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let $="none";if(R?$="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(D=>D.proceedLowLatencyLive()),$="active_low_latency"):v!==0&&w<S?$="live_forward_buffering":w<S+y&&($="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),$==="live_forward_buffering"||$==="live_with_target_offset"){let D=p-(S+T),k=this.normalizeLiveOffset(Math.trunc(v+D/f)),V=Math.abs(k-v),M=0;!h||V<=this.tuning.dashCmafLive.offsetCalculationError?M=v:k>0&&V>this.tuning.dashCmafLive.offsetCalculationError&&(M=k),this.manifestUrlString=Ee(this.manifestUrlString,M,2)}($==="live_with_target_offset"||$==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:Ze.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let u=Wi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(jr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),l=Wi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(jr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=Ur({allBuffersFull:u,someBufferEnded:l}).pipe(Ds(),jr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),nu(p=>p));if(this.representationSubscription.add(Wi(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Ze.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Wi(...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(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var f;if(((f=this.source)==null?void 0:f.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:Ze.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),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(c=this.manifest.duration)!=null?c:0,...(0,Zd.default)((0,Zd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Qe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Vs(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,s;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||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Xd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Ze.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.forceVideoCodec=e.forceVideoCodec,this.fetcher=new iu({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.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=Qi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){qr(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?Jd()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ee(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){var t,i,r;await((t=this.videoBufferManager)==null?void 0:t.seekLive(e.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(e.streams.audio)),(r=this.liveTextManager)==null||r.seekLive(e.streams.text)}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){qr(this.element),this.state$.setState("running"),this.subscription.add(Wi(...UV.map(e=>Bt(this.element,e)),Bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ze.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Bt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Bt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&si(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var y,w,R,L,$,D,k,V,M,q,G;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||((y=this.source)==null?void 0:y.readyState)!=="open")return;let d=this.currentStallDuration$.getValue();d+=n,this.currentStallDuration$.next(d);let c={timeInWaiting:d},p=Jd(),h=100,m=(R=(w=this.videoBufferManager)==null?void 0:w.lastDataObtainedTimestamp)!=null?R:0;this.videoLastDataObtainedTimestamp$.next(m);let f=($=(L=this.audioBufferManager)==null?void 0:L.lastDataObtainedTimestamp)!=null?$:0,v=(k=(D=this.videoBufferManager)==null?void 0:D.getForwardBufferDuration())!=null?k:0,g=(M=(V=this.audioBufferManager)==null?void 0:V.getForwardBufferDuration())!=null?M:0,S=v<h&&p-m>r,T=this.audioBufferManager&&g<h&&p-f>r;if((!t||l)&&((S||T)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%s===0){let H=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(H),this.updateManifest()):this.seekLive(H).catch(E=>{this.error$.next({id:"stallIntervalCallback",category:Ze.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:E})}),c.liveLastOffset=H}else{let H=this.element.currentTime*1e3;(q=this.videoBufferManager)==null||q.maintain(H),(G=this.audioBufferManager)==null||G.maintain(H),c.position=H}this.tracer.log("stallIntervalCallback",Bs(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Xd(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ze.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){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)}async seek(e,t){var r,s,n,o,u;qr(this.element),qr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),si(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(gE(this.element)||gE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Bs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Vs(this.element)&&Vs(this.source)&&Vs(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}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.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=OV(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.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},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(r&&l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=s&&l.to+o>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Bs(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};import{combine as HV,map as QV,observeElementSize as WV,Subscription as zV,ValueSubject as ep,noop as GV}from"@vkontakte/videoplayer-shared/es2018";var uu=class{constructor(){this.subscription=new zV;this.pipSize$=new ep(void 0);this.videoSize$=new ep(void 0);this.elementSize$=new ep(void 0);this.pictureInPictureWindowRemoveEventListener=GV}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(WV(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(HV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(QV(({videoSize:r,inPip:s,pipSize:n})=>s?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 zi=class{constructor(e){this.subscription=new i_;this.videoState=new j("stopped");this.observableVideo=null;this.droppedFramesManager=new Pr;this.stallsManager=new Po;this.elementSizeManager=new uu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return KV(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Ar(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Be(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(we(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 ou({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;t_(this.observableVideo)&&(this.observableVideo=Oe(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:yE.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(tp(c=>!!c.length),IE()).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(Os(c=>c.to.state!=="none"),_s());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(tp(TE),IE()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Os(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(gt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Jt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Ge(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Xe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")})),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 p=this.player.getStreams(),h=this.player.getCodecs();if(XV(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let v of p.audio){f.push(Cd(v));let g=[];for(let S of v.representations){let T=Ts(S);g.push(T),this.audioTracksMap.set(T,{stream:v,representation:S})}this.audioStreamsMap.set(v,g)}this.params.output.availableAudioStreams$.next(f)}let m=[];for(let f of p.video){m.push(Ld(f));let v=[];for(let g of f.representations){let S=ti({...g,streamId:f.id});S&&(v.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,v)}this.params.output.availableVideoStreams$.next(m);for(let f of p.text)for(let v of f.representations){let g=WI(f,v);this.textTracksMap.set(g,{stream:f,representation:v})}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),h!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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 o=Ns(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$,e_(this.video,"progress")).pipe(tp(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(r_(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,f]=h,v=[...this.videoTracksMap.keys()].find(S=>{var T;return((T=this.videoTracksMap.get(S))==null?void 0:T.representation.id)===m.id});TE(v)&&(this.stallsManager.lastVideoTrackSelected=v);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(m.id,f==null?void 0:f.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),f){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,S)}},r)),this.subscription.add(JV({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Ns(lu([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Os(c=>c.to)))}).pipe(Os(({videoState:c,autoVideoTrackState:p})=>c.to!=="stopped"&&p),_s()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),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(_s()).subscribe(c=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Ld(m));let v=this.player.calculateDurationFromSegments();v&&this.params.output.duration$.next(v/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(_s()).subscribe(c=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:v}])=>v.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Cd(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.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(Os(({to:c})=>c==="ready"),_s());this.subscription.add(Ns(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,lu(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(Ns(l,this.player.state$.stateChangeEnded$,lu(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Ns(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,lu(["init"])).pipe(ZV(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var $,D,k,V,M,q,G,H,E,P,I,x,F;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?La:Ca,t=this.params.tuning.useNewAutoSelectVideoTrack?go:bo,i=this.params.tuning.useNewAutoSelectVideoTrack?yt:fo,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=($=r.videoTrack.getState())==null?void 0:$.id,u=[...this.videoTracksMap.keys()].find(({id:O})=>O===o),l=s.currentVideoTrack$.getValue(),d=((V=(k=r.videoStream.getState())!=null?k:u&&((D=this.videoTracksMap.get(u))==null?void 0:D.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=[...this.videoStreamsMap.keys()].find(({id:O})=>O===d.id),p=c&&this.videoStreamsMap.get(c);if(!p)return;let h=ii(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 f=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,v=Math.min(h/Math.min(m,f||1/0),1),g=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(q=[...this.audioStreamsMap.keys()].find(({id:O})=>O===(g==null?void 0:g.id)))!=null?q:this.audioStreamsMap.keys().next().value,T=0;if(S){if(u&&!n){let O=e(u,p,(G=this.audioStreamsMap.get(S))!=null?G:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(H=O==null?void 0:O.bitrate)!=null?H:-1/0)}if(l){let O=e(l,p,(E=this.audioStreamsMap.get(S))!=null?E:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(P=O==null?void 0:O.bitrate)!=null?P:-1/0)}}let y=u;(n||!y)&&(y=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:v,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 w=S&&t(y,p,(I=this.audioStreamsMap.get(S))!=null?I:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),R=(x=this.videoTracksMap.get(y))==null?void 0:x.representation,L=w&&((F=this.audioTracksMap.get(w))==null?void 0:F.representation);if(R&&L)return[R,L];if(R&&!L&&this.audioTracksMap.size===0)return[R,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:yE.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),Ve(this.video),this.tracer.end()}};var Fs=class extends zi{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 ip,merge as EE,filter as wE,filterChanged as xE,isNullable as rp,map as PE,ValueSubject as ap,isNonNullable as a_}from"@vkontakte/videoplayer-shared/es2018";var qs=class extends zi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new ap(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(xE()).subscribe(u=>{let l=i.position$.getValue(),d=i.volume$.getValue(),c=!d.volume||d.muted;!u&&!l&&c?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(PE(u=>u.to)).subscribe(this.player.isLowLatency$)).add(ip({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(PE(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u*1e3+l+t:void 0)).subscribe(i.liveTime$)).add(ip({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:EE(r.playbackRateState$,new ap(1))}).pipe(wE(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let d=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-p||this.video.paused||rp(d)||(t=u-d)})).add(ip({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:EE(r.playbackRateState$,new ap(1))}).pipe(xE((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:d})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&d>=1-p||rp(u)||rp(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=zI(u);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(wE(u=>a_(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var AE="X-Playback-Duration",sp=async a=>{var r;let e=await Je(a),t=await 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(AE)?parseInt(e.headers.get(AE),10):void 0};import{assertNever as f_,combine as b_,debounce as g_,ErrorCategory as pu,filter as v_,filterChanged as S_,isNonNullable as $E,isNullable as hu,map as ME,merge as y_,observableFrom as T_,Subscription as I_,ValueSubject as up,VideoQuality as E_}from"@vkontakte/videoplayer-shared/es2018";var op=_(zl(),1);import{videoSizeToQuality as s_,getExponentialDelay as n_}from"@vkontakte/videoplayer-shared/es2018";var o_=a=>{let e=null;if(a.QUALITY&&(e=Kt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=s_({width:t,height:i})}return e!=null?e:null},u_=(a,e)=>{var s,n;let t=a.split(`
|
|
179
|
-
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],
|
|
180
|
-
`),s=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:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-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),s=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(c_(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([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new te;let{textTracks:e}=await this.fetchManifestData(),t=await 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}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:m_.WTF,thrown:t,message:e})}};var Us=class{constructor(e){this.subscription=new I_;this.videoState=new j("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new up([]);this.liveOffset=new Ci;this.manifestStartTime$=new up(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let 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"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(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"&&A(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"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return f_(t)}};var i;this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:E_.INVARIANT,url:this.params.source.url};let t=(r,s)=>cu(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new du(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ye(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:pu.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:pu.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(we(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new up((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(),s=(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":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:pu.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Oe(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ge(this.video,t.playbackRate,r.playbackRateState$,i)),s(Xe(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(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"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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(S_(),ME(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&&$E(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(we(p.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(b_({startTime:this.manifestStartTime$.pipe(v_($E)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(ME(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=y_(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,T_(["init"])).pipe(g_(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),Ve(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(hu(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[p,h]of[[d,"mq"],[c,"lq"]]){let m=String(parseFloat(p||""));h&&p&&r.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ee(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),sp(n).then(d=>{var c;if(!hu(d))this.maxSeekBackTime$.next(d);else{let p=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(hu(p)||!isFinite(p))&&Je(n).then(h=>h.text()).then(h=>{var f;let m=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:f[1];if(m){let v=new URL(m,n).toString();sp(v).then(g=>{hu(g)||this.maxSeekBackTime$.next(g)})}}).catch(()=>{})}})}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pu.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=Ee(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 w_,debounce as x_,ErrorCategory as lp,fromEvent as cp,isNonNullable as P_,isNullable as A_,map as CE,merge as LE,observableFrom as DE,Subscription as k_,ValueSubject as BE,VideoQuality as R_}from"@vkontakte/videoplayer-shared/es2018";var js=class{constructor(e){this.subscription=new k_;this.videoState=new j("stopped");this.manifests$=new BE([]);this.unmuteAfterBrowserResetsHappened=new BE(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let 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"?A(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return w_(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:R_.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(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),cu(Ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:lp.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(),s=(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":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:lp.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Oe(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(CE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(gt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ge(this.video,t.playbackRate,r.playbackRateState$,i)),Jt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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 h;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&&P_(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(v=>v.id===m);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(we(f.url)))}let c=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(c!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(c),m.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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(CE(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!B.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(LE(cp(o,"addtrack"),cp(o,"removetrack"),cp(o,"change"),DE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=LE(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,DE(["init"])).pipe(x_(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ve(this.video)}prepare(){var s,n;let e=this.selectManifest();if(A_(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,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(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:lp.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var OE=_(zt(),1),dp=_(Ei(),1),NE=_(Ke(),1);import{assertNever as $_,assertNonNullable as VE,debounce as M_,ErrorCategory as _E,isHigherOrEqual as C_,isLowerOrEqual as L_,isNonNullable as D_,merge as B_,observableFrom as V_,Subscription as __,map as O_}from"@vkontakte/videoplayer-shared/es2018";var Hs=class{constructor(e){this.subscription=new __;this.videoState=new j("stopped");this.trackUrls={};this.textTracksManager=new Ye;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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);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"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return $_(e)}};this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),(0,OE.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,dp.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:_E.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Oe(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(O_(o=>o.to)),this.params.output.playbackState$),this.subscription.add(gt(this.video,t.isLooped,i)),Jt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ge(this.video,t.playbackRate,r.playbackRateState$,i)),s(Xe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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&&D_(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 p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=B_(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,V_(["init"])).pipe(M_(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),Ve(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;VE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];VE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Zt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(we(t))}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_E.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 p=yt(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(p)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,dp.default)(this.trackUrls).map(c=>c.track);if(!r||!s||Ir(e,n[0].quality,(d=(0,NE.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?L_(r,e.max):!0,u=e.min?C_(r,e.min):!0;o&&u||i(e)}};import{assertNever as qE,debounce as U_,merge as UE,observableFrom as j_,Subscription as H_,map as jE,ValueSubject as Q_,ErrorCategory as hp,VideoQuality as W_}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as N_}from"@vkontakte/videoplayer-shared/es2018";var FE=["stun:videostun.mycdn.me:80"],F_=1e3,q_=3,pp=()=>null,mu=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=pp;this.externalStopCallback=pp;this.externalErrorCallback=pp;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}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:FE}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:N_.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),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),F_)}normalizeOptions(e={}){let t={stunServerList:FE,maxRetryNumber:q_,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Qs=class{constructor(e){this.videoState=new j("stopped");this.maxSeekBackTime$=new Q_(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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return qE(e)}};this.subscription=new H_,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Be(e.container,e.tuning),this.liveStreamClient=new mu(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),Ve(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:hp.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(UE(this.videoState.stateChangeStarted$.pipe(jE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(jE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Oe(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(Xe(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(_e(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 qE(n.to)}},i)).add(UE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,j_(["init"])).pipe(U_(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(we(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:W_.INVARIANT}),this.video.srcObject=e,A(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.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:hp.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hp.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Hr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as zs,assertNonNullable as _t,ErrorCategory as fu,filter as YE,isNonNullable as KE,isNullable as Z_,map as eO,merge as tO,once as iO,Subject as se,Subscription as XE,ValueSubject as U,flattenObject as mp,devNull as rO,getWindow as aO}from"@vkontakte/videoplayer-shared/es2018";import{Observable as z_,map as HE,Subscription as G_,Subject as Y_}from"@vkontakte/videoplayer-shared/es2018";var QE=a=>new z_(e=>{let t=new G_,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(HE(({from:l,to:d})=>`${l}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(HE(({type:l})=>l!==void 0)),n=new Y_,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval),N({m:"hangup.set",l,id:o})})),t.add(r.subscribe(()=>{N({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(N({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval),N({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as K_,Subscription as X_,combine as J_,filter as zE,once as GE}from"@vkontakte/videoplayer-shared/es2018";function WE(){return new(window.AudioContext||window.webkitAudioContext)}var Ws=class Ws{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new te;this.subscriptions=new X_;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(zE(s=>!!s.type),GE()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){B.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(J_({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(zE(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),GE()).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}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=WE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.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:Ws.errorId,category:K_.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ws.errorId} exception`,thrown:e})}};Ws.errorId="VolumeMultiplierManager";var Qr=Ws;var sO={chunkDuration:5e3,maxParallelRequests:5},Gs=class{constructor(e){this.current$=new U({type:void 0});this.providerError$=new se;this.noAvailableProvidersError$=new se;this.volumeMultiplierError$=new se;this.providerOutput={position$:new U(0),duration$:new U(1/0),volume$:new U({muted:!1,volume:1}),availableVideoStreams$:new U([]),currentVideoStream$:new U(void 0),availableVideoTracks$:new U([]),currentVideoTrack$:new U(void 0),availableVideoCodecs$:new U([]),availableAudioStreams$:new U([]),currentAudioStream$:new U(void 0),availableAudioTracks$:new U([]),availableAudioCodecs$:new U([]),currentVideoSegmentLength$:new U(0),currentAudioSegmentLength$:new U(0),isAudioAvailable$:new U(!0),autoVideoTrackLimitingAvailable$:new U(!1),autoVideoTrackLimits$:new U(void 0),currentBuffer$:new U(void 0),currentNativeBuffer$:new U(void 0),isBuffering$:new U(!0),error$:new se,fetcherError$:new se,fetcherRecoverableError$:new se,warning$:new se,willSeekEvent$:new se,soundProhibitedEvent$:new se,seekedEvent$:new se,loopedEvent$:new se,endedEvent$:new se,manifestRequested$:new se,firstBytesManifest$:new se,manifestReceived$:new se,firstBytesRequested$:new se,firstBytesReceived$:new se,firstBytesEvent$:new se,loadedMetadataEvent$:new se,firstFrameEvent$:new se,canplay$:new se,isLive$:new U(void 0),isLiveEnded$:new U(null),canPlayLiveTailBuffer$:new U(!1),isLowLatency$:new U(!1),canChangePlaybackSpeed$:new U(!0),liveTime$:new U(void 0),liveBufferTime$:new U(void 0),liveLatency$:new U(void 0),severeStallOccurred$:new se,availableTextTracks$:new U([]),currentTextTrack$:new U(void 0),hostname$:new U(void 0),httpConnectionType$:new U(void 0),httpConnectionReused$:new U(void 0),inPiP$:new U(!1),inFullscreen$:new U(!1),element$:new U(void 0),elementVisible$:new U(!0),availableSources$:new U(void 0),is3DVideo$:new U(!1),playbackState$:new U(""),getCurrentTime$:new U(null)};this.subscription=new XE;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=vl([...BI(this.params.tuning),...DI(this.params.tuning)]).filter(l=>KE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,fp.default)(r,l)),...t.filter(l=>(0,fp.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",mp(s)),this.screenFormatsIterator=new Hr(s);let n=[...Rd(!0),...Rd(!1)];this.chromecastFormatsIterator=new Hr(n.filter(l=>KE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Qr.isSupported()&&(this.volumeMultiplierManager=new Qr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){N.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Hr(e))}))}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(Z_(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:fu.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()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),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 s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return zs(e)}}createScreenProvider(e){var u,l,d;let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let c=this.applyFailoverHost(t[e]),p=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return _t(c),this.params.tuning.useDashProviderVirtual&&!B.device.isMobile?new Or({...o,source:c,sourceHls:p,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&B.device.isMobile?new Or({...o,source:c,sourceHls:p,forceVideoCodec:(l=this.videoCodecsIterator)==null?void 0:l.getValue()}):new Fs({...o,source:c,sourceHls:p,forceVideoCodec:(d=this.videoCodecsIterator)==null?void 0:d.getValue()})}case"DASH_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return _t(c),new qs({...o,source:c})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let c=this.applyFailoverHost(t[e]);return _t(c),new js({...o,source:c})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=this.applyFailoverHost(t[e]);return _t(c),new Us({...o,source:c,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let c=this.applyFailoverHost(t[e]);return _t(c),new Hs({...o,source:c})}case"DASH_LIVE":{let c=this.applyFailoverHost(t[e]);return _t(c),new _y({...o,source:c,config:{...sO,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let c=this.applyFailoverHost(t[e]);return _t(c),new Qs({container:i,source:c,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 zs(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o={meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof At){let{chromecastConnector:l}=this.params.dependencies.chromecastInitializer;return _t(l),new da({...o,chromecastConnector:l})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return _t(u),new Aa({...o,connection:u})}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 zs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return zs(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 zs(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,JE.default)((0,bp.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new XE,t=!1,i=0;e.add(tO(this.providerOutput.error$.pipe(YE(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),QE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(eO(s=>({id:`ProviderHangup:${s}`,category:fu.WTF,message:`A ${s} 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 s=this.params.desiredState.playbackState.transitionEnded$.pipe(YE(({to:n})=>n==="playing"),iO()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=N.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&aO().console.log(`===== DASH_LIVE DEBUG START ====
|
|
181
|
-
`,s.map(({time:u,data:
|
|
178
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var DI=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ut=(a,e)=>{let t=a;t=(0,$d.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,LI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,$d.default)(t,n,(o,u)=>CI(s)?o:CI(u)?s:(0,BI.default)(s,parseInt(u,10),"0"))}return t},Uo=(a,e)=>{var L,A,B,$,U,G,j,E,P,I,w,N,O,lt,dt,K,Se,ye,Te,Fe,It,Et,di,Ki,Xi,Cp,Dp,Lp,Bp,Vp,_p,Op,Np,Fp,qp,Up,Hp,jp,Qp,Wp,zp,Gp,Yp,Kp,Xp,Jp,Zp,eh,th,ih,rh,ah,sh,nh,oh,uh,ch,lh,dh,ph,hh;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(et=>{var ee,pi;return(pi=(ee=et.textContent)==null?void 0:ee.trim())!=null?pi:""}),o=(L=(0,VI.default)(n,0))!=null?L:"",u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),l=s.getElementsByTagName("vk:Attrs")[0],p=l==null?void 0:l.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=l==null?void 0:l.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=l==null?void 0:l.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=l==null?void 0:l.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:c?new Date(c).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let g,S=s.getAttribute("mediaPresentationDuration"),T=[...s.getElementsByTagName("Period")],y=T.reduce((et,ee)=>({...et,[ee.id]:ee.children}),{}),x=T.reduce((et,ee)=>({...et,[ee.id]:ee.getAttribute("duration")}),{});S?g=DI(S):(0,Cd.default)(x).filter(et=>et).length&&!u?g=(0,Cd.default)(x).reduce((et,ee)=>{var pi;return et+((pi=DI(ee))!=null?pi:0)},0):m&&(g=parseInt(m,10));let R=0,D=(B=(A=s.getAttribute("profiles"))==null?void 0:A.split(","))!=null?B:[];for(let et of T.map(ee=>ee.id))for(let ee of y[et]){let pi=($=ee.getAttribute("id"))!=null?$:"id"+(R++).toString(10),Kr=(U=ee.getAttribute("mimeType"))!=null?U:"",Ru=(G=ee.getAttribute("codecs"))!=null?G:"",Mu=(j=ee.getAttribute("contentType"))!=null?j:Kr==null?void 0:Kr.split("/")[0],Ew=(P=(E=ee.getAttribute("profiles"))==null?void 0:E.split(","))!=null?P:[],fh=(w=$I((I=ee.getAttribute("lang"))!=null?I:""))!=null?w:{},Zs=(lt=(O=(N=ee.querySelector("Label"))==null?void 0:N.textContent)==null?void 0:O.trim())!=null?lt:void 0,ww=ee.querySelectorAll("Representation"),xw=ee.querySelector("SegmentTemplate"),Pw=(K=(dt=ee.querySelector("Role"))==null?void 0:dt.getAttribute("value"))!=null?K:void 0,Ji=Mu,ue={id:pi,language:fh.language,isDefault:Pw==="main",label:Zs,codecs:Ru,hdr:Ji==="video"&&Md(Ru),mime:Kr,representations:[]};for(let J of ww){let Nt=(Se=J.getAttribute("lang"))!=null?Se:void 0,en=(Te=(ye=Zs!=null?Zs:ee.getAttribute("label"))!=null?ye:J.getAttribute("label"))!=null?Te:void 0,tn=(Et=(It=(Fe=J.querySelector("BaseURL"))==null?void 0:Fe.textContent)==null?void 0:It.trim())!=null?Et:"",hi=new URL(tn||o,e).toString(),Ft=(di=J.getAttribute("mimeType"))!=null?di:Kr,rn=(Xi=(Ki=J.getAttribute("codecs"))!=null?Ki:Ru)!=null?Xi:"",an;if(Mu==="text"){let qt=J.getAttribute("id")||"",sn=((Cp=fh.privateuse)==null?void 0:Cp.includes("x-auto"))||qt.includes("_auto"),fi=J.querySelector("SegmentTemplate");if(fi){let Xr={representationId:(Dp=J.getAttribute("id"))!=null?Dp:void 0,bandwidth:(Lp=J.getAttribute("bandwidth"))!=null?Lp:void 0},nn=parseInt((Bp=J.getAttribute("bandwidth"))!=null?Bp:"",10)/1e3,on=(_p=parseInt((Vp=fi.getAttribute("startNumber"))!=null?Vp:"",10))!=null?_p:1,Zi=parseInt((Op=fi.getAttribute("timescale"))!=null?Op:"",10),$u=(Np=fi.querySelectorAll("SegmentTimeline S"))!=null?Np:[],er=fi.getAttribute("media");if(!er)continue;let un=[],cn=0,ln="",tr=0,Jr=on,xe=0;for(let tt of $u){let mi=parseInt((Fp=tt.getAttribute("d"))!=null?Fp:"",10),ze=parseInt((qp=tt.getAttribute("r"))!=null?qp:"",10)||0,Ut=parseInt((Up=tt.getAttribute("t"))!=null?Up:"",10);xe=Number.isFinite(Ut)?Ut:xe;let bi=mi/Zi*1e3,Ht=xe/Zi*1e3;for(let pt=0;pt<ze+1;pt++){let jt=ut(er,{...Xr,segmentNumber:Jr.toString(10),segmentTime:(xe+pt*mi).toString(10)}),ir=(Ht!=null?Ht:0)+pt*bi,ea=ir+bi;Jr++,un.push({time:{from:ir,to:ea},url:jt})}xe+=(ze+1)*mi,cn+=(ze+1)*bi}tr=xe/Zi*1e3,ln=ut(er,{...Xr,segmentNumber:Jr.toString(10),segmentTime:xe.toString(10)});let Zr={time:{from:tr,to:1/0},url:ln},wt={type:"template",baseUrl:hi,segmentTemplateUrl:er,initUrl:"",totalSegmentsDurationMs:cn,segments:un,nextSegmentBeyondManifest:Zr,timescale:Zi};an={id:qt,kind:"text",segmentReference:wt,profiles:[],duration:g,bitrate:nn,mime:"",codecs:"",width:0,height:0,isAuto:sn}}else an={id:qt,isAuto:sn,kind:"text",url:hi}}else{let qt=(jp=(Hp=J.getAttribute("contentType"))!=null?Hp:Ft==null?void 0:Ft.split("/")[0])!=null?jp:Mu,sn=(Wp=(Qp=ee.getAttribute("profiles"))==null?void 0:Qp.split(","))!=null?Wp:[],fi=parseInt((zp=J.getAttribute("width"))!=null?zp:"",10),Xr=parseInt((Gp=J.getAttribute("height"))!=null?Gp:"",10),nn=parseInt((Yp=J.getAttribute("bandwidth"))!=null?Yp:"",10)/1e3,on=(Kp=J.getAttribute("frameRate"))!=null?Kp:"",Zi=(Xp=J.getAttribute("quality"))!=null?Xp:void 0,$u=on?MI(on):void 0,er=(Jp=J.getAttribute("id"))!=null?Jp:"id"+(R++).toString(10),un=qt==="video"?`${Xr}p`:qt==="audio"?`${nn}Kbps`:rn,cn=`${er}@${un}`,ln=[...D,...Ew,...sn],tr,Jr=J.querySelector("SegmentBase"),xe=(Zp=J.querySelector("SegmentTemplate"))!=null?Zp:xw;if(Jr){let wt=(th=(eh=J.querySelector("SegmentBase Initialization"))==null?void 0:eh.getAttribute("range"))!=null?th:"",[tt,mi]=wt.split("-").map(jt=>parseInt(jt,10)),ze={from:tt,to:mi},Ut=(ih=J.querySelector("SegmentBase"))==null?void 0:ih.getAttribute("indexRange"),[bi,Ht]=Ut?Ut.split("-").map(jt=>parseInt(jt,10)):[],pt=Ut?{from:bi,to:Ht}:void 0;tr={type:"byteRange",url:hi,initRange:ze,indexRange:pt}}else if(xe){let wt={representationId:(rh=J.getAttribute("id"))!=null?rh:void 0,bandwidth:(ah=J.getAttribute("bandwidth"))!=null?ah:void 0},tt=parseInt((sh=xe.getAttribute("timescale"))!=null?sh:"",10),mi=(nh=xe.getAttribute("initialization"))!=null?nh:"",ze=xe.getAttribute("media"),Ut=(uh=parseInt((oh=xe.getAttribute("startNumber"))!=null?oh:"",10))!=null?uh:1,bi=ut(mi,wt);if(!ze)throw new ReferenceError("No media attribute in SegmentTemplate");let Ht=(ch=xe.querySelectorAll("SegmentTimeline S"))!=null?ch:[],pt=[],jt=0,ir="",ea=0;if(Ht.length){let dn=Ut,it=0;for(let rr of Ht){let ht=parseInt((lh=rr.getAttribute("d"))!=null?lh:"",10),gi=parseInt((dh=rr.getAttribute("r"))!=null?dh:"",10)||0,pn=parseInt((ph=rr.getAttribute("t"))!=null?ph:"",10);it=Number.isFinite(pn)?pn:it;let Cu=ht/tt*1e3,Du=it/tt*1e3;for(let hn=0;hn<gi+1;hn++){let Aw=ut(ze,{...wt,segmentNumber:dn.toString(10),segmentTime:(it+hn*ht).toString(10)}),mh=(Du!=null?Du:0)+hn*Cu,Rw=mh+Cu;dn++,pt.push({time:{from:mh,to:Rw},url:Aw})}it+=(gi+1)*ht,jt+=(gi+1)*Cu}ea=it/tt*1e3,ir=ut(ze,{...wt,segmentNumber:dn.toString(10),segmentTime:it.toString(10)})}else if(EB(g)){let it=parseInt((hh=xe.getAttribute("duration"))!=null?hh:"",10)/tt*1e3,rr=Math.ceil(g/it),ht=0;for(let gi=1;gi<rr;gi++){let pn=ut(ze,{...wt,segmentNumber:gi.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+it},url:pn}),ht+=it}ea=ht,ir=ut(ze,{...wt,segmentNumber:rr.toString(10),segmentTime:ht.toString(10)})}let kw={time:{from:ea,to:1/0},url:ir};tr={type:"template",baseUrl:hi,segmentTemplateUrl:ze,initUrl:bi,totalSegmentsDurationMs:jt,segments:pt,nextSegmentBeyondManifest:kw,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!qt||!Ft)continue;let Zr={video:"video",audio:"audio",text:"text"}[qt];if(!Zr)continue;Ji||(Ji=Zr),an={id:cn,kind:Zr,segmentReference:tr,profiles:ln,duration:g,bitrate:nn,mime:Ft,codecs:rn,width:fi,height:Xr,fps:$u,quality:Zi}}ue.language||(ue.language=Nt),ue.label||(ue.label=en),ue.mime||(ue.mime=Ft),ue.codecs||(ue.codecs=rn),ue.hdr||(ue.hdr=Ji==="video"&&Md(rn)),ue.representations.push(an)}if(Ji){let J=r[Ji].find(Nt=>Nt.id===ue.id);if(J&&ue.representations.every(Nt=>Nt.segmentReference.type==="template"))for(let Nt of J.representations){let en=ue.representations.find(Ft=>Ft.id===Nt.id);if(!en)continue;let tn=en.segmentReference,hi=Nt.segmentReference;hi.segments.push(...tn.segments),hi.nextSegmentBeyondManifest=tn.nextSegmentBeyondManifest}else r[Ji].push(ue)}}return{duration:g,streams:r,baseUrls:n,live:v}};var Qo=_(Ke(),1),Dd=_(Le(),1);import{assertNever as Wo}from"@vkontakte/videoplayer-shared/es2018";var Ho=(s=>(s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient",s))(Ho||{});var jo=a=>{let{webmDecodingInfo:e}=V.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){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:Wo(a)}},_I=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...jo(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(V.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...jo(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...jo(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...jo(a),...s,"HLS","HLS_ONDEMAND"];default:Wo(e)}if(V.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:Wo(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},OI=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=V.device.isMac&&V.browser.isSafari;if(V.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Wo(a)}else V.video.nativeHlsSupported&&!u&&!V.browser.isChromiumBased?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Ld=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],zo=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Qo.default)(t.value.split("."),0)}for(let t of a){let i=(0,Qo.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Qo.default)(e.value.split("."),0)},Go=a=>{let e=a.map(i=>Vr(i)),{codecs:t}=V.video;return PB().filter(i=>{if((0,Dd.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},Yo=a=>{let e=a.map(i=>Vr(i)),{codecs:t}=V.video;return kB().filter(i=>{if((0,Dd.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Vr=a=>a.split(".")[0].replace("0",""),PB=()=>["av1","vp9","hev1","avc1"],kB=()=>["opus","mp4a"];var JI=_(Ke(),1);var AB=(a,e={})=>{let i=e.timeout||1,r=performance.now();return de.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},RB=a=>de.clearTimeout(a),NI=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),FI=!NI(de.requestIdleCallback)||!NI(de.cancelIdleCallback),_i=FI?AB:de.requestIdleCallback,Oi=FI?RB:de.cancelIdleCallback;import{abortable as Fd,assertNonNullable as Tt,ErrorCategory as KB,fromEvent as XB,getExponentialDelay as JB,getWindow as XI,isHigher as ZB,isNonNullable as ce,isNullable as ge,once as eV,Subject as tV,Subscription as iV,ValueSubject as Ps}from"@vkontakte/videoplayer-shared/es2018";var qI=_(Ke(),1);var Ko=a=>a.valid,W=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===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}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 _r=class extends W{};import{assertNever as MB}from"@vkontakte/videoplayer-shared/es2018";var es=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:MB(e)}}};var ts=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var is=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var re=class extends W{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var rs=class extends re{constructor(e,t){super(e,t),this.valid&&(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 as=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ss=class extends W{constructor(e,t){super(e,t),this.data=this.content}};var Ni=class extends re{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:c})}}}};var ns=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var os=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var us=class extends re{constructor(e,t){if(super(e,t),!this.valid)return;switch(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 cs=class extends re{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var ls=class extends re{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var ds=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ps=class extends re{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 hs=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fs=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ms=class extends re{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var bs=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var gs=class extends re{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 vs=class extends re{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 Ss=class extends re{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 ys=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ts=class extends re{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var Is=class extends W{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var CB={ftyp:ts,moov:is,mvhd:rs,moof:as,mdat:ss,sidx:Ni,trak:ns,mdia:ds,mfhd:ms,tkhd:ps,traf:bs,tfhd:gs,tfdt:vs,trun:Ss,minf:hs,sv3d:os,st3d:us,prhd:cs,proj:fs,equi:ls,uuid:es,stbl:ys,stsd:Ts,avc1:Is,unknown:_r},$t=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!Ko(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=CB[e];return i?new i(t,new a):new _r(t,new a)}};var ei=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;Ko(t)&&((s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var LB=new TextDecoder("ascii"),BB=a=>LB.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",VB=a=>{let e=new Ni(a,new $t),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},_B=(a,e)=>{let i=new $t().parse(a),r=new ei(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],c=o.source.byteOffset,l=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,c,l)},OB=a=>{let t=new $t().parse(a),i=new ei(t),r={},s=i.findAll("uuid"),n=(0,qI.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},NB=a=>{var r;let t=new $t().parse(a);return(r=new ei(t).find("sidx"))==null?void 0:r.timescale},FB=(a,e)=>{let i=new $t().parse(a),s=new ei(i).findAll("traf"),n=s[s.length-1].children.find(l=>l.type==="tfhd"),o=s[s.length-1].children.find(l=>l.type==="tfdt"),u=s[s.length-1].children.find(l=>l.type==="trun"),c=0;return u.sampleDuration.length?c=u.sampleDuration.reduce((l,p)=>l+p,0):c=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+c)/e*1e3},qB=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new $t().parse(a),r=new ei(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},UI={validateData:BB,parseInit:qB,getIndexRange:()=>{},parseSegments:VB,parseFeedableSegmentChunk:_B,getChunkEndTime:FB,getServerLatencyTimestamps:OB,getTimescaleFromIndex:NB};var ws=_(Le(),1);import{assertNonNullable as Bd,isNonNullable as WI,isNullable as HB}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as UB}from"@vkontakte/videoplayer-shared/es2018";var HI={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"}},jI=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Es(a,t),r=i in HI,s=r?HI[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),c=n&255>>o,d=Es(u),l=c*2**((o-1)*8)+d,p=t+o,h;return p+l>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,l),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+l,value:h,valueSize:l}},Es=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ct=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Es(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:UB(e)}},Fi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=jI(i);if(!e(r))return;r.type==="master"&&Fi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},QI=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=jI(a);return Fi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ct(o,n):s===17026?t=ct(o,n):s===17029&&(i=ct(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var zI=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],jB=[231,22612,22743,167,171,163,160,175],QB=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,c,d=!1,l=0;return Fi(a,({tag:p,type:h,value:f,valueSize:m})=>{if(p===21419){let v=ct(f,h);c=Es(v)}else p!==21420&&(c=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+m):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=ct(f,h):p===17545?r=ct(f,h):p===21420&&c===475249515?u=ct(f,h):p===374648427?Fi(f,({tag:v,type:g,value:S})=>v===30321?(d=ct(S,g)===1,!1):!0):s&&n&&(0,ws.default)(zI,p)&&(o=!0),!o}),Bd(e,"Failed to parse webm Segment start"),Bd(t,"Failed to parse webm Segment end"),Bd(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:l,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},WB=a=>{if(HB(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},zB=(a,e)=>{let t=!1,i=!1,r=o=>WI(o.time)&&WI(o.position),s=[],n;return Fi(a,({tag:o,type:u,value:c})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=ct(c,u));break;case 183:break;case 241:n&&(n.position=ct(c,u));break;default:t&&(0,ws.default)(zI,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:c,position:d}=o,l=s[u+1];return{status:"none",time:{from:c,to:l?l.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:l?e.segmentStart+l.position-1:e.segmentEnd-1}}})},GB=a=>{let e=0,t=!1;try{Fi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ws.default)(jB,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,ws.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},GI={validateData:QI,parseInit:QB,getIndexRange:WB,parseSegments:zB,parseFeedableSegmentChunk:GB};var qi=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return GI;case"mp4":return UI}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Vd=_(Ke(),1);import{videoSizeToQuality as YB}from"@vkontakte/videoplayer-shared/es2018";var ti=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:YB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},xs=({id:a,bitrate:e})=>({id:a,bitrate:e}),YI=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),KI=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),_d=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Vd.default)(i.split("."),0),isDefault:r}),Od=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Vd.default)(r.split("."),0)}),Nd=a=>"url"in a,Qe=a=>a.type==="template";var Or=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,getCurrentStallDuration:o,manifest:u}){this.error$=new tV;this.playingRepresentation$=new Ps(void 0);this.playingRepresentationInit$=new Ps(void 0);this.currentSegmentLength$=new Ps(0);this.onLastSegment$=new Ps(!1);this.fullyBuffered$=new Ps(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new ie;this.downloadAbortController=new ie;this.subscription=new iV;this.startWith=Fd(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Tt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=qi(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Tt(i,"No init buffer for starting representation"),Tt(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s)}.bind(this));this.switchTo=Fd(this.destroyAbortController.signal,async function*(e,t=!0){var l;if(ge(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);Tt(r,`No such representation ${e}`),Tt(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let s=this.initData.get(r.id),n=this.segments.get(r.id);Tt(s,"No init buffer for switching representation"),Tt(n,"No segments for switching representation");let o=(l=this.getCurrentPosition())!=null?l:0,u=p=>p.segment.bufferStatus!=="fed",c=p=>{let h=this.representations.get(p.representationId);return Tt(h,"No itemRepresentation for previous track before switch"),p.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(h,r)},d=p=>t?u(p)&&c(p):u(p);this.bufferPlaybackQueue.filter(d).forEach(p=>p.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(p=>!d(p)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=Fd(this.downloadAbortController.signal,async function*(){let e=JB(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=XI();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add(XB(i,"online").pipe(eV()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));var c;this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=s,this.getCurrentPosition=n,this.getCurrentStallDuration=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.baseUrls=(c=u==null?void 0:u.baseUrls)!=null?c:[],this.representations=new Map(i.map(d=>[d.id,d]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){ge(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.bufferPlaybackQueue.filter(s=>s.segment.networkStatus==="downloaded"),i=t[t.length-1],r=ce(e)&&ce(i)?i.segment.time.to-e:0;return Math.max(r,0)}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){var s,n;let t=(n=(s=this.downloadingRepresentationId)!=null?s:this.playingRepresentationId)!=null?n:"",i=this.segments.get(t),r=i==null?void 0:i.find(o=>o.time.from<=e&&o.time.to>=e);return r==null?void 0:r.time.from}getRepresentationInitialTime(){var t;if(ge(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return((t=e==null?void 0:e[0].time.from)!=null?t:0)/1e3}calculateDurationFromSegments(e){var i;let t=this.segments.get(e);return(t?(i=(0,JI.default)(t,-1))==null?void 0:i.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=XI();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.__polyfill_cancelIdleCallback_28a81g6h3c8f)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_28a81g6h3c8f(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=ti(e),s=ti(t);i=ce(r)&&ce(s)&&ZB(s.quality,r.quality)}else if(this.kind==="audio"){let r=xs(e),s=xs(t);i=ce(r==null?void 0:r.bitrate)&&ce(s==null?void 0:s.bitrate)&&s.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new ie,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,this.maintainNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,_i(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),s;this.initData.has(e.id)&&this.segments.has(e.id)?s=Promise.resolve():ce(r)?s=r:s=this.loadInit(e,t,i),await s}async loadInit(e,t="auto",i=!1){var r;try{let s=this.tuning.dash.useFetchPriorityHints?t:"auto",n=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s);this.initDataPromises.set(e.id,n);let{initMetadata:o,initDataView:u,segments:c}=(r=await n)!=null?r:{};if(this.initDataPromises.delete(e.id),ge(u)||ge(c))return;o&&this.parsedInitData.set(e.id,o);let d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d),this.segments.set(e.id,c),this.failedDownloads=0}catch(s){i&&this.error$.next({id:"LoadInits",category:KB.WTF,message:"loadInit threw",thrown:s})}}async maintainNativeBuffer(){var h,f,m;let e=this.getCurrentPosition(),t=this.segments.get((h=this.downloadingRepresentationId)!=null?h:""),i=t==null?void 0:t[(t==null?void 0:t.length)-1];if(ge(e)||ge(i)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let r=this.bufferPlaybackQueue.find(v=>this.withinInterval(e,v.segment.time)),s=this.bufferPlaybackQueue.find(v=>v.segment.bufferStatus!=="fed"),n=this.initData.get((f=s==null?void 0:s.representationId)!=null?f:""),o=this.bufferPlaybackQueue[0],u=this.downloadAbortController.signal,d=((m=this.getCurrentStallDuration())!=null?m:0)>0;this.tuning.dash.useBufferHoldingOnlyOnStall&&d&&(d=e>0);let l=Math.min(this.tuning.dash.minSafeBufferToPlay,i.time.to-e),p=d?this.getForwardPlaybackBufferDuration()>=l:!0;ce(n)&&ce(s)&&ce(r)&&this.playingRepresentationId!==s.representationId&&this.withinAppendInterval(e,s.segment.time)&&(s===r||r.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(n,this.downloadAbortController.signal),this.playingRepresentationId=s.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),ce(s)&&this.withinAppendInterval(e,s.segment.time)&&p&&(s.segment.loadedBytes===s.segment.size&&s.segment.bufferStatus==="none"?await this.appendSegmentFully(s,u):await this.appendSegmentPartially(s,u)),ce(o)&&this.withinRemoveInterval(e,o.segment.time)&&await this.removeSegment(o,u),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){Tt(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(ge(t)||ge(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(n=>e>=n.time.from&&e<n.time.to);ce(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let s=this.selectItemsToLoad();await this.loadItems(s,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){var r;let t=this.segments.get((r=this.downloadingRepresentationId)!=null?r:"");if(ge(t)||t.length===0)return;let i=t[(t==null?void 0:t.length)-1];ge(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){Tt(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,s;ce(i)&&this.withinInterval(e,i)?(s=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(s=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&s>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;s-=u-o,r++}return n}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return ce(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return ce(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return ce(e)?e-i>t:!1}async appendSegmentFully(e,t){if(ge(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if(ge(e.segment.data)||ge(e.segment.loadedBytes)||ge(e.segment.feedingBytes)||ge(e.segment.fedBytes)||ge(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),s=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;s!=null&&s.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=s.byteLength,await this.nativeBufferManager.append(s,t)&&(e.segment.fedBytes+=s.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,s=(r-i)/4;await this.nativeBufferManager.remove(0,r-s,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||ce(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let s=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)ce(o.size)&&s>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())ce(o.size)&&s>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,s-=o.size)}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())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as rV,isNonNullable as aV,isNullable as ZI,now as eE}from"@vkontakte/videoplayer-shared/es2018";var Xo=class extends Or{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(s,{...n,priority:i}),this.lastDataObtainedTimestampMs=eE(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),ot(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,s=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=s);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if($e(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,s={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:s,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=eE(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:s?s.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:rV.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:s,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||ZI(o)||ZI(r)||n.aborted))for(let u of e){let{segment:c}=u,d=c.byte.from-r,l=c.byte.to-r,p=l-d+1,h=d<s,f=l<=s;c.size=p,h&&(c.networkStatus==="downloading"&&c.bufferStatus==="none"&&f?(c.data=new DataView(t.buffer,t.byteOffset+d,p),this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u),c.loadedBytes=Math.min(p,s-d),await this.onDownloadItem(u)):aV(c.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&c.networkStatus==="downloading"&&(c.loadedBytes=Math.min(p,s-d),f&&(this.currentVirtualBufferSize+=c.size,this.onItemFullyDownloaded(u)),c.loadedBytes>c.feedingBytes&&(c.data=new DataView(t.buffer,t.byteOffset+d,c.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if($e(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as sV,isNullable as qd,now as tE}from"@vkontakte/videoplayer-shared/es2018";var Nr=class extends Or{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:s,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(s,{...n,priority:i});if(this.lastDataObtainedTimestampMs=tE(),qd(o))return;let u=e[0],c=new DataView(o);u.segment.size=c.byteLength,u.segment.loadedBytes=c.byteLength,u.segment.data=c,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),ot(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(n,o)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=tE(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:sV.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!$e(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:s}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||qd(u)||qd(o.feedingBytes)||o.networkStatus!=="downloading"||s.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(n)))}updateRepresentationBaseUrl(e,t){if(!$e(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var Ud=_(za(),1),rE=_(Ke(),1);import{assertNonNullable as nV,ErrorCategory as oV,isNullable as Ct,ValueSubject as iE}from"@vkontakte/videoplayer-shared/es2018";var Jo=class extends Nr{constructor(t,i,r,s){super(t,i,r,s);this.currentLiveSegmentServerLatency$=new iE(0);this.currentLowLatencySegmentLength$=new iE(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=s.isActiveLowLatency}updateManifest(t){var r,s,n;if(!t||[...this.segments.values()].every(o=>!o.length))return;let i=(0,Ud.default)(t.streams[this.kind],o=>o.representations);for(let o of i){if(Ct(o)||!$e(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,networkStatus:"none",bufferStatus:"none",size:void 0})),c=100,d=(r=this.segments.get(o.id))!=null?r:[],l=(n=(s=(0,rE.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>l>=h.time.from+c&&l<=h.time.to+c);if(p===-1){let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...d,...h])}this.representations.set(o.id,o)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;nV(t);let i=this.segments.get(t);if(i!=null&&i.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t==null?void 0:t.streams[this.kind],r=(0,Ud.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if(Ct(r))return;let s=this.segments.get(r.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}getRepresentationInitialTime(){var r;if(Ct(this.playingRepresentationId))return 0;let t=(r=this.representations.get(this.playingRepresentationId))==null?void 0:r.segmentReference;return Ct(t)||!$e(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),Ct(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:s,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);s&&n&&this.currentLiveSegmentServerLatency$.next(n-s),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){var n;let i=t.segment.data,r=(n=this.representations.get(t.representationId))==null?void 0:n.segmentReference;if(Ct(t.segment.data)||Ct(r)||!$e(r))return;let s=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:o}=r;t.segment.time.to=s.getChunkEndTime(i,o)}}updateLowLatencyLive(t){var r;let i=0;for(let s of this.representations.values()){let n=s.segmentReference;if(!$e(n))return;let o=(r=this.segments.get(s.id))!=null?r:[],u=o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.from));if(u!=null&&u.isCurrentLowLatency&&(u.time.to=t.segment.time.to,i=u.time.to-u.time.from,u.isCurrentLowLatency=!1),!!!o.find(d=>Math.floor(d.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let d=Math.round(t.segment.time.to*n.timescale/1e3).toString(10),l=ut(n.segmentTemplateUrl,{segmentTime:d});o.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:l,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){var s;try{let n=this.tuning.dash.useFetchPriorityHints?i:"auto",o=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,n);this.initDataPromises.set(t.id,o);let{initMetadata:u,initDataView:c,segments:d}=(s=await o)!=null?s:{};if(this.initDataPromises.delete(t.id),Ct(c)||Ct(d))return;u&&this.parsedInitData.set(t.id,u);let l=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,l);let p=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(t.id,p),this.failedDownloads=0}catch(n){r&&this.error$.next({id:"LoadInits",category:oV.WTF,message:"loadInit threw",thrown:n})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[],n=0,o=i.length-1;do s.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[s[0]]:s}};var ks=class{static getBufferManager(e,t,i,r){var s;return(s=r.manifest)!=null&&s.live?new Jo(e,t,i,r):$e(i[0].segmentReference)?new Nr(e,t,i,r):new Xo(e,t,i,r)}};import{ErrorCategory as lV,fromEvent as dV,isNullable as Fr,Subject as pV,Subscription as hV}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as uV,ErrorCategory as aE,Subject as sE}from"@vkontakte/videoplayer-shared/es2018";var cV=18,nE=!1;try{nE=V.browser.isSafari&&!!V.browser.safariVersion&&V.browser.safariVersion<=cV}catch(a){console.error(a)}var Hd=class{constructor(e,t=!1){this.bufferFull$=new sE;this.error$=new sE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!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.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:aE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};nE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!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.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:aE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:uV(t)}}},oE=Hd;var ii=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var As=class{constructor(e){this.error$=new pV;this.subscription=new hV;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new oE(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add(dV(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:lV.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if(Fr(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&(i=await this.sourceBufferTaskQueue.remove(r.from,r.to,e));return i}warmUpMediaSource(){!Fr(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(Fr(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return Fr(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Fr(e)?0:ii(this.sourceBuffer.buffered,e)}async abortBuffer(e){return Fr(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){var e;if(this.subscription.unsubscribe(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null}};var Zo=(a,e)=>{a.video.forEach(t=>{let i=t.representations.filter(({fps:r,height:s})=>{var o;let n=(o=e.find(([u])=>u===`${s}p`))==null?void 0:o[1];return n&&Number.isInteger(n)&&r&&Number.isInteger(r)?r<=n:!0});t.representations=i})};var vV=["timeupdate","progress","play","seeked","stalled","waiting"],dE=["timeupdate","progress","loadeddata","playing","seeked"],tu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new lE;this.subscriptionRemovable=new gV;this.representationSubscription=new lE;this.forceEnded$=new ai;this.destroyController=new ie;this.state$=new H("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new ai;this.manifestRequested=new ai;this.manifestReceived=new ai;this.firstBytesRequested=new ai;this.firstBytesReceived=new ai;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.lastConnectionMetrics$=new Z(void 0);this.lastDownloadMetrics$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.isActiveLive$=new Z(!1);this.isLowLatency$=new Z(!1);this.liveDuration$=new Z(0);this.liveSeekableDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(0);this.liveStreamStatus$=new Z(void 0);this.currentBuffer$=new Z({from:0,to:0});this.bufferLength$=new Z(0);this.nativeBufferLength$=new Z(0);this.liveLatency$=new Z(void 0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.currentStallDuration$=new Z(0);this.videoLastDataObtainedTimestamp$=new Z(0);this.fetcherRecoverableError$=new ai;this.fetcherError$=new ai;this.initRepresentations=uE(this.destroyController.signal,async function*(e,t,i){var s;this.tracer.log("initRepresentationsStart",eu({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,getCurrentStallDuration:()=>this.currentStallDuration$.getValue(),isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),Dt(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?(s=this.audioBufferManager)==null?void 0:s.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=uE(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Ms(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ui.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new No({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.initTracerSubscription()}async initManifest(e,t,i){var r;this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ui.PARSER,message:"No playable video representations"})}initBuffer(){var t,i;Dt(this.element),this.state$.setState("running"),this.subscription.add($s(...vV.map(r=>Hi(this.element,r)),Hi(Rs(),"online"),cE(this.tuning.dash.tickMaintainInterval)).subscribe(()=>this.tick(),r=>this.error$.next({id:"DashVKPlayer",category:Ui.WTF,message:"Internal logic error",thrown:r})));let e=[...(i=(t=this.source)==null?void 0:t.activeSourceBuffers)!=null?i:[]];this.subscription.add($s(...e.map(r=>Hi(r,"updateend"))).subscribe(r=>this.reinitDecoderIfNeeded())),this.subscription.add(Hi(this.element,"waiting").subscribe(r=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=cE(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),s=>this.error$.next({id:"StallWatchdogCallback",category:Ui.NETWORK,message:"Can't restore DASH after stall.",thrown:s})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}async seek(e,t=!1){var r,s,n,o;Dt(this.element),Dt(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await((o=this.audioBufferManager)==null?void 0:o.seek(i)),this.tracer.log("seek",eu({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){ri(this.element)&&ri(this.source)&&ri(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(i=>i.warmUpMediaSource())}calculateDurationFromSegments(e){var t,i;return Math.max(((t=this.videoBufferManager)==null?void 0:t.calculateDurationFromSegments(e))||0,((i=this.audioBufferManager)==null?void 0:i.calculateDurationFromSegments(e))||0)}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}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),this.nativeBufferManagers.forEach(r=>r.destroy()),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&Rs().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),ri(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){var e;return((e=this.source)==null?void 0:e.readyState)!=="open"}async reinitDecoderIfNeeded(e=!1){var r,s;let t=(s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[];if(Ms(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(n=>i>=n.from&&i<=n.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){Dt(this.element),Dt(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t)){if(this.tuning.dash.useNewStallExitPolicy)return this.seek(this.element.currentTime*1e3);throw new Error(`Stall timeout exceeded: ${t} ms`)}await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",eu(i))}isStallExceeded(e){var p,h,f,m,v,g,S,T;let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=bV(),s=100,n=(h=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?h:0;this.videoLastDataObtainedTimestamp$.next(n);let o=(m=(f=this.audioBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0,u=(g=(v=this.videoBufferManager)==null?void 0:v.getForwardPlaybackBufferDuration())!=null?g:0,c=(T=(S=this.audioBufferManager)==null?void 0:S.getForwardPlaybackBufferDuration())!=null?T:0,d=ri(this.videoBufferManager)&&u<s&&r-n>i,l=ri(this.audioBufferManager)&&c<s&&r-o>i;return(d||l)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Ms(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",eu(i)),i}parseManifest(e){var t;try{return Uo(e!=null?e:"",this.manifestUrlString)}catch(i){let r=(t=Bo(e))!=null?t:{id:"ManifestParsing",category:Ui.PARSER,message:"Failed to parse MPD manifest",thrown:i};this.error$.next(r)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,c)=>{var d,l,p,h;return!!((l=(d=this.element)==null?void 0:d.canPlayType)!=null&&l.call(d,u)&&((h=(p=He())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${u}; codecs="${c}"`))||o==="text")},r,s;for(let o of["video","audio"]){let c=e.streams[o].filter(({mime:l,codecs:p})=>i(o,l,p));t[o]=c;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let l=c.map(({codecs:p})=>p);o==="audio"&&(s=Yo(l),d=s[0]),o==="video"&&(r=Go(l),this.forceVideoCodec&&(0,pE.default)(r,this.forceVideoCodec)?d=this.forceVideoCodec:d=r[0]),d&&(t[o]=c.filter(({codecs:p})=>Vr(p)===d))}else{let l=new Set(c.map(({codecs:p})=>p));d=zo(l),d&&(t[o]=c.filter(({codecs:p})=>p.startsWith(d)))}if(o==="video"){let l=this.tuning.preferHDR,p=t.video.some(m=>m.hdr),h=t.video.some(m=>!m.hdr);V.display.isHDR&&l&&p?t.video=t.video.filter(m=>m.hdr):h&&(t.video=t.video.filter(m=>!m.hdr));let{videoStreamRepresentaionsFilter:f}=this.tuning.dash;f.length&&Zo(t,f)}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:s}),n}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){Dt(this.manifest),Dt(this.element);let s=c=>{this.representationSubscription.add(Hi(c,"error").pipe(jd(d=>{var l;return!!((l=this.element)!=null&&l.played.length)})).subscribe(d=>{this.error$.next({id:"VideoSource",category:Ui.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=$n();let n=Rs().document,o=n.createElement("source");if(s(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),dr())if(r){let c=n.createElement("source");s(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((c,d)=>[...c,...d.representations],[]);if(this.videoNativeBufferManager=new As(this.source),this.videoBufferManager=ks.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],ri(i)){this.audioNativeBufferManager=new As(this.source);let c=this.manifest.streams.audio.reduce((d,l)=>[...d,...l.representations],[]);this.audioBufferManager=ks.getBufferManager("audio",this.audioNativeBufferManager,c,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}async waitStreamToOpen(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;await new Promise(t=>{var i;e&&(this.timeoutSourceOpenId=Rs().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:Ui.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(i=this.source)==null||i.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&Rs().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.representationSubscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.representationSubscription.add($s(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),Dt(this.videoBufferManager),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.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add($s(...dE.map(e=>Hi(this.element,e))).pipe(Qd(e=>{var t;return(t=this.videoBufferManager)==null?void 0:t.getPlaybackBufferState()}),jd(ri),Qd(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add($s(...dE.map(e=>Hi(this.element,e))).pipe(Qd(e=>{var t,i,r,s,n,o;return Math.min((i=(t=this.videoBufferManager)==null?void 0:t.getForwardPlaybackBufferDuration())!=null?i:0,(s=(r=this.audioBufferManager)==null?void 0:r.getForwardPlaybackBufferDuration())!=null?s:0,(o=(n=this.audioBufferManager)==null?void 0:n.getForwardPlaybackBufferDuration())!=null?o:0)}),fV()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(jd(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=mV(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){var r,s,n;if(Ms(this.element)||Ms(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=((s=(r=this.videoNativeBufferManager)==null?void 0:r.getBufferState())!=null?s:[]).find(o=>e>=o.from&&e<=o.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await((n=this.audioBufferManager)==null?void 0:n.maintain(e))}};import{assertNonNullable as iu,combine as SV,ErrorCategory as yV,filter as Wd,filterChanged as TV,fromEvent as IV,isNonNullable as EV,map as zd,merge as Cs}from"@vkontakte/videoplayer-shared/es2018";var ru=class extends tu{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){var t;iu(this.manifest),iu(this.source);let e=[(t=this.manifest.duration)!=null?t:0,...(0,Gd.default)((0,Gd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],i=>i.representations),i=>{let r=[];return i.duration&&r.push(i.duration),$e(i.segmentReference)&&i.segmentReference.totalSegmentsDurationMs&&r.push(i.segmentReference.totalSegmentsDurationMs),r})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){var i,r;iu(this.element);let t=this.element.currentTime*1e3;await Promise.all([(i=this.videoBufferManager)==null?void 0:i.maintain(t),(r=this.audioBufferManager)==null?void 0:r.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){iu(this.element);let e=Cs(IV(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(Wd(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(Cs(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=Cs(...this.bufferManagers.map(s=>s.fullyBuffered$)).pipe(zd(()=>this.bufferManagers.every(s=>s.fullyBuffered$.getValue()))),t=Cs(...this.bufferManagers.map(s=>s.onLastSegment$)).pipe(zd(()=>this.bufferManagers.some(s=>s.onLastSegment$.getValue()))),i=SV({allBuffersFull:e,someBufferEnded:t}).pipe(TV(),zd(({allBuffersFull:s,someBufferEnded:n})=>s&&n),Wd(s=>s)),r=()=>{var s;try{(s=this.source)==null||s.endOfStream()}catch(n){this.error$.next({id:"EndOfStream",category:yV.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:n})}};this.representationSubscription.add(Cs(this.forceEnded$,i).pipe(Wd(s=>EV(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var qr=class extends Wa{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe(xV(),wV(s=>PV(s))).subscribe(s=>{let n=this.player.calculateDurationFromSegments(s);n&&this.params.output.duration$.next(n/1e3)},r))}getPlayer(){return new ru({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{assertNever as JV,assertNonNullable as ZV,combine as e_,debounce as t_,ErrorCategory as wE,filter as sp,filterChanged as qs,fromEvent as i_,isNonNullable as xE,isNullable as r_,map as Us,merge as Hs,observableFrom as mu,once as PE,Subscription as a_,throttle as s_}from"@vkontakte/videoplayer-shared/es2018";var EE=_(Le(),1),rp=_(za(),1);var si=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as ep,assertNonNullable as Qr,combine as Wr,ErrorCategory as Ze,filter as pu,filterChanged as Os,flattenObject as Ns,fromEvent as Bt,getTraceSubscriptionMethod as FV,interval as tp,isNonNullable as Fs,isNullable as TE,map as zr,merge as Gi,now as ip,Subject as Vt,Subscription as IE,SubscriptionRemovable as qV,tap as UV,throttle as HV,ValueSubject as ae}from"@vkontakte/videoplayer-shared/es2018";var su=_(Le(),1),Qi=_(Ke(),1),nu=_(za(),1);var gE=_(Nl(),1);import{assertNever as kV,ErrorCategory as hE,Subject as fE}from"@vkontakte/videoplayer-shared/es2018";var AV=18,mE=!1;try{mE=V.browser.isSafari&&!!V.browser.safariVersion&&V.browser.safariVersion<=AV}catch(a){console.error(a)}var Yd=class{constructor(e,t=!1){this.bufferFull$=new fE;this.error$=new fE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!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.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:hE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};mE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!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.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:hE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:kV(t)}}},bE=Yd;var Kd=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as ni,assertNonNullable as Ce,ErrorCategory as Lt,fromEvent as Xd,getExponentialDelay as Jd,isHigher as RV,isNonNullable as oi,isNullable as pe,now as au,once as MV,Subject as $V,Subscription as CV,ValueSubject as ji}from"@vkontakte/videoplayer-shared/es2018";var Ds=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:c}){this.currentLiveSegmentServerLatency$=new ji(0);this.currentLowLatencySegmentLength$=new ji(0);this.currentSegmentLength$=new ji(0);this.onLastSegment$=new ji(!1);this.fullyBuffered$=new ji(!1);this.playingRepresentation$=new ji(void 0);this.playingRepresentationInit$=new ji(void 0);this.error$=new $V;this.gaps=[];this.subscription=new CV;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ie;this.switchAbortController=new ie;this.destroyAbortController=new ie;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=ni(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ce(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new bE(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(Xd(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Lt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Lt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Xd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Lt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!te(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Kd(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let c=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,c<d).catch(l=>{this.handleAsyncError(l,"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),s=this.parsedInitData.get(t.id);Ce(i,"No init buffer for starting representation"),Ce(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=ni(this.destroyAbortController.signal,async function*(e,t=!1){if(!te(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ce(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(pe(s)||pe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ce(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();oi(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=ni(this.destroyAbortController.signal,async function*(e,t=!1){if(!te(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ce(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(pe(s)||pe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ce(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();oi(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=ni(this.destroyAbortController.signal,async function*(e){var u;let t=(0,nu.default)(e,c=>c.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let l=this.representations.get(c);if(!l||!Qe(l.segmentReference)){this.isSeekingLive=!1;return}let p=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,p)}let i=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,r=this.representations.get(i);Ce(r,`Representation not found by id ${i}`);let s=this.segments.get(i);Ce(s,"No segments for starting representation");let n=this.initData.get(i);if(Ce(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(c!=null&&c.live),this.baseUrls=(d=c==null?void 0:c.baseUrls)!=null?d:[],this.initData=new Map(i.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!te(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ie,ni(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Ce(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(pe(o)||pe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Ce(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!te(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();oi(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(){!pe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ie,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var p;if(pe(e)||pe(this.downloadingRepresentationId)||pe(this.playingRepresentationId)||pe(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer)||oi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if(Ce(t,`No such representation ${this.downloadingRepresentationId}`),Ce(i,`No such representation ${this.playingRepresentationId}`),pe(r)||pe(s))return;let n=r.find(h=>e>=h.time.from&&e<h.time.to);oi(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next((n==null?void 0:n.time.to)-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=this.getForwardBufferDuration(e),f=ti(i),m=ti(t),v=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&oi(f)&&oi(m)&&RV(f.quality,m.quality),g=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(v||g?o+=Math.min(h,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let T=(p=[...this.segments.entries()].map(([y,x])=>{let R=x.find(D=>e>=D.time.from&&e<D.time.to);return{representationId:y,status:R==null?void 0:R.status}}).find(y=>y.status==="fed"))==null?void 0:p.representationId;T&&(this.playingRepresentationId=T,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&Kd(this.sourceBuffer.buffered)>=this.bufferLimit){let h=this.getForwardBufferDuration(e),f=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,h<f).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let d=[];if(!this.activeSegments.size&&(d=this.selectForwardBufferSegments(r,t.segmentReference.type,o),d.length)){let h="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,su.default)(d,n))h="high";else{let f=(0,Qi.default)(d,0);f&&f.time.from-n.time.to>=this.forwardBufferTarget/2&&(h="low")}this.loadSegments(d,t,h).catch(f=>{this.handleAsyncError(f,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!d.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Qi.default)(r,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<u),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 s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;oi(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=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind];if(!t)return;let i=(0,nu.default)(t,s=>s.representations).find(s=>s.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var i,r,s;if(!e||[...this.segments.values()].every(n=>!n.length))return;let t=(0,nu.default)(e.streams[this.kind],n=>n.representations);for(let n of t){if(!n||!Qe(n.segmentReference))return;let o=n.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),u=100,c=(i=this.segments.get(n.id))!=null?i:[],d=(s=(r=(0,Qi.default)(c,-1))==null?void 0:r.time.to)!=null?s:0,l=o==null?void 0:o.findIndex(p=>d>=p.time.from+u&&d<=p.time.to+u);if(l===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,p)}else{let p=o.slice(l+1);this.segments.set(n.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Ce(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,Qi.default)(e,-1))==null?void 0:t.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Qe(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(c=>Math.floor(c.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(c=>Math.floor(c.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let c=Math.round(e.time.to*s.timescale/1e3).toString(10),d=ut(s.segmentTemplateUrl,{segmentTime:c});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let 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&&Oi&&Oi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Oi&&Oi(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=this.getForwardBufferDuration(i),s=e.findIndex(({status:p,time:{from:h,to:f}},m)=>{let v=h<=i&&f>=i,g=h>i||v||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+S||r<S&&f-h>=S||f<=i+S;return(p==="none"||p==="partially_ejected"&&g&&T&&this.sourceBuffer&&te(this.mediaSource,this.sourceBuffer)&&!(si(this.sourceBuffer.buffered,h)&&si(this.sourceBuffer.buffered,f)))&&g&&T});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,c=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=d||u<=l);p++){let h=n[p];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")c.push(h);else break}return c}async loadSegments(e,t,i="auto"){Qe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:c}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ni(o,async function*(){let d=Jd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=au(),!d)return;let l=new DataView(d),p=qi(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(l,m)}u&&r.feedingBytes&&c?await Promise.all(c):await this.sourceBufferTaskQueue.append(l,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(l);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),ot(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())Qe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ni(n,async function*(){let u=Jd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(c,u),Xd(window,"online").pipe(MV()).subscribe(()=>{c(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=au(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ot(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Qe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Qi.default)(e,0).byte.from,to:(0,Qi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=au(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:Lt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Qe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=au();let l=this.onSomeTemplateDataLoaded({dataView:c,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(l)}catch(l){this.error$.next({id:"SegmentFeeding",category:Lt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,su.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!te(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=qi(n.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!te(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:c}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let d=c.byte.from-i,l=c.byte.to-i,p=l-d+1,h=d<r,f=l<=r;if(!h)continue;let m=qi(o.mime);if(c.status==="downloading"&&f){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-d),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?v:m.parseFeedableSegmentChunk(v);g!=null&&g.byteLength&&(c.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(pe(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer))){!this.isLive&&V.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(si(this.sourceBuffer.buffered,e.segment.time.from,100)&&si(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Lt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",Nd(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=_i(()=>(0,gE.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?ni(this.destroyAbortController.signal,async function*(){let u=Jd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,qi(e.mime),{priority:r,ignoreNetworkErrors:s})).then(async u=>{if(!u)return;let{init:c,dataView:d,segments:l}=u,p=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,p);let h=l;this.isLive&&Qe(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,u=>{s||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Lt.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||pe(e))return!1;let r=[],s=0,n=u=>{u.sort((d,l)=>d.from-l.from);let c=[u[0]];for(let d=1;d<u.length;d++){let{from:l,to:p}=u[d],h=c[c.length-1];h.to>=l?h.to=Math.max(h.to,p):c.push(u[d])}return c},o=u=>{var d;if(s>=t)return r;r.push({...u.time}),r=n(r);let c=Nd(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=c};for(let u of this.segments.values())for(let c of u){let d=c.time.to<=e-this.tuning.dash.bufferPruningSafeZone,l=c.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||l)&&c.status==="fed"&&o(c)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,l=0;for(let p of this.segments.values())for(let h of p)(0,su.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)&&l++;if(l===this.segments.size){let p={time:{from:c,to:d},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(c=>this.sourceBufferTaskQueue.remove(c.from,c.to)))).reduce((c,d)=>c||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!te(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||!te(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||!te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||pe(e)?0:ii(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let o=s.start(n)*1e3,u=s.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!te(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.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}),this.gapDetectionIdleCallback=_i(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:Lt.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(pe(this.sourceBuffer)||!te(this.mediaSource,this.sourceBuffer)||pe(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),c=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(c.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:Lt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as Ls,assertNever as vE,fromEvent as SE,merge as DV,now as Wi,Subject as Ur,ValueSubject as Bs,flattenObject as Hr,ErrorCategory as jr,SubscriptionRemovable as LV,getWindow as Vs}from"@vkontakte/videoplayer-shared/es2018";var uu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested$=new Ur;this.firstBytesManifest$=new Ur;this.firstBytesRequested$=new Ur;this.firstBytesReceived$=new Ur;this.lastConnectionType$=new Bs(void 0);this.lastConnectionReused$=new Bs(void 0);this.lastRequestFirstBytes$=new Bs(void 0);this.lastConnectionMetrics$=new Bs(void 0);this.lastDownloadMetrics$=new Bs(void 0);this.recoverableError$=new Ur;this.error$=new Ur;this.abortAllController=new ie;this.subscription=new LV;this.performanceObserver=null;this.pendingConnectionMetrics=new Map;this.fetchManifest=Ls(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Zt(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=_o(i)),this.trackRequestStart(i,performance.now());let r=Wi();this.manifestRequested$.next();let s=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ou);if(s){let n=Wi();t.log("success",Hr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(s.headers),this.firstBytesManifest$.next();let o=s.headers.get("content-length"),u=0;o&&(u=parseInt(o,10));let c=await s.text();if((!o||isNaN(u)||u<=0)&&(u=new TextEncoder().encode(c).length),u>0){let d=n-r,p=u/(d/1e3)*8/1024,h={bytes:u,speed:p,url:e};this.lastDownloadMetrics$.next(h)}return c}else return t.error("error",Hr({url:i,message:"No data in request manifest"})),t.end(),null}.bind(this));this.fetch=Ls(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:c=!1,ignoreNetworkErrors:d=!1}={}){var G,j,E;let l=e,p=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let P=new URL(l,Vs().location.href);P.searchParams.append("bytes",`${i.from}-${i.to}`),l=P.toString();break}default:vE(t)}this.requestQuic&&(l=Zt(l));let f=this.abortAllController.signal,m;if(n){let P=new ie;if(m=DV(SE(this.abortAllController.signal,"abort"),SE(n,"abort")).subscribe(()=>{try{P.abort()}catch(I){ou(I)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{P.abort()}catch(I){ou(I)}f=P.signal}let v=0,g=Wi();h.log("startRequest",Hr({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.trackRequestStart(l,performance.now()),this.firstBytesRequested$.next();let S=yield this.doFetch(l,{priority:s,headers:p,signal:f},{ignoreNetworkErrors:d}),T=Wi();if(!S)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(m),null;if((G=this.throughputEstimator)==null||G.addRawRtt(T-g),!S.ok||!S.body){this.unsubscribeAbortSubscription(m);let P=`Fetch error ${S.status}: ${S.statusText}`;return h.error("error",{message:P}),h.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!o){this.unsubscribeAbortSubscription(m);let P=Wi(),I={requestStartedAt:g,requestEndedAt:P,duration:P-g};return h.log("endRequest",Hr(I)),h.end(),S.arrayBuffer()}let y=S.body;if(o){let P;[y,P]=S.body.tee(),(j=this.throughputEstimator)==null||j.trackStream(P,u)}let x=y.getReader(),R,D=parseInt((E=S.headers.get("content-length"))!=null?E:"",10);Number.isFinite(D)&&(R=D),!R&&i&&(R=i.to-i.from+1);let M=R?new Uint8Array(R):new Uint8Array(0),L=!1,A=P=>{this.unsubscribeAbortSubscription(m),L=!0,ou(P)},B=Ls(f,async function*({done:P,value:I}){if(v===0&&(this.lastRequestFirstBytes$.next(Wi()-g),this.firstBytesReceived$.next()),f.aborted){this.unsubscribeAbortSubscription(m);return}if(!P&&I){if(c&&R)M.set(I,v),v+=I.byteLength;else{let w=new Uint8Array(M.length+I.length);w.set(M),w.set(I,M.length),M=w,v+=I.byteLength}r==null||r(new DataView(M.buffer),v),yield x==null?void 0:x.read().then(B,A)}}.bind(this));yield x==null?void 0:x.read().then(B,A),this.unsubscribeAbortSubscription(m);let $=Wi(),U={failed:L,requestStartedAt:g,requestEndedAt:$,duration:$-g};if(L)return h.error("endRequest",Hr(U)),h.end(),null;if(v>0){let P=$-g,w=v/(P/1e3)*8/1024,N={bytes:v,speed:w,url:e};this.lastDownloadMetrics$.next(N)}return h.log("endRequest",Hr(U)),h.end(),M.buffer}.bind(this));this.fetchByteRangeRepresentation=Ls(this.abortAllController.signal,async function*(e,t,i){var g;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,c,d;e.indexRange&&(c=e.indexRange.from,d=e.indexRange.to,u=s+1===c,u&&(n=Math.min(c,r),o=Math.max(d,s))),n=Math.min(n,0);let l=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!l)return null;let p=new DataView(l,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(g=e.indexRange)!=null?g:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(l,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,measureThroughput:!1});if(!S)return null;m=new DataView(S)}let v=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(l),segments:v}}.bind(this));this.fetchTemplateRepresentation=Ls(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...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=s,Vs().PerformanceObserver&&this.setupPerformanceObserver()}onHeadersReceived(e){let{type:t,reused:i}=Vo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}setupPerformanceObserver(){this.performanceObserver=new(Vs()).PerformanceObserver(e=>{e.getEntriesByType("resource").forEach(t=>{this.processPerformanceResourceTiming(t)})}),this.performanceObserver.observe({entryTypes:["resource"]})}processPerformanceResourceTiming(e){let t=this.findMatchingRequest(e);if(!t||!this.pendingConnectionMetrics.get(t))return;this.pendingConnectionMetrics.delete(t);let r=this.extractConnectionMetrics(e);r&&this.lastConnectionMetrics$.next(r)}estimateNetworkType(){if(!("connection"in Vs().navigator))return"unknown";let e=Vs().navigator.connection;return e.effectiveType?{"slow-2g":"2g","2g":"2g","3g":"3g","4g":"lte"}[e.effectiveType]||e.effectiveType:e.downlink?e.downlink<1?"2g":e.downlink<5?"3g":e.downlink<50?"lte":"wifi":e.rtt?e.rtt>500?"2g":e.rtt>250?"3g":e.rtt>50?"lte":"wifi":"unknown"}extractConnectionMetrics(e){let t=0,i=0,r=0,s=0;return e.domainLookupStart>0&&e.domainLookupEnd>0&&(t=e.domainLookupEnd-e.domainLookupStart),e.connectStart>0&&e.connectEnd>0&&(s=e.connectEnd-e.connectStart,e.secureConnectionStart>0?(r=e.connectEnd-e.secureConnectionStart,i=e.secureConnectionStart-e.connectStart):i=s),{dnsResolveTime:Math.max(0,t),tcpHandshakeTime:Math.max(0,i),tlsHandshakeTime:Math.max(0,r),totalConnectTime:Math.max(0,s),networkType:this.estimateNetworkType(),url:e.name}}findMatchingRequest(e){try{for(let[t,i]of this.pendingConnectionMetrics.entries()){let r=new URL(e.name),s=r.origin+r.pathname,n=new URL(i.url),o=n.origin+n.pathname;if(s===o&&e.startTime>=i.startTime-10&&e.startTime<=i.startTime+1e3)return t}}catch(t){this.recoverableError$.next({id:"VideoDataFetchError",message:"Video data fetch error with getting download metrics",category:jr.WTF})}return null}trackRequestStart(e,t){let i=`${e}_${t}_${Math.random().toString(36).substr(2,9)}`;this.pendingConnectionMetrics.set(i,{url:e,startTime:t})}async fetchRepresentation(e,t,i){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:vE(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.performanceObserver&&(this.performanceObserver.disconnect(),this.performanceObserver=null),this.pendingConnectionMetrics.clear(),this.tracer.end()}async doFetch(e,t,i){let r=await Je(e,t);if(r.ok)return r;if(i!=null&&i.ignoreNetworkErrors)return;let s=await r.text(),n=parseInt(s);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:jr.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:jr.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:jr.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:jr.FATAL,httpCode:r.status,UVBackendErrorCode:s});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:jr.FATAL,httpCode:r.status,UVBackendErrorCode:s})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},ou=a=>{if(!ot(a))throw a};import{isNullable as BV,ValueSubject as yE}from"@vkontakte/videoplayer-shared/es2018";var ui=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 yE(e.initial),this.debounced$=new yE(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Re(`raw_${t}`),this.smoothedSeries$=new Re(`smoothed_${t}`),this.reportedSeries$=new Re(`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+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(BV(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 cu=class extends ui{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Mt(this.slow,e,this.params.emaAlphaSlow),this.fast=Mt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var lu=class extends ui{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=cd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Mt(this.emaSmoothed,e,this.params.emaAlpha);let i=Wy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var du=class extends ui{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?Mt(this.smoothed,t,this.params.emaAlpha):t}};var zi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new cu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new lu({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 du({initial:e,label:"liveEdgeDelay",...t})}};var Zd=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as VV,ValueSubject as _V}from"@vkontakte/videoplayer-shared/es2018";var _s=class a{constructor(e,t){this.currentRepresentation$=new _V(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(!VV(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let c=s.segments.find(d=>d.time.from<=e&&d.time.to>=e);!c||((t=this.currentSegment)==null?void 0:t.time.from)===c.time.from&&this.currentSegment.time.to===c.time.to||(this.currentSegment=c,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(c.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Qe(t.segmentReference))}};var jV=["timeupdate","progress","play","seeked","stalled","waiting"],QV=["timeupdate","progress","loadeddata","playing","seeked"];var hu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new IE;this.subscriptionRemovable=new qV;this.representationSubscription=new IE;this.state$=new H("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentAudioRepresentation$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new Vt;this.manifestRequested$=new Vt;this.firstBytesManifest$=new Vt;this.manifestReceived$=new Vt;this.firstBytesRequested$=new Vt;this.firstBytesReceived$=new Vt;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.lastConnectionMetrics$=new ae(void 0);this.lastDownloadMetrics$=new ae(void 0);this.currentLiveTextRepresentation$=new ae(null);this.isLive$=new ae(!1);this.isActiveLive$=new ae(!1);this.isLowLatency$=new ae(!1);this.liveDuration$=new ae(0);this.liveSeekableDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(0);this.liveStreamStatus$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLatency$=new ae(void 0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.currentStallDuration$=new ae(0);this.videoLastDataObtainedTimestamp$=new ae(0);this.fetcherRecoverableError$=new Vt;this.fetcherError$=new Vt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Vt;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new ie;this.initManifest=ep(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ee(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:Ze.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=ep(this.destroyController.signal,async function*(){var u,c;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(d=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ze.NETWORK,message:"Failed to load manifest",thrown:d})});if(!e)return null;let t=null;try{t=Uo(e!=null?e:"",this.manifestUrlString),this.manifestReceived$.next()}catch(d){let l=(u=Bo(e))!=null?u:{id:"ManifestParsing",category:Ze.PARSER,message:"Failed to parse MPD manifest",thrown:d};this.error$.next(l)}if(!t)return null;let i=(d,l,p)=>{var h,f,m,v;return!!((f=(h=this.element)==null?void 0:h.canPlayType)!=null&&f.call(h,l)&&((v=(m=He())==null?void 0:m.isTypeSupported)!=null&&v.call(m,`${l}; codecs="${p}"`))||d==="text")};if(t.live){this.isLive$.next(!0);let{availabilityStartTime:d,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:h}=t.live,f=((c=t.duration)!=null?c:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-d)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";if(h||(m=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m),h&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let v=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(v).catch(g=>{this.error$.next({id:"updateManifest",category:Ze.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:g})})}}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let d of["video","audio"]){let p=t.streams[d].filter(({mime:f,codecs:m})=>i(d,f,m));r[d]=p;let h;if(this.tuning.dash.codecsPrioritizeEnabled){let f=p.map(({codecs:m})=>m);d==="audio"&&(n=Yo(f),h=n[0]),d==="video"&&(s=Go(f),this.forceVideoCodec&&(0,EE.default)(s,this.forceVideoCodec)?h=this.forceVideoCodec:h=s[0]),h&&(r[d]=p.filter(({codecs:m})=>Vr(m)===h))}else{let f=new Set(p.map(({codecs:m})=>m));h=zo(f),h&&(r[d]=p.filter(({codecs:m})=>m.startsWith(h)))}if(d==="video"){let f=this.tuning.preferHDR,m=r.video.some(S=>S.hdr),v=r.video.some(S=>!S.hdr);V.display.isHDR&&f&&m?r.video=r.video.filter(S=>S.hdr):v&&(r.video=r.video.filter(S=>!S.hdr));let{videoStreamRepresentaionsFilter:g}=this.tuning.dash;g.length&&Zo(r,g)}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",Ns(o)),o}.bind(this));this.initRepresentations=ep(this.destroyController.signal,async function*(e,t,i){var l;this.tracer.log("initRepresentationsStart",Ns({initialVideo:e,initialAudio:t,sourceHls:i})),Qr(this.manifest),Qr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Bt(p,"error").pipe(pu(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Ze.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=$n();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),dr())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,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Ds("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Fs(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Ds("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(_s.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new _s(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Gi(...QV.map(p=>Bt(this.element,p))).pipe(zr(p=>this.element?ii(this.element.buffered,this.element.currentTime*1e3):0),Os(),UV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Gi(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Os()).subscribe(h=>this.liveStreamEndTimestamp=ip())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:h}=this.tuning.dash;this.livePauseWatchdogSubscription=tp(h).subscribe(f=>{let m=wn(this.manifestUrlString,2);this.manifestUrlString=Ee(this.manifestUrlString,m+h,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Bt(this.element,"play").subscribe(h=>{var f;return(f=this.livePauseWatchdogSubscription)==null?void 0:f.unsubscribe()})),this.representationSubscription.add(Wr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(zr(({isActiveLive:h,isLowLatency:f})=>h&&f),Os()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Zd(this.element,1)})),this.representationSubscription.add(Wr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(pu(({bufferLength:h,isActiveLive:f,isLowLatency:m})=>f&&m&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(Wr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(pu(({isLive:h})=>h),Os((h,f)=>f.bufferLength<h.bufferLength),zr(({rtt:h,bufferLength:f,segmentServerLatency:m})=>{let v=wn(this.manifestUrlString,2);return(h/2+f+m+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Wr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:m})=>{if(!m||!f)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-v;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(T)>g&&(y=1+Math.sign(T)*S),Zd(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var m,v;let f=0;if(h){let g=((v=(m=this.element)==null?void 0:m.currentTime)!=null?v:0)*1e3;f=Math.min(...this.bufferManagers.map(T=>{var y,x;return(x=(y=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:y.to)!=null?x:g}))-g}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(Wr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(HV(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,v=wn(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,x=isFinite(h)?h:f,R=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),D=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(D);let M="none";if(R?M="active_low_latency":this.isLowLatency$.getValue()&&D?(this.bufferManagers.forEach(L=>L.proceedLowLatencyLive()),M="active_low_latency"):v!==0&&x<S?M="live_forward_buffering":x<S+y&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let L=p-(S+T),A=this.normalizeLiveOffset(Math.trunc(v+L/m)),B=Math.abs(A-v),$=0;!h||B<=this.tuning.dashCmafLive.offsetCalculationError?$=v:A>0&&B>this.tuning.dashCmafLive.offsetCalculationError&&($=A),this.manifestUrlString=Ee(this.manifestUrlString,$,2)}(M==="live_with_target_offset"||M==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:Ze.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let u=Gi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(zr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Gi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(zr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=Wr({allBuffersFull:u,someBufferEnded:c}).pipe(Os(),zr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),pu(p=>p));if(this.representationSubscription.add(Gi(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:Ze.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Gi(...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(h=>{var f;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var m;if(((m=this.source)==null?void 0:m.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:Ze.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(f=this.source)==null||f.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(l=this.manifest.duration)!=null?l:0,...(0,rp.default)((0,rp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),Qe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Fs(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,s;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||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=tp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Ze.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.forceVideoCodec=e.forceVideoCodec,this.fetcher=new uu({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.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastConnectionMetrics$.subscribe(this.lastConnectionMetrics$)),this.subscription.add(this.fetcher.lastDownloadMetrics$.subscribe(this.lastDownloadMetrics$)),this.liveBuffer=zi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){Qr(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?ip()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Ee(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){var t,i,r;await((t=this.videoBufferManager)==null?void 0:t.seekLive(e.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(e.streams.audio)),(r=this.liveTextManager)==null||r.seekLive(e.streams.text)}stopStallWatchdogSubscription(){var e;(e=this.stallWatchdogSubscription)==null||e.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){Qr(this.element),this.state$.setState("running"),this.subscription.add(Gi(...jV.map(e=>Bt(this.element,e)),Bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ze.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Bt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Bt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&si(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var y,x,R,D,M,L,A,B,$,U,G;let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:s,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),c=this.liveStreamStatus$.getValue()==="active";if(!this.element||((y=this.source)==null?void 0:y.readyState)!=="open")return;let d=this.currentStallDuration$.getValue();d+=n,this.currentStallDuration$.next(d);let l={timeInWaiting:d},p=ip(),h=100,f=(R=(x=this.videoBufferManager)==null?void 0:x.lastDataObtainedTimestamp)!=null?R:0;this.videoLastDataObtainedTimestamp$.next(f);let m=(M=(D=this.audioBufferManager)==null?void 0:D.lastDataObtainedTimestamp)!=null?M:0,v=(A=(L=this.videoBufferManager)==null?void 0:L.getForwardBufferDuration())!=null?A:0,g=($=(B=this.audioBufferManager)==null?void 0:B.getForwardBufferDuration())!=null?$:0,S=v<h&&p-f>r,T=this.audioBufferManager&&g<h&&p-m>r;if((!t||c)&&((S||T)&&d>r||d>=i))throw new Error(`Stall timeout exceeded: ${d} ms`);if(o&&d%s===0){let j=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!c&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(j),this.updateManifest()):this.seekLive(j).catch(E=>{this.error$.next({id:"stallIntervalCallback",category:Ze.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:E})}),l.liveLastOffset=j}else{let j=this.element.currentTime*1e3;(U=this.videoBufferManager)==null||U.maintain(j),(G=this.audioBufferManager)==null||G.maintain(j),l.position=j}this.tracer.log("stallIntervalCallback",Ns(l))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=tp(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ze.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){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)}async seek(e,t){var r,s,n,o,u;Qr(this.element),Qr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),si(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(TE(this.element)||TE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Ns({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Fs(this.element)&&Fs(this.source)&&Fs(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}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.subscriptionRemovable.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=FV(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(t=>t.updateLive(this.manifest)),(e=this.liveTextManager)==null||e.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},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let c of u.gaps)(r&&c.persistent||u.playingRepresentation$.getValue()===c.representation)&&c.from-o<=s&&c.to+o>s&&(this.element.duration*1e3-c.to<this.tuning.endGapTolerance?n.push(1/0):n.push(c.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ns(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};import{combine as WV,map as zV,observeElementSize as GV,Subscription as YV,ValueSubject as ap,noop as KV}from"@vkontakte/videoplayer-shared/es2018";var fu=class{constructor(){this.subscription=new YV;this.pipSize$=new ap(void 0);this.videoSize$=new ap(void 0);this.elementSize$=new ap(void 0);this.pictureInPictureWindowRemoveEventListener=KV}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(GV(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(WV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(zV(({videoSize:r,inPip:s,pipSize:n})=>s?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 Yi=class{constructor(e){this.subscription=new a_;this.videoState=new H("stopped");this.observableVideo=null;this.droppedFramesManager=new Ar;this.stallsManager=new Ro;this.elementSizeManager=new fu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return JV(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Rr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Be(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(we(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 hu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;r_(this.observableVideo)&&(this.observableVideo=Oe(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:wE.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(sp(l=>!!l.length),PE()).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(Us(l=>l.to.state!=="none"),qs());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.currentBuffer$,e.currentNativeBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.manifestRequested$,e.manifestRequested$),s(this.player.firstBytesManifest$,e.firstBytesManifest$),s(this.player.manifestReceived$,e.manifestReceived$),s(this.player.firstBytesRequested$,e.firstBytesRequested$),s(this.player.firstBytesReceived$,e.firstBytesReceived$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.lastConnectionMetrics$,e.httpConnectionMetrics$),s(this.player.lastDownloadMetrics$,e.httpDownloadMetrics$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(sp(xE),PE()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(Us(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(gt(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),Jt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(Ge(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Xe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),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 p=this.player.getStreams(),h=this.player.getCodecs();if(ZV(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let v of p.audio){m.push(_d(v));let g=[];for(let S of v.representations){let T=xs(S);g.push(T),this.audioTracksMap.set(T,{stream:v,representation:S})}this.audioStreamsMap.set(v,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of p.video){f.push(Od(m));let v=[];for(let g of m.representations){let S=ti({...g,streamId:m.id});S&&(v.push(S),this.videoTracksMap.set(S,{stream:m,representation:g}))}this.videoStreamsMap.set(m,v)}this.params.output.availableVideoStreams$.next(f);for(let m of p.text)for(let v of m.representations){let g=YI(m,v);this.textTracksMap.set(g,{stream:m,representation:v})}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),h!=null&&h.video&&this.params.output.availableVideoCodecs$.next(h.video),h!=null&&h.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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));let o=Hs(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$,i_(this.video,"progress")).pipe(sp(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(s_(u))),this.subscription.add(o.subscribe(async()=>{let l=this.player.state$.getState(),p=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[f,m]=h,v=[...this.videoTracksMap.keys()].find(S=>{var T;return((T=this.videoTracksMap.get(S))==null?void 0:T.representation.id)===f.id});xE(v)&&(this.stallsManager.lastVideoTrackSelected=v);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")await this.player.initRepresentations(f.id,m==null?void 0:m.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),m){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,S)}},r)),this.subscription.add(e_({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:Hs(mu([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(Us(l=>l.to)))}).pipe(Us(({videoState:l,autoVideoTrackState:p})=>l.to!=="stopped"&&p),qs()).subscribe(l=>this.player.setSmartRepresentationSwitch(l))),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(qs()).subscribe(l=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===l);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=p,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Od(f));let v=this.player.calculateDurationFromSegments();v&&this.params.output.duration$.next(v/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(qs()).subscribe(l=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:v}])=>v.id===l);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=p,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(_d(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var p,h;if(l!=null&&l.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.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 c=t.playbackState.stateChangeStarted$.pipe(Us(({to:l})=>l==="ready"),qs());this.subscription.add(Hs(c,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,mu(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(Hs(c,this.player.state$.stateChangeEnded$,mu(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Hs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,mu(["init"])).pipe(t_(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var M,L,A,B,$,U,G,j,E,P,I,w,N;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?_a:Va,t=this.params.tuning.useNewAutoSelectVideoTrack?To:yo,i=this.params.tuning.useNewAutoSelectVideoTrack?yt:So,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(M=r.videoTrack.getState())==null?void 0:M.id,u=[...this.videoTracksMap.keys()].find(({id:O})=>O===o),c=s.currentVideoTrack$.getValue(),d=((B=(A=r.videoStream.getState())!=null?A:u&&((L=this.videoTracksMap.get(u))==null?void 0:L.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let l=[...this.videoStreamsMap.keys()].find(({id:O})=>O===d.id),p=l&&this.videoStreamsMap.get(l);if(!p)return;let h=ii(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,v=Math.min(h/Math.min(f,m||1/0),1),g=($=r.audioStream.getState())!=null?$:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(U=[...this.audioStreamsMap.keys()].find(({id:O})=>O===(g==null?void 0:g.id)))!=null?U:this.audioStreamsMap.keys().next().value,T=0;if(S){if(u&&!n){let O=e(u,p,(G=this.audioStreamsMap.get(S))!=null?G:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(j=O==null?void 0:O.bitrate)!=null?j:-1/0)}if(c){let O=e(c,p,(E=this.audioStreamsMap.get(S))!=null?E:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(P=O==null?void 0:O.bitrate)!=null?P:-1/0)}}let y=u;(n||!y)&&(y=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:v,current:c,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 x=S&&t(y,p,(I=this.audioStreamsMap.get(S))!=null?I:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),R=(w=this.videoTracksMap.get(y))==null?void 0:w.representation,D=x&&((N=this.audioTracksMap.get(x))==null?void 0:N.representation);if(R&&D)return[R,D];if(R&&!D&&this.audioTracksMap.size===0)return[R,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:wE.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),Ve(this.video),this.tracer.end()}};var js=class extends Yi{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 np,merge as kE,filter as AE,filterChanged as RE,isNullable as op,map as ME,ValueSubject as up,isNonNullable as n_}from"@vkontakte/videoplayer-shared/es2018";var Qs=class extends Yi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new up(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(RE()).subscribe(u=>{let c=i.position$.getValue(),d=i.volume$.getValue(),l=!d.volume||d.muted;!u&&!c&&l?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(ME(u=>u.to)).subscribe(this.player.isLowLatency$)).add(np({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(ME(({liveBufferTime:u,liveAvailabilityStartTime:c})=>u&&c?u*1e3+c+t:void 0)).subscribe(i.liveTime$)).add(np({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:kE(r.playbackRateState$,new up(1))}).pipe(AE(({liveStreamStatus:u,liveDuration:c})=>u==="active"&&!!c)).subscribe(({liveDuration:u,playbackRate:c})=>{let d=i.liveBufferTime$.getValue(),l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;l||c<1-p||this.video.paused||op(d)||(t=u-d)})).add(np({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:kE(r.playbackRateState$,new up(1))}).pipe(RE((u,c)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===c.liveDuration:u.time===c.time)).subscribe(({time:u,liveDuration:c,playbackRate:d})=>{let l=i.position$.getValue(),{playbackCatchupSpeedup:p}=this.params.tuning.dashCmafLive.lowLatency;if(!l&&!this.video.paused&&d>=1-p||op(u)||op(c))return;let h=-1*(c-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let c=KI(u);this.params.output.availableTextTracks$.next([c])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(AE(u=>n_(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}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 $E="X-Playback-Duration",cp=async a=>{var r;let e=await Je(a),t=await 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($E)?parseInt(e.headers.get($E),10):void 0};import{assertNever as g_,combine as v_,debounce as S_,ErrorCategory as vu,filter as y_,filterChanged as T_,isNonNullable as LE,isNullable as Su,map as BE,merge as I_,observableFrom as E_,Subscription as w_,ValueSubject as pp,VideoQuality as x_}from"@vkontakte/videoplayer-shared/es2018";var dp=_(Zc(),1);import{videoSizeToQuality as o_,getExponentialDelay as u_}from"@vkontakte/videoplayer-shared/es2018";var c_=a=>{let e=null;if(a.QUALITY&&(e=Kt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=o_({width:t,height:i})}return e!=null?e:null},l_=(a,e)=>{var s,n;let t=a.split(`
|
|
179
|
+
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],c=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!d)){if(c){let l=(0,dp.default)(c[1].split(",").map(S=>S.split("="))),p=(s=l.QUALITY)!=null?s:`stream-${l.BANDWIDTH}`,h=c_(l),f;l.BANDWIDTH&&(f=parseInt(l.BANDWIDTH,10)/1e3||void 0),!f&&l["AVERAGE-BANDWIDTH"]&&(f=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,v;if(l.RESOLUTION){let[S,T]=l.RESOLUTION.split("x").map(y=>parseInt(y,10));S&&T&&(v={width:S,height:T})}let g=new URL(t[++o],e).toString();h&&i.push({id:p,quality:h,url:g,bandwidth:f,size:v,fps:m})}if(d){let l=(0,dp.default)(d[1].split(",").map(m=>{let v=m.indexOf("=");return[m.substring(0,v),m.substring(v+1)]}).map(([m,v])=>[m,v.replace(/^"|"$/g,"")])),p=(n=l.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=l.LANGUAGE,f=l.NAME;p&&h&&r.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},d_=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),lp=0,CE=async(a,e=a,t,i)=>{let s=await(await Je(a,i)).text();lp+=1;try{let{qualityManifests:n,textTracks:o}=l_(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(lp<=t.manifestRetryMaxCount)return await d_(u_(lp-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),CE(a,e,t)}return{qualityManifests:[],textTracks:[]}},bu=CE;import{isNonNullable as p_,Subscription as h_,throttle as f_,ValueSubject as DE,Subject as m_,ErrorCategory as b_}from"@vkontakte/videoplayer-shared/es2018";var gu=class{constructor(e,t,i,r,s){this.subscription=new h_;this.abortControllers={destroy:new ie,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new DE(null);this.getCurrentTime$=new DE(null);this.error$=new m_;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(f_(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()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await Je(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(`
|
|
180
|
+
`),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],c=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:c}),s=s+d,!i.segmentStartTime){let l=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-l}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 c=new Date(u);c.setMilliseconds(0),s=c.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(p_(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([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ie;let{textTracks:e}=await this.fetchManifestData(),t=await 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}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:b_.WTF,thrown:t,message:e})}};var Ws=class{constructor(e){this.subscription=new w_;this.videoState=new H("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new pp([]);this.liveOffset=new Ci;this.manifestStartTime$=new pp(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||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),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&c.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(c.position&&c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(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"&&k(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"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return g_(t)}};var i;this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:x_.INVARIANT,url:this.params.source.url};let t=(r,s)=>bu(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new gu(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ye(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:vu.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:vu.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(we(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new pp((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,c,d,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(l=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(c=t.getState())==null?void 0:c.id)!=null?l:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:vu.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Oe(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ge(this.video,t.playbackRate,r.playbackRateState$,i)),s(Xe(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(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"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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(T_(),BE(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(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&LE(c.to)){let l=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let p=this.manifests$.getValue().find(h=>h.id===l);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(we(p.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,c,d;let o=(d=(c=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:c.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(v_({startTime:this.manifestStartTime$.pipe(y_(LE)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(BE(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i));let n=I_(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,E_(["init"])).pipe(S_(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),Ve(this.video)}prepare(){var o,u,c;let e=this.selectManifest();if(Su(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:l}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[p,h]of[[d,"mq"],[l,"lq"]]){let f=String(parseFloat(p||""));h&&p&&r.searchParams.set(h,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ee(r.toString(),this.liveOffset.getTotalOffset(),s);(c=this.liveTextManager)==null||c.prepare(n),this.video.setAttribute("src",n),this.video.load(),cp(n).then(d=>{var l;if(!Su(d))this.maxSeekBackTime$.next(d);else{let p=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();(Su(p)||!isFinite(p))&&Je(n).then(h=>h.text()).then(h=>{var m;let f=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:m[1];if(f){let v=new URL(f,n).toString();cp(v).then(g=>{Su(g)||this.maxSeekBackTime$.next(g)})}}).catch(()=>{})}})}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vu.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=Ee(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 P_,debounce as k_,ErrorCategory as hp,fromEvent as fp,isNonNullable as A_,isNullable as R_,map as VE,merge as _E,observableFrom as OE,Subscription as M_,ValueSubject as NE,VideoQuality as $_}from"@vkontakte/videoplayer-shared/es2018";var zs=class{constructor(e){this.subscription=new M_;this.videoState=new H("stopped");this.manifests$=new NE([]);this.unmuteAfterBrowserResetsHappened=new NE(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let c=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:l}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),c.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:l*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&c.state==="requested"&&this.seek(c.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return P_(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:$_.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(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),bu(Ee(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:hp.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,c,d,l;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(l=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(c=t.getState())==null?void 0:c.id)!=null?l:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:hp.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Oe(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(VE(o=>o.to)),this.params.output.playbackState$),this.subscription.add(gt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ge(this.video,t.playbackRate,r.playbackRateState$,i)),Jt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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 h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&A_(c.to)){let f=c.to.id;this.params.desiredState.videoTrack.setState(c.to);let m=this.manifests$.getValue().find(v=>v.id===f);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(we(m.url)))}let l=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(l!==p){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(l),f.playbackRate=l)}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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(VE(o=>o.map(({id:u,quality:c,size:d,bandwidth:l,fps:p})=>({id:u,quality:c,size:d,fps:p,bitrate:l})))).subscribe(this.params.output.availableVideoTracks$,i)),!V.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(_E(fp(o,"addtrack"),fp(o,"removetrack"),fp(o,"change"),OE(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=_E(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,OE(["init"])).pipe(k_(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ve(this.video)}prepare(){var s,n;let e=this.selectManifest();if(R_(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[c,d]of[[o,"mq"],[u,"lq"]]){let l=String(parseFloat(c||""));d&&c&&r.searchParams.set(d,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hp.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var UE=_(zt(),1),mp=_(Ei(),1),HE=_(Ke(),1);import{assertNever as C_,assertNonNullable as FE,debounce as D_,ErrorCategory as qE,isHigherOrEqual as L_,isLowerOrEqual as B_,isNonNullable as V_,merge as __,observableFrom as O_,Subscription as N_,map as F_}from"@vkontakte/videoplayer-shared/es2018";var Gs=class{constructor(e){this.subscription=new N_;this.videoState=new H("stopped");this.trackUrls={};this.textTracksManager=new Ye;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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);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"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return C_(e)}};this.params=e,this.video=Be(e.container,e.tuning),this.params.output.element$.next(this.video),(0,UE.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,mp.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:qE.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Oe(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentNativeBuffer$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(F_(o=>o.to)),this.params.output.playbackState$),this.subscription.add(gt(this.video,t.isLooped,i)),Jt({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ge(this.video,t.playbackRate,r.playbackRateState$,i)),s(Xe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,c;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&V_(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(),l=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(d!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=__(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,O_(["init"])).pipe(D_(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),Ve(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;FE(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];FE(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Zt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(we(t))}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:qE.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var c,d;this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=yt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=(c=this.params.output.currentVideoTrack$.getValue())==null?void 0:c.quality,s=!!(e.max||e.min),n=(0,mp.default)(this.trackUrls).map(l=>l.track);if(!r||!s||wr(e,n[0].quality,(d=(0,HE.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?B_(r,e.max):!0,u=e.min?L_(r,e.min):!0;o&&u||i(e)}};import{assertNever as QE,debounce as j_,merge as WE,observableFrom as Q_,Subscription as W_,map as zE,ValueSubject as z_,ErrorCategory as gp,VideoQuality as G_}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as q_}from"@vkontakte/videoplayer-shared/es2018";var jE=["stun:videostun.mycdn.me:80"],U_=1e3,H_=3,bp=()=>null,yu=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=bp;this.externalStopCallback=bp;this.externalErrorCallback=bp;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}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:jE}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:q_.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),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),U_)}normalizeOptions(e={}){let t={stunServerList:jE,maxRetryNumber:H_,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ys=class{constructor(e){this.videoState=new H("stopped");this.maxSeekBackTime$=new z_(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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return QE(e)}};this.subscription=new W_,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Be(e.container,e.tuning),this.liveStreamClient=new yu(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),Ve(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:gp.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(WE(this.videoState.stateChangeStarted$.pipe(zE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(zE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Oe(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.currentBuffer$,e.currentNativeBuffer$),s(Xe(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(_e(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 QE(n.to)}},i)).add(WE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Q_(["init"])).pipe(j_(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(we(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:G_.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.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:gp.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ne(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gp.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Gr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Xs,assertNonNullable as _t,ErrorCategory as Tu,filter as ZE,isNonNullable as ew,isNullable as tO,map as iO,merge as rO,once as aO,Subject as se,Subscription as tw,ValueSubject as q,flattenObject as vp,devNull as sO,getWindow as nO}from"@vkontakte/videoplayer-shared/es2018";import{Observable as Y_,map as GE,Subscription as K_,Subject as X_}from"@vkontakte/videoplayer-shared/es2018";var YE=a=>new Y_(e=>{let t=new K_,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(GE(({from:c,to:d})=>`${c}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(GE(({type:c})=>c!==void 0)),n=new X_,o=0,u="unknown";return t.add(i.subscribe(c=>{o&&window.clearTimeout(o),u=c,o=window.setTimeout(()=>n.next(c),a.maxTransitionInterval),F({m:"hangup.set",l:c,id:o})})),t.add(r.subscribe(()=>{F({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(c=>{o&&(F({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,c&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval),F({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as J_,Subscription as Z_,combine as eO,filter as XE,once as JE}from"@vkontakte/videoplayer-shared/es2018";function KE(){return new(window.AudioContext||window.webkitAudioContext)}var Ks=class Ks{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ie;this.subscriptions=new Z_;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(XE(s=>!!s.type),JE()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){V.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(eO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(XE(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),JE()).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}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=KE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.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:Ks.errorId,category:J_.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ks.errorId} exception`,thrown:e})}};Ks.errorId="VolumeMultiplierManager";var Yr=Ks;var oO={chunkDuration:5e3,maxParallelRequests:5},Js=class{constructor(e){this.current$=new q({type:void 0});this.providerError$=new se;this.noAvailableProvidersError$=new se;this.volumeMultiplierError$=new se;this.providerOutput={position$:new q(0),duration$:new q(1/0),volume$:new q({muted:!1,volume:1}),availableVideoStreams$:new q([]),currentVideoStream$:new q(void 0),availableVideoTracks$:new q([]),currentVideoTrack$:new q(void 0),availableVideoCodecs$:new q([]),availableAudioStreams$:new q([]),currentAudioStream$:new q(void 0),availableAudioTracks$:new q([]),availableAudioCodecs$:new q([]),currentVideoSegmentLength$:new q(0),currentAudioSegmentLength$:new q(0),isAudioAvailable$:new q(!0),autoVideoTrackLimitingAvailable$:new q(!1),autoVideoTrackLimits$:new q(void 0),currentBuffer$:new q(void 0),currentNativeBuffer$:new q(void 0),isBuffering$:new q(!0),error$:new se,fetcherError$:new se,fetcherRecoverableError$:new se,warning$:new se,willSeekEvent$:new se,soundProhibitedEvent$:new se,seekedEvent$:new se,loopedEvent$:new se,endedEvent$:new se,manifestRequested$:new se,firstBytesManifest$:new se,manifestReceived$:new se,firstBytesRequested$:new se,firstBytesReceived$:new se,firstBytesEvent$:new se,loadedMetadataEvent$:new se,firstFrameEvent$:new se,canplay$:new se,isLive$:new q(void 0),isLiveEnded$:new q(null),canPlayLiveTailBuffer$:new q(!1),isLowLatency$:new q(!1),canChangePlaybackSpeed$:new q(!0),liveTime$:new q(void 0),liveBufferTime$:new q(void 0),liveLatency$:new q(void 0),severeStallOccurred$:new se,availableTextTracks$:new q([]),currentTextTrack$:new q(void 0),hostname$:new q(void 0),httpConnectionType$:new q(void 0),httpConnectionReused$:new q(void 0),httpConnectionMetrics$:new q(void 0),httpDownloadMetrics$:new q(void 0),inPiP$:new q(!1),inFullscreen$:new q(!1),element$:new q(void 0),elementVisible$:new q(!0),availableSources$:new q(void 0),is3DVideo$:new q(!1),playbackState$:new q(""),getCurrentTime$:new q(null)};this.subscription=new tw;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=wc([...OI(this.params.tuning),..._I(this.params.tuning)]).filter(c=>ew(e.sources[c])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(c=>!(0,Sp.default)(r,c)),...t.filter(c=>(0,Sp.default)(r,c))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",vp(s)),this.screenFormatsIterator=new Gr(s);let n=[...Ld(!0),...Ld(!1)];this.chromecastFormatsIterator=new Gr(n.filter(c=>ew(e.sources[c]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Yr.isSupported()&&(this.volumeMultiplierManager=new Yr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){F.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new Gr(e))}))}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(tO(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Tu.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()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),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 s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Xs(e)}}createScreenProvider(e){var u,c,d;let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let l=this.applyFailoverHost(t[e]),p=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return _t(l),this.params.tuning.useDashProviderVirtual&&!V.device.isMobile?new qr({...o,source:l,sourceHls:p,forceVideoCodec:(u=this.videoCodecsIterator)==null?void 0:u.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&V.device.isMobile?new qr({...o,source:l,sourceHls:p,forceVideoCodec:(c=this.videoCodecsIterator)==null?void 0:c.getValue()}):new js({...o,source:l,sourceHls:p,forceVideoCodec:(d=this.videoCodecsIterator)==null?void 0:d.getValue()})}case"DASH_LIVE_CMAF":{let l=this.applyFailoverHost(t[e]);return _t(l),new Qs({...o,source:l})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let l=this.applyFailoverHost(t[e]);return _t(l),new zs({...o,source:l})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=this.applyFailoverHost(t[e]);return _t(l),new Ws({...o,source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let l=this.applyFailoverHost(t[e]);return _t(l),new Gs({...o,source:l})}case"DASH_LIVE":{let l=this.applyFailoverHost(t[e]);return _t(l),new Fy({...o,source:l,config:{...oO,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let l=this.applyFailoverHost(t[e]);return _t(l),new Ys({container:i,source:l,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 Xs(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o={meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof kt){let{chromecastConnector:c}=this.params.dependencies.chromecastInitializer;return _t(c),new ma({...o,chromecastConnector:c})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return _t(u),new $a({...o,connection:u})}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 Xs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Xs(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 Xs(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,iw.default)((0,yp.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new tw,t=!1,i=0;e.add(rO(this.providerOutput.error$.pipe(ZE(s=>!this.params.tuning.ignoreAudioRendererError||!s.message||!/AUDIO_RENDERER_ERROR/ig.test(s.message))),YE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(iO(s=>({id:`ProviderHangup:${s}`,category:Tu.WTF,message:`A ${s} 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 s=this.params.desiredState.playbackState.transitionEnded$.pipe(ZE(({to:n})=>n==="playing"),aO()).subscribe(()=>t=!0);e.add(s)}));let r=()=>{let s=F.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&nO().console.log(`===== DASH_LIVE DEBUG START ====
|
|
181
|
+
`,s.map(({time:u,data:c,stack:d})=>`${u}: ${JSON.stringify(c)}${d?`
|
|
182
182
|
`+d:""}`).join(`
|
|
183
183
|
`),`
|
|
184
|
-
===== DASH_LIVE DEBUG END ====`),o){let u=s.reduce((l,{time:d,data:c,stack:p})=>{let h=(0,bp.default)(c).map(([m,f])=>`${m}:${f}`).join(",");return l+=`${d}: ${h}${p?`: ${p}`:""};`,l},"");rO.push("core",{key:"vp_dash_live_debug",strings:[u]})}};return e.add(this.providerError$.subscribe(s=>{s.id.startsWith("ProviderHangup")&&(N({m:"final.0",e:s.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{N({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(s=>{let n=this.current$.getValue().destination,o={error:s,currentDestination:n};if(n==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=s.category===fu.NETWORK,l=s.category===fu.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!l,p=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,h=d&&!l&&(u&&t||!c);o={...o,isNetworkError:u,isFatalError:l,haveFailoverHost:d,tryFailover:h,canReinitProvider:c},c?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):p?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(n!=null?n:"SCREEN"))}s.traceAsLog?this.tracer.log("providerInfo",mp(o)):this.tracer.error("providerError",mp(o))})),e}};import{fromEvent as bu,once as nO,combine as oO,Subscription as ZE,ValueSubject as gp,map as ew,filter as uO,isNonNullable as gu,now as We,safeStorage as vp,getWindow as lO}from"@vkontakte/videoplayer-shared/es2018";var cO=5e3,tw="one_video_throughput",iw="one_video_rtt",yp=()=>{let{navigator:a}=lO();if(a)return a.connection},rw=()=>{var e;let a=(e=yp())==null?void 0:e.downlink;if(gu(a)&&a!==10)return a*1e3},aw=()=>{var e;let a=(e=yp())==null?void 0:e.rtt;if(gu(a)&&a!==3e3)return a},sw=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Sp=class a{constructor(e){this.subscription=new ZE;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(tw)||(e.useBrowserEstimation?rw():void 0)||cO,i=(s=(r=a.load(iw))!=null?r:e.useBrowserEstimation?aw():void 0)!=null?s:0;if(this.throughput$=new gp(t),this.rtt$=new gp(i),this.rttAdjustedThroughput$=new gp(sw(t,i,e.rttPenaltyRequestSize)),this.throughput=Qi.getSmoothedValue(t,-1,e),this.rtt=Qi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let l=rw();l&&this.throughput.next(l);let d=aw();gu(d)&&this.rtt.next(d)},o=yp();o&&"onchange"in o&&this.subscription.add(bu(o,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{vp.set(tw,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{vp.set(iw,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(ew(n=>Math.round(n))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(oO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(ew(({throughput:n,rtt:o})=>sw(n,o,e.rttPenaltyRequestSize)),uO(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=We(),r=new ZE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(bu(e,"progress").pipe(nO()).subscribe(s=>{t=s.loaded,i=We()}));break;case 1:case 0:r.add(bu(e,"loadstart").subscribe(()=>{t=0,i=We()}));break}r.add(bu(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=We(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=We(),n=0,o=We(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(r,We()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=We();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=c.byteLength,s=We()}else n+=c.byteLength;o=We()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&We()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,We()-o,this.concurrentDownloads.size),n=0,o=We());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=vp.get(e);if(gu(t))return(i=parseInt(t,10))!=null?i:void 0}},nw=Sp;import{fillWithDefault as dO,VideoQuality as vu}from"@vkontakte/videoplayer-shared/es2018";var pO={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:vu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:vu.Q_720P,trafficSavingLimit:vu.Q_480P},stallsManager:{enabled:!1,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,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:vu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,useAbortMSEFix:!1,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,actionTimeShiftFromSegment:500},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,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",chromecastPresentationApi:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",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,useNewSwitchTo:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1},ow=a=>dO(a,pO);import{assertNonNullable as Ep,combine as Ot,ErrorCategory as Su,filter as he,filterChanged as K,fromEvent as wp,isNonNullable as hw,isNullable as EO,Logger as wO,map as z,mapTo as mw,merge as li,now as yu,once as ve,Subject as Q,Subscription as fw,tap as xp,ValueSubject as C,isHigher as xO,isInvariantQuality as bw,flattenObject as ci,throttle as Pp,getTraceSubscriptionMethod as gw,TracerFactory as PO,InternalsExposure as AO,getPlayerId as kO,devNull as Tu}from"@vkontakte/videoplayer-shared/es2018";import{merge as hO,map as mO,filter as uw,isNonNullable as fO}from"@vkontakte/videoplayer-shared/es2018";var Tp=({seekState:a,position$:e})=>hO(a.stateChangeEnded$.pipe(mO(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),uw(fO)),e.pipe(uw(()=>a.getState().state==="none")));import{assertNonNullable as bO}from"@vkontakte/videoplayer-shared/es2018";var lw=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return bO(e,`Wrong container or containerId {${a.container}}`),e};import{filter as gO,once as vO}from"@vkontakte/videoplayer-shared/es2018";var cw=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(gO(r=>r.length>0),vO()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var dw=_(zt(),1);import{devNull as SO,getWindow as Ip}from"@vkontakte/videoplayer-shared/es2018";var pw=()=>{let a="mediaCapabilities"in Ip().navigator?yO:TO,e=Vi(async()=>{let t=await Promise.all((0,dw.default)(IO).map(async([r,s])=>({codec:r,supported:await a(s)}))),i=[B.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return SO.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>_i(e)},yO=async a=>{if(!a)return Promise.resolve({supported:!1});let e={["channels"in a?"audio":"video"]:a};return await Ip().navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},TO=a=>{var i;if(!a)return Promise.resolve({supported:!1});let e=Ip().document,t="channels"in a?e.createElement("audio"):e.createElement("video");return Promise.resolve({supported:t.canPlayType((i=a==null?void 0:a.contentType)!=null?i:"")==="probably"})},IO={H264:{contentType:'video/mp4; codecs="avc1.4D400C"',width:720,height:720,bitrate:2886,framerate:30},H265:{contentType:'video/mp4; codecs="hvc1.1.6.L123.B0"',width:720,height:720,bitrate:2886,framerate:30},VP8:{contentType:'video/webm; codecs="vp8"',width:720,height:720,bitrate:2886,framerate:30},VP9:{contentType:'video/webm; codecs="vp09.00.10.08"',width:720,height:720,bitrate:2886,framerate:30},AV1:{contentType:'video/mp4; codecs="av01.0.01M.08"',width:720,height:720,bitrate:2886,framerate:30},OPUS:{contentType:'audio/ogg; codecs="opus"',channels:"2",bitrate:128e3},AAC_LC:{contentType:'audio/mp4; codecs="mp4a.40.2"',channels:"2",bitrate:128e3},AC3:{contentType:'audio/mp4; codecs="ac-3"',channels:"6",bitrate:128e3},EAC3:{contentType:'audio/mp4; codecs="ec-3"',channels:"6",bitrate:128e3},AAC_HE_V1:{contentType:'audio/mp4; codecs="mp4a.40.5"',channels:"2",bitrate:128e3},AAC_HE_V2:{contentType:'audio/mp4; codecs="mp4a.40.29"',channels:"2",bitrate:128e3},AAC_xHE:{contentType:'audio/mp4; codecs="mp4a.40.42"',channels:"2",bitrate:128e3}};var Iu=class{constructor(e={},t=PO.createRootTracer(!1),i){this.subscription=new fw;this.logger=new wO;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new C(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new C(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new j("stopped"),seekState:new j({state:"none"}),volume:new j({volume:1,muted:!1}),videoTrack:new j(void 0),videoStream:new j(void 0),audioStream:new j(void 0),autoVideoTrackSwitching:new j(!0),autoVideoTrackLimits:new j({}),isLooped:new j(!1),isLowLatency:new j(!1),playbackRate:new j(1),externalTextTracks:new j([]),internalTextTracks:new j([]),currentTextTrack:new j(void 0),textTrackCuesSettings:new j({}),cameraOrientation:new j({x:0,y:0})};this.info={playbackState$:new C(void 0),position$:new C(0),duration$:new C(1/0),muted$:new C(!1),volume$:new C(1),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableQualities$:new C([]),availableQualitiesFps$:new C({}),currentQuality$:new C(void 0),isAutoQualityEnabled$:new C(!0),autoQualityLimitingAvailable$:new C(!1),autoQualityLimits$:new C({}),predefinedQualityLimitType$:new C("unknown"),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),isAudioAvailable$:new C(!0),currentPlaybackRate$:new C(1),currentBuffer$:new C({start:0,end:0}),currentNativeBuffer$:new C({start:0,end:0}),isBuffering$:new C(!0),isStalled$:new C(!1),isEnded$:new C(!1),isLooped$:new C(!1),isLive$:new C(void 0),isLiveEnded$:new C(null),canPlayLiveTailBuffer$:new C(!1),canChangePlaybackSpeed$:new C(void 0),atLiveEdge$:new C(void 0),atLiveDurationEdge$:new C(void 0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),liveLatency$:new C(void 0),currentFormat$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),throughputEstimation$:new C(void 0),rttEstimation$:new C(void 0),videoBitrate$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),surface$:new C("none"),chromecastState$:new C("NOT_AVAILABLE"),chromecastDeviceName$:new C(void 0),intrinsicVideoSize$:new C(void 0),availableSources$:new C(void 0),is3DVideo$:new C(!1),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0)};this.events={inited$:new Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willReady$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,fetcherRecoverableError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,autoplaySoundProhibited$:new Q,manifestRequested$:new Q,firstBytesManifest$:new Q,manifestReceived$:new Q,firstBytesRequested$:new Q,firstBytesReceived$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q,fetcherError$:new Q,severeStallOccured$:new Q};this.experimental={element$:new C(void 0),enableDebugTelemetry$:new C(!1),dumpTelemetry:sy,getCurrentTime$:new C(null)};this.initLogs(),this.tuning=ow(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,Ap.default)(this.info).forEach(s=>s.setSuppressErrors(!0)),(0,Ap.default)(this.events).forEach(s=>s.setSuppressErrors(!0)));let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new At(r):new Sn(r),this.throughputEstimator=new nw(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new AO("core",kO(i==null?void 0:i.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i==null?void 0:i.onDevNullLog,Tu.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(s,n,o)=>{let u=Reflect.get(s,n,o);return typeof u!="function"?u:(...l)=>{try{return u.apply(s,l)}catch(d){let c=l.map(m=>JSON.stringify(m,(f,v)=>{let g=typeof v;return(0,vw.default)(["number","string","boolean"],g)?v:v===null?null:`<${g}>`})),p=`Player.${String(n)}`,h=`Exception calling ${p} (${c.join(", ")})`;throw this.events.fatalError$.next({id:p,category:Su.WTF,message:h,thrown:d}),d}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,d;let{container:n,...o}=e;this.tracer.log("initVideo",ci(o)),this.domContainer=lw(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Gs({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],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),this.devNullLog&&this.tuning.devNullLogEnabled?(Tu.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=pw())):Tu.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?B.isInited$.pipe(he(n=>!!n),ve()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),wp(document,"visibilitychange").pipe(ve()).subscribe(r)):r(),this}destroy(){var e,t,i;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(),Tu.destroy("core"),(i=this.collectDecodingInfoDestroyCb)==null||i.call(this)}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(he(t=>!!t),ve()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{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.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{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.waitInit(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof At)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})}),this}setMuted(e,t=!1){return this.waitInit(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(o=s==null?void 0:s.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof At)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{Ep(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(he(i=>i.length>0),ve()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",ci(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{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.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",ci(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{var t;cw(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.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...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.waitInit(()=>{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.waitInit(()=>{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.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(EO(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return hw(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(li(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(z(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(oy(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(he(({from:e})=>e==="stopped"),ve()).subscribe(()=>{this.initedAt=yu(),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"ready":this.events.willReady$.next();break;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",ci(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Su.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ve()).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",ci(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(z(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(z(n=>n.destination),K()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Ot({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(z(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>bw(u)?1:bw(l)?-1:xO(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(K()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(he(n=>hw(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(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(K()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(K()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(K()).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(z(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe(z(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).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(xp(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).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(Ot({hasLiveOffsetByPaused:li(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(z(n=>n.to),K(),z(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(Ot({atLiveEdge:Ot({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Tp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(z(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),K(),xp(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(z(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ot({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(z(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),K(),xp(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(z(n=>n.muted),K()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(z(n=>n.volume),K()).subscribe(this.info.volume$)).add(Tp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(li(e.providerOutput.endedEvent$.pipe(mw(!0)),e.providerOutput.seekedEvent$.pipe(mw(!1))).pipe(K()).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(z(n=>({id:n?`No${n}`:"NoProviders",category:Su.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.manifestRequested$.pipe(ve()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(ve()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(ve()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(ve()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(ve()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(ve(),z(n=>n!=null?n:yu()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ve(),z(()=>yu()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ve(),z(()=>yu()-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 C(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new C(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(he(({to:n})=>n==="playing"),ve()).subscribe(()=>i.next(!1)));let r=0,s=li(e.providerOutput.isBuffering$,t,i).pipe(z(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),K());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(li(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(li(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(z(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 fw;this.subscription.add(t),this.subscription.add(e.current$.pipe(K((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(he(i=>i.length>0),ve()).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:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=yt(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(li(this.desiredState.videoTrack.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(z(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;Ep(this.providerContainer),Ep(e),ay(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>ry(i)),this.providerContainer.current$.subscribe(({type:i})=>Ma("provider",i)),e.duration$.subscribe(i=>Ma("duration",i)),e.availableVideoTracks$.pipe(he(i=>!!i.length),ve()).subscribe(i=>Ma("tracks",i)),this.events.fatalError$.subscribe(new Re("fatalError")),this.events.managedError$.subscribe(new Re("managedError")),e.position$.subscribe(new Re("position")),e.currentVideoTrack$.pipe(z(i=>i==null?void 0:i.quality)).subscribe(new Re("quality")),this.info.currentBuffer$.subscribe(new Re("buffer")),e.isBuffering$.subscribe(new Re("isBuffering"))].forEach(i=>this.subscription.add(i)),Ma("codecs",B.video.supportedCodecs)}initTracerSubscription(){let e=gw(this.tracer.log.bind(this.tracer)),t=gw(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(K()).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(Ot({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(he(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),K((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(he(i=>i>0),K()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(he(i=>i>0),K()).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(Ot({currentBuffer:this.info.currentBuffer$.pipe(he(i=>i.end>0),K((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(K())}).pipe(Pp(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(K()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(K()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(K()).subscribe(e("canChangePlaybackSpeed"))).add(Ot({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(he(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Pp(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(K(),he(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(K(),he(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(K()).subscribe(e("muted"))).add(this.info.volume$.pipe(K()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(K(),he(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ot({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(he(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Pp(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(K(),he(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=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Su.DOM,message:String(r)})})};this.subscription.add(li(wp(document,"visibilitychange"),wp(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",ci({quality:t,availableTracks:ci(e),track:ci(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&&!Oa()}};import{Subscription as $ee,Observable as Mee,Subject as Cee,ValueSubject as Lee,VideoQuality as Dee}from"@vkontakte/videoplayer-shared/es2018";var Bee=`@vkontakte/videoplayer-core@${hh}`;export{Xr as ChromecastState,ku as HttpConnectionType,Mee as Observable,Pe as PlaybackState,Iu as Player,cn as PredefinedQualityLimits,Bee as SDK_VERSION,Cee as Subject,$ee as Subscription,Ru as Surface,hh as VERSION,Lee as ValueSubject,xt as VideoFormat,Dee as VideoQuality,KA as areValidLiveRecordSources,B as clientChecker,xi as isMobile};
|
|
184
|
+
===== DASH_LIVE DEBUG END ====`),o){let u=s.reduce((c,{time:d,data:l,stack:p})=>{let h=(0,yp.default)(l).map(([f,m])=>`${f}:${m}`).join(",");return c+=`${d}: ${h}${p?`: ${p}`:""};`,c},"");sO.push("core",{key:"vp_dash_live_debug",strings:[u]})}};return e.add(this.providerError$.subscribe(s=>{s.id.startsWith("ProviderHangup")&&(F({m:"final.0",e:s.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{F({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(s=>{let n=this.current$.getValue().destination,o={error:s,currentDestination:n};if(n==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=s.category===Tu.NETWORK,c=s.category===Tu.FATAL,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<this.params.tuning.providerErrorLimit&&!c,p=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,h=d&&!c&&(u&&t||!l);o={...o,isNetworkError:u,isFatalError:c,haveFailoverHost:d,tryFailover:h,canReinitProvider:l},l?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):p?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(n!=null?n:"SCREEN"))}s.traceAsLog?this.tracer.log("providerInfo",vp(o)):this.tracer.error("providerError",vp(o))})),e}};import{fromEvent as Iu,once as uO,combine as cO,Subscription as rw,ValueSubject as Tp,map as aw,filter as lO,isNonNullable as Eu,now as We,safeStorage as Ip,getWindow as dO}from"@vkontakte/videoplayer-shared/es2018";var pO=5e3,sw="one_video_throughput",nw="one_video_rtt",wp=()=>{let{navigator:a}=dO();if(a)return a.connection},ow=()=>{var e;let a=(e=wp())==null?void 0:e.downlink;if(Eu(a)&&a!==10)return a*1e3},uw=()=>{var e;let a=(e=wp())==null?void 0:e.rtt;if(Eu(a)&&a!==3e3)return a},cw=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Ep=class a{constructor(e){this.subscription=new rw;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(sw)||(e.useBrowserEstimation?ow():void 0)||pO,i=(s=(r=a.load(nw))!=null?r:e.useBrowserEstimation?uw():void 0)!=null?s:0;if(this.throughput$=new Tp(t),this.rtt$=new Tp(i),this.rttAdjustedThroughput$=new Tp(cw(t,i,e.rttPenaltyRequestSize)),this.throughput=zi.getSmoothedValue(t,-1,e),this.rtt=zi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let c=ow();c&&this.throughput.next(c);let d=uw();Eu(d)&&this.rtt.next(d)},o=wp();o&&"onchange"in o&&this.subscription.add(Iu(o,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Ip.set(sw,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Ip.set(nw,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(aw(n=>Math.round(n))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(cO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(aw(({throughput:n,rtt:o})=>cw(n,o,e.rttPenaltyRequestSize)),lO(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=We(),r=new rw;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Iu(e,"progress").pipe(uO()).subscribe(s=>{t=s.loaded,i=We()}));break;case 1:case 0:r.add(Iu(e,"loadstart").subscribe(()=>{t=0,i=We()}));break}r.add(Iu(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=We(),u=n-t,c=o-i;this.addRawSpeed(u,c,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=We(),n=0,o=We(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},c=async({done:d,value:l})=>{if(d)!t&&this.addRawSpeed(r,We()-s,1),this.concurrentDownloads.delete(e);else if(l){if(t){let p=We();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=l.byteLength,s=We()}else n+=l.byteLength;o=We()}else r+=l.byteLength,n+=l.byteLength,n>=this.tuningConfig.streamMinSampleSize&&We()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,We()-o,this.concurrentDownloads.size),n=0,o=We());await(i==null?void 0:i.read().then(c,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(c,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=Ip.get(e);if(Eu(t))return(i=parseInt(t,10))!=null?i:void 0}},lw=Ep;import{fillWithDefault as hO,VideoQuality as wu}from"@vkontakte/videoplayer-shared/es2018";var fO={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:wu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:wu.Q_720P,trafficSavingLimit:wu.Q_480P},stallsManager:{enabled:!1,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,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:wu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,useAbortMSEFix:!1,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,actionTimeShiftFromSegment:500,tickMaintainInterval:1e3,minSafeBufferToPlay:1e4,useBufferHoldingOnlyOnStall:!0,useNewStallExitPolicy:!1,videoStreamRepresentaionsFilter:[]},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,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",chromecastPresentationApi:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",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,useNewSwitchTo:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1},dw=a=>hO(a,fO);import{assertNonNullable as kp,combine as Ot,ErrorCategory as xu,filter as he,filterChanged as Y,fromEvent as Ap,isNonNullable as gw,isNullable as xO,Logger as PO,map as z,mapTo as vw,merge as ci,now as Pu,once as ve,Subject as Q,Subscription as Sw,tap as Rp,ValueSubject as C,isHigher as kO,isInvariantQuality as yw,flattenObject as li,throttle as Mp,getTraceSubscriptionMethod as Tw,TracerFactory as AO,InternalsExposure as RO,getPlayerId as MO,devNull as ku}from"@vkontakte/videoplayer-shared/es2018";import{merge as mO,map as bO,filter as pw,isNonNullable as gO}from"@vkontakte/videoplayer-shared/es2018";var xp=({seekState:a,position$:e})=>mO(a.stateChangeEnded$.pipe(bO(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),pw(gO)),e.pipe(pw(()=>a.getState().state==="none")));import{assertNonNullable as vO}from"@vkontakte/videoplayer-shared/es2018";var hw=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return vO(e,`Wrong container or containerId {${a.container}}`),e};import{filter as SO,once as yO}from"@vkontakte/videoplayer-shared/es2018";var fw=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(SO(r=>r.length>0),yO()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var mw=_(zt(),1);import{devNull as TO,getWindow as Pp}from"@vkontakte/videoplayer-shared/es2018";var bw=()=>{let a="mediaCapabilities"in Pp().navigator?IO:EO,e=_i(async()=>{let t=await Promise.all((0,mw.default)(wO).map(async([r,s])=>({codec:r,supported:await a(s)}))),i=[V.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return TO.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>Oi(e)},IO=async a=>{if(!a)return Promise.resolve({supported:!1});let e={["channels"in a?"audio":"video"]:a};return await Pp().navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},EO=a=>{var i;if(!a)return Promise.resolve({supported:!1});let e=Pp().document,t="channels"in a?e.createElement("audio"):e.createElement("video");return Promise.resolve({supported:t.canPlayType((i=a==null?void 0:a.contentType)!=null?i:"")==="probably"})},wO={H264:{contentType:'video/mp4; codecs="avc1.4D400C"',width:720,height:720,bitrate:2886,framerate:30},H265:{contentType:'video/mp4; codecs="hvc1.1.6.L123.B0"',width:720,height:720,bitrate:2886,framerate:30},VP8:{contentType:'video/webm; codecs="vp8"',width:720,height:720,bitrate:2886,framerate:30},VP9:{contentType:'video/webm; codecs="vp09.00.10.08"',width:720,height:720,bitrate:2886,framerate:30},AV1:{contentType:'video/mp4; codecs="av01.0.01M.08"',width:720,height:720,bitrate:2886,framerate:30},OPUS:{contentType:'audio/ogg; codecs="opus"',channels:"2",bitrate:128e3},AAC_LC:{contentType:'audio/mp4; codecs="mp4a.40.2"',channels:"2",bitrate:128e3},AC3:{contentType:'audio/mp4; codecs="ac-3"',channels:"6",bitrate:128e3},EAC3:{contentType:'audio/mp4; codecs="ec-3"',channels:"6",bitrate:128e3},AAC_HE_V1:{contentType:'audio/mp4; codecs="mp4a.40.5"',channels:"2",bitrate:128e3},AAC_HE_V2:{contentType:'audio/mp4; codecs="mp4a.40.29"',channels:"2",bitrate:128e3},AAC_xHE:{contentType:'audio/mp4; codecs="mp4a.40.42"',channels:"2",bitrate:128e3}};var Au=class{constructor(e={},t=AO.createRootTracer(!1),i){this.subscription=new Sw;this.logger=new PO;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new C(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new C(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new H("stopped"),seekState:new H({state:"none"}),volume:new H({volume:1,muted:!1}),videoTrack:new H(void 0),videoStream:new H(void 0),audioStream:new H(void 0),autoVideoTrackSwitching:new H(!0),autoVideoTrackLimits:new H({}),isLooped:new H(!1),isLowLatency:new H(!1),playbackRate:new H(1),externalTextTracks:new H([]),internalTextTracks:new H([]),currentTextTrack:new H(void 0),textTrackCuesSettings:new H({}),cameraOrientation:new H({x:0,y:0})};this.info={playbackState$:new C(void 0),position$:new C(0),duration$:new C(1/0),muted$:new C(!1),volume$:new C(1),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableQualities$:new C([]),availableQualitiesFps$:new C({}),currentQuality$:new C(void 0),isAutoQualityEnabled$:new C(!0),autoQualityLimitingAvailable$:new C(!1),autoQualityLimits$:new C({}),predefinedQualityLimitType$:new C("unknown"),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),isAudioAvailable$:new C(!0),currentPlaybackRate$:new C(1),currentBuffer$:new C({start:0,end:0}),currentNativeBuffer$:new C({start:0,end:0}),isBuffering$:new C(!0),isStalled$:new C(!1),isEnded$:new C(!1),isLooped$:new C(!1),isLive$:new C(void 0),isLiveEnded$:new C(null),canPlayLiveTailBuffer$:new C(!1),canChangePlaybackSpeed$:new C(void 0),atLiveEdge$:new C(void 0),atLiveDurationEdge$:new C(void 0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),liveLatency$:new C(void 0),currentFormat$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),throughputEstimation$:new C(void 0),rttEstimation$:new C(void 0),videoBitrate$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),httpConnectionMetrics$:new C(void 0),httpDownloadMetrics$:new C(void 0),surface$:new C("none"),chromecastState$:new C("NOT_AVAILABLE"),chromecastDeviceName$:new C(void 0),intrinsicVideoSize$:new C(void 0),availableSources$:new C(void 0),is3DVideo$:new C(!1),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0)};this.events={inited$:new Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willReady$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,fetcherRecoverableError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,autoplaySoundProhibited$:new Q,manifestRequested$:new Q,firstBytesManifest$:new Q,manifestReceived$:new Q,firstBytesRequested$:new Q,firstBytesReceived$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q,fetcherError$:new Q,severeStallOccured$:new Q};this.experimental={element$:new C(void 0),enableDebugTelemetry$:new C(!1),dumpTelemetry:cy,getCurrentTime$:new C(null)};this.initLogs(),this.tuning=dw(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,$p.default)(this.info).forEach(s=>s.setSuppressErrors(!0)),(0,$p.default)(this.events).forEach(s=>s.setSuppressErrors(!0)));let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new kt(r):new En(r),this.throughputEstimator=new lw(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new RO("core",MO(i==null?void 0:i.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i==null?void 0:i.onDevNullLog,ku.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(s,n,o)=>{let u=Reflect.get(s,n,o);return typeof u!="function"?u:(...c)=>{try{return u.apply(s,c)}catch(d){let l=c.map(f=>JSON.stringify(f,(m,v)=>{let g=typeof v;return(0,Iw.default)(["number","string","boolean"],g)?v:v===null?null:`<${g}>`})),p=`Player.${String(n)}`,h=`Exception calling ${p} (${l.join(", ")})`;throw this.events.fatalError$.next({id:p,category:xu.WTF,message:h,thrown:d}),d}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,c,d;let{container:n,...o}=e;this.tracer.log("initVideo",li(o)),this.domContainer=hw(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Js({sources:e.sources,meta:(c=e.meta)!=null?c:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],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),this.devNullLog&&this.tuning.devNullLogEnabled?(ku.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=bw())):ku.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?V.isInited$.pipe(he(n=>!!n),ve()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Ap(document,"visibilitychange").pipe(ve()).subscribe(r)):r(),this}destroy(){var e,t,i;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(),ku.destroy("core"),(i=this.collectDecodingInfoDestroyCb)==null||i.call(this)}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(he(t=>!!t),ve()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{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.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{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.waitInit(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof kt)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})}),this}setMuted(e,t=!1){return this.waitInit(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(o=s==null?void 0:s.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof kt)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{kp(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(he(i=>i.length>0),ve()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",li(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{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.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",li(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{var t;fw(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.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...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.waitInit(()=>{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.waitInit(()=>{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.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(xO(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return gw(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(ci(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(z(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(z(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(dy(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(he(({from:e})=>e==="stopped"),ve()).subscribe(()=>{this.initedAt=Pu(),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"ready":this.events.willReady$.next();break;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",li(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:xu.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ve()).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",li(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(z(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(z(n=>n.destination),Y()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Ot({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(z(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,c)=>yw(u)?1:yw(c)?-1:kO(c,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(Y()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(he(n=>gw(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(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.httpConnectionMetrics$.pipe(Y()).subscribe(this.info.httpConnectionMetrics$)).add(e.providerOutput.httpDownloadMetrics$.pipe(Y()).subscribe(this.info.httpDownloadMetrics$)).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(z(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe(z(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).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(Rp(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).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(Ot({hasLiveOffsetByPaused:ci(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(z(n=>n.to),Y(),z(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(Ot({atLiveEdge:Ot({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:xp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(z(({isLive:n,position:o,isLowLatency:u})=>{let c=this.getActiveLiveDelay(u);return n&&Math.abs(o)<c/1e3}),Y(),Rp(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(z(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ot({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(z(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Y(),Rp(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(z(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(z(n=>n.volume),Y()).subscribe(this.info.volume$)).add(xp({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(ci(e.providerOutput.endedEvent$.pipe(vw(!0)),e.providerOutput.seekedEvent$.pipe(vw(!1))).pipe(Y()).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(z(n=>({id:n?`No${n}`:"NoProviders",category:xu.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.manifestRequested$.pipe(ve()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(ve()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(ve()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(ve()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(ve()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(ve(),z(n=>n!=null?n:Pu()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ve(),z(()=>Pu()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ve(),z(()=>Pu()-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 C(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new C(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(he(({to:n})=>n==="playing"),ve()).subscribe(()=>i.next(!1)));let r=0,s=ci(e.providerOutput.isBuffering$,t,i).pipe(z(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),Y());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ci(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,c;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(c=n==null?void 0:n.size)==null?void 0:c.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ci(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),c=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),l;d==="CONNECTED"?l="second_screen":u?c?n?l="pip":o?l="fullscreen":l="inline":l="invisible":l="none",this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(z(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 Sw;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(he(i=>i.length>0),ve()).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:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=yt(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(ci(this.desiredState.videoTrack.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(z(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(z(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(z(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;kp(this.providerContainer),kp(e),uy(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>oy(i)),this.providerContainer.current$.subscribe(({type:i})=>Ba("provider",i)),e.duration$.subscribe(i=>Ba("duration",i)),e.availableVideoTracks$.pipe(he(i=>!!i.length),ve()).subscribe(i=>Ba("tracks",i)),this.events.fatalError$.subscribe(new Re("fatalError")),this.events.managedError$.subscribe(new Re("managedError")),e.position$.subscribe(new Re("position")),e.currentVideoTrack$.pipe(z(i=>i==null?void 0:i.quality)).subscribe(new Re("quality")),this.info.currentBuffer$.subscribe(new Re("buffer")),e.isBuffering$.subscribe(new Re("isBuffering"))].forEach(i=>this.subscription.add(i)),Ba("codecs",V.video.supportedCodecs)}initTracerSubscription(){let e=Tw(this.tracer.log.bind(this.tracer)),t=Tw(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(Y()).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(Ot({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(he(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(he(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(he(i=>i>0),Y()).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(Ot({currentBuffer:this.info.currentBuffer$.pipe(he(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe(Mp(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(Ot({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(he(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Mp(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),he(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),he(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),he(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ot({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(he(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Mp(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),he(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=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:xu.DOM,message:String(r)})})};this.subscription.add(ci(Ap(document,"visibilitychange"),Ap(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",li({quality:t,availableTracks:li(e),track:li(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ua()}};import{Subscription as Vee,Observable as _ee,Subject as Oee,ValueSubject as Nee,VideoQuality as Fee}from"@vkontakte/videoplayer-shared/es2018";var qee=`@vkontakte/videoplayer-core@${gh}`;export{ta as ChromecastState,Lu as HttpConnectionType,_ee as Observable,Pe as PlaybackState,Au as Player,fn as PredefinedQualityLimits,qee as SDK_VERSION,Oee as Subject,Vee as Subscription,Bu as Surface,gh as VERSION,Nee as ValueSubject,xt as VideoFormat,Fee as VideoQuality,Ho as WebmCodecStrategy,eA as areValidLiveRecordSources,V as clientChecker,xi as isMobile};
|