@vkontakte/videoplayer-core 2.0.171-dev.881304e5f.0 → 2.0.171-dev.992281cf5.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.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.171-dev.881304e5f.0
3
- * Thu, 20 Aug 2026 13:26:54 GMT
2
+ * @vkontakte/videoplayer-core v2.0.171-dev.992281cf5.0
3
+ * Thu, 20 Aug 2026 16:32:39 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-171/doc/
5
5
  */
6
- import{objectEntries as ce}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as le}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as ue}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as de,assertNonNullable as fe,isNonNullable as pe,ValueSubject as me,Subject as he,Subscription as ge,merge as _e,observableFrom as ve,fromEvent as ye,map as be,tap as xe,filterChanged as Se,isNullable as Ce,ErrorCategory as we}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as Oe,combine as ke,debounce as Ae,ErrorCategory as je,filter as Me,filterChanged as Ne,isNonNullable as Pe,isNullable as Fe,map as Ie,Subscription as Le,ValueSubject as Re}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as ze,assertNonNullable as Be,ErrorCategory as Ve,getHighestQuality as He,isNonNullable as Ue}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as We}from"@vkontakte/videoplayer-shared/es2015";import{createTimers as Ze,TimerModule as Qe}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as et}from"@vkontakte/videoplayer-shared/es2015";import{isBrowserWindow as tt,ValueSubject as nt}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as rt}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as it,isNullable as at}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as M}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as st,isBrowserWindow as ct}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as dt,isBrowserWindow as ft}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as ht,isBrowserWindow as gt}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as At,isBrowserWindow as jt}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as zt,ErrorCategory as Bt,filter as Vt,Subject as Ht,Subscription as Ut,tap as Wt,ValueSubject as Gt,fromEvent as Kt,getWindow as qt}from"@vkontakte/videoplayer-shared/es2015";import{ValueSubject as Zt,Subject as Qt,map as $t,Subscription as en,combine as tn,filterChanged as nn,assertNonNullable as rn}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as on}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as sn}from"@vkontakte/videoplayer-shared/es2015";import{objectFromEntries as cn}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as ln}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as un,Subject as dn,merge as fn}from"@vkontakte/videoplayer-shared/es2015";import"@vkontakte/videoplayer-shared/es2015";import{assertNever as hn,debounce as gn,ErrorCategory as _n,fromEvent as vn,map as yn,merge as bn,observableFrom as xn,Subject as Sn,Subscription as Cn,timeout as wn}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as An}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as jn,fromEvent as Mn,getWindow as Nn,Subscription as Pn}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as Fn}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as Yn}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Xn}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as Zn,isNonNullable as Qn,isNullable as $n,fromEvent as er,merge as tr,observableFrom as nr,filterChanged as rr,map as ir,Subject as ar,Subscription as or,ValueSubject as sr,ErrorCategory as cr}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as lr,isNullable as ur,Subscription as dr}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as P,map as Tr,merge as Er,filterChanged as Dr,isNonNullable as Or,Subject as kr,filter as Ar,mapTo as jr,combine as Mr,once as Nr,shareReplay as F,throttle as Pr,ErrorCategory as Fr,ValueSubject as Ir,Subscription as Lr}from"@vkontakte/videoplayer-shared/es2015";import{VideoQuality as Ur}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Gr}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Kr}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as qr}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as I,isNullable as Jr,now as Yr,isHigher as Xr,isHigherOrEqual as Zr,isInvariantQuality as Qr,isLowerOrEqual as $r,videoSizeToQuality as ei,assertNotEmptyArray as ti,assertNonNullable as ni}from"@vkontakte/videoplayer-shared/es2015";import{isHigher as ui,isLower as di,isNonNullable as fi,isNullable as pi,videoHeightToQuality as mi}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as Ri,assertNonNullable as zi,combine as Bi,debounce as Vi,ErrorCategory as Hi,filter as Ui,filterChanged as Wi,isNonNullable as Gi,map as Ki,merge as qi,observableFrom as Ji,once as Yi,Subscription as Xi,ValueSubject as Zi,videoQualityToHeight as Qi,videoSizeToQuality as $i}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as ea}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as ra,isNullable as ia,assertNonNullable as aa}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as oa}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as sa,assertNonNullable as ca,now as la}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as va}from"@vkontakte/videoplayer-shared/es2015";import{Subject as ba}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as xa}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Ca}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as wa}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Na}from"@vkontakte/videoplayer-shared/es2015";import{debounce as Pa,filter as Fa,fromEvent as Ia,interval as La,isHigher as Ra,isInvariantQuality as za,isLower as Ba,merge as Va,Subject as Ha,Subscription as Ua}from"@vkontakte/videoplayer-shared/es2015";import{map as Ka,Observable as qa}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as Ja}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Za}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as Qa}from"@vkontakte/videoplayer-shared/es2015";import{filter as So,filterChanged as Co,isNonNullable as wo}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as To,assertNonNullable as Eo,debounce as Do,ErrorCategory as Oo,filter as ko,filterChanged as Ao,fromEvent as jo,isNonNullable as Mo,isNullable as No,map as Po,mapTo as Fo,merge as Io,observableFrom as Lo,once as Ro,Subscription as zo,throttle as Bo}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Vo}from"@vkontakte/videoplayer-shared/es2015";import{videoSizeToQuality as Ho}from"@vkontakte/videoplayer-shared/es2015";import{isNullable as Xo,now as Zo,once as Qo,Subscription as $o,ValueSubject as es,isNonNullable as ts,safeStorage as ns,filterChanged as rs}from"@vkontakte/videoplayer-shared/es2015";import{combine as fs,map as ps,observeElementSize as ms,Subscription as hs,ValueSubject as gs,noop as _s}from"@vkontakte/videoplayer-shared/es2015";import{filter as ys,map as bs,once as xs}from"@vkontakte/videoplayer-shared/es2015";import{filterChanged as Cs,isNonNullable as ws,isNullable as Ts,now as Es,once as Ds,Subscription as Os,ValueSubject as ks}from"@vkontakte/videoplayer-shared/es2015";import{now as Ms}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Ps,now as Fs}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Is}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Ls}from"@vkontakte/videoplayer-shared/es2015";import{isLowerOrEqual as Rs,isNonNullable as zs,isNullable as Bs}from"@vkontakte/videoplayer-shared/es2015";import{isInvariantQuality as Zs,isNullable as Qs,Subscription as $s,ValueSubject as ec}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as tc,isNonNullable as nc,isNullable as rc}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as ic}from"@vkontakte/videoplayer-shared/es2015";import{Subscription as ac}from"@vkontakte/videoplayer-shared/es2015";import{Subscription as cc}from"@vkontakte/videoplayer-shared/es2015";import{isHigher as bc,isInvariantQuality as xc,isNonNullable as Sc}from"@vkontakte/videoplayer-shared/es2015";import{isHigherOrEqual as wc,isLowerOrEqual as Tc,isNonNullable as Ec,videoSizeToQuality as Dc}from"@vkontakte/videoplayer-shared/es2015";import{isHigherOrEqual as kc,isNullable as Ac}from"@vkontakte/videoplayer-shared/es2015";import{isHigherOrEqual as Nc,isNonNullable as Pc}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Ic}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Lc}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as Bc,isLowerOrEqual as Vc,isNonNullable as Hc,isNullable as Uc}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as Gc}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as qc,now as Jc}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Zc}from"@vkontakte/videoplayer-shared/es2015";import{arrayFlatMap as sl}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as cl}from"@vkontakte/videoplayer-shared/es2015";import{stringTrimStart as ll}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as ul}from"@vkontakte/videoplayer-shared/es2015";import{abortable as fl,assertNonNullable as pl,ErrorCategory as ml,filter as hl,filterChanged as gl,flattenObject as _l,fromEvent as vl,getTraceSubscriptionMethod as yl,getWindow as bl,interval as xl,isNonNullable as Sl,isNullable as Cl,map as wl,merge as Tl,nowInt as El,Subject as Dl,Subscription as Ol,SubscriptionRemovable as kl,ValueSubject as B}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as Al}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as jl}from"@vkontakte/videoplayer-shared/es2015";import{abortable as Pl,assertNever as Fl,ErrorCategory as Il,flattenObject as Ll,fromEvent as Rl,getWindow as zl,isNonNullable as Bl,merge as Vl,now as Hl,Subject as Ul,Subscription as Wl,suppressAbort as Gl,ValueSubject as Kl,videoQualityToHeight as ql,VideoQuality as Jl,isAbortError as Yl}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as Zl}from"@vkontakte/videoplayer-shared/es2015";import{devNull as iu,getWindow as au}from"@vkontakte/videoplayer-shared/es2015";import{stringReplaceAll as _u}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as vu}from"@vkontakte/videoplayer-shared/es2015";import{stringPadStart as yu}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as bu}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as xu}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Su}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Cu}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Tu,isNullable as Eu}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Du}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as Pu}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Fu}from"@vkontakte/videoplayer-shared/es2015";import{requestIdleCallbackPolyfilled as Iu}from"@vkontakte/videoplayer-shared/es2015";import{abortable as Lu,assertNonNullable as Ru,ErrorCategory as zu,flattenObject as V,fromEvent as Bu,getExponentialDelay as Vu,getWindow as Hu,isAbortError as Uu,isHigher as Wu,isNonNullable as H,isNullable as U,once as Gu,Subject as Ku,Subscription as qu,ValueSubject as Ju}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Yu}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as $u}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Ad}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as jd,isNonNullable as Md,isNullable as Nd}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as Pd}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Gd}from"@vkontakte/videoplayer-shared/es2015";import{videoSizeToQuality as Kd}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as nf,getWindow as rf,isNonNullable as af,isNullable as of,now as sf,isAbortError as cf}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as uf,getWindow as df,isAbortError as ff,isNullable as pf,now as mf}from"@vkontakte/videoplayer-shared/es2015";import{arrayFlatMap as gf}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as _f,ErrorCategory as vf,isNullable as yf,ValueSubject as bf}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as Cf,fromEvent as wf,isNullable as Tf,Subject as Ef,Subscription as Df,ValueSubject as Of}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as kf,ErrorCategory as Af,Subject as jf}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as Rf}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as zf,isHigher as Bf,isLower as Vf,isLowerOrEqual as Hf,VideoQuality as Uf}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as np,combine as rp,ErrorCategory as ip,filter as ap,filterChanged as op,fromEvent as sp,isNonNullable as cp,map as lp,merge as up}from"@vkontakte/videoplayer-shared/es2015";import{combine as pp,merge as mp,filter as hp,filterChanged as gp,isNullable as _p,map as vp,ValueSubject as yp,isNonNullable as bp}from"@vkontakte/videoplayer-shared/es2015";import{isNullable as xp,ValueSubject as Sp}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as Op,combine as kp,ErrorCategory as Ap,filter as jp,filterChanged as Mp,fromEvent as Np,interval as Pp,isNonNullable as Fp,isNullable as Ip,map as Lp,now as Rp,throttle as zp}from"@vkontakte/videoplayer-shared/es2015";import{isNullable as Vp,ValueSubject as Hp}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as Kp,assertNonNullable as qp,combine as Jp,debounce as Yp,ErrorCategory as Xp,filter as Zp,filterChanged as Qp,fromEvent as $p,isNonNullable as em,isNullable as tm,map as nm,merge as rm,observableFrom as im,once as am,Subscription as om,throttle as sm}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as cm}from"@vkontakte/videoplayer-shared/es2015";import{arrayFlatMap as lm}from"@vkontakte/videoplayer-shared/es2015";import{abortable as dm,assertNonNullable as fm,combine as pm,ErrorCategory as mm,filter as hm,filterChanged as gm,flattenObject as _m,fromEvent as vm,getTraceSubscriptionMethod as ym,interval as bm,isNonNullable as xm,isNullable as Sm,map as Cm,merge as wm,now as Tm,Subject as Em,Subscription as Dm,SubscriptionRemovable as Om,tap as km,throttle as Am,ValueSubject as W}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as jm}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Mm}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Nm}from"@vkontakte/videoplayer-shared/es2015";import{arrayFlatMap as Pm}from"@vkontakte/videoplayer-shared/es2015";import{cancelIdleCallbackPolyfilled as Fm}from"@vkontakte/videoplayer-shared/es2015";import{requestIdleCallbackPolyfilled as Im}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as Lm}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as Rm,ErrorCategory as zm,Subject as Bm}from"@vkontakte/videoplayer-shared/es2015";import{abortable as Gm,assertNonNullable as G,ErrorCategory as Km,fromEvent as qm,getExponentialDelay as Jm,getWindow as Ym,isHigher as Xm,isNonNullable as Zm,isNullable as K,now as Qm,once as $m,Subject as eh,Subscription as th,ValueSubject as nh,isAbortError as rh}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as ah}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as oh}from"@vkontakte/videoplayer-shared/es2015";import{abortable as sh,assertNever as ch,fromEvent as lh,merge as uh,now as dh,Subject as fh,ValueSubject as ph,flattenObject as mh,ErrorCategory as hh,SubscriptionRemovable as gh,getWindow as _h,isNonNullable as vh,suppressAbort as yh,videoQualityToHeight as bh,VideoQuality as xh}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as Sh}from"@vkontakte/videoplayer-shared/es2015";import{devNull as kh,getWindow as Ah}from"@vkontakte/videoplayer-shared/es2015";import{isNullable as Uh,ValueSubject as Wh}from"@vkontakte/videoplayer-shared/es2015";import{combine as Zh,merge as Qh,filter as $h,filterChanged as eg,isNullable as tg,map as ng,ValueSubject as rg,isNonNullable as ig}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as og}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as sg}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as ug,combine as dg,debounce as fg,ErrorCategory as pg,filter as mg,filterChanged as hg,isNonNullable as gg,isNullable as _g,map as vg,merge as yg,observableFrom as bg,Subscription as xg,ValueSubject as Sg,VideoQuality as Cg}from"@vkontakte/videoplayer-shared/es2015";import{objectFromEntries as wg}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as Tg}from"@vkontakte/videoplayer-shared/es2015";import{videoSizeToQuality as Eg,getExponentialDelay as Dg}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as Pg}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as Fg}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Ig,Subscription as Lg,throttle as Rg,ValueSubject as zg,Subject as Bg,ErrorCategory as Vg}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as Wg,debounce as Gg,ErrorCategory as Kg,fromEvent as qg,isNonNullable as Jg,isNullable as Yg,map as Xg,merge as Zg,observableFrom as Qg,Subscription as $g,ValueSubject as e_,VideoQuality as t_}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as r_}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as i_}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as a_}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as o_,assertNonNullable as s_,debounce as c_,ErrorCategory as l_,isHigherOrEqual as u_,isLowerOrEqual as d_,isNonNullable as f_,merge as p_,observableFrom as m_,Subscription as h_,map as g_}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as v_,debounce as y_,merge as b_,observableFrom as x_,Subscription as S_,map as C_,ValueSubject as w_,ErrorCategory as T_,VideoQuality as E_}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as D_}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as F_,assertNonNullable as I_,ErrorCategory as L_,filter as R_,isNonNullable as z_,isNullable as B_,map as V_,merge as H_,once as U_,Subject as q,Subscription as W_,ValueSubject as J,flattenObject as G_,devNull as K_,getWindow as q_}from"@vkontakte/videoplayer-shared/es2015";import{Observable as J_,map as Y_,Subscription as X_,Subject as Z_,now as Q_,combine as $_}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as tv}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as nv,Subscription as rv,combine as iv,filter as av,once as ov}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as sv}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as uv}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as dv,Subject as fv,Subscription as pv,merge as mv,isNonNullable as hv}from"@vkontakte/videoplayer-shared/es2015";import{flattenObject as gv,isNullable as _v}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as bv}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as Sv}from"@vkontakte/videoplayer-shared/es2015";import{flattenObject as wv,isNonNullable as Tv,merge as Ev,now as Dv,Subject as Ov,Subscription as kv}from"@vkontakte/videoplayer-shared/es2015";import{isNullable as jv,isNonNullable as Mv,getWindow as Nv}from"@vkontakte/videoplayer-shared/es2015";import{isNullable as Lv,isNonNullable as Rv,Subscription as zv}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as Uv,once as Wv,combine as Gv,Subscription as Kv,ValueSubject as qv,map as Jv,filter as Yv,isNonNullable as Xv,now as Zv,safeStorage as Qv,getWindow as $v}from"@vkontakte/videoplayer-shared/es2015";import{fillWithDefault as uy,VideoQuality as dy}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as my,combine as hy,devNull as gy,ErrorCategory as _y,filter as Y,filterChanged as X,flattenObject as vy,fromEvent as yy,getPlayerId as by,getTimersDiagnostics as xy,getTraceSubscriptionMethod as Sy,getWindow as Cy,InternalsExposure as wy,isHigher as Ty,isInvariantQuality as Ey,isNonNullable as Dy,isNullable as Oy,Logger as ky,map as Z,mapTo as Ay,merge as jy,now as My,once as Q,releaseTimers as Ny,retainTimers as Py,Subject as $,Subscription as Fy,tap as Iy,throttle as Ly,TracerFactory as Ry,ValueSubject as zy}from"@vkontakte/videoplayer-shared/es2015";import{merge as By,map as Vy,filter as Hy,isNonNullable as Uy}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as Gy}from"@vkontakte/videoplayer-shared/es2015";import{filter as qy,once as Jy}from"@vkontakte/videoplayer-shared/es2015";import{requestIdleCallbackPolyfilled as Xy}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Zy}from"@vkontakte/videoplayer-shared/es2015";import{cancelIdleCallbackPolyfilled as Qy}from"@vkontakte/videoplayer-shared/es2015";import{devNull as $y,getWindow as eb}from"@vkontakte/videoplayer-shared/es2015";import{Subscription as cb,Observable as lb,Subject as ub,ValueSubject as db,VideoQuality as fb}from"@vkontakte/videoplayer-shared/es2015";var _oxcMod2yytt7=function(){function e(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function t(t){return function(){var n=this,r=arguments;return new Promise(function(i,a){var o=t.apply(n,r);function s(t){e(o,i,a,s,c,`next`,t)}function c(t){e(o,i,a,s,c,`throw`,t)}s(void 0)})}}function n(e){"@babel/helpers - typeof";return n=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},n(e)}var r=n;function i(e,t){if(r(e)!=`object`||!e)return e;var n=e[Symbol._oxc_toPrimitive];if(n!==void 0){var i=n.call(e,t||`default`);if(r(i)!=`object`)return i;throw TypeError(`@@_oxc_toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var r=n,a=i;function o(e){var t=a(e,`string`);return r(t)==`symbol`?t:t+``}var s=o;function c(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var l=c;function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function d(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?u(Object(n),!0).forEach(function(t){l(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function f(e,t){this.v=e,this.k=t}var p=f;function m(e){return new p(e,0)}var p=f;function h(e){return function(){return new g(e.apply(this,arguments))}}function g(e){var t,n;function r(t,n){try{var a=e[t](n),o=a.value,s=o instanceof p;Promise.resolve(s?o.v:o).then(function(n){if(s){var c=t===`return`?`return`:`next`;if(!o.k||n.done)return r(c,n);n=e[c](n).value}i(a.done?`return`:`normal`,n)},function(e){r(`throw`,e)})}catch(e){i(`throw`,e)}}function i(e,i){switch(e){case`return`:t.resolve({value:i,done:!0});break;case`throw`:t.reject(i);break;default:t.resolve({value:i,done:!1})}(t=t.next)?r(t.key,t.arg):n=null}this._invoke=function(e,i){return new Promise(function(a,o){var s={key:e,arg:i,resolve:a,reject:o,next:null};n?n=n.next=s:(t=n=s,r(e,i))})},typeof e.return!=`function`&&(this.return=void 0)}g.prototype[typeof Symbol==`function`&&Symbol.asyncIterator||`@@asyncIterator`]=function(){return this},g.prototype.next=function(e){return this._invoke(`next`,e)},g.prototype.throw=function(e){return this._invoke(`throw`,e)},g.prototype.return=function(e){return this._invoke(`return`,e)};function _(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.includes(r))continue;n[r]=e[r]}return n}var v=_;function y(e,t){if(e==null)return{};var n,r,i=v(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.includes(n)||{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}const b=[`url`],x=[`url`],S=[`downloadingItems`],C=[`container`];var w=t,T=d,E=m,D=h,O=y,ee=`2.0.171-dev.881304e5f.0`,te;(e=>{e.STOPPED=`stopped`,e.READY=`ready`,e.PLAYING=`playing`,e.PAUSED=`paused`})(te||={});var ne;(e=>{e.MPEG=`MPEG`,e.DASH=`DASH`,e.DASH_SEP=`DASH_SEP`,e.DASH_SEP_VK=`DASH_SEP`,e.DASH_WEBM=`DASH_WEBM`,e.DASH_WEBM_AV1=`DASH_WEBM_AV1`,e.DASH_STREAMS=`DASH_STREAMS`,e.DASH_WEBM_VK=`DASH_WEBM`,e.DASH_ONDEMAND=`DASH_ONDEMAND`,e.DASH_ONDEMAND_VK=`DASH_ONDEMAND`,e.DASH_LIVE=`DASH_LIVE`,e.DASH_LIVE_CMAF=`DASH_LIVE_CMAF`,e.DASH_LIVE_WEBM=`DASH_LIVE_WEBM`,e.HLS=`HLS`,e.HLS_ONDEMAND=`HLS_ONDEMAND`,e.HLS_JS=`HLS`,e.HLS_FMP4=`HLS_FMP4`,e.HLS_LIVE=`HLS_LIVE`,e.HLS_LIVE_CMAF=`HLS_LIVE_CMAF`,e.WEB_RTC_LIVE=`WEB_RTC_LIVE`})(ne||={});var re;(e=>{e.AV1=`av1`,e.VP9=`vp9`,e.AVC1=`avc1`,e.HEV1=`hev1`})(re||={});var ie;(e=>{e.NOT_AVAILABLE=`NOT_AVAILABLE`,e.AVAILABLE=`AVAILABLE`,e.CONNECTING=`CONNECTING`,e.CONNECTED=`CONNECTED`})(ie||={});var ae;(e=>{e.HTTP1=`http1`,e.HTTP2=`http2`,e.QUIC=`quic`})(ae||={});var oe;(e=>{e.NONE=`none`,e.INLINE=`inline`,e.FULLSCREEN=`fullscreen`,e.SECOND_SCREEN=`second_screen`,e.PIP=`pip`,e.INVISIBLE=`invisible`})(oe||={});var se;(e=>{e.TRAFFIC_SAVING=`traffic_saving`,e.HIGH_QUALITY=`high_quality`,e.UNKNOWN=`unknown`})(se||={});var Te=e=>new Promise((t,n)=>{let r=document.createElement(`script`);r.setAttribute(`src`,e),r.onload=()=>t(),r.onerror=e=>n(e),document.body.appendChild(r)});class Ee{constructor(e){this.connection$=new me(void 0),this.castState$=new me(`NOT_AVAILABLE`),this.errorEvent$=new he,this.contentId=void 0,this.realCastState$=new me(`NOT_AVAILABLE`),this.subscription=new ge,this.log=void 0,this.params=void 0,this.isDestroyed=!1,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 n=pe(window.chrome?.cast),r=!!window.__onGCastApiAvailable;n?this.initializeCastApi():(window.__onGCastApiAvailable=e=>{delete window.__onGCastApiAvailable,e&&!this.isDestroyed&&this.initializeCastApi()},r||Te(`https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1`).catch(()=>this.errorEvent$.next({id:`ChromecastLoading`,category:we.NETWORK,message:`Script loading failed!`})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){var e;(e=cast.framework.CastContext.getInstance())==null||(e=e.getCurrentSession())==null||e.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var n;(n=cast.framework.CastContext.getInstance())==null||(n=n.getCurrentSession())==null||(n=n.getMediaSession())==null||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){pe(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ce(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ce(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),n=cast.framework.CastContext.getInstance();this.subscription.add(ye(n,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(e=>{switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:var t;this.contentId=(t=n.getCurrentSession())==null||(t=t.getMediaSession())==null||(t=t.media)==null?void 0:t.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 de(e.sessionState)}})).add(_e(ye(n,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(xe(e=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(e)}`})}),be(e=>e.castState)),ve([n.getCastState()])).pipe(Se(),be(De),xe(e=>{this.log({message:`realCastState$: ${e}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let i=r===`CONNECTED`,a=pe(this.connection$.getValue());if(i&&!a){var o;let r=n.getCurrentSession();fe(r);let i=r.getCastDevice(),a=(o=r.getMediaSession())==null||(o=o.media)==null?void 0:o.contentId;(Ce(a)||a===this.contentId)&&(this.log({message:`connection created`}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:r,castDevice:i}))}else!i&&a&&(this.log({message:`connection destroyed`}),this.connection$.next(void 0));this.castState$.next(r===`CONNECTED`?pe(this.connection$.getValue())?`CONNECTED`:`AVAILABLE`:r)}))}initializeCastApi(){let e,t,n;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,n=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:n}),this.initListeners()}catch(e){this.errorEvent$.next({id:`ChromecastInitializer`,category:we.EXTERNAL_API,message:`[initializeCastApi] failed`,thrown:e})}}}var De=e=>{switch(e){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 de(e)}};var k=(e,t=0,n=0)=>{switch(n){case 0:return e.replace(`_offset_p`,t===0?``:`_`+t.toFixed(0));case 1:{if(t===0)return e;let n=new URL(e);return n.searchParams.append(`playback_shift`,t.toFixed(0)),n.toString()}case 2:{let n=new URL(e);return!n.searchParams.get(`offset_p`)&&t===0?e:(n.searchParams.set(`offset_p`,t.toFixed(0)),n.toString())}default:We(n)}return e},Ge=(e,t)=>{switch(t){case 0:return NaN;case 1:{let t=new URL(e);return Number(t.searchParams.get(`playback_shift`))}case 2:{let t=new URL(e);return Number(t.searchParams.get(`offset_p`)??0)}default:We(t)}},Ke=e=>{let{source:t,format:n,meta:r,output:i}=e,a,o,s;switch(n){case`MPEG`:{let e=t[n];Be(e);let r=He(Object.keys(e));Be(r);let i=e[r];Be(i),a=i,o=`video/mp4`,s=qe();break}case`HLS`:case`HLS_FMP4`:case`HLS_ONDEMAND`:{let e=t[n];Be(e),a=e.url,o=`application/x-mpegurl`,s=qe();break}case`DASH_SEP`:case`DASH_ONDEMAND`:case`DASH_WEBM`:case`DASH_WEBM_AV1`:case`DASH_STREAMS`:{let e=t[n];Be(e),a=e.url,o=`application/dash+xml`,s=qe();break}case`DASH_LIVE_CMAF`:{let e=t[n];Be(e),a=e.url,o=`application/dash+xml`,s=Je();break}case`HLS_LIVE`:case`HLS_LIVE_CMAF`:{let e=t[n];Be(e),a=k(e.url),o=`application/x-mpegurl`,s=Je();break}case`DASH_LIVE`:case`WEB_RTC_LIVE`:{let e=`Unsupported format for Chromecast`,t=Error(e);throw i.error$.next({id:`ChromecastProvider.createMediaInfo()`,category:Ve.VIDEO_PIPELINE,message:e,thrown:t}),t}case`DASH`:case`DASH_LIVE_WEBM`:throw Error(`${n} is no longer supported`);default:return ze(n)}let c=Ye(r.videoId??a,o);c.contentUrl=a,c.streamType=s,c.metadata=Xe();let{title:l,subtitle:u}=r;return Ue(l)&&(c.metadata.title=l),Ue(u)&&(c.metadata.subtitle=u),c};function qe(){var e;return((e=chrome.cast)==null||(e=e.media)==null||(e=e.StreamType)==null?void 0:e.BUFFERED)??`BUFFERED`}function Je(){var e;return((e=chrome.cast)==null||(e=e.media)==null||(e=e.StreamType)==null?void 0:e.LIVE)??`LIVE`}function Ye(e,t){var n;return!((n=chrome.cast)==null||(n=n.media)==null)&&n.MediaInfo?new chrome.cast.media.MediaInfo(e,t):{contentId:e,contentType:t,metadata:{title:``,subtitle:``},streamType:qe()}}function Xe(){var e;return!((e=chrome.cast)==null||(e=e.media)==null)&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:``,subtitle:``,title:``,releaseYear:1970,type:0}}var A=(e,t,n=!1)=>{let r=e.getTransition();(n||!r||r.to===t)&&e.setState(t)};var j=Ze(Qe.CORE);class $e{constructor(e){this.params=void 0,this.interval=0,this.startVideoPosition=void 0,this.startTs=void 0,this.params=e}start(e=0){j.clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=j.setInterval(()=>{let e=(Date.now()-this.startTs)/1e3,t=this.startVideoPosition+e;this.params.output.position$.next(t)},1e3)}pause(){j.clearInterval(this.interval)}destroy(){j.clearInterval(this.interval)}}class ot{constructor(){this._current=void 0,this._current_version=void 0,this._chromeVersion=void 0,this._firefoxVersion=void 0,this._safariVersion=void 0,this._operaVersion=void 0,this._edgeVersion=void 0,this._yandexVersion=void 0,this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current===`Chrome`}get isChromiumBased(){return rt([`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,n=/samsungbrowser/i.test(e)?`SamsungBrowser`:void 0,r=/chrome|crios/i.test(e)?`Chrome`:void 0,i=/chromium/i.test(e)?`Chromium`:void 0,a=/firefox|fxios/i.test(e)?`Firefox`:void 0,o=/smart-tv;.*tizen/i.test(e)?`Chrome`:void 0,s=/webkit|safari|khtml/i.test(e)?`Safari`:void 0,c=/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||n||a||c||l||r||i||o||s||`Rest`}catch(e){console.error(e)}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}=it().navigator,n=t.match(e);if(!n)return;let r=n[1],i=parseInt(r,10);if(!isNaN(i))return this._current_version=i,i}catch(e){console.error(e)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/),at(this._chromeVersion)&&(this._chromeVersion=this.detectVersion(/(\d+\.\d+\.\d+\.\d+)\/\d+\.\d+ TV/))}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 lt=()=>{var e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||((e=navigator)==null||(e=e.userAgentData)==null?void 0:e.mobile)};class ut{constructor(e){this._displayChecker=void 0,this._isMobile=void 0,this._current=void 0,this._iosVersion=void 0,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(){return this._highEntropyValues.platform===`iOS`||M(this.os.name.toLowerCase(),`ios`)||M([`iPhone`,`iPad`,`iPod`],this.current)}get isIPadOS(){let e=this.current===`Mac`&&this._displayChecker.isTouch;return this.current===`iPad`||e}get isMac(){return this._highEntropyValues.platform===`macOS`||M(this.os.name.toLowerCase(),`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`||M(this.os.name.toLowerCase(),`android`)||this.current===`Android`}get isWindows(){return M(this.os.name.toLowerCase(),`windows`)}get isLinux(){return M(this.os.name.toLowerCase(),`linux`)&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=st();if(!ct(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=lt()}catch(e){console.error(`DeviceChecker: calling isMobile error - `,e)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){var e=this;return w(function*(){let t=st();if(!ct(t))return;let{userAgentData:n}=t.navigator;if(n?.getHighEntropyValues){let t=yield n.getHighEntropyValues([`architecture`,`bitness`,`brands`,`mobile`,`platform`,`formFactor`,`model`,`platformVersion`,`wow64`]);e._highEntropyValues=t,t.platform&&(e._os.name=e.normalizeOSName(t.platform),t.platformVersion&&(e._os.version=e.normalizeOSVersion(t.platformVersion),e._os.full=`${e._os.name} ${e._os.version}`)),t.model&&(e._details.model=t.model)}})()}detectDevice(e){try{let t=/android/i.test(e)?`Android`:void 0,n=/iphone/i.test(e)?`iPhone`:void 0,r=/ipad/i.test(e)?`iPad`:void 0,i=/ipod/i.test(e)?`iPod`:void 0,a=/mac/i.test(e)?`Mac`:void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?`RestMobile`:void 0;this._current=t||n||r||i||o||a||`Desktop`}catch(e){console.error(`DeviceChecker: device detection error - `,e)}}detectOS(e){try{for(let[t,n]of[[/(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]]]){let r=e.match(t);if(r){let t=n.length>0,i=n.length>1,a=`Unknown`,o=`Unknown`;if(t){let e=n[0];typeof e==`number`?e<r.length&&r[e]!==void 0&&(a=r[e]):a=e}if(i){let e=n[1];typeof e==`number`?e<r.length&&r[e]!==void 0&&(o=r[e]):e!==void 0&&(o=e)}else r[2]===void 0?r[1]!==void 0&&t&&typeof n[0]==`string`&&(o=r[1]):o=r[2];a=this.normalizeOSName(a),o=this.normalizeOSVersion(o,a),a===`iOS`&&/ipad/i.test(e)?a=`iPadOS`:a===`iPadOS`&&/ip(hone|od)/i.test(e)&&(a=`iOS`),this._os={name:a,version:o||`Unknown`,full:o&&o!==`Unknown`?`${a} ${o}`:a};break}}}catch(e){console.error(`DeviceChecker: OS detection error - `,e)}}normalizeOSName(e){if(!e)return`Unknown`;let t=e.toLowerCase();return M(t,`windows`)?`Windows`:M(t,`mac os`)||M(t,`macintosh`)?`macOS`:M(t,`iphone`)||M(t,`ios`)?`iOS`:M(t,`ipados`)?`iPadOS`:M(t,`android`)?`Android`:M(t,`harmonyos`)?`HarmonyOS`:M(t,`linux`)?`Linux`:M(t,`cros`)?`Chrome OS`:M(t,`freebsd`)?`FreeBSD`:M(t,`openbsd`)?`OpenBSD`:M(t,`solaris`)||M(t,`sunos`)?`Solaris`:M(t,`aix`)?`AIX`:e}normalizeOSVersion(e,t){if(!e)return`Unknown`;if(e!==`Unknown`&&(e=e.replace(/_/g,`.`),t===`Windows`)){let t=parseFloat(e);if(!isNaN(t)){if(t>=11)return`11`;if(t>=10)return`10`;if(t===6.3)return`8.1`;if(t===6.2)return`8`;if(t===6.1)return`7`;if(t===6)return`Vista`;if(t===5.1||t===5.2)return`XP`;if(t===5)return`2000`;if(t===4)return`NT 4.0`}}return e}detectDeviceDetails(e){try{for(let[t,n]of[[/(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]]]){let r=e.match(t);if(r){let e=n[0],t=n[1],i=typeof e==`number`?r[e]===void 0?`Unknown`:this.normalizeVendorName(r[e]):this.normalizeVendorName(e),a=`Unknown`;typeof t==`number`?a=r[t]===void 0?`Unknown`:r[t]:t===void 0?r[1]===void 0?r[0]!==void 0&&(a=r[0]):a=r[1]:a=t,a=this.normalizeModelName(a,i),this.details.vendor=i,this.details.model=a;break}}}catch(e){console.error(`DeviceChecker: device details detection error - `,e)}}normalizeVendorName(e){return e?{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`}[e.toLowerCase()]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():`Unknown`}normalizeModelName(e,t){if(!e||e===`Unknown`)return e;if(e===`0`)return`Unknown`;let n=e.replace(/^build\//i,``).replace(/\s+bui$/i,``).replace(/\)$/,``).replace(/[;,)]/g,``).replace(/\s*\(.*?\)\s*/g,``).trim(),r=t.toLowerCase();return M(r,`samsung`)?n=n.replace(/^(sm-|gt-|sgh-|sch-)/i,``):M(r,`xiaomi`)?n=n.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,``):M(r,`oneplus`)?n=n.replace(/^oneplus[\s\-_]*/i,``):M(r,`google`)&&(n=n.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,``)),n=n.replace(/_/g,` `).replace(/-/g,` `).replace(/\s+/g,` `).trim(),n?(n.length>0&&/^[a-z]/.test(n)&&(n=n.charAt(0).toUpperCase()+n.slice(1)),n):`Unknown`}detectIOSVersion(){try{let e=st();if(!ct(e))return;if(this._highEntropyValues.platformVersion){let e=this._highEntropyValues.platformVersion.split(`.`).slice(0,2).join(`.`);this._iosVersion=parseFloat(e);return}if(this._os.version!==`Unknown`){let e=this._os.version.split(`.`),t=e.length>=2?`${e[0]}.${e[1]}`:e[0];this._iosVersion=parseFloat(t);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t?.[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,`.`)))}catch(e){console.error(`DeviceChecker: iOS version detection error - `,e)}}}var pt=[`standalone`,`minimal-ui`,`fullscreen`,`window-controls-overlay`,`picture-in-picture`];class mt{constructor(){this._maxTouchPoints=void 0,this._height=void 0,this._width=void 0,this._isHdr=void 0,this._pixelRatio=void 0,this._screenHeight=void 0,this._screenWidth=void 0,this._colorDepth=void 0,this._displayMode=`browser`,this._isStandalone=!1}get isTouch(){return typeof this._maxTouchPoints==`number`?this._maxTouchPoints>1:`ontouchstart`in dt()}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}get displayMode(){return this._displayMode}get isStandalone(){return this._isStandalone}detect(){let e=dt();if(!ft(e))return;let{navigator:t,screen:n}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r??0,this._isHdr=!!e.matchMedia(`(dynamic-range: high)`)?.matches,this._colorDepth=n.colorDepth}catch(e){console.error(e)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=n.height,this._width=n.width,this._height=n.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(e){console.error(e)}try{this._displayMode=this.detectDisplayMode(e);let n=t.standalone===!0;this._isStandalone=n||this._displayMode!==`browser`}catch(e){console.error(e)}}detectDisplayMode(e){return pt.find(t=>{var n;return(n=e.matchMedia)==null||(n=n.call(e,`(display-mode: ${t})`))==null?void 0:n.matches})??`browser`}}var _t=()=>window.ManagedMediaSource||window.MediaSource,vt=()=>{var e;return!!(window.ManagedMediaSource&&!((e=window.ManagedSourceBuffer)==null||(e=e.prototype)==null)&&e.appendBuffer)},yt=()=>{var e;return!!(window.MediaSource&&!((e=window.SourceBuffer)==null||(e=e.prototype)==null)&&e.appendBuffer)},bt=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,xt=ht().document?.createElement(`video`),St=`video/mp4; codecs="avc1.42000a,mp4a.40.2"`,Ct=`video/mp4; codecs="hev1.1.6.L93.B0"`,wt=`video/webm; codecs="vp09.00.10.08"`,Tt=`video/webm; codecs="av01.0.00M.08"`,Et=`audio/mp4; codecs="mp4a.40.2"`,Dt=`audio/webm; codecs="opus"`,Ot;(function(){var e=w(function*(){let e=ht();if(!gt(e)||!(`mediaCapabilities`in e.navigator))return;let t={type:`media-source`,video:{contentType:`video/webm`,width:1280,height:720,bitrate:1e6,framerate:30}},[n,r]=yield Promise.all([e.navigator.mediaCapabilities.decodingInfo(T(T({},t),{},{video:T(T({},t.video),{},{contentType:Tt})})),e.navigator.mediaCapabilities.decodingInfo(T(T({},t),{},{video:T(T({},t.video),{},{contentType:wt})}))]);Ot={DASH_WEBM_AV1:n,DASH_WEBM:r}});return function(){return e.apply(this,arguments)}})()().catch(e=>{console.log(xt),console.error(e)});class kt{constructor(e,t){this._video=void 0,this._deviceChecker=void 0,this._browserChecker=void 0,this._protocols=void 0,this._containers=void 0,this._codecs=void 0,this._nativeHlsSupported=void 0,this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return Ot}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=ht();if(!gt(e))return;let t=e.document;this._video=t.createElement(`video`);try{var n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_;this._protocols={mms:vt(),mse:yt(),hls:!!((n=this._video).canPlayType?.call(n,`application/x-mpegurl`)||(r=this._video).canPlayType?.call(r,`vnd.apple.mpegURL`)),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!(i=this._video).canPlayType?.call(i,`video/mp4`),webm:!!(a=this._video).canPlayType?.call(a,`video/webm`),cmaf:!0};let t=!!(!((o=_t())==null||(s=o.isTypeSupported)==null)&&s.call(o,St)),v=!!(!((c=_t())==null||(l=c.isTypeSupported)==null)&&l.call(c,Ct)),y=!!(!((u=_t())==null||(d=u.isTypeSupported)==null)&&d.call(u,Et));this._codecs={h264:t,h265:v,vp9:!!(!((f=_t())==null||(p=f.isTypeSupported)==null)&&p.call(f,wt)),av1:!!(!((m=_t())==null||(h=m.isTypeSupported)==null)&&h.call(m,Tt)),aac:y,opus:!!(!((g=_t())==null||(_=g.isTypeSupported)==null)&&_.call(g,Dt)),mpeg:(t||v)&&y},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error(`Error destroying video element:`,e)}}destroyVideoElement(){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);this._video.parentNode?.replaceChild(e,this._video),this._video=null}}var Mt=`audio/mpeg`;class Nt{constructor(){this._audio=void 0,this._containers=void 0,this._codecs=void 0}supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=At();if(!jt(e))return;let t=e.document;this._audio=t.createElement(`audio`);try{var n,r,i;this._containers={mpeg:!!(n=this._audio).canPlayType?.call(n,Mt)},this._codecs={mp3:!!(!((r=_t())==null||(i=r.isTypeSupported)==null)&&i.call(r,Mt))}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error(`Error destroying audio element:`,e)}}destroyAudioElement(){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);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}}class Pt{constructor(){this.isInited$=new nt(!1),this._displayChecker=void 0,this._deviceChecker=void 0,this._browserChecker=void 0,this._videoChecker=void 0,this._audioChecker=void 0,this._displayChecker=new mt,this._deviceChecker=new ut(this._displayChecker),this._browserChecker=new ot,this._videoChecker=new kt(this._deviceChecker,this._browserChecker),this._audioChecker=new Nt,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){var e=this;return w(function*(){tt()&&(e._displayChecker.detect(),e._deviceChecker.detect(),e._browserChecker.detect(),e._videoChecker.detect(),e._audioChecker.detect(),e.isInited$.next(!0))})()}}var N=new Pt,Ft=(e,t=!1)=>{let{containers:n,protocols:r,codecs:i,nativeHlsSupported:a}=N.video,{isMobile:o}=N.device,s=N.device.isMac&&N.browser.isSafari,c=t&&!o&&!s,l=(i.h264||i.h265)&&i.aac,u=r.mse||r.mms;return e.filter(e=>{switch(e){case`DASH_SEP`:return u&&n.mp4&&l;case`DASH_WEBM`:return u&&n.webm&&i.vp9&&i.opus;case`DASH_WEBM_AV1`:return u&&n.webm&&i.av1&&i.opus;case`DASH_STREAMS`:return u&&(n.mp4&&l||n.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case`DASH_LIVE`:return u&&n.mp4&&l;case`DASH_LIVE_CMAF`:return u&&n.mp4&&l&&n.cmaf;case`DASH_ONDEMAND`:return u&&n.mp4&&l;case`HLS`:case`HLS_ONDEMAND`:case`HLS_FMP4`:case`HLS_LIVE`:case`HLS_LIVE_CMAF`:return a&&!c;case`MPEG`:return n.mp4;case`DASH`:case`DASH_LIVE_WEBM`:return!1;case`WEB_RTC_LIVE`:return r.webrtc&&r.ws&&i.h264&&(n.mp4||n.webm);default:return et(e)}})},It=e=>{switch(e){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 et(e)}},Lt=(e,t=!1)=>Ft(Object.keys(e).filter(e=>!It(e)),t).length>0;class Rt{constructor(e){this.subscription=new Le,this.log=void 0,this.params=void 0,this.sessionId$=new Re(null),this.mediaSessionId$=new Re(null),this.contentId$=new Re(null),this.progressTicker=void 0,this.isMobile=lt(),this.mobileVolumeState={muted:!1,volume:0},this.media=null,this.lastRequestedVolume=null,this.syncMediaState=e=>{if(Fe(e))return;this.media=e,this.mediaSessionId$.next(e.mediaSessionId??null);let t=e.media?.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let n=e.media?.duration;Pe(n)&&this.params.output.duration$.next(Math.max(0,n));let r=e.currentTime;if(Pe(r)){this.params.desiredState.seekState.getState().state===`applying`&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let t=this.params.output.isLive$.getValue();e.playerState===`PLAYING`&&!t?this.progressTicker.start(r):this.progressTicker.pause()}},this.params=e,this.progressTicker=new $e(e),this.log=this.params.dependencies.logger.createComponentLog(`ChromecastPresentationApiProvider`),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(It(e.format)),this.subscribe()}subscribe(){let e=e=>{this.params.output.error$.next({category:je.WTF,id:`ChromecastPresentationApiProvider`,message:e?.message??`Unknown error`,thrown:e})};this.subscription.add(this.params.chromecastConnector.message$.pipe(Me(e=>!!e)).subscribe(e=>{this.handleMessage(e)},e)),this.subscription.add(this.sessionId$.pipe(Me(Pe),Ne(),Ae(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(Ne(),Ie(Boolean));this.subscription.add(ke({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(Me(({mediaLoaded:e})=>e)).subscribe(()=>{let e=this.params.desiredState.seekState.getState();e.state===`requested`&&this.seek(e.position/1e3)},e));let n=ke({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(n.pipe(Me(({mediaLoaded:e})=>e),Ae(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(n.pipe(Me(({mediaLoaded:e,playbackState:{from:t,to:n}})=>!e&&t===`stopped`&&n===`playing`)).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(ke({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(Ae(30)),mediaLoaded:t}).pipe(Me(({mediaLoaded:e})=>e)).subscribe(({volumeState:e})=>{let{muted:t,volume:n}=e.to;this.setVolume(n,t)},e))}handleMessage(e){switch(e.type){case`new_session`:case`update_session`:{var t;this.sessionId$.next(e.message.sessionId);let n=(t=e.message)==null||(t=t.media)==null?void 0:t[0];this.syncMediaState(n);let r=e.message?.receiver.volume;this.syncVolumeState(r)}break;case`v2_message`:switch(e.message?.type){case`MEDIA_STATUS`:{var n;let t=(n=e.message)==null||(n=n.status)==null?void 0:n[0];this.syncMediaState(t);break}}break}}loadMedia(){let e=Ke(this.params),t=this.media?.currentTime,n=this.params.desiredState.seekState.getState(),r=t??(n.state===`none`?0:n.position/1e3),i=this.params.desiredState.playbackState.getState()===`playing`;this.params.chromecastConnector.sendV2Message({type:`LOAD`,requestId:0,media:e,autoplay:i,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();Oe(e,`play on null mediaSessionId`),this.params.chromecastConnector.sendV2Message({type:`PLAY`,mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Oe(e,`pause on null mediaSessionId`),this.params.chromecastConnector.sendV2Message({type:`PAUSE`,mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Oe(t,`seek on null mediaSessionId`),this.params.chromecastConnector.sendV2Message({type:`SEEK`,currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let n=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(n=this.mobileVolumeState.volume,r+=`, mobile next volume: ${n}`),this.log({message:r}),this.lastRequestedVolume={volume:n,muted:t},this.params.chromecastConnector.sendV2Message({type:`SET_VOLUME`,requestId:0,volume:{level:t?0:n,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let n=this.params.output.isBuffering$.getValue(),r=e===`BUFFERING`;switch(n!==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(Fe(e))return;let{level:t,muted:n}=e,r={muted:n??!1,volume:t??0};this.lastRequestedVolume&&=(n&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!n&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),null);let i=`[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,i+=`, volume passed to state machine: ${r.volume}`),this.log({message:i}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}}var Jt=e=>({castDevice:{friendlyName:e},remotePlayer:{},remotePlayerController:{},session:{}}),Yt=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));class Xt{constructor(e){this.params=void 0,this.clientId=void 0,this.capabilities=[`WEB`],this.presentationRequest$=new Gt(null),this.log=void 0,this.sessionId$=new Gt(null),this.broadcastChannel=new BroadcastChannel(`vk_player_chromecast_events`),this.subscription=new Ut,this.subscriptionEvents=new Ut,this.isDestroyed=!1,this.sequenceNumber=0,this.presentationAvailable$=new Gt(!1),this.presentationConnection$=new Gt(null),this.message$=new Gt(null),this.friendlyName$=new Gt(null),this.errorEvent$=new Ht,this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog(`ChromecastPresentationApiConnector`),this.log({message:`constructor`}),this.safeReinitPresentation(),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(),n=new PresentationRequest(t);this.presentationRequest$.next(n),this.log({message:`PresentationRequest created`}),n.getAvailability().then(e=>{let t=()=>{this.log({message:`PresentationRequest presentation availability: ${e.value}`}),this.presentationAvailable$.next(e.value)};this.subscriptionEvents.add(Kt(e,`change`).subscribe(()=>{t()})),t()}).catch(()=>{this.presentationAvailable$.next(!0)}),qt().navigator.presentation.defaultRequest=n,e&&n.reconnect(`auto-join`).then(e=>{this.log({message:`PresentationRequest reconnect success`}),this.handleConnection(e)}).catch(()=>{this.log({message:`PresentationRequest reconnect failed`})})}safeReinitPresentation(e){try{this.reinitPresentation(e)}catch(e){this.errorEvent$.next({category:Bt.WTF,id:`ChromecastPresentationApiConnector`,message:e?.message??`reinitPresentation error`,thrown:e})}}connect(){var e=this;return w(function*(){e.log({message:`connect`});try{e.presentationRequest$.getValue()||(e.log({message:`reinitPresentation`}),e.reinitPresentation(!1));let t=e.presentationRequest$.getValue();zt(t,`connect with null presentationRequest`);let n=yield t.start();e.handleConnection(n)}catch(t){switch(t?.name){case`AbortError`:case`NotAllowedError`:break;default:e.errorEvent$.next({category:Bt.WTF,id:`ChromecastPresentationApiConnector`,message:t?.message??`connect error`,thrown:t});break}}})()}subscribe(){this.subscription.add(Kt(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(Wt(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),Vt(e=>!!e)).subscribe(e=>{let t=Kt(e,`message`).subscribe(e=>{let t=JSON.parse(e.data);t.clientId===this.clientId&&(this.log({message:`[onmessage] ${e.data}`}),this.handleMessage(t),this.message$.next(t))}),n=Kt(e,`connect`).subscribe(()=>{this.send(`client_connect`)}),r=Kt(e,`close`).subscribe(e=>{switch(e.reason){case`error`:this.errorEvent$.next({category:Bt.WTF,id:`ChromecastPresentationApiConnector`,message:`Session error`,thrown:e});break;case`closed`:break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(n),this.subscriptionEvents.add(r)}))}send(e){switch(e){case`client_connect`:{let e={type:`client_connect`,message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(e));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let n={type:`v2_message`,sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:T(T({},e),{},{sessionId:t})};this.safeSend(JSON.stringify(n))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();t?.state===`connected`&&t?.send(e)}catch(t){this.errorEvent$.next({category:Bt.WTF,id:`ChromecastPresentationApiConnector`,message:`PresentationConnection send error`,data:{message:e},thrown:t})}}handleMessage(e){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`:e.message?.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)%(2**53-1),e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e=`__vk_player_chromecast_id`;return qt()[e]=qt()[e]||Yt()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new Ut}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))}}class an{static isSupported(){return`chrome`in window&&`presentation`in navigator&&`BroadcastChannel`in window}constructor(e){this.subscription=new en,this.log=void 0,this.contentId=void 0,this.connection$=new Zt(void 0),this.castState$=new Zt(`NOT_AVAILABLE`),this.errorEvent$=new Qt,this.chromecastConnector=void 0;let t=an.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 Xt({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}subscribe(){rn(this.chromecastConnector,`subscribe with null chromecastConnector`),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=tn({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(nn())});this.subscription.add(e.pipe($t(({connection:e,friendlyName:t})=>!!(e&&t)),nn()).subscribe(e=>{let t=this.chromecastConnector?.friendlyName$.getValue()??``;this.connection$.next(e?Jt(t):void 0)})).add(e.subscribe(({available:e,connection:t})=>{e?t?this.castState$.next(`CONNECTED`):this.castState$.next(`AVAILABLE`):this.castState$.next(`NOT_AVAILABLE`)}))}connect(){this.log({message:`connect`}),this.chromecastConnector?.connect()}disconnect(){this.log({message:`disconnect`}),this.chromecastConnector?.disconnect()}stopMedia(){var e=this;return w(function*(){e.log({message:`stopMedia`}),e.chromecastConnector?.stopMedia()})()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:`destroy`}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}}var pn=(e,t)=>e===t;class mn{constructor(e,t=pn){this.comparator=void 0,this.state=void 0,this.prevState=void 0,this.transition=void 0,this.transitionStarted$=new dn,this.transitionEnded$=new dn,this.transitionUpdated$=new dn,this.forceChanged$=new dn,this.stateChangeStarted$=fn(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=fn(this.transitionEnded$,this.forceChanged$),this.comparator=t,this.state=e,this.prevState=void 0}setState(e){let t=this.transition,n=this.state;this.transition=void 0,this.prevState=n,this.state=e,t?this.comparator(t.to,e)?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:n,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,n=this.state;this.comparator(n,e)||un(t)&&this.comparator(t.to,e)||(this.prevState=n,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:n,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}var Tn=5,En=5,Dn=500,On=7e3;class kn{constructor(e){this.subscription=new Cn,this.loadMediaTimeoutSubscription=new Cn,this.videoState=new mn(`stopped`),this.params=void 0,this.log=void 0,this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(i)};`}),n===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.stop());return}if(!t){if(r?.to!==`paused`&&i.state===`requested`&&e!==`stopped`){this.seek(i.position/1e3);return}switch(n){case`ready`:switch(e){case`playing`:case`paused`:case`ready`:break;case`stopped`:this.videoState.startTransitionTo(`ready`),this.prepare();break;default:hn(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:hn(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:hn(e)}break;default:hn(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog(`ChromecastProvider`),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(It(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 Cn;this.subscription.add(e),this.subscription.add(bn(this.videoState.stateChangeStarted$.pipe(yn(e=>`stateChangeStarted$ ${JSON.stringify(e)}`)),this.videoState.stateChangeEnded$.pipe(yn(e=>`stateChangeEnded$ ${JSON.stringify(e)}`))).subscribe(e=>this.log({message:`[videoState] ${e}`})));let t=(e,t)=>this.subscription.add(e.subscribe(t));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let t=new Sn;e.add(t.pipe(gn(Dn)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(e=>{this.logRemoteEvent(e);let r=e.value;this.params.output.position$.next(r),(this.params.desiredState.seekState.getState().state===`applying`||Math.abs(r-n)>Tn)&&t.next(r),n=r})),e.add(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(e=>{this.logRemoteEvent(e),this.params.output.duration$.next(e.value)}))}t(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),t=>{this.logRemoteEvent(t),t.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),e=>{this.logRemoteEvent(e),e.value?this.handleRemotePause():this.handleRemotePlay()}),t(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),e=>{this.logRemoteEvent(e);let{remotePlayer:t}=this.params.connection,n=e.value,r=this.params.output.isBuffering$.getValue(),i=n===chrome.cast.media.PlayerState.BUFFERING;switch(r!==i&&this.params.output.isBuffering$.next(i),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&t.duration-t.currentTime<En&&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:hn(n)}}),t(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({volume:e.value})}),t(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({muted:e.value})}),t(bn(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xn([`init`])).pipe(gn(0)),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 e=this.params.output.isLive$.getValue();this.params.output.duration$.next(e?0:t.duration),this.params.output.position$.next(e?0:t.currentTime),this.params.desiredState.seekState.setState({state:`none`})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=Ke(this.params),n=this.createLoadRequest(t);this.loadMedia(n)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to===`paused`||e===`playing`)&&(this.videoState.setState(`paused`),A(this.params.desiredState.playbackState,`paused`))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to===`playing`||e===`paused`)&&(this.videoState.setState(`playing`),A(this.params.desiredState.playbackState,`playing`))}handleRemoteReady(){this.videoState.getTransition()?.to===`ready`&&this.videoState.setState(`ready`),this.params.desiredState.playbackState.getTransition()?.to===`ready`&&A(this.params.desiredState.playbackState,`ready`)}handleRemoteStop(){this.videoState.getState()!==`stopped`&&this.videoState.setState(`stopped`)}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),n={volume:e.volume??t.volume,muted:e.muted??t.muted};(n.volume!==t.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:n}=this.params.connection;t.currentTime=e,n.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let n=this.params.desiredState.seekState.getState();return n.state===`applying`||n.state===`requested`?t.currentTime=this.params.output.isLive$.getValue()?0:n.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),n=new Promise((e,t)=>{this.loadMediaTimeoutSubscription.add(wn(On).subscribe(()=>t(`timeout(${On})`)))});ln(Promise.race([t,n]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===`applying`&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},e=>{let t=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${e}`;this.log({message:t}),this.params.output.error$.next({id:`ChromecastProvider.loadMedia`,category:_n.VIDEO_PIPELINE,message:t,thrown:e})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var In=e=>{try{e.pause(),e.playbackRate=0,Fn(e),e.remove()}catch(e){console.error(e)}},Ln=`__spvc`;class Rn{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)}}var zn=Nn(),Bn=zn.WeakMap?new zn.WeakMap:new Rn,Vn=zn.WeakMap?new zn.WeakMap:new Map,Hn=(e,t=20)=>{let n=0;return Mn(e,`ratechange`).subscribe(r=>{n++,n>=t&&(e.currentTime=e.currentTime,n=0)})};function Un(e){e.style.position=`fixed`,e.style.left=`100%`,e.setAttribute(`data-role`,`screen`),Nn().document.body.appendChild(e)}function Wn(e,t){e.style.position=``,e.style.left=``,t.appendChild(e)}var Gn=(e,{audioVideoSyncRate:t,disableYandexPiP:n,reuseOwnVideoElement:r})=>{let i,a=e.querySelector(`video`),o=!!a,s=Nn().document.querySelector(`body > video[data-role=screen]`)||void 0;r?zn[Ln]=s:(s?.remove(),delete zn[Ln]),a?(i=a,jn(i)):s&&s===zn[Ln]?(i=s,Wn(i,e)):(i=Nn().document.createElement(`video`),e.appendChild(i),r&&(zn[Ln]=i)),Bn.set(i,o);let c=new Pn;return c.add(Hn(i,t)),Vn.set(i,c),i.setAttribute(`crossorigin`,`anonymous`),i.setAttribute(`playsinline`,`playsinline`),n&&i.setAttribute(`x-yandex-pip`,`false`),i.controls=!1,i.setAttribute(`poster`,`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=`),i},Kn=e=>(e.setAttribute(`crossorigin`,`anonymous`),e.controls=!1,e),qn=(e,t)=>{if(e instanceof HTMLAudioElement){In(e);return}if(e instanceof HTMLVideoElement){Jn(e,t);return}};function Jn(e,{reuseOwnVideoElement:t}){Vn.get(e)?.unsubscribe(),Vn.delete(e);let n=Bn.get(e);Bn.delete(e),jn(e),t&&!n&&Un(e)}var fr=(e,t,n,{equal:r=(e,t)=>e===t,changed$:i,onError:a}={})=>{let o=e.getState(),s=t(),c=ur(i),l=new dr;return i&&l.add(i.subscribe(t=>{r(t,e.getState())&&e.setState(t)},a)),r(s,o)||(n(o),c&&e.setState(o)),l.add(e.stateChangeStarted$.subscribe(t=>{n(t.to),c&&e.setState(t.to)},a)),l},pr=(e,t,n)=>fr(t,()=>e.loop,t=>{lr(t)&&(e.loop=t)},{onError:n}),mr=(e,t,n,r,i)=>fr(t,()=>({muted:e.muted,volume:e.volume}),t=>{i?.skipVideoElVolumeSync$.getValue()||lr(t)&&(e.muted=t.muted,e.volume=t.volume)},{equal:(e,t)=>e===t||e?.muted===t?.muted&&e?.volume===t?.volume,changed$:n,onError:r}),hr=(e,t,n,r)=>fr(t,()=>e.playbackRate,t=>{lr(t)&&(e.playbackRate=t)},{changed$:n,onError:r}),gr=fr,_r=e=>[`__`,e.language,e.label].join(`|`),vr=(e,t)=>{if(e.id===t)return!0;let[n,r,i]=t.split(`|`);return e.language===r&&e.label===i};class yr{constructor(e){this.available$=new ar,this.current$=new sr(void 0),this.error$=new ar,this.video=void 0,this.cueSettings=void 0,this.subscription=new or,this.externalTracks=new Map,this.internalTracks=new Map,this.baseURL=void 0,this.baseURL=e}connect(e,t,n){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=e=>{this.error$.next({id:`TextTracksManager`,category:cr.WTF,message:`Generic HtmlVideoTextTrackManager error`,thrown:e})};this.subscription.add(this.available$.subscribe(n.availableTextTracks$)),this.subscription.add(this.current$.subscribe(n.currentTextTrack$)),this.subscription.add(this.error$.subscribe(n.error$)),this.subscription.add(gr(t.internalTextTracks,()=>Yn(this.internalTracks),e=>{Qn(e)&&this.setInternal(e)},{equal:(e,t)=>Qn(e)&&Qn(t)&&e.length===t.length&&e.every(({id:e},n)=>e===t[n].id),changed$:this.available$.pipe(ir(e=>e.filter(({type:e})=>e===`internal`))),onError:r})),this.subscription.add(gr(t.externalTextTracks,()=>Yn(this.externalTracks),e=>{Qn(e)&&this.setExternal(e)},{equal:(e,t)=>Qn(e)&&Qn(t)&&e.length===t.length&&e.every(({id:e},n)=>e===t[n].id),changed$:this.available$.pipe(ir(e=>e.filter(({type:e})=>e===`external`))),onError:r})),this.subscription.add(gr(t.currentTextTrack,()=>{if(this.video)return;let e=this.htmlTextTracksAsArray().find(({mode:e})=>e===`showing`);return e&&this.htmlTextTrackToITextTrack(e).id},e=>this.select(e),{changed$:this.current$,onError:r})),this.subscription.add(gr(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let e of this.htmlTextTracksAsArray())this.applyCueSettings(e.cues),this.applyCueSettings(e.activeCues)}))}subscribe(){Zn(this.video);let{textTracks:e}=this.video;this.subscription.add(er(e,`addtrack`).subscribe(()=>{let e=this.current$.getValue();e&&this.select(e)})),this.subscription.add(tr(er(e,`addtrack`),er(e,`removetrack`),nr([`init`])).pipe(ir(()=>this.htmlTextTracksAsArray().map(e=>this.htmlTextTrackToITextTrack(e))),rr((e,t)=>e.length===t.length&&e.every(({id:e},n)=>e===t[n].id))).subscribe(this.available$)),this.subscription.add(tr(er(e,`change`),nr([`init`])).pipe(ir(()=>this.htmlTextTracksAsArray().find(({mode:e})=>e===`showing`)),ir(e=>e&&this.htmlTextTrackToITextTrack(e).id),rr()).subscribe(this.current$));let t=e=>this.applyCueSettings(e.target?.activeCues??null);this.subscription.add(er(e,`addtrack`).subscribe(e=>{e.track?.addEventListener(`cuechange`,t);let n=e=>{let t=e.target?.cues??null;t&&t.length&&(this.applyCueSettings(e.target?.cues??null),e.target?.removeEventListener(`cuechange`,n))};e.track?.addEventListener(`cuechange`,n)})),this.subscription.add(er(e,`removetrack`).subscribe(e=>{e.track?.removeEventListener(`cuechange`,t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let n of Array.from(e)){let e=n;Qn(t.align)&&(e.align=t.align),Qn(t.position)&&(e.position=t.position),Qn(t.size)&&(e.size=t.size),Qn(t.line)&&(e.line=t.line)}}htmlTextTracksAsArray(e=!1){Zn(this.video);let t=[...this.video.textTracks];return e?t:t.filter(yr.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:n}=e,r=e.id?e.id:_r(e),i=this.externalTracks.has(r),a=(i?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??Xn(r,`auto`);return i?{id:r,type:`external`,isAuto:a,language:t,label:n,url:this.externalTracks.get(r)?.url}:{id:r,type:`internal`,isAuto:a,language:t,label:n,url:this.internalTracks.get(r)?.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(([,e])=>this.detach(e)),e.filter(({id:e})=>!this.externalTracks.has(e)).forEach(e=>this.attach(e)),Array.from(this.externalTracks).filter(([t])=>!e.find(e=>e.id===t)).forEach(([,e])=>this.detach(e))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:e,language:n,isAuto:r})=>!this.internalTracks.has(e)&&!t.some(([,e])=>e.language===n&&e.isAuto===r)).forEach(e=>this.attach(e)),Array.from(this.internalTracks).filter(([t])=>!e.find(e=>e.id===t)).forEach(([,e])=>this.detach(e))}select(e){Zn(this.video);for(let e of this.htmlTextTracksAsArray(!0))e.mode=`showing`;for(let t of this.htmlTextTracksAsArray(!0))($n(e)||!vr(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){Zn(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){Zn(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName(`track`),t=>t.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)}}var br=yr;class xr{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 Sr=e=>{let t=e;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t?.parentNode;return t??void 0},Cr=e=>{let t=Sr(e);return!!(t&&t.fullscreenElement&&t.fullscreenElement===e)},wr=e=>{let t=Sr(e);return!!(t&&t.pictureInPictureElement&&t.pictureInPictureElement===e)};var Rr=3,zr=(e,t,n=Rr)=>{let r=0,i=0;for(let a=0;a<e.length;a++){let o=e.start(a),s=e.end(a);if(o<=t&&t<=s){if(r=o,i=s,!n)return{from:r,to:i};for(let t=a-1;t>=0;t--)e.end(t)+n>=r&&(r=e.start(t));for(let t=a+1;t<e.length;t++)e.start(t)-n<=i&&(i=e.end(t))}}return{from:r,to:i}},Br=e=>{let t=0;for(let n=0;n<e.length;n++)t+=e.end(n)-e.start(n);return t},Vr=e=>{let t=0;for(let n=0;n<e.length;n++)t+=e.end(n)-e.start(n);return t*1e3},Hr=e=>{let t=t=>P(e,t).pipe(jr(void 0),F(1)),n=new Lr,r=()=>n.unsubscribe(),i=Er(P(e,`progress`),P(e,`timeupdate`)),a=i.pipe(Tr(()=>zr(e.buffered,e.currentTime)),F(1)),o=i.pipe(Tr(()=>Vr(e.buffered)),F(1)),s=i.pipe(Tr(()=>e.buffered.length),F(1)),c=N.browser.isSafari?Mr({play:t(`play`).pipe(Nr()),playing:t(`playing`)}).pipe(jr(void 0),F(1)):t(`playing`),l=P(e,`volumechange`).pipe(Tr(()=>({muted:e.muted,volume:e.volume})),F(1)),u=P(e,`ratechange`).pipe(Tr(()=>e.playbackRate),F(1)),d=P(e,`error`).pipe(Ar(()=>!!(e.error||e.played.length)),Tr(()=>{let t=e.error;return{id:t?`MediaError#${t.code}`:`HtmlVideoError`,category:Fr.VIDEO_PIPELINE,message:t?t.message:`Error event from HTML video element`,thrown:e.error??void 0,origin:`mediaError`,data:t?{code:t.code}:void 0}}),F(1)),f=P(e,`timeupdate`).pipe(Tr(()=>e.currentTime),F(1)),p=Er(P(e,`loadedmetadata`),P(e,`timeupdate`),P(e,`pause`),P(e,`seeked`),P(e,`ended`)).pipe(Tr(()=>Br(e.played)),Dr(),F(1)),m=[`waiting`,`seeking`,`seeked`,`timeupdate`],h=new kr,g=.3,_;n.add(Er(...m.map(t=>P(e,t))).subscribe(t=>{let n=e.currentTime;e.loop&&Or(_)&&Or(n)&&_>=e.duration-g&&n<=g&&h.next(_),_=n}));let v=t(`pause`).pipe(Ar(()=>!e.error&&_!==e.duration),F(1)),y=P(e,`enterpictureinpicture`).pipe(F(1)),b=P(e,`leavepictureinpicture`).pipe(F(1)),x=new Ir(wr(e));n.add(y.subscribe(()=>x.next(!0))),n.add(b.subscribe(()=>x.next(!1)));let S=new Ir(Cr(e)),C=P(e,`fullscreenchange`).pipe(F(1));n.add(C.pipe(Tr(()=>Cr(e))).subscribe(S));let w=P(e,`timeupdate`).pipe(Tr(t=>e.duration-e.currentTime<.1),Dr(),F(1)),T=Er(w.pipe(Ar(t=>!e.loop&&t)),P(e,`ended`)).pipe(Pr(1e3),jr(void 0),F(1)),E=Er(...[`waiting`,`pause`,`canplay`,`play`,`canplaythrough`,`playing`,`seeking`,`seeked`,`ended`].map(t=>P(e,t)),w.pipe(Tr(e=>({type:e?`ended`:`unknown`})))).pipe(Tr(t=>N.browser.isFirefox&&t.type===`ended`?e.readyState<2:e.readyState<3),Dr(),F(1));return{playing$:c,pause$:v,canplay$:t(`canplay`),ended$:T,looped$:h,error$:d,seeked$:t(`seeked`),seeking$:t(`seeking`),progress$:t(`progress`),loadStart$:t(`loadstart`),loadedMetadata$:t(`loadedmetadata`),loadedData$:t(`loadeddata`),timeUpdate$:f,durationChange$:P(e,`durationchange`).pipe(Tr(()=>e.duration),F(1)),playedTime$:p,isBuffering$:E,currentBuffer$:a,totalBufferDuration$:o,bufferRangeCount$:s,volumeState$:l,playbackRateState$:u,inPiP$:x,inFullscreen$:S,enterPip$:y,leavePip$:b,destroy:r}};var Wr=e=>{switch(e){case`mobile`:return Ur.Q_144P;case`lowest`:return Ur.Q_240P;case`low`:return Ur.Q_360P;case`sd`:case`medium`:return Ur.Q_480P;case`hd`:case`high`:return Ur.Q_720P;case`fullhd`:case`full`:return Ur.Q_1080P;case`quadhd`:case`quad`:return Ur.Q_1440P;case`ultrahd`:case`ultra`:return Ur.Q_2160P}};var ri=!1,ii={},ai=e=>{ri=e},oi=()=>{ii={}},si=e=>{e(ii)},ci=(e,t)=>{ri&&(ii.meta=ii.meta??{},ii.meta[e]=t)};class li{constructor(e){this.name=void 0,this.name=e}next(e){if(!ri)return;ii.series=ii.series??{};let t=ii.series[this.name]??[];t.push([Date.now(),e]),ii.series[this.name]=t}}function hi(e,t,n){return!e.max&&e.min===t?`high_quality`:!e.min&&e.max===n?`traffic_saving`:`unknown`}function gi(e,t,n){return pi(e)||fi(e.min)&&fi(e.max)&&di(e.max,e.min)||fi(e.min)&&fi(t)&&ui(e.min,t)||fi(e.max)&&fi(n)&&di(e.max,n)}function _i({limits:e,highestAvailableHeight:t,lowestAvailableHeight:n}){return gi({max:e?.max?mi(e.max):void 0,min:e?.min?mi(e.min):void 0},t?mi(t):void 0,n?mi(n):void 0)}var vi=new li(`best_bitrate`),yi=(e,t,n)=>(t-n)*2**(-10*e)+n,bi=e=>(t,n)=>e*(Number(t.bitrate)-Number(n.bitrate));class xi{constructor(){this.last=void 0,this.history={}}recordSelection(e){this.history[e.id]=Yr()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}var Si=`Assertion "ABR Tracks is empty array" failed`,Ci=new WeakMap,wi=new WeakMap,Ti=new WeakMap,Ei=(e,t,n,r)=>{let i=[...t].sort(bi(1)),a=[...n].sort(bi(1)),o=a.filter(t=>I(t.bitrate)&&I(e.bitrate)?e.bitrate/t.bitrate>r:!0),s=Gr(a,Math.round(a.length*i.indexOf(e)/(i.length+1)))??Gr(a,-1);return s&&Kr(o,s)?s:o.length?Gr(o,-1):Gr(a,0)},Di=(e,t,n,r)=>{let i=Ci.get(t);i||(i=[...t].sort(bi(1)),Ci.set(t,i));let a=Ci.get(n);a||(a=[...n].sort(bi(1)),Ci.set(n,a));let o=Ti.get(e);o||(o=a.filter(t=>I(t.bitrate)&&I(e.bitrate)?e.bitrate/t.bitrate>r:!0),Ti.set(e,o));let s=Gr(a,Math.round(a.length*i.indexOf(e)/(i.length+1)))??Gr(a,-1);return s&&Kr(o,s)?s:o.length?Gr(o,-1):Gr(a,0)},Oi=e=>`quality`in e,ki=(e,t,n,r)=>{var i;let a=I(r==null||(i=r.last)==null?void 0:i.bitrate)&&I(n?.bitrate)&&r.last.bitrate<n.bitrate?e.trackCooldownIncreaseQuality:e.trackCooldownDecreaseQuality,o=n&&r&&r.history[n.id]&&Yr()-r.history[n.id]<=a&&(!r.last||n.id!==r.last.id);if(n?.id&&r&&!o&&r.recordSelection(n),o&&r?.last){let e=r.last;return r?.recordSwitch(e),t({message:`
6
+ import{objectEntries as ce}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as le}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as ue}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as de,assertNonNullable as fe,isNonNullable as pe,ValueSubject as me,Subject as he,Subscription as ge,merge as _e,observableFrom as ve,fromEvent as ye,map as be,tap as xe,filterChanged as Se,isNullable as Ce,ErrorCategory as we}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as Oe,combine as ke,debounce as Ae,ErrorCategory as je,filter as Me,filterChanged as Ne,isNonNullable as Pe,isNullable as Fe,map as Ie,Subscription as Le,ValueSubject as Re}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as ze,assertNonNullable as Be,ErrorCategory as Ve,getHighestQuality as He,isNonNullable as Ue}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as We}from"@vkontakte/videoplayer-shared/es2015";import{createTimers as Ze,TimerModule as Qe}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as et}from"@vkontakte/videoplayer-shared/es2015";import{isBrowserWindow as tt,ValueSubject as nt}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as rt}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as it,isNullable as at}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as M}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as st,isBrowserWindow as ct}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as dt,isBrowserWindow as ft}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as ht,isBrowserWindow as gt}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as At,isBrowserWindow as jt}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as zt,ErrorCategory as Bt,filter as Vt,Subject as Ht,Subscription as Ut,tap as Wt,ValueSubject as Gt,fromEvent as Kt,getWindow as qt}from"@vkontakte/videoplayer-shared/es2015";import{ValueSubject as Zt,Subject as Qt,map as $t,Subscription as en,combine as tn,filterChanged as nn,assertNonNullable as rn}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as on}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as sn}from"@vkontakte/videoplayer-shared/es2015";import{objectFromEntries as cn}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as ln}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as un,Subject as dn,merge as fn}from"@vkontakte/videoplayer-shared/es2015";import"@vkontakte/videoplayer-shared/es2015";import{assertNever as hn,debounce as gn,ErrorCategory as _n,fromEvent as vn,map as yn,merge as bn,observableFrom as xn,Subject as Sn,Subscription as Cn,timeout as wn}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as An}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as jn,fromEvent as Mn,getWindow as Nn,Subscription as Pn}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as Fn}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as Yn}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Xn}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as Zn,isNonNullable as Qn,isNullable as $n,fromEvent as er,merge as tr,observableFrom as nr,filterChanged as rr,map as ir,Subject as ar,Subscription as or,ValueSubject as sr,ErrorCategory as cr}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as lr,isNullable as ur,Subscription as dr}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as P,map as Tr,merge as Er,filterChanged as Dr,isNonNullable as Or,Subject as kr,filter as Ar,mapTo as jr,combine as Mr,once as Nr,shareReplay as F,throttle as Pr,ErrorCategory as Fr,ValueSubject as Ir,Subscription as Lr}from"@vkontakte/videoplayer-shared/es2015";import{VideoQuality as Ur}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Gr}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Kr}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as qr}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as I,isNullable as Jr,now as Yr,isHigher as Xr,isHigherOrEqual as Zr,isInvariantQuality as Qr,isLowerOrEqual as $r,videoSizeToQuality as ei,assertNotEmptyArray as ti,assertNonNullable as ni}from"@vkontakte/videoplayer-shared/es2015";import{isHigher as ui,isLower as di,isNonNullable as fi,isNullable as pi,videoHeightToQuality as mi}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as Ri,assertNonNullable as zi,combine as Bi,debounce as Vi,ErrorCategory as Hi,filter as Ui,filterChanged as Wi,isNonNullable as Gi,map as Ki,merge as qi,observableFrom as Ji,once as Yi,Subscription as Xi,ValueSubject as Zi,videoQualityToHeight as Qi,videoSizeToQuality as $i}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as ea}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as ra,isNullable as ia,assertNonNullable as aa}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as oa}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as sa,assertNonNullable as ca,now as la}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as va}from"@vkontakte/videoplayer-shared/es2015";import{Subject as ba}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as xa}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Ca}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as wa}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Na}from"@vkontakte/videoplayer-shared/es2015";import{debounce as Pa,filter as Fa,fromEvent as Ia,interval as La,isHigher as Ra,isInvariantQuality as za,isLower as Ba,merge as Va,Subject as Ha,Subscription as Ua}from"@vkontakte/videoplayer-shared/es2015";import{map as Ka,Observable as qa}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as Ja}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Za}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as Qa}from"@vkontakte/videoplayer-shared/es2015";import{filter as So,filterChanged as Co,isNonNullable as wo}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as To,assertNonNullable as Eo,debounce as Do,ErrorCategory as Oo,filter as ko,filterChanged as Ao,fromEvent as jo,isNonNullable as Mo,isNullable as No,map as Po,mapTo as Fo,merge as Io,observableFrom as Lo,once as Ro,Subscription as zo,throttle as Bo}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Vo}from"@vkontakte/videoplayer-shared/es2015";import{videoSizeToQuality as Ho}from"@vkontakte/videoplayer-shared/es2015";import{isNullable as Xo,now as Zo,once as Qo,Subscription as $o,ValueSubject as es,isNonNullable as ts,safeStorage as ns,filterChanged as rs}from"@vkontakte/videoplayer-shared/es2015";import{combine as fs,map as ps,observeElementSize as ms,Subscription as hs,ValueSubject as gs,noop as _s}from"@vkontakte/videoplayer-shared/es2015";import{filter as ys,map as bs,once as xs}from"@vkontakte/videoplayer-shared/es2015";import{filterChanged as Cs,isNonNullable as ws,isNullable as Ts,now as Es,once as Ds,Subscription as Os,ValueSubject as ks}from"@vkontakte/videoplayer-shared/es2015";import{now as Ms}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Ps,now as Fs}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Is}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Ls}from"@vkontakte/videoplayer-shared/es2015";import{isLowerOrEqual as Rs,isNonNullable as zs,isNullable as Bs}from"@vkontakte/videoplayer-shared/es2015";import{isInvariantQuality as Zs,isNullable as Qs,Subscription as $s,ValueSubject as ec}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as tc,isNonNullable as nc,isNullable as rc}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as ic}from"@vkontakte/videoplayer-shared/es2015";import{Subscription as ac}from"@vkontakte/videoplayer-shared/es2015";import{Subscription as cc}from"@vkontakte/videoplayer-shared/es2015";import{isHigher as bc,isInvariantQuality as xc,isNonNullable as Sc}from"@vkontakte/videoplayer-shared/es2015";import{isHigherOrEqual as wc,isLowerOrEqual as Tc,isNonNullable as Ec,videoSizeToQuality as Dc}from"@vkontakte/videoplayer-shared/es2015";import{isHigherOrEqual as kc,isNullable as Ac}from"@vkontakte/videoplayer-shared/es2015";import{isHigherOrEqual as Nc,isNonNullable as Pc}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Ic}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Lc}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as Bc,isLowerOrEqual as Vc,isNonNullable as Hc,isNullable as Uc}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as Gc}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as qc,now as Jc}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Zc}from"@vkontakte/videoplayer-shared/es2015";import{arrayFlatMap as sl}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as cl}from"@vkontakte/videoplayer-shared/es2015";import{stringTrimStart as ll}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as ul}from"@vkontakte/videoplayer-shared/es2015";import{abortable as fl,assertNonNullable as pl,ErrorCategory as ml,filter as hl,filterChanged as gl,flattenObject as _l,fromEvent as vl,getTraceSubscriptionMethod as yl,getWindow as bl,interval as xl,isNonNullable as Sl,isNullable as Cl,map as wl,merge as Tl,nowInt as El,Subject as Dl,Subscription as Ol,SubscriptionRemovable as kl,ValueSubject as B}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as Al}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as jl}from"@vkontakte/videoplayer-shared/es2015";import{abortable as Pl,assertNever as Fl,ErrorCategory as Il,flattenObject as Ll,fromEvent as Rl,getWindow as zl,isNonNullable as Bl,merge as Vl,now as Hl,Subject as Ul,Subscription as Wl,suppressAbort as Gl,ValueSubject as Kl,videoQualityToHeight as ql,VideoQuality as Jl,isAbortError as Yl}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as Zl}from"@vkontakte/videoplayer-shared/es2015";import{devNull as iu,getWindow as au}from"@vkontakte/videoplayer-shared/es2015";import{stringReplaceAll as _u}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as vu}from"@vkontakte/videoplayer-shared/es2015";import{stringPadStart as yu}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as bu}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as xu}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Su}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Cu}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Tu,isNullable as Eu}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Du}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as Pu}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Fu}from"@vkontakte/videoplayer-shared/es2015";import{requestIdleCallbackPolyfilled as Iu}from"@vkontakte/videoplayer-shared/es2015";import{abortable as Lu,assertNonNullable as Ru,ErrorCategory as zu,flattenObject as V,fromEvent as Bu,getExponentialDelay as Vu,getWindow as Hu,isAbortError as Uu,isHigher as Wu,isNonNullable as H,isNullable as U,once as Gu,Subject as Ku,Subscription as qu,ValueSubject as Ju}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Yu}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as $u}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Ad}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as jd,isNonNullable as Md,isNullable as Nd}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as Pd}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Gd}from"@vkontakte/videoplayer-shared/es2015";import{videoSizeToQuality as Kd}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as nf,getWindow as rf,isNonNullable as af,isNullable as of,now as sf,isAbortError as cf}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as uf,getWindow as df,isAbortError as ff,isNullable as pf,now as mf}from"@vkontakte/videoplayer-shared/es2015";import{arrayFlatMap as gf}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as _f,ErrorCategory as vf,isNullable as yf,ValueSubject as bf}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as Cf,fromEvent as wf,isNullable as Tf,Subject as Ef,Subscription as Df,ValueSubject as Of}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as kf,ErrorCategory as Af,Subject as jf}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as Rf}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as zf,isHigher as Bf,isLower as Vf,isLowerOrEqual as Hf,VideoQuality as Uf}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as np,combine as rp,ErrorCategory as ip,filter as ap,filterChanged as op,fromEvent as sp,isNonNullable as cp,map as lp,merge as up}from"@vkontakte/videoplayer-shared/es2015";import{combine as pp,merge as mp,filter as hp,filterChanged as gp,isNullable as _p,map as vp,ValueSubject as yp,isNonNullable as bp}from"@vkontakte/videoplayer-shared/es2015";import{isNullable as xp,ValueSubject as Sp}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as Op,combine as kp,ErrorCategory as Ap,filter as jp,filterChanged as Mp,fromEvent as Np,interval as Pp,isNonNullable as Fp,isNullable as Ip,map as Lp,now as Rp,throttle as zp}from"@vkontakte/videoplayer-shared/es2015";import{isNullable as Vp,ValueSubject as Hp}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as Kp,assertNonNullable as qp,combine as Jp,debounce as Yp,ErrorCategory as Xp,filter as Zp,filterChanged as Qp,fromEvent as $p,isNonNullable as em,isNullable as tm,map as nm,merge as rm,observableFrom as im,once as am,Subscription as om,throttle as sm}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as cm}from"@vkontakte/videoplayer-shared/es2015";import{arrayFlatMap as lm}from"@vkontakte/videoplayer-shared/es2015";import{abortable as dm,assertNonNullable as fm,combine as pm,ErrorCategory as mm,filter as hm,filterChanged as gm,flattenObject as _m,fromEvent as vm,getTraceSubscriptionMethod as ym,interval as bm,isNonNullable as xm,isNullable as Sm,map as Cm,merge as wm,now as Tm,Subject as Em,Subscription as Dm,SubscriptionRemovable as Om,tap as km,throttle as Am,ValueSubject as W}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as jm}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as Mm}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as Nm}from"@vkontakte/videoplayer-shared/es2015";import{arrayFlatMap as Pm}from"@vkontakte/videoplayer-shared/es2015";import{cancelIdleCallbackPolyfilled as Fm}from"@vkontakte/videoplayer-shared/es2015";import{requestIdleCallbackPolyfilled as Im}from"@vkontakte/videoplayer-shared/es2015";import{promiseFinally as Lm}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as Rm,ErrorCategory as zm,Subject as Bm}from"@vkontakte/videoplayer-shared/es2015";import{abortable as Gm,assertNonNullable as G,ErrorCategory as Km,fromEvent as qm,getExponentialDelay as Jm,getWindow as Ym,isHigher as Xm,isNonNullable as Zm,isNullable as K,now as Qm,once as $m,Subject as eh,Subscription as th,ValueSubject as nh,isAbortError as rh}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as ah}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as oh}from"@vkontakte/videoplayer-shared/es2015";import{abortable as sh,assertNever as ch,fromEvent as lh,merge as uh,now as dh,Subject as fh,ValueSubject as ph,flattenObject as mh,ErrorCategory as hh,SubscriptionRemovable as gh,getWindow as _h,isNonNullable as vh,suppressAbort as yh,videoQualityToHeight as bh,VideoQuality as xh}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as Sh}from"@vkontakte/videoplayer-shared/es2015";import{devNull as kh,getWindow as Ah}from"@vkontakte/videoplayer-shared/es2015";import{isNullable as Uh,ValueSubject as Wh}from"@vkontakte/videoplayer-shared/es2015";import{combine as Zh,merge as Qh,filter as $h,filterChanged as eg,isNullable as tg,map as ng,ValueSubject as rg,isNonNullable as ig}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as og}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as sg}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as ug,combine as dg,debounce as fg,ErrorCategory as pg,filter as mg,filterChanged as hg,isNonNullable as gg,isNullable as _g,map as vg,merge as yg,observableFrom as bg,Subscription as xg,ValueSubject as Sg,VideoQuality as Cg}from"@vkontakte/videoplayer-shared/es2015";import{objectFromEntries as wg}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as Tg}from"@vkontakte/videoplayer-shared/es2015";import{videoSizeToQuality as Eg,getExponentialDelay as Dg}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as Pg}from"@vkontakte/videoplayer-shared/es2015";import{fetchPolyfilled as Fg}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Ig,Subscription as Lg,throttle as Rg,ValueSubject as zg,Subject as Bg,ErrorCategory as Vg}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as Wg,debounce as Gg,ErrorCategory as Kg,fromEvent as qg,isNonNullable as Jg,isNullable as Yg,map as Xg,merge as Zg,observableFrom as Qg,Subscription as $g,ValueSubject as e_,VideoQuality as t_}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as r_}from"@vkontakte/videoplayer-shared/es2015";import{objectValues as i_}from"@vkontakte/videoplayer-shared/es2015";import{arrayAt as a_}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as o_,assertNonNullable as s_,debounce as c_,ErrorCategory as l_,isHigherOrEqual as u_,isLowerOrEqual as d_,isNonNullable as f_,merge as p_,observableFrom as m_,Subscription as h_,map as g_}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as v_,debounce as y_,merge as b_,observableFrom as x_,Subscription as S_,map as C_,ValueSubject as w_,ErrorCategory as T_,VideoQuality as E_}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as D_}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as F_,assertNonNullable as I_,ErrorCategory as L_,filter as R_,isNonNullable as z_,isNullable as B_,map as V_,merge as H_,once as U_,Subject as q,Subscription as W_,ValueSubject as J,flattenObject as G_,devNull as K_,getWindow as q_}from"@vkontakte/videoplayer-shared/es2015";import{Observable as J_,map as Y_,Subscription as X_,Subject as Z_,now as Q_,combine as $_}from"@vkontakte/videoplayer-shared/es2015";import{AbortControllerPolyfilled as tv}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as nv,Subscription as rv,combine as iv,filter as av,once as ov}from"@vkontakte/videoplayer-shared/es2015";import{getWindow as sv}from"@vkontakte/videoplayer-shared/es2015";import{arrayIncludes as uv}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as dv,Subject as fv,Subscription as pv,merge as mv,isNonNullable as hv}from"@vkontakte/videoplayer-shared/es2015";import{flattenObject as gv,isNullable as _v}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as bv}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as Sv}from"@vkontakte/videoplayer-shared/es2015";import{flattenObject as wv,isNonNullable as Tv,merge as Ev,now as Dv,Subject as Ov,Subscription as kv}from"@vkontakte/videoplayer-shared/es2015";import{isNullable as jv,isNonNullable as Mv,getWindow as Nv}from"@vkontakte/videoplayer-shared/es2015";import{isNullable as Lv,isNonNullable as Rv,Subscription as zv}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as Uv,once as Wv,combine as Gv,Subscription as Kv,ValueSubject as qv,map as Jv,filter as Yv,isNonNullable as Xv,now as Zv,safeStorage as Qv,getWindow as $v}from"@vkontakte/videoplayer-shared/es2015";import{fillWithDefault as uy,VideoQuality as dy}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as my,combine as hy,devNull as gy,ErrorCategory as _y,filter as Y,filterChanged as X,flattenObject as vy,fromEvent as yy,getPlayerId as by,getTimersDiagnostics as xy,getTraceSubscriptionMethod as Sy,getWindow as Cy,InternalsExposure as wy,isHigher as Ty,isInvariantQuality as Ey,isNonNullable as Dy,isNullable as Oy,Logger as ky,map as Z,mapTo as Ay,merge as jy,now as My,once as Q,releaseTimers as Ny,retainTimers as Py,Subject as $,Subscription as Fy,tap as Iy,throttle as Ly,TracerFactory as Ry,ValueSubject as zy}from"@vkontakte/videoplayer-shared/es2015";import{merge as By,map as Vy,filter as Hy,isNonNullable as Uy}from"@vkontakte/videoplayer-shared/es2015";import{assertNonNullable as Gy}from"@vkontakte/videoplayer-shared/es2015";import{filter as qy,once as Jy}from"@vkontakte/videoplayer-shared/es2015";import{requestIdleCallbackPolyfilled as Xy}from"@vkontakte/videoplayer-shared/es2015";import{objectEntries as Zy}from"@vkontakte/videoplayer-shared/es2015";import{cancelIdleCallbackPolyfilled as Qy}from"@vkontakte/videoplayer-shared/es2015";import{devNull as $y,getWindow as eb}from"@vkontakte/videoplayer-shared/es2015";import{Subscription as cb,Observable as lb,Subject as ub,ValueSubject as db,VideoQuality as fb}from"@vkontakte/videoplayer-shared/es2015";var _oxcModehgni7=function(){function e(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function t(t){return function(){var n=this,r=arguments;return new Promise(function(i,a){var o=t.apply(n,r);function s(t){e(o,i,a,s,c,`next`,t)}function c(t){e(o,i,a,s,c,`throw`,t)}s(void 0)})}}function n(e){"@babel/helpers - typeof";return n=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},n(e)}var r=n;function i(e,t){if(r(e)!=`object`||!e)return e;var n=e[Symbol._oxc_toPrimitive];if(n!==void 0){var i=n.call(e,t||`default`);if(r(i)!=`object`)return i;throw TypeError(`@@_oxc_toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var r=n,a=i;function o(e){var t=a(e,`string`);return r(t)==`symbol`?t:t+``}var s=o;function c(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var l=c;function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function d(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?u(Object(n),!0).forEach(function(t){l(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function f(e,t){this.v=e,this.k=t}var p=f;function m(e){return new p(e,0)}var p=f;function h(e){return function(){return new g(e.apply(this,arguments))}}function g(e){var t,n;function r(t,n){try{var a=e[t](n),o=a.value,s=o instanceof p;Promise.resolve(s?o.v:o).then(function(n){if(s){var c=t===`return`?`return`:`next`;if(!o.k||n.done)return r(c,n);n=e[c](n).value}i(a.done?`return`:`normal`,n)},function(e){r(`throw`,e)})}catch(e){i(`throw`,e)}}function i(e,i){switch(e){case`return`:t.resolve({value:i,done:!0});break;case`throw`:t.reject(i);break;default:t.resolve({value:i,done:!1})}(t=t.next)?r(t.key,t.arg):n=null}this._invoke=function(e,i){return new Promise(function(a,o){var s={key:e,arg:i,resolve:a,reject:o,next:null};n?n=n.next=s:(t=n=s,r(e,i))})},typeof e.return!=`function`&&(this.return=void 0)}g.prototype[typeof Symbol==`function`&&Symbol.asyncIterator||`@@asyncIterator`]=function(){return this},g.prototype.next=function(e){return this._invoke(`next`,e)},g.prototype.throw=function(e){return this._invoke(`throw`,e)},g.prototype.return=function(e){return this._invoke(`return`,e)};function _(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.includes(r))continue;n[r]=e[r]}return n}var v=_;function y(e,t){if(e==null)return{};var n,r,i=v(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.includes(n)||{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}const b=[`url`],x=[`url`],S=[`downloadingItems`],C=[`container`];var w=t,T=d,E=m,D=h,O=y,ee=`2.0.171-dev.992281cf5.0`,te;(e=>{e.STOPPED=`stopped`,e.READY=`ready`,e.PLAYING=`playing`,e.PAUSED=`paused`})(te||={});var ne;(e=>{e.MPEG=`MPEG`,e.DASH=`DASH`,e.DASH_SEP=`DASH_SEP`,e.DASH_SEP_VK=`DASH_SEP`,e.DASH_WEBM=`DASH_WEBM`,e.DASH_WEBM_AV1=`DASH_WEBM_AV1`,e.DASH_STREAMS=`DASH_STREAMS`,e.DASH_WEBM_VK=`DASH_WEBM`,e.DASH_ONDEMAND=`DASH_ONDEMAND`,e.DASH_ONDEMAND_VK=`DASH_ONDEMAND`,e.DASH_LIVE=`DASH_LIVE`,e.DASH_LIVE_CMAF=`DASH_LIVE_CMAF`,e.DASH_LIVE_WEBM=`DASH_LIVE_WEBM`,e.HLS=`HLS`,e.HLS_ONDEMAND=`HLS_ONDEMAND`,e.HLS_JS=`HLS`,e.HLS_FMP4=`HLS_FMP4`,e.HLS_LIVE=`HLS_LIVE`,e.HLS_LIVE_CMAF=`HLS_LIVE_CMAF`,e.WEB_RTC_LIVE=`WEB_RTC_LIVE`})(ne||={});var re;(e=>{e.AV1=`av1`,e.VP9=`vp9`,e.AVC1=`avc1`,e.HEV1=`hev1`})(re||={});var ie;(e=>{e.NOT_AVAILABLE=`NOT_AVAILABLE`,e.AVAILABLE=`AVAILABLE`,e.CONNECTING=`CONNECTING`,e.CONNECTED=`CONNECTED`})(ie||={});var ae;(e=>{e.HTTP1=`http1`,e.HTTP2=`http2`,e.QUIC=`quic`})(ae||={});var oe;(e=>{e.NONE=`none`,e.INLINE=`inline`,e.FULLSCREEN=`fullscreen`,e.SECOND_SCREEN=`second_screen`,e.PIP=`pip`,e.INVISIBLE=`invisible`})(oe||={});var se;(e=>{e.TRAFFIC_SAVING=`traffic_saving`,e.HIGH_QUALITY=`high_quality`,e.UNKNOWN=`unknown`})(se||={});var Te=e=>new Promise((t,n)=>{let r=document.createElement(`script`);r.setAttribute(`src`,e),r.onload=()=>t(),r.onerror=e=>n(e),document.body.appendChild(r)});class Ee{constructor(e){this.connection$=new me(void 0),this.castState$=new me(`NOT_AVAILABLE`),this.errorEvent$=new he,this.contentId=void 0,this.realCastState$=new me(`NOT_AVAILABLE`),this.subscription=new ge,this.log=void 0,this.params=void 0,this.isDestroyed=!1,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 n=pe(window.chrome?.cast),r=!!window.__onGCastApiAvailable;n?this.initializeCastApi():(window.__onGCastApiAvailable=e=>{delete window.__onGCastApiAvailable,e&&!this.isDestroyed&&this.initializeCastApi()},r||Te(`https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1`).catch(()=>this.errorEvent$.next({id:`ChromecastLoading`,category:we.NETWORK,message:`Script loading failed!`})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){var e;(e=cast.framework.CastContext.getInstance())==null||(e=e.getCurrentSession())==null||e.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var n;(n=cast.framework.CastContext.getInstance())==null||(n=n.getCurrentSession())==null||(n=n.getMediaSession())==null||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){pe(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ce(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ce(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),n=cast.framework.CastContext.getInstance();this.subscription.add(ye(n,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(e=>{switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:var t;this.contentId=(t=n.getCurrentSession())==null||(t=t.getMediaSession())==null||(t=t.media)==null?void 0:t.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 de(e.sessionState)}})).add(_e(ye(n,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(xe(e=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(e)}`})}),be(e=>e.castState)),ve([n.getCastState()])).pipe(Se(),be(De),xe(e=>{this.log({message:`realCastState$: ${e}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let i=r===`CONNECTED`,a=pe(this.connection$.getValue());if(i&&!a){var o;let r=n.getCurrentSession();fe(r);let i=r.getCastDevice(),a=(o=r.getMediaSession())==null||(o=o.media)==null?void 0:o.contentId;(Ce(a)||a===this.contentId)&&(this.log({message:`connection created`}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:r,castDevice:i}))}else!i&&a&&(this.log({message:`connection destroyed`}),this.connection$.next(void 0));this.castState$.next(r===`CONNECTED`?pe(this.connection$.getValue())?`CONNECTED`:`AVAILABLE`:r)}))}initializeCastApi(){let e,t,n;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,n=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:n}),this.initListeners()}catch(e){this.errorEvent$.next({id:`ChromecastInitializer`,category:we.EXTERNAL_API,message:`[initializeCastApi] failed`,thrown:e})}}}var De=e=>{switch(e){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 de(e)}};var k=(e,t=0,n=0)=>{switch(n){case 0:return e.replace(`_offset_p`,t===0?``:`_`+t.toFixed(0));case 1:{if(t===0)return e;let n=new URL(e);return n.searchParams.append(`playback_shift`,t.toFixed(0)),n.toString()}case 2:{let n=new URL(e);return!n.searchParams.get(`offset_p`)&&t===0?e:(n.searchParams.set(`offset_p`,t.toFixed(0)),n.toString())}default:We(n)}return e},Ge=(e,t)=>{switch(t){case 0:return NaN;case 1:{let t=new URL(e);return Number(t.searchParams.get(`playback_shift`))}case 2:{let t=new URL(e);return Number(t.searchParams.get(`offset_p`)??0)}default:We(t)}},Ke=e=>{let{source:t,format:n,meta:r,output:i}=e,a,o,s;switch(n){case`MPEG`:{let e=t[n];Be(e);let r=He(Object.keys(e));Be(r);let i=e[r];Be(i),a=i,o=`video/mp4`,s=qe();break}case`HLS`:case`HLS_FMP4`:case`HLS_ONDEMAND`:{let e=t[n];Be(e),a=e.url,o=`application/x-mpegurl`,s=qe();break}case`DASH_SEP`:case`DASH_ONDEMAND`:case`DASH_WEBM`:case`DASH_WEBM_AV1`:case`DASH_STREAMS`:{let e=t[n];Be(e),a=e.url,o=`application/dash+xml`,s=qe();break}case`DASH_LIVE_CMAF`:{let e=t[n];Be(e),a=e.url,o=`application/dash+xml`,s=Je();break}case`HLS_LIVE`:case`HLS_LIVE_CMAF`:{let e=t[n];Be(e),a=k(e.url),o=`application/x-mpegurl`,s=Je();break}case`DASH_LIVE`:case`WEB_RTC_LIVE`:{let e=`Unsupported format for Chromecast`,t=Error(e);throw i.error$.next({id:`ChromecastProvider.createMediaInfo()`,category:Ve.VIDEO_PIPELINE,message:e,thrown:t}),t}case`DASH`:case`DASH_LIVE_WEBM`:throw Error(`${n} is no longer supported`);default:return ze(n)}let c=Ye(r.videoId??a,o);c.contentUrl=a,c.streamType=s,c.metadata=Xe();let{title:l,subtitle:u}=r;return Ue(l)&&(c.metadata.title=l),Ue(u)&&(c.metadata.subtitle=u),c};function qe(){var e;return((e=chrome.cast)==null||(e=e.media)==null||(e=e.StreamType)==null?void 0:e.BUFFERED)??`BUFFERED`}function Je(){var e;return((e=chrome.cast)==null||(e=e.media)==null||(e=e.StreamType)==null?void 0:e.LIVE)??`LIVE`}function Ye(e,t){var n;return!((n=chrome.cast)==null||(n=n.media)==null)&&n.MediaInfo?new chrome.cast.media.MediaInfo(e,t):{contentId:e,contentType:t,metadata:{title:``,subtitle:``},streamType:qe()}}function Xe(){var e;return!((e=chrome.cast)==null||(e=e.media)==null)&&e.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:``,subtitle:``,title:``,releaseYear:1970,type:0}}var A=(e,t,n=!1)=>{let r=e.getTransition();(n||!r||r.to===t)&&e.setState(t)};var j=Ze(Qe.CORE);class $e{constructor(e){this.params=void 0,this.interval=0,this.startVideoPosition=void 0,this.startTs=void 0,this.params=e}start(e=0){j.clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=j.setInterval(()=>{let e=(Date.now()-this.startTs)/1e3,t=this.startVideoPosition+e;this.params.output.position$.next(t)},1e3)}pause(){j.clearInterval(this.interval)}destroy(){j.clearInterval(this.interval)}}class ot{constructor(){this._current=void 0,this._current_version=void 0,this._chromeVersion=void 0,this._firefoxVersion=void 0,this._safariVersion=void 0,this._operaVersion=void 0,this._edgeVersion=void 0,this._yandexVersion=void 0,this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current===`Chrome`}get isChromiumBased(){return rt([`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,n=/samsungbrowser/i.test(e)?`SamsungBrowser`:void 0,r=/chrome|crios/i.test(e)?`Chrome`:void 0,i=/chromium/i.test(e)?`Chromium`:void 0,a=/firefox|fxios/i.test(e)?`Firefox`:void 0,o=/smart-tv;.*tizen/i.test(e)?`Chrome`:void 0,s=/webkit|safari|khtml/i.test(e)?`Safari`:void 0,c=/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||n||a||c||l||r||i||o||s||`Rest`}catch(e){console.error(e)}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}=it().navigator,n=t.match(e);if(!n)return;let r=n[1],i=parseInt(r,10);if(!isNaN(i))return this._current_version=i,i}catch(e){console.error(e)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/),at(this._chromeVersion)&&(this._chromeVersion=this.detectVersion(/(\d+\.\d+\.\d+\.\d+)\/\d+\.\d+ TV/))}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 lt=()=>{var e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||((e=navigator)==null||(e=e.userAgentData)==null?void 0:e.mobile)};class ut{constructor(e){this._displayChecker=void 0,this._isMobile=void 0,this._current=void 0,this._iosVersion=void 0,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(){return this._highEntropyValues.platform===`iOS`||M(this.os.name.toLowerCase(),`ios`)||M([`iPhone`,`iPad`,`iPod`],this.current)}get isIPadOS(){let e=this.current===`Mac`&&this._displayChecker.isTouch;return this.current===`iPad`||e}get isMac(){return this._highEntropyValues.platform===`macOS`||M(this.os.name.toLowerCase(),`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`||M(this.os.name.toLowerCase(),`android`)||this.current===`Android`}get isWindows(){return M(this.os.name.toLowerCase(),`windows`)}get isLinux(){return M(this.os.name.toLowerCase(),`linux`)&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=st();if(!ct(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=lt()}catch(e){console.error(`DeviceChecker: calling isMobile error - `,e)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){var e=this;return w(function*(){let t=st();if(!ct(t))return;let{userAgentData:n}=t.navigator;if(n?.getHighEntropyValues){let t=yield n.getHighEntropyValues([`architecture`,`bitness`,`brands`,`mobile`,`platform`,`formFactor`,`model`,`platformVersion`,`wow64`]);e._highEntropyValues=t,t.platform&&(e._os.name=e.normalizeOSName(t.platform),t.platformVersion&&(e._os.version=e.normalizeOSVersion(t.platformVersion),e._os.full=`${e._os.name} ${e._os.version}`)),t.model&&(e._details.model=t.model)}})()}detectDevice(e){try{let t=/android/i.test(e)?`Android`:void 0,n=/iphone/i.test(e)?`iPhone`:void 0,r=/ipad/i.test(e)?`iPad`:void 0,i=/ipod/i.test(e)?`iPod`:void 0,a=/mac/i.test(e)?`Mac`:void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?`RestMobile`:void 0;this._current=t||n||r||i||o||a||`Desktop`}catch(e){console.error(`DeviceChecker: device detection error - `,e)}}detectOS(e){try{for(let[t,n]of[[/(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]]]){let r=e.match(t);if(r){let t=n.length>0,i=n.length>1,a=`Unknown`,o=`Unknown`;if(t){let e=n[0];typeof e==`number`?e<r.length&&r[e]!==void 0&&(a=r[e]):a=e}if(i){let e=n[1];typeof e==`number`?e<r.length&&r[e]!==void 0&&(o=r[e]):e!==void 0&&(o=e)}else r[2]===void 0?r[1]!==void 0&&t&&typeof n[0]==`string`&&(o=r[1]):o=r[2];a=this.normalizeOSName(a),o=this.normalizeOSVersion(o,a),a===`iOS`&&/ipad/i.test(e)?a=`iPadOS`:a===`iPadOS`&&/ip(hone|od)/i.test(e)&&(a=`iOS`),this._os={name:a,version:o||`Unknown`,full:o&&o!==`Unknown`?`${a} ${o}`:a};break}}}catch(e){console.error(`DeviceChecker: OS detection error - `,e)}}normalizeOSName(e){if(!e)return`Unknown`;let t=e.toLowerCase();return M(t,`windows`)?`Windows`:M(t,`mac os`)||M(t,`macintosh`)?`macOS`:M(t,`iphone`)||M(t,`ios`)?`iOS`:M(t,`ipados`)?`iPadOS`:M(t,`android`)?`Android`:M(t,`harmonyos`)?`HarmonyOS`:M(t,`linux`)?`Linux`:M(t,`cros`)?`Chrome OS`:M(t,`freebsd`)?`FreeBSD`:M(t,`openbsd`)?`OpenBSD`:M(t,`solaris`)||M(t,`sunos`)?`Solaris`:M(t,`aix`)?`AIX`:e}normalizeOSVersion(e,t){if(!e)return`Unknown`;if(e!==`Unknown`&&(e=e.replace(/_/g,`.`),t===`Windows`)){let t=parseFloat(e);if(!isNaN(t)){if(t>=11)return`11`;if(t>=10)return`10`;if(t===6.3)return`8.1`;if(t===6.2)return`8`;if(t===6.1)return`7`;if(t===6)return`Vista`;if(t===5.1||t===5.2)return`XP`;if(t===5)return`2000`;if(t===4)return`NT 4.0`}}return e}detectDeviceDetails(e){try{for(let[t,n]of[[/(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]]]){let r=e.match(t);if(r){let e=n[0],t=n[1],i=typeof e==`number`?r[e]===void 0?`Unknown`:this.normalizeVendorName(r[e]):this.normalizeVendorName(e),a=`Unknown`;typeof t==`number`?a=r[t]===void 0?`Unknown`:r[t]:t===void 0?r[1]===void 0?r[0]!==void 0&&(a=r[0]):a=r[1]:a=t,a=this.normalizeModelName(a,i),this.details.vendor=i,this.details.model=a;break}}}catch(e){console.error(`DeviceChecker: device details detection error - `,e)}}normalizeVendorName(e){return e?{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`}[e.toLowerCase()]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():`Unknown`}normalizeModelName(e,t){if(!e||e===`Unknown`)return e;if(e===`0`)return`Unknown`;let n=e.replace(/^build\//i,``).replace(/\s+bui$/i,``).replace(/\)$/,``).replace(/[;,)]/g,``).replace(/\s*\(.*?\)\s*/g,``).trim(),r=t.toLowerCase();return M(r,`samsung`)?n=n.replace(/^(sm-|gt-|sgh-|sch-)/i,``):M(r,`xiaomi`)?n=n.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,``):M(r,`oneplus`)?n=n.replace(/^oneplus[\s\-_]*/i,``):M(r,`google`)&&(n=n.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,``)),n=n.replace(/_/g,` `).replace(/-/g,` `).replace(/\s+/g,` `).trim(),n?(n.length>0&&/^[a-z]/.test(n)&&(n=n.charAt(0).toUpperCase()+n.slice(1)),n):`Unknown`}detectIOSVersion(){try{let e=st();if(!ct(e))return;if(this._highEntropyValues.platformVersion){let e=this._highEntropyValues.platformVersion.split(`.`).slice(0,2).join(`.`);this._iosVersion=parseFloat(e);return}if(this._os.version!==`Unknown`){let e=this._os.version.split(`.`),t=e.length>=2?`${e[0]}.${e[1]}`:e[0];this._iosVersion=parseFloat(t);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t?.[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,`.`)))}catch(e){console.error(`DeviceChecker: iOS version detection error - `,e)}}}var pt=[`standalone`,`minimal-ui`,`fullscreen`,`window-controls-overlay`,`picture-in-picture`];class mt{constructor(){this._maxTouchPoints=void 0,this._height=void 0,this._width=void 0,this._isHdr=void 0,this._pixelRatio=void 0,this._screenHeight=void 0,this._screenWidth=void 0,this._colorDepth=void 0,this._displayMode=`browser`,this._isStandalone=!1}get isTouch(){return typeof this._maxTouchPoints==`number`?this._maxTouchPoints>1:`ontouchstart`in dt()}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}get displayMode(){return this._displayMode}get isStandalone(){return this._isStandalone}detect(){let e=dt();if(!ft(e))return;let{navigator:t,screen:n}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r??0,this._isHdr=!!e.matchMedia(`(dynamic-range: high)`)?.matches,this._colorDepth=n.colorDepth}catch(e){console.error(e)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=n.height,this._width=n.width,this._height=n.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(e){console.error(e)}try{this._displayMode=this.detectDisplayMode(e);let n=t.standalone===!0;this._isStandalone=n||this._displayMode!==`browser`}catch(e){console.error(e)}}detectDisplayMode(e){return pt.find(t=>{var n;return(n=e.matchMedia)==null||(n=n.call(e,`(display-mode: ${t})`))==null?void 0:n.matches})??`browser`}}var _t=()=>window.ManagedMediaSource||window.MediaSource,vt=()=>{var e;return!!(window.ManagedMediaSource&&!((e=window.ManagedSourceBuffer)==null||(e=e.prototype)==null)&&e.appendBuffer)},yt=()=>{var e;return!!(window.MediaSource&&!((e=window.SourceBuffer)==null||(e=e.prototype)==null)&&e.appendBuffer)},bt=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,xt=ht().document?.createElement(`video`),St=`video/mp4; codecs="avc1.42000a,mp4a.40.2"`,Ct=`video/mp4; codecs="hev1.1.6.L93.B0"`,wt=`video/webm; codecs="vp09.00.10.08"`,Tt=`video/webm; codecs="av01.0.00M.08"`,Et=`audio/mp4; codecs="mp4a.40.2"`,Dt=`audio/webm; codecs="opus"`,Ot;(function(){var e=w(function*(){let e=ht();if(!gt(e)||!(`mediaCapabilities`in e.navigator))return;let t={type:`media-source`,video:{contentType:`video/webm`,width:1280,height:720,bitrate:1e6,framerate:30}},[n,r]=yield Promise.all([e.navigator.mediaCapabilities.decodingInfo(T(T({},t),{},{video:T(T({},t.video),{},{contentType:Tt})})),e.navigator.mediaCapabilities.decodingInfo(T(T({},t),{},{video:T(T({},t.video),{},{contentType:wt})}))]);Ot={DASH_WEBM_AV1:n,DASH_WEBM:r}});return function(){return e.apply(this,arguments)}})()().catch(e=>{console.log(xt),console.error(e)});class kt{constructor(e,t){this._video=void 0,this._deviceChecker=void 0,this._browserChecker=void 0,this._protocols=void 0,this._containers=void 0,this._codecs=void 0,this._nativeHlsSupported=void 0,this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return Ot}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=ht();if(!gt(e))return;let t=e.document;this._video=t.createElement(`video`);try{var n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_;this._protocols={mms:vt(),mse:yt(),hls:!!((n=this._video).canPlayType?.call(n,`application/x-mpegurl`)||(r=this._video).canPlayType?.call(r,`vnd.apple.mpegURL`)),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!(i=this._video).canPlayType?.call(i,`video/mp4`),webm:!!(a=this._video).canPlayType?.call(a,`video/webm`),cmaf:!0};let t=!!(!((o=_t())==null||(s=o.isTypeSupported)==null)&&s.call(o,St)),v=!!(!((c=_t())==null||(l=c.isTypeSupported)==null)&&l.call(c,Ct)),y=!!(!((u=_t())==null||(d=u.isTypeSupported)==null)&&d.call(u,Et));this._codecs={h264:t,h265:v,vp9:!!(!((f=_t())==null||(p=f.isTypeSupported)==null)&&p.call(f,wt)),av1:!!(!((m=_t())==null||(h=m.isTypeSupported)==null)&&h.call(m,Tt)),aac:y,opus:!!(!((g=_t())==null||(_=g.isTypeSupported)==null)&&_.call(g,Dt)),mpeg:(t||v)&&y},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error(`Error destroying video element:`,e)}}destroyVideoElement(){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);this._video.parentNode?.replaceChild(e,this._video),this._video=null}}var Mt=`audio/mpeg`;class Nt{constructor(){this._audio=void 0,this._containers=void 0,this._codecs=void 0}supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=At();if(!jt(e))return;let t=e.document;this._audio=t.createElement(`audio`);try{var n,r,i;this._containers={mpeg:!!(n=this._audio).canPlayType?.call(n,Mt)},this._codecs={mp3:!!(!((r=_t())==null||(i=r.isTypeSupported)==null)&&i.call(r,Mt))}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error(`Error destroying audio element:`,e)}}destroyAudioElement(){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);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}}class Pt{constructor(){this.isInited$=new nt(!1),this._displayChecker=void 0,this._deviceChecker=void 0,this._browserChecker=void 0,this._videoChecker=void 0,this._audioChecker=void 0,this._displayChecker=new mt,this._deviceChecker=new ut(this._displayChecker),this._browserChecker=new ot,this._videoChecker=new kt(this._deviceChecker,this._browserChecker),this._audioChecker=new Nt,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){var e=this;return w(function*(){tt()&&(e._displayChecker.detect(),e._deviceChecker.detect(),e._browserChecker.detect(),e._videoChecker.detect(),e._audioChecker.detect(),e.isInited$.next(!0))})()}}var N=new Pt,Ft=(e,t=!1)=>{let{containers:n,protocols:r,codecs:i,nativeHlsSupported:a}=N.video,{isMobile:o}=N.device,s=N.device.isMac&&N.browser.isSafari,c=t&&!o&&!s,l=(i.h264||i.h265)&&i.aac,u=r.mse||r.mms;return e.filter(e=>{switch(e){case`DASH_SEP`:return u&&n.mp4&&l;case`DASH_WEBM`:return u&&n.webm&&i.vp9&&i.opus;case`DASH_WEBM_AV1`:return u&&n.webm&&i.av1&&i.opus;case`DASH_STREAMS`:return u&&(n.mp4&&l||n.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case`DASH_LIVE`:return u&&n.mp4&&l;case`DASH_LIVE_CMAF`:return u&&n.mp4&&l&&n.cmaf;case`DASH_ONDEMAND`:return u&&n.mp4&&l;case`HLS`:case`HLS_ONDEMAND`:case`HLS_FMP4`:case`HLS_LIVE`:case`HLS_LIVE_CMAF`:return a&&!c;case`MPEG`:return n.mp4;case`DASH`:case`DASH_LIVE_WEBM`:return!1;case`WEB_RTC_LIVE`:return r.webrtc&&r.ws&&i.h264&&(n.mp4||n.webm);default:return et(e)}})},It=e=>{switch(e){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 et(e)}},Lt=(e,t=!1)=>Ft(Object.keys(e).filter(e=>!It(e)),t).length>0;class Rt{constructor(e){this.subscription=new Le,this.log=void 0,this.params=void 0,this.sessionId$=new Re(null),this.mediaSessionId$=new Re(null),this.contentId$=new Re(null),this.progressTicker=void 0,this.isMobile=lt(),this.mobileVolumeState={muted:!1,volume:0},this.media=null,this.lastRequestedVolume=null,this.syncMediaState=e=>{if(Fe(e))return;this.media=e,this.mediaSessionId$.next(e.mediaSessionId??null);let t=e.media?.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let n=e.media?.duration;Pe(n)&&this.params.output.duration$.next(Math.max(0,n));let r=e.currentTime;if(Pe(r)){this.params.desiredState.seekState.getState().state===`applying`&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let t=this.params.output.isLive$.getValue();e.playerState===`PLAYING`&&!t?this.progressTicker.start(r):this.progressTicker.pause()}},this.params=e,this.progressTicker=new $e(e),this.log=this.params.dependencies.logger.createComponentLog(`ChromecastPresentationApiProvider`),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(It(e.format)),this.subscribe()}subscribe(){let e=e=>{this.params.output.error$.next({category:je.WTF,id:`ChromecastPresentationApiProvider`,message:e?.message??`Unknown error`,thrown:e})};this.subscription.add(this.params.chromecastConnector.message$.pipe(Me(e=>!!e)).subscribe(e=>{this.handleMessage(e)},e)),this.subscription.add(this.sessionId$.pipe(Me(Pe),Ne(),Ae(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(Ne(),Ie(Boolean));this.subscription.add(ke({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(Me(({mediaLoaded:e})=>e)).subscribe(()=>{let e=this.params.desiredState.seekState.getState();e.state===`requested`&&this.seek(e.position/1e3)},e));let n=ke({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(n.pipe(Me(({mediaLoaded:e})=>e),Ae(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(n.pipe(Me(({mediaLoaded:e,playbackState:{from:t,to:n}})=>!e&&t===`stopped`&&n===`playing`)).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(ke({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(Ae(30)),mediaLoaded:t}).pipe(Me(({mediaLoaded:e})=>e)).subscribe(({volumeState:e})=>{let{muted:t,volume:n}=e.to;this.setVolume(n,t)},e))}handleMessage(e){switch(e.type){case`new_session`:case`update_session`:{var t;this.sessionId$.next(e.message.sessionId);let n=(t=e.message)==null||(t=t.media)==null?void 0:t[0];this.syncMediaState(n);let r=e.message?.receiver.volume;this.syncVolumeState(r)}break;case`v2_message`:switch(e.message?.type){case`MEDIA_STATUS`:{var n;let t=(n=e.message)==null||(n=n.status)==null?void 0:n[0];this.syncMediaState(t);break}}break}}loadMedia(){let e=Ke(this.params),t=this.media?.currentTime,n=this.params.desiredState.seekState.getState(),r=t??(n.state===`none`?0:n.position/1e3),i=this.params.desiredState.playbackState.getState()===`playing`;this.params.chromecastConnector.sendV2Message({type:`LOAD`,requestId:0,media:e,autoplay:i,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();Oe(e,`play on null mediaSessionId`),this.params.chromecastConnector.sendV2Message({type:`PLAY`,mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();Oe(e,`pause on null mediaSessionId`),this.params.chromecastConnector.sendV2Message({type:`PAUSE`,mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();Oe(t,`seek on null mediaSessionId`),this.params.chromecastConnector.sendV2Message({type:`SEEK`,currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let n=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(n=this.mobileVolumeState.volume,r+=`, mobile next volume: ${n}`),this.log({message:r}),this.lastRequestedVolume={volume:n,muted:t},this.params.chromecastConnector.sendV2Message({type:`SET_VOLUME`,requestId:0,volume:{level:t?0:n,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let n=this.params.output.isBuffering$.getValue(),r=e===`BUFFERING`;switch(n!==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(Fe(e))return;let{level:t,muted:n}=e,r={muted:n??!1,volume:t??0};this.lastRequestedVolume&&=(n&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!n&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),null);let i=`[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,i+=`, volume passed to state machine: ${r.volume}`),this.log({message:i}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}}var Jt=e=>({castDevice:{friendlyName:e},remotePlayer:{},remotePlayerController:{},session:{}}),Yt=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));class Xt{constructor(e){this.params=void 0,this.clientId=void 0,this.capabilities=[`WEB`],this.presentationRequest$=new Gt(null),this.log=void 0,this.sessionId$=new Gt(null),this.broadcastChannel=new BroadcastChannel(`vk_player_chromecast_events`),this.subscription=new Ut,this.subscriptionEvents=new Ut,this.isDestroyed=!1,this.sequenceNumber=0,this.presentationAvailable$=new Gt(!1),this.presentationConnection$=new Gt(null),this.message$=new Gt(null),this.friendlyName$=new Gt(null),this.errorEvent$=new Ht,this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog(`ChromecastPresentationApiConnector`),this.log({message:`constructor`}),this.safeReinitPresentation(),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(),n=new PresentationRequest(t);this.presentationRequest$.next(n),this.log({message:`PresentationRequest created`}),n.getAvailability().then(e=>{let t=()=>{this.log({message:`PresentationRequest presentation availability: ${e.value}`}),this.presentationAvailable$.next(e.value)};this.subscriptionEvents.add(Kt(e,`change`).subscribe(()=>{t()})),t()}).catch(()=>{this.presentationAvailable$.next(!0)}),qt().navigator.presentation.defaultRequest=n,e&&n.reconnect(`auto-join`).then(e=>{this.log({message:`PresentationRequest reconnect success`}),this.handleConnection(e)}).catch(()=>{this.log({message:`PresentationRequest reconnect failed`})})}safeReinitPresentation(e){try{this.reinitPresentation(e)}catch(e){this.errorEvent$.next({category:Bt.WTF,id:`ChromecastPresentationApiConnector`,message:e?.message??`reinitPresentation error`,thrown:e})}}connect(){var e=this;return w(function*(){e.log({message:`connect`});try{e.presentationRequest$.getValue()||(e.log({message:`reinitPresentation`}),e.reinitPresentation(!1));let t=e.presentationRequest$.getValue();zt(t,`connect with null presentationRequest`);let n=yield t.start();e.handleConnection(n)}catch(t){switch(t?.name){case`AbortError`:case`NotAllowedError`:break;default:e.errorEvent$.next({category:Bt.WTF,id:`ChromecastPresentationApiConnector`,message:t?.message??`connect error`,thrown:t});break}}})()}subscribe(){this.subscription.add(Kt(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(Wt(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),Vt(e=>!!e)).subscribe(e=>{let t=Kt(e,`message`).subscribe(e=>{let t=JSON.parse(e.data);t.clientId===this.clientId&&(this.log({message:`[onmessage] ${e.data}`}),this.handleMessage(t),this.message$.next(t))}),n=Kt(e,`connect`).subscribe(()=>{this.send(`client_connect`)}),r=Kt(e,`close`).subscribe(e=>{switch(e.reason){case`error`:this.errorEvent$.next({category:Bt.WTF,id:`ChromecastPresentationApiConnector`,message:`Session error`,thrown:e});break;case`closed`:break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(n),this.subscriptionEvents.add(r)}))}send(e){switch(e){case`client_connect`:{let e={type:`client_connect`,message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(e));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let n={type:`v2_message`,sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:T(T({},e),{},{sessionId:t})};this.safeSend(JSON.stringify(n))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();t?.state===`connected`&&t?.send(e)}catch(t){this.errorEvent$.next({category:Bt.WTF,id:`ChromecastPresentationApiConnector`,message:`PresentationConnection send error`,data:{message:e},thrown:t})}}handleMessage(e){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`:e.message?.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)%(2**53-1),e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e=`__vk_player_chromecast_id`;return qt()[e]=qt()[e]||Yt()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new Ut}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))}}class an{static isSupported(){return`chrome`in window&&`presentation`in navigator&&`BroadcastChannel`in window}constructor(e){this.subscription=new en,this.log=void 0,this.contentId=void 0,this.connection$=new Zt(void 0),this.castState$=new Zt(`NOT_AVAILABLE`),this.errorEvent$=new Qt,this.chromecastConnector=void 0;let t=an.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 Xt({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}subscribe(){rn(this.chromecastConnector,`subscribe with null chromecastConnector`),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=tn({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(nn())});this.subscription.add(e.pipe($t(({connection:e,friendlyName:t})=>!!(e&&t)),nn()).subscribe(e=>{let t=this.chromecastConnector?.friendlyName$.getValue()??``;this.connection$.next(e?Jt(t):void 0)})).add(e.subscribe(({available:e,connection:t})=>{e?t?this.castState$.next(`CONNECTED`):this.castState$.next(`AVAILABLE`):this.castState$.next(`NOT_AVAILABLE`)}))}connect(){this.log({message:`connect`}),this.chromecastConnector?.connect()}disconnect(){this.log({message:`disconnect`}),this.chromecastConnector?.disconnect()}stopMedia(){var e=this;return w(function*(){e.log({message:`stopMedia`}),e.chromecastConnector?.stopMedia()})()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:`destroy`}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}}var pn=(e,t)=>e===t;class mn{constructor(e,t=pn){this.comparator=void 0,this.state=void 0,this.prevState=void 0,this.transition=void 0,this.transitionStarted$=new dn,this.transitionEnded$=new dn,this.transitionUpdated$=new dn,this.forceChanged$=new dn,this.stateChangeStarted$=fn(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=fn(this.transitionEnded$,this.forceChanged$),this.comparator=t,this.state=e,this.prevState=void 0}setState(e){let t=this.transition,n=this.state;this.transition=void 0,this.prevState=n,this.state=e,t?this.comparator(t.to,e)?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:n,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,n=this.state;this.comparator(n,e)||un(t)&&this.comparator(t.to,e)||(this.prevState=n,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:n,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}var Tn=5,En=5,Dn=500,On=7e3;class kn{constructor(e){this.subscription=new Cn,this.loadMediaTimeoutSubscription=new Cn,this.videoState=new mn(`stopped`),this.params=void 0,this.log=void 0,this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(i)};`}),n===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.stop());return}if(!t){if(r?.to!==`paused`&&i.state===`requested`&&e!==`stopped`){this.seek(i.position/1e3);return}switch(n){case`ready`:switch(e){case`playing`:case`paused`:case`ready`:break;case`stopped`:this.videoState.startTransitionTo(`ready`),this.prepare();break;default:hn(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:hn(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:hn(e)}break;default:hn(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog(`ChromecastProvider`),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(It(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 Cn;this.subscription.add(e),this.subscription.add(bn(this.videoState.stateChangeStarted$.pipe(yn(e=>`stateChangeStarted$ ${JSON.stringify(e)}`)),this.videoState.stateChangeEnded$.pipe(yn(e=>`stateChangeEnded$ ${JSON.stringify(e)}`))).subscribe(e=>this.log({message:`[videoState] ${e}`})));let t=(e,t)=>this.subscription.add(e.subscribe(t));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let t=new Sn;e.add(t.pipe(gn(Dn)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(e=>{this.logRemoteEvent(e);let r=e.value;this.params.output.position$.next(r),(this.params.desiredState.seekState.getState().state===`applying`||Math.abs(r-n)>Tn)&&t.next(r),n=r})),e.add(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(e=>{this.logRemoteEvent(e),this.params.output.duration$.next(e.value)}))}t(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),t=>{this.logRemoteEvent(t),t.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),e=>{this.logRemoteEvent(e),e.value?this.handleRemotePause():this.handleRemotePlay()}),t(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),e=>{this.logRemoteEvent(e);let{remotePlayer:t}=this.params.connection,n=e.value,r=this.params.output.isBuffering$.getValue(),i=n===chrome.cast.media.PlayerState.BUFFERING;switch(r!==i&&this.params.output.isBuffering$.next(i),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&t.duration-t.currentTime<En&&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:hn(n)}}),t(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({volume:e.value})}),t(vn(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),e=>{this.logRemoteEvent(e),this.handleRemoteVolumeChange({muted:e.value})}),t(bn(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xn([`init`])).pipe(gn(0)),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 e=this.params.output.isLive$.getValue();this.params.output.duration$.next(e?0:t.duration),this.params.output.position$.next(e?0:t.currentTime),this.params.desiredState.seekState.setState({state:`none`})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=Ke(this.params),n=this.createLoadRequest(t);this.loadMedia(n)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to===`paused`||e===`playing`)&&(this.videoState.setState(`paused`),A(this.params.desiredState.playbackState,`paused`))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to===`playing`||e===`paused`)&&(this.videoState.setState(`playing`),A(this.params.desiredState.playbackState,`playing`))}handleRemoteReady(){this.videoState.getTransition()?.to===`ready`&&this.videoState.setState(`ready`),this.params.desiredState.playbackState.getTransition()?.to===`ready`&&A(this.params.desiredState.playbackState,`ready`)}handleRemoteStop(){this.videoState.getState()!==`stopped`&&this.videoState.setState(`stopped`)}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),n={volume:e.volume??t.volume,muted:e.muted??t.muted};(n.volume!==t.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:n}=this.params.connection;t.currentTime=e,n.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let n=this.params.desiredState.seekState.getState();return n.state===`applying`||n.state===`requested`?t.currentTime=this.params.output.isLive$.getValue()?0:n.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),n=new Promise((e,t)=>{this.loadMediaTimeoutSubscription.add(wn(On).subscribe(()=>t(`timeout(${On})`)))});ln(Promise.race([t,n]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===`applying`&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},e=>{let t=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${e}`;this.log({message:t}),this.params.output.error$.next({id:`ChromecastProvider.loadMedia`,category:_n.VIDEO_PIPELINE,message:t,thrown:e})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var In=e=>{try{e.pause(),e.playbackRate=0,Fn(e),e.remove()}catch(e){console.error(e)}},Ln=`__spvc`;class Rn{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)}}var zn=Nn(),Bn=zn.WeakMap?new zn.WeakMap:new Rn,Vn=zn.WeakMap?new zn.WeakMap:new Map,Hn=(e,t=20)=>{let n=0;return Mn(e,`ratechange`).subscribe(r=>{n++,n>=t&&(e.currentTime=e.currentTime,n=0)})};function Un(e){e.style.position=`fixed`,e.style.left=`100%`,e.setAttribute(`data-role`,`screen`),Nn().document.body.appendChild(e)}function Wn(e,t){e.style.position=``,e.style.left=``,t.appendChild(e)}var Gn=(e,{audioVideoSyncRate:t,disableYandexPiP:n,reuseOwnVideoElement:r})=>{let i,a=e.querySelector(`video`),o=!!a,s=Nn().document.querySelector(`body > video[data-role=screen]`)||void 0;r?zn[Ln]=s:(s?.remove(),delete zn[Ln]),a?(i=a,jn(i)):s&&s===zn[Ln]?(i=s,Wn(i,e)):(i=Nn().document.createElement(`video`),e.appendChild(i),r&&(zn[Ln]=i)),Bn.set(i,o);let c=new Pn;return c.add(Hn(i,t)),Vn.set(i,c),i.setAttribute(`crossorigin`,`anonymous`),i.setAttribute(`playsinline`,`playsinline`),n&&i.setAttribute(`x-yandex-pip`,`false`),i.controls=!1,i.setAttribute(`poster`,`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=`),i},Kn=e=>(e.setAttribute(`crossorigin`,`anonymous`),e.controls=!1,e),qn=(e,t)=>{if(e instanceof HTMLAudioElement){In(e);return}if(e instanceof HTMLVideoElement){Jn(e,t);return}};function Jn(e,{reuseOwnVideoElement:t}){Vn.get(e)?.unsubscribe(),Vn.delete(e);let n=Bn.get(e);Bn.delete(e),jn(e),t&&!n&&Un(e)}var fr=(e,t,n,{equal:r=(e,t)=>e===t,changed$:i,onError:a}={})=>{let o=e.getState(),s=t(),c=ur(i),l=new dr;return i&&l.add(i.subscribe(t=>{r(t,e.getState())&&e.setState(t)},a)),r(s,o)||(n(o),c&&e.setState(o)),l.add(e.stateChangeStarted$.subscribe(t=>{n(t.to),c&&e.setState(t.to)},a)),l},pr=(e,t,n)=>fr(t,()=>e.loop,t=>{lr(t)&&(e.loop=t)},{onError:n}),mr=(e,t,n,r,i)=>fr(t,()=>({muted:e.muted,volume:e.volume}),t=>{i?.skipVideoElVolumeSync$.getValue()||lr(t)&&(e.muted=t.muted,e.volume=t.volume)},{equal:(e,t)=>e===t||e?.muted===t?.muted&&e?.volume===t?.volume,changed$:n,onError:r}),hr=(e,t,n,r)=>fr(t,()=>e.playbackRate,t=>{lr(t)&&(e.playbackRate=t)},{changed$:n,onError:r}),gr=fr,_r=e=>[`__`,e.language,e.label].join(`|`),vr=(e,t)=>{if(e.id===t)return!0;let[n,r,i]=t.split(`|`);return e.language===r&&e.label===i};class yr{constructor(e){this.available$=new ar,this.current$=new sr(void 0),this.error$=new ar,this.video=void 0,this.cueSettings=void 0,this.subscription=new or,this.externalTracks=new Map,this.internalTracks=new Map,this.baseURL=void 0,this.baseURL=e}connect(e,t,n){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=e=>{this.error$.next({id:`TextTracksManager`,category:cr.WTF,message:`Generic HtmlVideoTextTrackManager error`,thrown:e})};this.subscription.add(this.available$.subscribe(n.availableTextTracks$)),this.subscription.add(this.current$.subscribe(n.currentTextTrack$)),this.subscription.add(this.error$.subscribe(n.error$)),this.subscription.add(gr(t.internalTextTracks,()=>Yn(this.internalTracks),e=>{Qn(e)&&this.setInternal(e)},{equal:(e,t)=>Qn(e)&&Qn(t)&&e.length===t.length&&e.every(({id:e},n)=>e===t[n].id),changed$:this.available$.pipe(ir(e=>e.filter(({type:e})=>e===`internal`))),onError:r})),this.subscription.add(gr(t.externalTextTracks,()=>Yn(this.externalTracks),e=>{Qn(e)&&this.setExternal(e)},{equal:(e,t)=>Qn(e)&&Qn(t)&&e.length===t.length&&e.every(({id:e},n)=>e===t[n].id),changed$:this.available$.pipe(ir(e=>e.filter(({type:e})=>e===`external`))),onError:r})),this.subscription.add(gr(t.currentTextTrack,()=>{if(this.video)return;let e=this.htmlTextTracksAsArray().find(({mode:e})=>e===`showing`);return e&&this.htmlTextTrackToITextTrack(e).id},e=>this.select(e),{changed$:this.current$,onError:r})),this.subscription.add(gr(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let e of this.htmlTextTracksAsArray())this.applyCueSettings(e.cues),this.applyCueSettings(e.activeCues)}))}subscribe(){Zn(this.video);let{textTracks:e}=this.video;this.subscription.add(er(e,`addtrack`).subscribe(()=>{let e=this.current$.getValue();e&&this.select(e)})),this.subscription.add(tr(er(e,`addtrack`),er(e,`removetrack`),nr([`init`])).pipe(ir(()=>this.htmlTextTracksAsArray().map(e=>this.htmlTextTrackToITextTrack(e))),rr((e,t)=>e.length===t.length&&e.every(({id:e},n)=>e===t[n].id))).subscribe(this.available$)),this.subscription.add(tr(er(e,`change`),nr([`init`])).pipe(ir(()=>this.htmlTextTracksAsArray().find(({mode:e})=>e===`showing`)),ir(e=>e&&this.htmlTextTrackToITextTrack(e).id),rr()).subscribe(this.current$));let t=e=>this.applyCueSettings(e.target?.activeCues??null);this.subscription.add(er(e,`addtrack`).subscribe(e=>{e.track?.addEventListener(`cuechange`,t);let n=e=>{let t=e.target?.cues??null;t&&t.length&&(this.applyCueSettings(e.target?.cues??null),e.target?.removeEventListener(`cuechange`,n))};e.track?.addEventListener(`cuechange`,n)})),this.subscription.add(er(e,`removetrack`).subscribe(e=>{e.track?.removeEventListener(`cuechange`,t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let n of Array.from(e)){let e=n;Qn(t.align)&&(e.align=t.align),Qn(t.position)&&(e.position=t.position),Qn(t.size)&&(e.size=t.size),Qn(t.line)&&(e.line=t.line)}}htmlTextTracksAsArray(e=!1){Zn(this.video);let t=[...this.video.textTracks];return e?t:t.filter(yr.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:n}=e,r=e.id?e.id:_r(e),i=this.externalTracks.has(r),a=(i?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??Xn(r,`auto`);return i?{id:r,type:`external`,isAuto:a,language:t,label:n,url:this.externalTracks.get(r)?.url}:{id:r,type:`internal`,isAuto:a,language:t,label:n,url:this.internalTracks.get(r)?.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(([,e])=>this.detach(e)),e.filter(({id:e})=>!this.externalTracks.has(e)).forEach(e=>this.attach(e)),Array.from(this.externalTracks).filter(([t])=>!e.find(e=>e.id===t)).forEach(([,e])=>this.detach(e))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:e,language:n,isAuto:r})=>!this.internalTracks.has(e)&&!t.some(([,e])=>e.language===n&&e.isAuto===r)).forEach(e=>this.attach(e)),Array.from(this.internalTracks).filter(([t])=>!e.find(e=>e.id===t)).forEach(([,e])=>this.detach(e))}select(e){Zn(this.video);for(let e of this.htmlTextTracksAsArray(!0))e.mode=`showing`;for(let t of this.htmlTextTracksAsArray(!0))($n(e)||!vr(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){Zn(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){Zn(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName(`track`),t=>t.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)}}var br=yr;class xr{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 Sr=e=>{let t=e;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t?.parentNode;return t??void 0},Cr=e=>{let t=Sr(e);return!!(t&&t.fullscreenElement&&t.fullscreenElement===e)},wr=e=>{let t=Sr(e);return!!(t&&t.pictureInPictureElement&&t.pictureInPictureElement===e)};var Rr=3,zr=(e,t,n=Rr)=>{let r=0,i=0;for(let a=0;a<e.length;a++){let o=e.start(a),s=e.end(a);if(o<=t&&t<=s){if(r=o,i=s,!n)return{from:r,to:i};for(let t=a-1;t>=0;t--)e.end(t)+n>=r&&(r=e.start(t));for(let t=a+1;t<e.length;t++)e.start(t)-n<=i&&(i=e.end(t))}}return{from:r,to:i}},Br=e=>{let t=0;for(let n=0;n<e.length;n++)t+=e.end(n)-e.start(n);return t},Vr=e=>{let t=0;for(let n=0;n<e.length;n++)t+=e.end(n)-e.start(n);return t*1e3},Hr=e=>{let t=t=>P(e,t).pipe(jr(void 0),F(1)),n=new Lr,r=()=>n.unsubscribe(),i=Er(P(e,`progress`),P(e,`timeupdate`)),a=i.pipe(Tr(()=>zr(e.buffered,e.currentTime)),F(1)),o=i.pipe(Tr(()=>Vr(e.buffered)),F(1)),s=i.pipe(Tr(()=>e.buffered.length),F(1)),c=N.browser.isSafari?Mr({play:t(`play`).pipe(Nr()),playing:t(`playing`)}).pipe(jr(void 0),F(1)):t(`playing`),l=P(e,`volumechange`).pipe(Tr(()=>({muted:e.muted,volume:e.volume})),F(1)),u=P(e,`ratechange`).pipe(Tr(()=>e.playbackRate),F(1)),d=P(e,`error`).pipe(Ar(()=>!!(e.error||e.played.length)),Tr(()=>{let t=e.error;return{id:t?`MediaError#${t.code}`:`HtmlVideoError`,category:Fr.VIDEO_PIPELINE,message:t?t.message:`Error event from HTML video element`,thrown:e.error??void 0,origin:`mediaError`,data:t?{code:t.code}:void 0}}),F(1)),f=P(e,`timeupdate`).pipe(Tr(()=>e.currentTime),F(1)),p=Er(P(e,`loadedmetadata`),P(e,`timeupdate`),P(e,`pause`),P(e,`seeked`),P(e,`ended`)).pipe(Tr(()=>Br(e.played)),Dr(),F(1)),m=[`waiting`,`seeking`,`seeked`,`timeupdate`],h=new kr,g=.3,_;n.add(Er(...m.map(t=>P(e,t))).subscribe(t=>{let n=e.currentTime;e.loop&&Or(_)&&Or(n)&&_>=e.duration-g&&n<=g&&h.next(_),_=n}));let v=t(`pause`).pipe(Ar(()=>!e.error&&_!==e.duration),F(1)),y=P(e,`enterpictureinpicture`).pipe(F(1)),b=P(e,`leavepictureinpicture`).pipe(F(1)),x=new Ir(wr(e));n.add(y.subscribe(()=>x.next(!0))),n.add(b.subscribe(()=>x.next(!1)));let S=new Ir(Cr(e)),C=P(e,`fullscreenchange`).pipe(F(1));n.add(C.pipe(Tr(()=>Cr(e))).subscribe(S));let w=P(e,`timeupdate`).pipe(Tr(t=>e.duration-e.currentTime<.1),Dr(),F(1)),T=Er(w.pipe(Ar(t=>!e.loop&&t)),P(e,`ended`)).pipe(Pr(1e3),jr(void 0),F(1)),E=Er(...[`waiting`,`pause`,`canplay`,`play`,`canplaythrough`,`playing`,`seeking`,`seeked`,`ended`].map(t=>P(e,t)),w.pipe(Tr(e=>({type:e?`ended`:`unknown`})))).pipe(Tr(t=>N.browser.isFirefox&&t.type===`ended`?e.readyState<2:e.readyState<3),Dr(),F(1));return{playing$:c,pause$:v,canplay$:t(`canplay`),ended$:T,looped$:h,error$:d,seeked$:t(`seeked`),seeking$:t(`seeking`),progress$:t(`progress`),loadStart$:t(`loadstart`),loadedMetadata$:t(`loadedmetadata`),loadedData$:t(`loadeddata`),timeUpdate$:f,durationChange$:P(e,`durationchange`).pipe(Tr(()=>e.duration),F(1)),playedTime$:p,isBuffering$:E,currentBuffer$:a,totalBufferDuration$:o,bufferRangeCount$:s,volumeState$:l,playbackRateState$:u,inPiP$:x,inFullscreen$:S,enterPip$:y,leavePip$:b,destroy:r}};var Wr=e=>{switch(e){case`mobile`:return Ur.Q_144P;case`lowest`:return Ur.Q_240P;case`low`:return Ur.Q_360P;case`sd`:case`medium`:return Ur.Q_480P;case`hd`:case`high`:return Ur.Q_720P;case`fullhd`:case`full`:return Ur.Q_1080P;case`quadhd`:case`quad`:return Ur.Q_1440P;case`ultrahd`:case`ultra`:return Ur.Q_2160P}};var ri=!1,ii={},ai=e=>{ri=e},oi=()=>{ii={}},si=e=>{e(ii)},ci=(e,t)=>{ri&&(ii.meta=ii.meta??{},ii.meta[e]=t)};class li{constructor(e){this.name=void 0,this.name=e}next(e){if(!ri)return;ii.series=ii.series??{};let t=ii.series[this.name]??[];t.push([Date.now(),e]),ii.series[this.name]=t}}function hi(e,t,n){return!e.max&&e.min===t?`high_quality`:!e.min&&e.max===n?`traffic_saving`:`unknown`}function gi(e,t,n){return pi(e)||fi(e.min)&&fi(e.max)&&di(e.max,e.min)||fi(e.min)&&fi(t)&&ui(e.min,t)||fi(e.max)&&fi(n)&&di(e.max,n)}function _i({limits:e,highestAvailableHeight:t,lowestAvailableHeight:n}){return gi({max:e?.max?mi(e.max):void 0,min:e?.min?mi(e.min):void 0},t?mi(t):void 0,n?mi(n):void 0)}var vi=new li(`best_bitrate`),yi=(e,t,n)=>(t-n)*2**(-10*e)+n,bi=e=>(t,n)=>e*(Number(t.bitrate)-Number(n.bitrate));class xi{constructor(){this.last=void 0,this.history={}}recordSelection(e){this.history[e.id]=Yr()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}var Si=`Assertion "ABR Tracks is empty array" failed`,Ci=new WeakMap,wi=new WeakMap,Ti=new WeakMap,Ei=(e,t,n,r)=>{let i=[...t].sort(bi(1)),a=[...n].sort(bi(1)),o=a.filter(t=>I(t.bitrate)&&I(e.bitrate)?e.bitrate/t.bitrate>r:!0),s=Gr(a,Math.round(a.length*i.indexOf(e)/(i.length+1)))??Gr(a,-1);return s&&Kr(o,s)?s:o.length?Gr(o,-1):Gr(a,0)},Di=(e,t,n,r)=>{let i=Ci.get(t);i||(i=[...t].sort(bi(1)),Ci.set(t,i));let a=Ci.get(n);a||(a=[...n].sort(bi(1)),Ci.set(n,a));let o=Ti.get(e);o||(o=a.filter(t=>I(t.bitrate)&&I(e.bitrate)?e.bitrate/t.bitrate>r:!0),Ti.set(e,o));let s=Gr(a,Math.round(a.length*i.indexOf(e)/(i.length+1)))??Gr(a,-1);return s&&Kr(o,s)?s:o.length?Gr(o,-1):Gr(a,0)},Oi=e=>`quality`in e,ki=(e,t,n,r)=>{var i;let a=I(r==null||(i=r.last)==null?void 0:i.bitrate)&&I(n?.bitrate)&&r.last.bitrate<n.bitrate?e.trackCooldownIncreaseQuality:e.trackCooldownDecreaseQuality,o=n&&r&&r.history[n.id]&&Yr()-r.history[n.id]<=a&&(!r.last||n.id!==r.last.id);if(n?.id&&r&&!o&&r.recordSelection(n),o&&r?.last){let e=r.last;return r?.recordSwitch(e),t({message:`
7
7
  [last ${Oi(e)?`video`:`audio`} selected] ${Oi(e)?e.quality:e.bitrate}
8
8
  `}),e}return r?.recordSwitch(n),n},Ai=(e,t)=>Math.log(t)/Math.log(e),ji=({tuning:e,container:t,limits:n,panelSize:r})=>{let i=e.containerSizeFactor;if(r)return{containerSizeLimit:r,containerSizeFactor:i};if(e.usePixelRatio&&N.display.pixelRatio){let t=N.display.pixelRatio;if(e.pixelRatioMultiplier)i*=e.pixelRatioMultiplier*(t-1)+1;else{let n=e.pixelRatioLogBase,[r=0,a=0,o=0]=e.pixelRatioLogCoefficients,s=Ai(n,r*t+a)+o;Number.isFinite(s)&&(i*=s)}}return I(n?.min)&&Zr(n.min,e.highQualityLimit)&&(i*=2),{containerSizeLimit:e.limitByContainer&&t&&t.width>0&&t.height>0?{width:t.width*i,height:t.height*i}:void 0,containerSizeFactor:i}},Mi=new WeakMap,Ni=(e,{container:t,estimatedThroughput:n,tuning:r,limits:i,reserve:a=0,forwardBufferHealth:o,playbackRate:s,current:c,history:l,visible:u,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:m,panelSize:h})=>{ti(e,Si);let{containerSizeFactor:g,containerSizeLimit:_}=ji({container:t,tuning:r,limits:i,panelSize:h}),v=r.considerPlaybackRate&&I(s)?s:1,y=Mi.get(e);y||(y=e.filter(e=>!Qr(e.quality)).sort((e,t)=>Xr(e.quality,t.quality)?-1:1),Mi.set(e,y));let b=Gr(y,-1)?.quality,x=Gr(y,0)?.quality,S=gi(i,x,b),C=v*yi(o??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),w={},T=null;for(let e of y){if(e.tvDisabled){w[e.quality]=`TvDisabled`;continue}let t=!0;if(_)if(e.size)t=e.size.width<=_.width&&e.size.height<=_.height;else{let n=_&&ei(_);t=n?$r(e.quality,n):!0}if(!t){w[e.quality]=`FitsContainer`;continue}let s=p||n,l=I(s)&&isFinite(s)&&I(e.bitrate)?s-a>=e.bitrate*C:!0,m=i?.min===e.quality||I(i?.min)&&I(x)&&Xr(i.min,x)&&e.quality===x;if(!l&&!m){w[e.quality]=`FitsThroughput`;continue}if(r.lazyQualitySwitch&&I(r.minBufferToSwitchUp)&&c&&!Qr(c.quality)&&(o??0)<r.minBufferToSwitchUp&&Xr(e.quality,c.quality)){w[e.quality]=`Buffer`;continue}if(d&&Zr(e.quality,d)&&!m){w[e.quality]=`DroppedFramesLimit`;continue}if(f&&Zr(e.quality,f)&&!m){w[e.quality]=`StallsLimit`;continue}let h=S||(Jr(i?.max)||$r(e.quality,i.max))&&(Jr(i?.min)||Zr(e.quality,i.min)),g=I(u)&&!u?$r(e.quality,r.backgroundVideoQualityLimit):!0;if(!h||!g){w[e.quality]=`FitsQualityLimits`;continue}T||=e}T&&T.bitrate&&vi.next(T.bitrate);let E=T??Gr(y,-1)??e[0],D=l?.last,O=ki(r,m,E,l);return I(l)&&O.quality!==D?.quality&&m({message:`
9
9
  [VIDEO TRACKS ABR]
@@ -113,7 +113,7 @@ import{objectEntries as ce}from"@vkontakte/videoplayer-shared/es2015";import{obj
113
113
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
114
114
 
115
115
  [selected audio track] ${v?.id}
116
- `}),v},Li=e=>new URL(e).hostname;var ta=e=>{if(e instanceof DOMException&&ea([`Failed to load because no supported source was found.`,`The element has no supported sources.`],e.message))throw e;return!(e instanceof DOMException&&(e.code===20||e.name===`AbortError`))},na=function(){var e=w(function*(e,t){let n=e.muted;try{yield e.play()}catch(r){if(!ta(r))return!1;if(t&&t(),n)return console.warn(r),!1;e.muted=!0;try{yield e.play()}catch(t){return ta(t)?(e.muted=!1,console.warn(t),!1):!1}}return!0});return function(t,n){return e.apply(this,arguments)}}();function L(){return la()}function ua(e){return L()-e}function da(e){let t=e.split(`/`),n=t.slice(0,t.length-1).join(`/`),r=/^([a-z]+:)?\/\//i,i=e=>r.test(e);return{resolve:(e,t,r=!1)=>{i(e)||(e.startsWith(`/`)||(e=`/`+e),e=n+e);let a=e.indexOf(`?`)>-1?`&`:`?`;return r&&(e+=a+`lowLat=1`,a=`&`),t&&(e+=a+`_rnd=`+Math.floor(999999999*Math.random())),e}}}function fa(e,t,n){let r=(...i)=>{n.apply(null,i),e.removeEventListener(t,r)};e.addEventListener(t,r)}function pa(e,t,n,r){let i=window.XMLHttpRequest,a,o,s,c=!1,l=0,u,d,f=!1,p=`arraybuffer`,m=7e3,h=2e3,g=()=>{if(c)return;ca(u);let e=ua(u),t;if(e<h){t=h-e,j.setTimeout(g,t);return}h*=2,h>m&&(h=m),o&&o.abort(),o=new i,S()},_=e=>(a=e,C),v=e=>(d=e,C),y=()=>(p=`json`,C),b=()=>{if(!c){if(--l>=0){g(),r&&r();return}c=!0,d&&d(),n&&n()}},x=e=>(f=e,C),S=()=>{u=L(),o=new i,o.open(`get`,e);let n=0,r,l=0,m=()=>(ca(u),Math.max(u,Math.max(r||0,l||0)));if(a&&o.addEventListener(`progress`,e=>{let t=L();a.updateChunk&&e.loaded>n&&(a.updateChunk(m(),e.loaded-n),n=e.loaded,r=t)}),s&&(o.timeout=s,o.addEventListener(`timeout`,()=>b())),o.addEventListener(`load`,()=>{if(c)return;ca(o);let e=o.status;if(e>=200&&e<300){let{response:e,responseType:r}=o,i=e?.byteLength;if(typeof i==`number`&&a){let e=i-n;e&&a.updateChunk&&a.updateChunk(m(),e)}r===`json`&&(!e||!oa(e).length)?b():(d&&d(),t(e))}else b()}),o.addEventListener(`error`,()=>{b()}),f){let e=()=>{ca(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(l=L(),o.removeEventListener(`readystatechange`,e))};o.addEventListener(`readystatechange`,e)}return o.responseType=p,o.send(),C},C={withBitrateReporting:_,withParallel:x,withJSONResponse:y,withRetryCount:e=>(l=e,C),withRetryInterval:(e,t)=>(sa(e)&&(h=e),sa(t)&&(m=t),C),withTimeout:e=>(s=e,C),withFinally:v,send:S,abort:()=>{o&&=(o.abort(),void 0),c=!0,d&&d()}};return C}var ma=100,ha=2e3,ga=500;class _a{constructor(e){this.intervals=[],this.currentRate=0,this.logger=void 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,n){return{start:e,end:t,bytes:n}}_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-ga;if(t-e>ha){let n=0,r=0;for(;this.intervals.length>0;){let e=this.intervals[0];if(e.end<=t)n+=e.end-e.start,r+=e.bytes,this.intervals.splice(0,1);else if(e.start>=t)break;else{let i=t-e.start,a=e.end-e.start;n+=i;let o=e.bytes*i/a;r+=o,e.start=t,e.bytes-=o}}if(r>0&&n>0){let i=r*8/(n/1e3);return this._updateRate(i),this.logger(`rate updated, new=${Math.round(i/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(n)} 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,n){return this.intervals.push(this._createInterval(e,t,n)),this._joinIntervals(),this.intervals.length>ma&&(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}}class ya{constructor(e,t,n,r,i){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=void 0,this.TIMEOUT=void 0,this.BITRATE_ESTIMATOR=void 0,this.MAX_PARALLEL_REQUESTS=void 0,this.logger=void 0,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=n,this.MAX_PARALLEL_REQUESTS=r,this.logger=i}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 n=L(),r=n=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=n,e._errorCB?e._errorCB(n):(this.limitCompleteCount(),this.completeRequests[t]=e)};e._request=pa(t,r=>{e._complete=1,e._responseData=r,e._downloadTime=L()-n,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(r,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},()=>r(`error`),()=>{e._retry=1,e._retryCB&&e._retryCB()}),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(()=>{e._finallyCB&&e._finallyCB()}),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=L()}_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=L();if(Object.keys(this.activeRequests).length>=e)return!1;let n=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&j.clearTimeout(this.throttleTimeout),n>0?(this.throttleTimeout=j.setTimeout(()=>this._sendPending(),n),!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(){va(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,n,r){let i={};return i.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=n,a._retryCB=r,a._finallyCB=i._finallyCB,a._error||a._complete?(this._removeFromActive(e),j.setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),n(a._errorMsg)),i._finallyCB&&i._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let t=this.pendingQueue.indexOf(e);t!==-1&&this.pendingQueue.splice(t,1),this.logger(`Request not prefetched, starting new request, url=${e}${t===-1?``:`; removed pending`}`),this._sendRequest(i,e)}},i._cb=t,i._errorCB=n,i._retryCB=r,i.abort=function(){i.request&&i.request.abort()},i.withFinally=e=>(i._finallyCB=e,i),i}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}var R=(e,t)=>xa(e)&&xa(t)&&e.readyState===`open`&&Sa(e,t);function Sa(e,t){for(let n=0;n<e.activeSourceBuffers.length;++n)if(e.activeSourceBuffers[n]===t)return!0;return!1}class Ta{constructor(e,t,n,r){this.tag=void 0,this.time=void 0,this.data=void 0,this.stack=void 0,this.tag=e,this.time=t,this.data=n,this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:``}`}toDevNullEntry(){let e=Ca(this.data).map(([e,t])=>`${e}:${t}`).join(`,`);return{key:this.tag,strings:[e,this.stack??``],numbers:[this.time]}}}var z=((e,t=`warn`)=>{let n=wa(),r=[];function i(i,a=!1){var o;let s=((o=n.performance)==null||(o=o.timing)==null?void 0:o.navigationStart)??0,c=new Ta(e,Math.round((Date.now()-s)/1e3),i,a?Error().stack:void 0);r.push(c),t&&n.console[t](c.toString())}return i.reset=()=>{r=[]},i.drain=()=>{let e=r;return r=[],e},i})(`vp_dash_live_debug`,!1),Ea=1e4,Da=3,Oa=6e4,ka=10,Aa=1,ja=500;class Ma{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.rep=void 0,this.bitrate=0,this.manifest=[],this.bitrateSwitcher=void 0,this.filesFetcher=void 0,this.sourceBuffer=0,this.mediaSource=void 0,this.currentManifestEntry=void 0,this.manifestRequest=void 0,this.manifestRefetchTimer=void 0,this.bufferStates=[],this.downloadRate=void 0,this.sourceJitter=-1,this.srcToken=0,this.chunkRateEstimator=void 0,this.manifestUrl=void 0,this.urlResolver=void 0,this.waitingForFirstBufferAfterSrcChange=!1,this.params=void 0,this.soundProhibitedEvent$=void 0,this.params=e,this.soundProhibitedEvent$=new ba,this.chunkRateEstimator=new _a(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=da(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let n=0;n<this.manifest.length;++n)if(t=this.manifest[n],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&(z({m:`ldp.catchUp.1`}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e===`paused`,z({m:`ldp.catchUp.2`}),this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&=(this.rep.stop(),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()?(z({m:`ldp.play.1`}),this._playVideoElement()):(z({m:`ldp.play.2`}),this._notifyBuffering(!0))):e&&(z({m:`ldp.play.3`}),this.catchUp())}startPlay(e,t){this.autoQuality=t,z({m:`startPlay`,url:e.jidxUrl}),this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&=(this.rep.stop(),null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&=(j.clearTimeout(this.manifestRefetchTimer),void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=da(e),z({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,n=e.buffered.length;return n!==0&&(t=e.buffered.end(n-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;z({m:`iv`}),e.addEventListener(`error`,()=>{e.error&&!this.destroyed&&(z({m:`iv.err`,e:e.error?.code+`:`+e.error?.message}),t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:`error`,type:`media`}))}),e.addEventListener(`timeupdate`,()=>{let e=this._getBufferSizeSec();!this.paused&&e<.3?this.buffering||(this.buffering=!0,j.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(e+.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,n=t.buffered.length,r;n!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(n-1),t.currentTime<r&&(e(`Fixup stall`),z({m:`ldp.fs`,t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,n,r,i,a=t&&1.62*(N.display.pixelRatio||1)*t.offsetHeight||520;for(let t=0;t<this.manifest.length;++t){i=this.manifest[t];let{max:o,min:s}=this.autoQualityLimits||{};!_i({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1)?.video.height})&&(o&&i.video.height>o||s&&i.video.height<s)||i.tvDisabled||(i.bitrate<e&&a>Math.min(i.video.height,i.video.width)?(!r||i.bitrate>r.bitrate)&&(r=i):(!n||n.bitrate>i.bitrate)&&(n=i))}return r||n}shouldPlay(){if(this.paused)return!1;let e=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return e>3||ra(this.downloadRate)&&(this.downloadRate>1.5&&e>2||this.downloadRate>2&&e>1)}_setVideoSrc(e,t){let{logger:n,videoElement:r,playerCallback:i}=this.params;this.srcToken=(this.srcToken+1)%(2**53-1);let a=this.srcToken;this.mediaSource=new window.MediaSource,n(`setting video src`),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener(`sourceopen`,()=>{if(a===this.srcToken){if(this.mediaSource?.readyState!==`open`){z({m:`sourceopen`,err:`not open: ${this.mediaSource?.readyState}`});return}z({m:`sourceopen`,c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t()}}),this.mediaSource?.addEventListener(`sourceclose`,e=>{z({m:`sourceclose`})}),this.videoPlayStarted=!1,r.addEventListener(`canplay`,()=>{z({m:`canplay`}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let o=()=>{fa(r,`progress`,()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,i({name:`playing`})):o()})};this.waitingForFirstBufferAfterSrcChange=!0,o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ya(Da,Ea,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:n,playerCallback:r}=this.params,i=!1,a=null,o=null,s=null,c=null,l=!1,u=()=>{let e=i&&(!l||l===this.rep);return e||t(`Not running!`),e},d=(e,t,n)=>{s&&s.abort(),s=pa(this.urlResolver.resolve(e,!1),t,n,()=>this._retryCallback()).withTimeout(Ea).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Da).withFinally(()=>{s=null}).send()},f=(e,t,n)=>{aa(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(e,!1),t,n,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},p=e=>{let r=n.playbackRate;n.playbackRate!==e&&(t(`Playback rate switch: ${r}=>${e}`),n.playbackRate=e)},m=e=>{this.lowLatency=e,t(`lowLatency changed to ${e}`),h()},h=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)p(1);else{let e=this._getBufferSizeSec();if(this.bufferStates.length<5){p(1);return}let n=L()-1e4,r=0;for(let t=0;t<this.bufferStates.length;t++){let i=this.bufferStates[t];e=Math.min(e,i.buf),i.ts<n&&r++}this.bufferStates.splice(0,r),t(`update playback rate; minBuffer=${e} drop=${r} jitter=${this.sourceJitter}`);let i=e-Aa;this.sourceJitter>=0?i-=this.sourceJitter/2:--this.sourceJitter,p(i>3?1.15:i>1?1.1:i>.3?1.05:1)}},g=e=>{let n,i=()=>n&&n.start?n.start.length:0,a=e=>n.start[e]/1e3,o=e=>n.dur[e]/1e3,s=e=>n.fragIndex+e,l=(e,t)=>({chunkIdx:s(e),startTS:a(e),dur:o(e),discontinuity:t}),d=()=>{let e=0;if(n&&n.dur){let t=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,r=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,i=t;this.sourceJitter>1&&(i+=this.sourceJitter-1);let a=n.dur.length-1;for(;a>=0&&(i-=n.dur[a],!(i<=0));--a);e=Math.min(a,n.dur.length-1-r),e=Math.max(e,0)}return l(e,!0)},f=e=>{let t=i();if(!(t<=0)){if(ra(e)){for(let n=0;n<t;n++)if(a(n)>e)return l(n)}return d()}},p=e=>{let r=i(),a=e?e.chunkIdx+1:0,o=a-n.fragIndex;if(!(r<=0)){if(!e||o<0||o-r>ka)return t(`Resync: offset=${o} bChunks=${r} chunk=`+JSON.stringify(e)),d();if(!(o>=r))return l(a-n.fragIndex,!1)}},h=(e,t,n)=>{c&&c.abort(),c=pa(this.urlResolver.resolve(e,!0,this.lowLatency),t,n,()=>this._retryCallback()).withTimeout(Ea).withRetryCount(Da).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(t,i)=>{h(e,e=>{if(!u())return;n=e;let a=!!n.lowLatency;a!==this.lowLatency&&m(a);let o=0;for(let e=0;e<n.dur.length;++e)o+=n.dur[e];o>0&&(aa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(o/n.dur.length)),r({name:`index`,zeroTime:n.zeroTime,shiftDuration:n.shiftDuration}),this.sourceJitter=n.hasOwnProperty(`jitter`)?Math.min(10,Math.max(.01,n.jitter/1e3)):1,t(f(i))},()=>this._handleNetworkError())},nextChunk:p}},_=()=>{i=!1,o&&o.abort(),s&&s.abort(),c&&c.abort(),aa(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:t=>{let{videoElement:n,logger:o}=this.params,s=g(e.jidxUrl),l,p,m,v,y=0,b,x,S,C=()=>{b&&=(j.clearTimeout(b),void 0);let e=Math.max(ja,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),t=y+e,n=L(),r=Math.min(1e4,t-n);y=n;let i=()=>{c||u()&&s.seek(()=>{u()&&(y=L(),w(),C())})};r>0?b=j.setTimeout(()=>{this.paused?C():i()},r):i()},w=()=>{let t;for(;t=s.nextChunk(v);)v=t,ee(t);let n=s.nextChunk(m);if(n){if(m&&n.discontinuity){o(`Detected discontinuity; restarting playback`),this.paused?C():(_(),z({m:`ldp.fetchChunkIdx.0`}),this._initPlayerWith(e));return}O(n)}else C()},T=(e,t)=>{if(!u()||!this.sourceBuffer){z({m:`ab.0`,c:[!u(),!this.sourceBuffer]});return}let i,a,s,c=n=>{z({m:`ldp.postpone`,t:n}),j.setTimeout(()=>{u()&&T(e,t)},n)};if(this.sourceBuffer.updating)o(`Source buffer is updating; delaying appendBuffer`),z({m:`ldp.ab.1`}),c(100);else{let l=L(),u=n.currentTime;!this.paused&&n.buffered.length>1&&x===u&&l-S>500&&(o(`Stall suspected; trying to fix`),this._fixupStall()),x!==u&&(x=u,S=l);let d=this._getBufferSizeSec();if(d>30)z({m:`ldp.ab.3`}),o(`Buffered ${d} seconds; delaying appendBuffer`),c(2e3);else try{if(this.params.config.useInvalidBufferFix&&R(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(e),this.videoPlayStarted?(z({m:`ldp.ab.5`}),this.bufferStates.push({ts:l,buf:d}),h(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(z({m:`ldp.ab.4`}),this.videoPlayStarted=!0,this._playVideoElement()),t&&t()}catch(e){z({m:`ldp.ab.err`,e:e.name}),e.name===`QuotaExceededError`?(o(`QuotaExceededError; delaying appendBuffer`),s=this.sourceBuffer.buffered.length,s!==0&&(i=this.sourceBuffer.buffered.start(0),a=u,a-i>4&&this.sourceBuffer.remove(i,a-3)),c(1e3)):(o(e.name),r({name:`error`,type:`buffer`,message:`appendBuffer failed due to ${e.name}`}))}}},E=()=>{p&&l&&(o([`Appending chunk, sz=${p.byteLength}:`,JSON.stringify(m)]),T(p,function(){p=null,w()}))},D=t=>e.fragUrlTemplate.replace(`%%id%%`,t.chunkIdx),O=e=>{u()&&f(D(e),(t,n)=>{if(u()){if(n/=1e3,p=t,m=e,a=e.startTS,n){let t=Math.min(10,e.dur/n);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*t:t}E()}},()=>this._handleNetworkError())},ee=e=>{u()&&(aa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(D(e),!1)))},te=t=>{u()&&(e.cachedHeader=t,T(t,()=>{l=!0,E()}))};i=!0,s.seek(e=>{if(u()){if(y=L(),!e){C();return}v=e,!ia(t)||e.startTS>t?O(e):(m=e,w())}},t),e.cachedHeader?te(e.cachedHeader):d(e.headerUrl,te,()=>this._handleNetworkError())},stop:_,getTimestampSec:()=>a},l}_switchToQuality(e){let{logger:t,playerCallback:n}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),ra(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,aa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),n({name:`qualitySwitch`,quality:e}))}_qualityAvailable(e){return ra(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,n=t=>{if(!this.autoQuality)return;let n,r,i;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&t<this.bitrate&&(r=this._getBufferSizeSec(),i=t/this.bitrate,r>10&&i>.8||r>15&&i>.5||r>20&&i>.3)){e(`Not switching: buffer=${Math.floor(r)}; bitrate=${this.bitrate}; newRate=${Math.floor(t)}`);return}n=this._selectQuality(t),n?this._switchToQuality(n):e(`Could not find quality by bitrate ${t}`)},r={updateChunk:(e,n)=>{let r=L();if(this.chunkRateEstimator.addInterval(e,r,n)){let i=this.chunkRateEstimator.getBitRate();return t({name:`bandwidth`,size:n,duration:r-e,speed:i}),!0}},get:()=>{let e=this.chunkRateEstimator.getBitRate();return e?e*.85:0}},i=-1/0,a,o=!0,s=()=>{let e=r.get();if(e&&a&&this.autoQuality){if(o&&e>a&&ua(i)<3e4)return;n(e)}o=this.autoQuality};return{updateChunk:(e,t)=>{let n=r.updateChunk(e,t);return n&&s(),n},notifySwitch:e=>{let t=L();e<a&&(i=t),a=e}}}_fetchManifest(e,t,n){this.manifestRequest=pa(this.urlResolver.resolve(e,!0),t,n,()=>this._retryCallback()).withJSONResponse().withTimeout(Ea).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;na(e,()=>{this.soundProhibitedEvent$.next()}).then(e=>{z({m:`ldp.pve.1`}),e||(z({m:`ldp.pve.2`}),this.params.liveOffset.pause(),this.params.videoState.setState(`paused`))})}_handleManifestUpdate(e){let{logger:t,playerCallback:n,videoElement:r}=this.params,i=e=>{let t=[];return e?.length?(e.forEach((e,n)=>{var i,a;e.video&&r.canPlayType(e.codecs).replace(/no/,``)&&!((i=window.MediaSource)==null||(a=i.isTypeSupported)==null)&&a.call(i,e.codecs)&&(e.index=n,t.push(e))}),t.sort(function(e,t){return e.video&&t.video?t.video.height-e.video.height:t.bitrate-e.bitrate}),t):(n({name:`error`,type:`empty_manifest`}),[])};this.manifest=i(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),n({name:`manifest`,manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&j.clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=j.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Oa))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Wa{constructor(){this.onDroopedVideoFramesLimit$=new Ha,this.subscription=new Ua,this.log=void 0,this.video=void 0,this.droppedFramesChecker=void 0,this.isAuto=void 0,this.playing=!1,this.tracks=[],this.forceChecker$=new Ha,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.currentTimer=void 0,this.limitCounts={},this.currentQuality=void 0,this.maxQualityLimit=void 0,this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:e})=>e?.height===this.video.videoHeight&&e?.width===this.video.videoWidth);e&&!za(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),n=e-this.prevTotalVideoFrames,r=1-(n-(t-this.prevDroppedVideoFrames))/n;!isNaN(r)&&r>0&&this.log({message:`[dropped]. current dropped percent: ${r}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(r)&&r>=this.droppedFramesChecker.percentLimit&&Ra(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&j.clearTimeout(this.currentTimer),this.currentTimer=j.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&&j.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}getMetrics(){if(!this.video||typeof this.video.getVideoPlaybackQuality!=`function`)return{totalVideoFrames:0,droppedVideoFrames:0,droppedPercent:0,stalledFrames:0};let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality();return{totalVideoFrames:e,droppedVideoFrames:t,droppedPercent:e>0?t/e:0,stalledFrames:e-t}}subscribe(){this.subscription.add(Ia(this.video,`resize`).subscribe(this.handleChangeVideoQuality));let e=Va(La(this.droppedFramesChecker.checkTime).pipe(Fa(()=>this.playing),Fa(()=>{let e=!!this.isForceCheckCounter;return e&&--this.isForceCheckCounter,!e})),this.forceChecker$.pipe(Pa(this.droppedFramesChecker.checkTime)));this.subscription.add(e.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:n}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,n),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 t;let n=(t=Na(this.limitCounts).filter(([,e])=>e>=this.droppedFramesChecker.countLimit).sort(([e],[t])=>Ba(e,t)?-1:1))==null||(t=t[0])==null?void 0:t[0];return e??n}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}}var Ga=Wa;var Ya=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement,Xa=(e,t)=>new qa(n=>{if(!window.IntersectionObserver)return;let r=new IntersectionObserver((e,t)=>{e.forEach(e=>n.next(e.isIntersecting||Ya()))},T(T({},{root:null}),t));r.observe(e);let i=Ja(document,`visibilitychange`).pipe(Ka(e=>!document.hidden||Ya())).subscribe(e=>n.next(e));return()=>{r.unobserve(e),i.unsubscribe()}});var $a;(e=>{e.VP9=`vp9`,e.AV1=`av1`,e.NONE=`none`,e.SMOOTH=`smooth`,e.POWER_EFFICIENT=`power_efficient`})($a||={});var eo=e=>{let{webmDecodingInfo:t}=N.video,n=`DASH_WEBM`,r=`DASH_WEBM_AV1`;switch(e){case`vp9`:return[n,r];case`av1`:return[r,n];case`none`:return[];case`smooth`:return t?t[r].smooth?[r,n]:t[n].smooth?[n,r]:[r,n]:[n,r];case`power_efficient`:return t?t[r].powerEfficient?[r,n]:t[n].powerEfficient?[n,r]:[r,n]:[n,r];default:Qa(e)}},to=({webmCodec:e,androidPreferredFormat:t,iosPreferredFormat:n,preferMultiStream:r})=>{let i=[...r?[`DASH_STREAMS`]:[],...eo(e),`DASH_SEP`,`DASH_ONDEMAND`,...r?[]:[`DASH_STREAMS`]],a=[...r?[`DASH_STREAMS`]:[],`DASH_SEP`,`DASH_ONDEMAND`,...r?[]:[`DASH_STREAMS`]];if(N.device.isAndroid)switch(t){case`mpeg`:return[`MPEG`,...i,`HLS`,`HLS_ONDEMAND`];case`hls`:return[`HLS`,`HLS_ONDEMAND`,...i,`MPEG`];case`dash`:return[...i,`HLS`,`HLS_ONDEMAND`,`MPEG`];case`dash_any_mpeg`:return[...a,`MPEG`,...eo(e),`HLS`,`HLS_ONDEMAND`];case`dash_any_webm`:return[...eo(e),`MPEG`,...a,`HLS`,`HLS_ONDEMAND`];case`dash_sep`:return[`DASH_SEP`,`MPEG`,...eo(e),...a,`HLS`,`HLS_ONDEMAND`];default:Qa(t)}if(N.video.nativeHlsSupported)switch(n){case`hls`:return[...i,`HLS`,`HLS_FMP4`,`HLS_ONDEMAND`,`MPEG`];case`hls_fmp4`:return[...i,`HLS_FMP4`,`HLS`,`HLS_ONDEMAND`,`MPEG`];default:Qa(n)}return[...i,`HLS`,`HLS_ONDEMAND`,`MPEG`]},no=({androidPreferredFormat:e,preferCMAF:t,preferWebRTC:n})=>{let r=t?[`DASH_LIVE_CMAF`,`DASH_LIVE`]:[`DASH_LIVE`,`DASH_LIVE_CMAF`],i=t?[`HLS_LIVE_CMAF`,`HLS_LIVE`]:[`HLS_LIVE`,`HLS_LIVE_CMAF`],a=[...r,...i],o=[...i,...r],s,c=N.device.isMac&&N.browser.isSafari;if(N.device.isAndroid)switch(e){case`dash`:case`dash_any_mpeg`:case`dash_any_webm`:case`dash_sep`:s=a;break;case`hls`:case`mpeg`:s=o;break;default:Qa(e)}else s=N.video.nativeHlsSupported&&!c&&!N.browser.isChromiumBased?o:c?t?[`DASH_LIVE_CMAF`,`HLS_LIVE_CMAF`,`HLS_LIVE`,`DASH_LIVE`]:[`HLS_LIVE`,`DASH_LIVE`,`DASH_LIVE_CMAF`,`HLS_LIVE_CMAF`]:a;return n?[`WEB_RTC_LIVE`,...s]:[...s,`WEB_RTC_LIVE`]},ro=e=>e?[`HLS_LIVE`,`HLS_LIVE_CMAF`,`DASH_LIVE_CMAF`]:[`DASH_WEBM`,`DASH_WEBM_AV1`,`DASH_SEP`,`DASH_ONDEMAND`,`HLS`,`HLS_ONDEMAND`,`MPEG`],io=(e,{preferHdr:t})=>{let n=e.filter(e=>e.hdr),r=e.filter(e=>!e.hdr),i=ao(n.map(({codecs:e})=>e)),a=ao(r.map(({codecs:e})=>e)),o=N.display.isHDR&&t&&i.length>0,s=[...i.map(e=>({name:e,hdr:!0})),...a.map(e=>({name:e,hdr:!1}))],c=[...a.map(e=>({name:e,hdr:!1})),...i.map(e=>({name:e,hdr:!0}))];return o?s:c},ao=e=>{let t=e.map(e=>so(e)),{codecs:n}=N.video;return co().filter(e=>{if(Za(t,e))switch(e){case`av1`:return n.av1;case`vp9`:return n.vp9;case`avc1`:return n.h264;case`hev1`:return n.h265;default:return!1}else return!1})},oo=e=>{let t=e.map(e=>so(e)),{codecs:n}=N.video;return lo().filter(e=>{if(Za(t,e))switch(e){case`opus`:return n.opus;case`mp4a`:return n.aac;default:return!1}else return!1})},so=e=>e.split(`.`)[0].replace(`0`,``),co=()=>[`av1`,`vp9`,`hev1`,`avc1`],lo=()=>[`opus`,`mp4a`],uo=(e,t)=>{e.video.forEach(e=>{e.representations.forEach(e=>{e.tvDisabled=e.tvDisabled||po(e,t)})})};function fo(e){return typeof e==`number`&&Number.isInteger(e)}function po({codecs:e,height:t,fps:n},r){let i=r.find(([n,r,i])=>n===`${t}p`&&mo(e,i))?.[1];return fo(i)&&fo(n)&&n>i}function mo(e,t){return Array.isArray(e)?e.some(e=>ho(e,t)):ho(e,t)}function ho(e,t){return so(e)===t}var go=e=>e.match(/codecs="([^"]+)"/)?.[1].split(/\s*,\s*/)??[];function _o(e,t){if(e instanceof HTMLAudioElement)return{target:Kn(e),video:null};let n=Gn(e,t);return{target:n,video:n}}var vo=[`paused`,`playing`,`ready`],yo=[`paused`,`playing`,`ready`];class bo{constructor(e){this.subscription=new Xi,this.volumeSubscription=new Xi,this.allocation=void 0,this.videoState=new mn(`stopped`),this.dash=void 0,this.representations$=new Zi([]),this.textTracksManager=null,this.droppedFramesManager=new Ga,this.maxSeekBackTime$=new Zi(1/0),this.zeroTime$=new Zi(void 0),this.liveOffset=new xr,this.log=void 0,this.params=void 0,this._dashCb=e=>{switch(e.name){case`buffering`:{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case`error`:this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Hi.WTF,message:`LiveDashPlayer reported error${e.message?`: ${e.message}`:``}`});break;case`manifest`:{let t=e.manifest,n=[];for(let e of t){let t=e.name??e.index.toString(10),r=Wr(e.name)??$i(e.video),i=e.bitrate/1e3,a=T({},e.video),o=e.frameRate,s=!1,{videoStreamRepresentaionsFilter:c}=this.params.tuning.dash;if(c.length&&(s=po({codecs:go(e.codecs),height:e.video.height,fps:o},c)),e.tvDisabled=s,!r)continue;let l={id:t,quality:r,bitrate:i,size:a,fps:o,tvDisabled:s};n.push({track:l,representation:e})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.map(({track:e})=>e)),this.videoState.getTransition()?.to===`manifest_ready`&&this.videoState.setState(`manifest_ready`);break}case`qualitySwitch`:{let t=e.quality,n=this.representations$.getValue().find(({representation:e})=>e===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Gi(n)&&this.params.output.currentVideoTrack$.next(n);break}case`bandwidth`:{let{size:t,duration:n}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,n);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(),n=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(i)};`}),n===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.dash.destroy(),this.allocation.target.removeAttribute(`src`),this.allocation.target.load(),this.videoState.setState(`stopped`));return}if(t)return;let a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(An(yo,e)&&(a||o)){this.prepare();return}if(r?.to!==`paused`&&i.state===`requested`&&An(vo,e)){let e=i.position<0?this.liveOffset.getCurrentPausedTime():0;this.seek(i.position-e);return}switch(e){case`stopped`:this.videoState.startTransitionTo(`manifest_ready`),this.dash.attachSource(k(this.params.source.url));return;case`manifest_ready`:this.videoState.startTransitionTo(`ready`),this.prepare();break;case`ready`:if(n===`paused`)this.videoState.setState(`paused`);else if(n===`playing`){z({m:`dlp.sync.1`}),this.videoState.startTransitionTo(`playing`);let e=r?.from;e&&e===`ready`&&(z({m:`dlp.sync.2`}),this.dash.catchUp()),z({m:`dlp.sync.3`}),this.dash.play()}return;case`playing`:n===`paused`&&(this.videoState.startTransitionTo(`paused`),this.liveOffset.pause(),this.dash.pause());return;case`paused`:if(n===`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 e=this.liveOffset.getTotalOffset();e>=this.maxSeekBackTime$.getValue()&&(e=0,this.liveOffset.resetTo(e)),this.liveOffset.resume(),this.params.output.position$.next(-e/1e3),this.dash.reinit(k(this.params.source.url,e))}return;default:return Ri(e)}},e.tuning.disableSubtitles||(this.textTracksManager=new br(e.source.url)),this.params=e,this.log=this.params.dependencies.logger.createComponentLog(`DashLiveProvider`);let t=t=>{e.output.error$.next({id:`DashLiveProvider`,category:Hi.WTF,message:`DashLiveProvider internal logic error`,thrown:t})};this.subscription.add(qi(this.videoState.stateChangeStarted$.pipe(Ki(e=>({transition:e,type:`start`}))),this.videoState.stateChangeEnded$.pipe(Ki(e=>({transition:e,type:`end`})))).subscribe(({transition:e,type:t})=>{z({m:`dlp.s.1`,t:t+`:${e.from}-${e.to}`}),this.log({message:`[videoState change] ${t}: ${JSON.stringify(e)}`})})),this.allocation=_o(e.container,e.tuning),this.params.output.element$.next(this.allocation.video??void 0),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(Li(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.allocation.video&&this.textTracksManager?.connect(this.allocation.video,this.params.desiredState,this.params.output);let n=Hr(this.allocation.target);this.subscription.add(()=>n.destroy());let r=this.allocation.video;r&&this.subscription.add(this.representations$.pipe(Ki(e=>e.map(({track:e})=>e)),Ui(e=>!!e.length),Yi()).subscribe(e=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:r,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks:e}))),this.subscription.add(n.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===`ready`&&this.videoState.setState(`ready`)},t)).add(n.pause$.subscribe(()=>{this.videoState.setState(`paused`)},t)).add(n.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===`applying`&&this.params.output.seekedEvent$.next(),this.videoState.setState(`playing`)},t)).add(n.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Wi(),Ki(e=>-e/1e3)).subscribe(this.params.output.duration$)).add(Bi({zeroTime:this.zeroTime$.pipe(Ui(Gi)),position:n.timeUpdate$}).subscribe(({zeroTime:e,position:t})=>{t===0&&this.videoState.getTransition()||this.params.output.liveTime$.next(e+t*1e3)},t)).add(pr(this.allocation.target,this.params.desiredState.isLooped,t)).add(mr(this.allocation.target,this.params.desiredState.volume,n.volumeState$,t,{skipVideoElVolumeSync$:this.params.skipVideoElVolumeSync$})),this.subscription.add(this.params.skipVideoElVolumeSync$.subscribe(e=>{this.volumeSubscription.unsubscribe(),e?this.volumeSubscription.add(this.params.desiredState.volume.stateChangeStarted$.subscribe(({to:e})=>this.params.output.volume$.next(e),t)):this.volumeSubscription.add(n.volumeState$.subscribe(this.params.output.volume$,t))})),this.subscription.add(hr(this.allocation.target,this.params.desiredState.playbackRate,n.playbackRateState$,t)).add(n.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(n.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(n.playing$.subscribe(this.params.output.firstFrameEvent$)).add(n.canplay$.subscribe(this.params.output.canplay$)).add(n.playedTime$.subscribe(this.params.output.playedTime$)).add(n.inPiP$.subscribe(this.params.output.inPiP$)).add(n.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Xa(this.allocation.target).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:e,min:t}})=>{this.dash.setAutoQualityLimits({max:e&&Qi(e),min:t&&Qi(t)}),this.params.output.autoVideoTrackLimits$.next({max:e,min:t})})).add(this.videoState.stateChangeEnded$.subscribe(e=>{switch(e.to){case`stopped`:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),z({m:`dlp.vse.s`}),this.params.desiredState.playbackState.setState(`stopped`);break;case`manifest_ready`:case`ready`:this.params.desiredState.playbackState.getTransition()?.to===`ready`&&(z({m:`dlp.vse.r`}),this.params.desiredState.playbackState.setState(`ready`));break;case`paused`:z({m:`dlp.vse.pa`}),this.params.desiredState.playbackState.setState(`paused`);break;case`playing`:z({m:`dlp.vse.pl`}),this.params.desiredState.playbackState.setState(`playing`);break;default:return Ri(e.to)}},t)).add(qi(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ji([`init`])).pipe(Vi(0)).subscribe(this.syncPlayback,t));let i=!1,{output:a}=this.params;this.params.tuning.live.catchupLiveForMutedInactiveTab&&this.subscription.add(a.elementVisible$.pipe(Wi()).subscribe(e=>{let t=a.position$.getValue(),n=a.volume$.getValue(),r=!n.volume||n.muted;!e&&!t&&r?i=!0:e&&i&&(this.seek(0),i=!1)}))}destroy(){z({m:`dlp.destroy`}),this.subscription.unsubscribe(),this.volumeSubscription.unsubscribe(),this.textTracksManager?.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),qn(this.allocation.target,this.params.tuning)}createLiveDashPlayer(){let e=new Ma({videoElement:this.allocation.target,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:e=>{this.params.dependencies.logger.log({message:String(e),component:`LiveDashPlayer`})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!n&&Gi(t)?t:Ni(e.map(({track:e})=>e),{container:this.allocation.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}),i=r?.id,a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,s=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||i!==o)&&this.setVideoTrack(r),s&&this.setAutoQuality(n),a||s||i!==o){let t=e.find(({track:e})=>e.id===i)?.representation;zi(t,`Representations missing`),this.dash.startPlay(t,n)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:t})=>t.id===e.id)?.representation;zi(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(),n=this.videoState.getState(),r=t===`paused`&&n===`paused`,i=-e,a=i<=this.maxSeekBackTime$.getValue()?i:0;this.params.output.position$.next(e/1e3),z({m:`dlp.seek`,p:e,no:a,url:this.params.source.url}),this.dash.reinit(k(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}}var xo=bo;var Uo=({id:e,width:t,height:n,bitrate:r,fps:i,quality:a,streamId:o,tvDisabled:s})=>{let c=(a?Wr(a):void 0)??Ho({width:t,height:n});return c&&{id:e,quality:c,bitrate:r,size:{width:t,height:n},fps:i,streamId:o,tvDisabled:s}},Wo=({id:e,bitrate:t})=>({id:e,bitrate:t}),Go=({language:e,label:t},{id:n,url:r,isAuto:i})=>({id:n,url:r,isAuto:i,type:`internal`,language:e,label:t}),Ko=({language:e,label:t,id:n,url:r,isAuto:i})=>({id:n,url:r,isAuto:i,type:`internal`,language:e,label:t}),qo=({id:e,language:t,label:n,codecs:r,isDefault:i,channels:a})=>({id:e,language:t,label:n,codec:Vo(r.split(`.`),0),isDefault:i,channels:a}),Jo=({id:e,language:t,label:n,hdr:r,codecs:i})=>({id:e,language:t,hdr:r,label:n,codec:Vo(i.split(`.`),0)}),Yo=e=>e.type===`template`;var is=(e,t,n)=>n*t+(1-n)*e,as=(e,t)=>e.reduce((e,t)=>e+t,0)/t,os=(e,t,n,r)=>{let i=0,a=n,o=as(e,t),s=t<r?t:r;for(let t=0;t<s;t++)e[a]>o?i++:i--,a=(e.length+a-1)%e.length;return Math.abs(i)===s},ss=`stalls_manager_metrics`,cs=`stalls_manager_abr_params`,ls=`stalls_manager_default_tuning_abr_params`;class us{constructor(){this.currentStallDuration$=void 0,this.videoLastDataObtainedTimestamp$=void 0,this.throughput$=void 0,this.rtt$=void 0,this.tuning=void 0,this.abrParams=void 0,this.duration=void 0,this.isSeeked$=new es(!1),this.isBuffering$=new es(!1),this.isPaused=!1,this.maxQualityLimit=void 0,this.lastUniqueVideoTrackSelected=void 0,this.currentStallsCount=0,this.sumStallsDuration=0,this.lastStallDuration=0,this.providerStartWatchingTimestamp=0,this.lastUniqueVideoTrackSelectedTimestamp=0,this.predictedThroughputWithoutData=0,this.qualityRestrictionTimer=void 0,this.subscription=new $o,this.severeStallOccurred$=new es(!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 e=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(cs):{};return T(T({},this.abrParams),e)}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Zo(),this.currentStallsCount=0)}destroy(){j.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Zo()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:n}=T({},this.getStoredData(ls)),{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:i,containerSizeFactor:a}=T({},this.abrParams);this.tuning.enabled&&e===r&&t===i&&n===a||(this.removeStoredData(cs),this.setStoredData(ls,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:i,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(ss,`[]`);if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let n=t.reduce((e,t)=>e+t.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let r=t.reduce((e,t)=>e+t.stallsDuration,0)/n;e.push(this.calculateOptimalAbrParams(r,n))}if(this.tuning.useAverageStallsDurationPerTvt){let r=t.reduce((e,t)=>e+t.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(r,n))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,n));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(e=>e.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(e=>e.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(e=>e.containerSizeFactor))};this.setStoredData(ss,[]),this.setStoredData(cs,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:n,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:i,abrAdjustingSpeed:a,significantTvt:o}=this.tuning,s=a*Math.min(t/o,1),c=this.abrTuningParams;return e<n-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-s,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-s,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+s,this.abrParams.maxContainerSizeFactor)}:e>n+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+s,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+s,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-s,this.abrParams.minContainerSizeFactor)}),e>i&&(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=`{}`){return JSON.parse(ns.get(e)??t)}setStoredData(e,t){ns.set(e,JSON.stringify(t))}removeStoredData(e){ns.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let n=this.getStoredData(ss,`[]`),r=t/e,i={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:n.length?is(n[n.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r};n.push(i),n.length>this.tuning.stallsMetricsHistoryLength&&n.shift(),this.setStoredData(ss,n)}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(e=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(Qo()).subscribe(e=>this.providerStartWatchingTimestamp=Zo())),this.subscription.add(e.playing$.subscribe(e=>this.isPaused=!1)),this.subscription.add(e.pause$.subscribe(e=>this.isPaused=!0)),this.subscription.add(this.currentStallDuration$.pipe(rs()).subscribe(e=>{let{stallDurationNoDataBeforeQualityDecrease:t,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:r,ignoreStallsOnSeek:i}=this.tuning;if(Xo(this.lastUniqueVideoTrackSelected)||i&&this.isSeeked$.getValue())return;if(this.tuning.ignoreStallsOnPause&&this.isPaused){this.lastStallDuration=e;return}let a=this.rtt$.getValue(),o=this.throughput$.getValue(),s=this.videoLastDataObtainedTimestamp$.getValue(),c=Zo(),l=n&&this.currentStallsCount>=n,u=t&&c-this.lastUniqueVideoTrackSelectedTimestamp>=t+a&&c-s>=t+a&&e>=t;(l||u)&&(this.severeStallOccurred$.next(!0),j.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,ts(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!e&&Zo()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),j.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=j.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},r)),this.lastStallDuration=e}))}}var ds=us;class vs{constructor(){this.subscription=new hs,this.pipSize$=new gs(void 0),this.videoSize$=new gs(void 0),this.elementSize$=new gs(void 0),this.pictureInPictureWindowRemoveEventListener=_s}connect({observableVideo:e,video:t}){let n=e=>{let t=e.target;this.pipSize$.next({width:t.width,height:t.height})};this.subscription.add(ms(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:e})=>{this.pipSize$.next({width:e.width,height:e.height}),e.addEventListener(`resize`,n),this.pictureInPictureWindowRemoveEventListener=()=>{e.removeEventListener(`resize`,n)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(fs({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(ps(({videoSize:e,inPip:t,pipSize:n})=>t?n:e)).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 Ss=({subscription:e,desiredState:t,videoElement$:n,observableVideo:r})=>{if(!N.browser.isSafari)return;let i=0,a=!1;e.add(t.volume.stateChangeStarted$.pipe(bs(()=>{let e=t.volume.getTransition(),r=n.getValue();return!r||!e?!1:!e.to.muted&&r.muted}),ys(e=>!!e),xs()).subscribe(()=>{i=performance.now(),a=!0})),e.add(r.playbackRateState$.pipe(ys(()=>a),xs()).subscribe(()=>{let e=n.getValue(),r=t.playbackRate.getState();e&&r!==e.playbackRate&&performance.now()-i<1e3&&(e.playbackRate=r)}))};class As{constructor(){this.currentStallDuration$=new ks(0),this.videoLastDataObtainedTimestamp$=new ks(0),this.isSeeked$=new ks(!1),this.rtt$=new ks(0),this.tuning=void 0,this.lastUniqueVideoTrackSelectedTimestamp=0,this.lastUniqueVideoTrackSelected=void 0,this.providerStartWatchingTimestamp=0,this.subscription=new Os,this.severeStallOccurred$=new ks(!1),this.totalStallsCount$=new ks(0),this.currentVideoTrackStallsCount$=new ks(0),this.sumStallsDuration$=new ks(0),this.lastStallDuration$=new ks(0)}init(e){this.tuning=e.tuning,this.subscription.add(e.currentStallDuration$.subscribe(this.currentStallDuration$)),this.subscription.add(e.rtt$.subscribe(this.rtt$)),this.subscription.add(e.videoLastDataObtainedTimestamp$.subscribe(this.videoLastDataObtainedTimestamp$)),this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.observableVideo.looped$.subscribe(e=>this.currentVideoTrackStallsCount$.next(0))),this.subscription.add(e.observableVideo.playing$.pipe(Ds()).subscribe(e=>this.providerStartWatchingTimestamp=Es())),this.subscription.add(e.lastVideoTrackSelected$.subscribe(e=>{ws(e)&&this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Es(),this.currentVideoTrackStallsCount$.next(0))})),this.subscription.add(this.currentStallDuration$.pipe(Cs()).subscribe(e=>{let{stallDurationNoDataBeforeQualityDecrease:t,stallCountBeforeQualityDecrease:n,ignoreStallsOnSeek:r}=this.tuning;if(Ts(this.lastUniqueVideoTrackSelected)||r&&this.isSeeked$.getValue())return;let i=this.rtt$.getValue(),a=this.videoLastDataObtainedTimestamp$.getValue(),o=Es(),s=n&&this.currentVideoTrackStallsCount$.getValue()>=n,c=t&&o-this.lastUniqueVideoTrackSelectedTimestamp>=t+i&&o-a>=t+i&&e>=t;(s||c)&&this.severeStallOccurred$.next(!0),!e&&Es()-this.providerStartWatchingTimestamp>this.lastStallDuration$.getValue()&&(this.updateStallData(),this.severeStallOccurred$.next(!1)),this.lastStallDuration$.next(e)}))}destroy(){this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData()}updateStallData(){if(this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&this.lastStallDuration$.getValue()>0){let e=this.sumStallsDuration$.getValue(),t=this.lastStallDuration$.getValue(),n=this.currentVideoTrackStallsCount$.getValue(),r=this.totalStallsCount$.getValue();this.sumStallsDuration$.next(e+Math.min(t,this.tuning.maxPossibleStallDuration)),this.currentVideoTrackStallsCount$.next(n+1),this.totalStallsCount$.next(r+1)}}}var js=e=>`audioTracksAsc`in e;class Ns{constructor(){this.last=void 0,this.history={}}recordSelection(e){this.history[e.id]=Ms()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}var Vs=(e,t)=>(e??0)/(t>0?t:1),Hs=e=>`quality`in e,Us=e=>(t,n)=>e*(Number(t.bitrate)-Number(n.bitrate)),Ws=e=>(t,n)=>e*(Rs(t.quality,n.quality)?-1:1),Gs=e=>(t,n)=>Hs(t)&&Hs(n)?Ws(e)(t,n):Us(e)(t,n),Ks=(e,t)=>Gs(1)(e,t)<0,qs=(e,t)=>Math.log(t)/Math.log(e),Js=(e,t,n)=>(t-n)*2**(-10*e)+n,Ys=(e,t,n,r)=>{if(Bs(e))return n[0];let i=n.filter(t=>zs(t.bitrate)&&zs(e.bitrate)?e.bitrate/t.bitrate>r:!0),a=Is(n,Math.round(n.length*t.indexOf(e)/(t.length+1)))??Is(n,-1);return a&&Ls(i,a)?a:i.length?Is(i,-1):Is(n,0)};class Xs{constructor(){this.history=new Ns,this.rules=[],this._context=void 0}get context(){return this._context}init(e,t){this.rules=e;for(let e of this.rules)e.init(t)}destroy(){for(let e of this.rules)e.destroy()}updateContext(e){this._context=T({},e)}autoSelectTrack(e=this.rules){let{context:t}=this,n=e=>(t,n)=>n.confidence-t.confidence||Gs(e)(t.track,n.track),r=e.map(e=>e.execute(t)),i=r.filter(e=>e.type===`limit_above`).sort(n(1)),a=r.filter(e=>e.type===`limit_below`).sort(n(-1)),o=r[0].track;i.length===0&&a.length?o=a[0].track:i&&a.length===0?o=i[0].track:i.length&&a.length&&(o=Ks(i[0].track,a[0].track)?a[0].track:i[0].track);let s=this.history.last,c=this.selectTrackBasedOnHistory(o);if(c.bitrate!==s?.bitrate){let e=r.map(e=>e.logMessage).join(`
116
+ `}),v},Li=e=>new URL(e).hostname;var ta=e=>{if(e instanceof DOMException&&ea([`Failed to load because no supported source was found.`,`The element has no supported sources.`],e.message))throw e;return!(e instanceof DOMException&&(e.code===20||e.name===`AbortError`))},na=function(){var e=w(function*(e,t){let n=e.muted;try{yield e.play()}catch(r){if(!ta(r))return!1;if(t&&t(),n)return console.warn(r),!1;e.muted=!0;try{yield e.play()}catch(t){return ta(t)?(e.muted=!1,console.warn(t),!1):!1}}return!0});return function(t,n){return e.apply(this,arguments)}}();function L(){return la()}function ua(e){return L()-e}function da(e){let t=e.split(`/`),n=t.slice(0,t.length-1).join(`/`),r=/^([a-z]+:)?\/\//i,i=e=>r.test(e);return{resolve:(e,t,r=!1)=>{i(e)||(e.startsWith(`/`)||(e=`/`+e),e=n+e);let a=e.indexOf(`?`)>-1?`&`:`?`;return r&&(e+=a+`lowLat=1`,a=`&`),t&&(e+=a+`_rnd=`+Math.floor(999999999*Math.random())),e}}}function fa(e,t,n){let r=(...i)=>{n.apply(null,i),e.removeEventListener(t,r)};e.addEventListener(t,r)}function pa(e,t,n,r){let i=window.XMLHttpRequest,a,o,s,c=!1,l=0,u,d,f=!1,p=`arraybuffer`,m=7e3,h=2e3,g=()=>{if(c)return;ca(u);let e=ua(u),t;if(e<h){t=h-e,j.setTimeout(g,t);return}h*=2,h>m&&(h=m),o&&o.abort(),o=new i,S()},_=e=>(a=e,C),v=e=>(d=e,C),y=()=>(p=`json`,C),b=()=>{if(!c){if(--l>=0){g(),r&&r();return}c=!0,d&&d(),n&&n()}},x=e=>(f=e,C),S=()=>{u=L(),o=new i,o.open(`get`,e);let n=0,r,l=0,m=()=>(ca(u),Math.max(u,Math.max(r||0,l||0)));if(a&&o.addEventListener(`progress`,e=>{let t=L();a.updateChunk&&e.loaded>n&&(a.updateChunk(m(),e.loaded-n),n=e.loaded,r=t)}),s&&(o.timeout=s,o.addEventListener(`timeout`,()=>b())),o.addEventListener(`load`,()=>{if(c)return;ca(o);let e=o.status;if(e>=200&&e<300){let{response:e,responseType:r}=o,i=e?.byteLength;if(typeof i==`number`&&a){let e=i-n;e&&a.updateChunk&&a.updateChunk(m(),e)}r===`json`&&(!e||!oa(e).length)?b():(d&&d(),t(e))}else b()}),o.addEventListener(`error`,()=>{b()}),f){let e=()=>{ca(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(l=L(),o.removeEventListener(`readystatechange`,e))};o.addEventListener(`readystatechange`,e)}return o.responseType=p,o.send(),C},C={withBitrateReporting:_,withParallel:x,withJSONResponse:y,withRetryCount:e=>(l=e,C),withRetryInterval:(e,t)=>(sa(e)&&(h=e),sa(t)&&(m=t),C),withTimeout:e=>(s=e,C),withFinally:v,send:S,abort:()=>{o&&=(o.abort(),void 0),c=!0,d&&d()}};return C}var ma=100,ha=2e3,ga=500;class _a{constructor(e){this.intervals=[],this.currentRate=0,this.logger=void 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,n){return{start:e,end:t,bytes:n}}_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-ga;if(t-e>ha){let n=0,r=0;for(;this.intervals.length>0;){let e=this.intervals[0];if(e.end<=t)n+=e.end-e.start,r+=e.bytes,this.intervals.splice(0,1);else if(e.start>=t)break;else{let i=t-e.start,a=e.end-e.start;n+=i;let o=e.bytes*i/a;r+=o,e.start=t,e.bytes-=o}}if(r>0&&n>0){let i=r*8/(n/1e3);return this._updateRate(i),this.logger(`rate updated, new=${Math.round(i/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(n)} 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,n){return this.intervals.push(this._createInterval(e,t,n)),this._joinIntervals(),this.intervals.length>ma&&(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}}class ya{constructor(e,t,n,r,i){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=void 0,this.TIMEOUT=void 0,this.BITRATE_ESTIMATOR=void 0,this.MAX_PARALLEL_REQUESTS=void 0,this.logger=void 0,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=n,this.MAX_PARALLEL_REQUESTS=r,this.logger=i}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 n=L(),r=n=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=n,e._errorCB?e._errorCB(n):(this.limitCompleteCount(),this.completeRequests[t]=e)};e._request=pa(t,r=>{e._complete=1,e._responseData=r,e._downloadTime=L()-n,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(r,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},()=>r(`error`),()=>{e._retry=1,e._retryCB&&e._retryCB()}),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(()=>{e._finallyCB&&e._finallyCB()}),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=L()}_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=L();if(Object.keys(this.activeRequests).length>=e)return!1;let n=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&j.clearTimeout(this.throttleTimeout),n>0?(this.throttleTimeout=j.setTimeout(()=>this._sendPending(),n),!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(){va(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,n,r){let i={};return i.send=()=>{let a=this.activeRequests[e]||this.completeRequests[e];if(a)a._cb=t,a._errorCB=n,a._retryCB=r,a._finallyCB=i._finallyCB,a._error||a._complete?(this._removeFromActive(e),j.setTimeout(()=>{a._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),n(a._errorMsg)),i._finallyCB&&i._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let t=this.pendingQueue.indexOf(e);t!==-1&&this.pendingQueue.splice(t,1),this.logger(`Request not prefetched, starting new request, url=${e}${t===-1?``:`; removed pending`}`),this._sendRequest(i,e)}},i._cb=t,i._errorCB=n,i._retryCB=r,i.abort=function(){i.request&&i.request.abort()},i.withFinally=e=>(i._finallyCB=e,i),i}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}var R=(e,t)=>xa(e)&&xa(t)&&e.readyState===`open`&&Sa(e,t);function Sa(e,t){for(let n=0;n<e.activeSourceBuffers.length;++n)if(e.activeSourceBuffers[n]===t)return!0;return!1}class Ta{constructor(e,t,n,r){this.tag=void 0,this.time=void 0,this.data=void 0,this.stack=void 0,this.tag=e,this.time=t,this.data=n,this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:``}`}toDevNullEntry(){let e=Ca(this.data).map(([e,t])=>`${e}:${t}`).join(`,`);return{key:this.tag,strings:[e,this.stack??``],numbers:[this.time]}}}var z=((e,t=`warn`)=>{let n=wa(),r=[];function i(i,a=!1){var o;let s=((o=n.performance)==null||(o=o.timing)==null?void 0:o.navigationStart)??0,c=new Ta(e,Math.round((Date.now()-s)/1e3),i,a?Error().stack:void 0);r.push(c),t&&n.console[t](c.toString())}return i.reset=()=>{r=[]},i.drain=()=>{let e=r;return r=[],e},i})(`vp_dash_live_debug`,!1),Ea=1e4,Da=3,Oa=6e4,ka=10,Aa=1,ja=500;class Ma{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.rep=void 0,this.bitrate=0,this.manifest=[],this.bitrateSwitcher=void 0,this.filesFetcher=void 0,this.sourceBuffer=0,this.mediaSource=void 0,this.currentManifestEntry=void 0,this.manifestRequest=void 0,this.manifestRefetchTimer=void 0,this.bufferStates=[],this.downloadRate=void 0,this.sourceJitter=-1,this.srcToken=0,this.videoListeners=[],this.objectUrl=null,this.chunkRateEstimator=void 0,this.manifestUrl=void 0,this.urlResolver=void 0,this.waitingForFirstBufferAfterSrcChange=!1,this.params=void 0,this.soundProhibitedEvent$=void 0,this.params=e,this.soundProhibitedEvent$=new ba,this.chunkRateEstimator=new _a(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=da(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let n=0;n<this.manifest.length;++n)if(t=this.manifest[n],t.name===e){this._switchToQuality(t);return}}catchUp(){let{logger:e}=this.params,t=this._getBufferSizeSec();if(e(`catchUp: hasRep=${!!this.rep}, bufferSizeSec=${t.toFixed(2)}, lowLatency=${this.lowLatency}`),this.rep&&(z({m:`ldp.catchUp.1`}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e===`paused`,z({m:`ldp.catchUp.2`}),this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&=(this.rep.stop(),null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){let{logger:e}=this.params;this.paused=!1;let t=this._getBufferSizeSec(),n=this.lowLatency&&t>this.sourceJitter+5;e(`play: rep=${!!this.rep}, mustCatchUp=${n}, bufferSizeSec=${t.toFixed(2)}, sourceJitter=${this.sourceJitter}, lowLatency=${this.lowLatency}`),this.rep&&!n?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?(z({m:`ldp.play.1`}),this._playVideoElement()):(z({m:`ldp.play.2`}),this._notifyBuffering(!0))):(z({m:`ldp.play.3`}),this.catchUp())}startPlay(e,t){this.autoQuality=t,z({m:`startPlay`,url:e.jidxUrl}),this._initPlayerWith(e)}destroy(){this.destroyed=!0;let{videoElement:e}=this.params;this.rep&&=(this.rep.stop(),null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&=(j.clearTimeout(this.manifestRefetchTimer),void 0);for(let[t,n]of this.videoListeners)e.removeEventListener(t,n);if(this.videoListeners=[],this.mediaSource&&this.mediaSource.readyState===`open`)try{this.mediaSource.endOfStream()}catch{}this.mediaSource=void 0,this.objectUrl&&=(URL.revokeObjectURL(this.objectUrl),null)}reinit(e){this.manifestUrl=e,this.urlResolver=da(e),z({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,n=e.buffered.length;return n!==0&&(t=e.buffered.end(n-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;z({m:`iv`});let n=(t,n)=>{this.videoListeners.push([t,n]),e.addEventListener(t,n)};n(`error`,()=>{e.error&&!this.destroyed&&(z({m:`iv.err`,e:e.error?.code+`:`+e.error?.message}),t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:`error`,type:`media`}))}),n(`timeupdate`,()=>{let e=this._getBufferSizeSec();!this.paused&&e<.3?this.buffering||(this.buffering=!0,j.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(e+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),n(`playing`,()=>{t(`playing`)}),n(`stalled`,()=>this._fixupStall()),n(`waiting`,()=>this._fixupStall()),n(`canplay`,()=>{z({m:`canplay`}),!(this.destroyed||this.waitingForFirstBufferAfterSrcChange)&&this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())})}_fixupStall(){let{logger:e,videoElement:t}=this.params,n=t.buffered.length,r;if(n!==0){if(this.waitingForFirstBufferAfterSrcChange){e(`_fixupStall: skipped (waitingForFirstBufferAfterSrcChange), currentTime=${t.currentTime}, bufferedStart=${t.buffered.start(n-1)}`);return}r=t.buffered.start(n-1),t.currentTime<r&&(e(`Fixup stall: currentTime=${t.currentTime}, bufferedStart=${r}`),z({m:`ldp.fs`,ct:t.currentTime,bufStart:r}),t.currentTime=r)}}_selectQuality(e){let{videoElement:t}=this.params,n,r,i,a=t&&1.62*(N.display.pixelRatio||1)*t.offsetHeight||520;for(let t=0;t<this.manifest.length;++t){i=this.manifest[t];let{max:o,min:s}=this.autoQualityLimits||{};!_i({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:this.manifest.at(-1)?.video.height})&&(o&&i.video.height>o||s&&i.video.height<s)||i.tvDisabled||(i.bitrate<e&&a>Math.min(i.video.height,i.video.width)?(!r||i.bitrate>r.bitrate)&&(r=i):(!n||n.bitrate>i.bitrate)&&(n=i))}return r||n}shouldPlay(){if(this.paused)return!1;let e=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return e>3||ra(this.downloadRate)&&(this.downloadRate>1.5&&e>2||this.downloadRate>2&&e>1)}_setVideoSrc(e,t){let{logger:n,videoElement:r,playerCallback:i}=this.params;this.srcToken=(this.srcToken+1)%(2**53-1);let a=this.srcToken;this.waitingForFirstBufferAfterSrcChange=!0,n(`setting video src (token=${a}, codecs=${e.codecs}), flag=true`),this.objectUrl&&=(URL.revokeObjectURL(this.objectUrl),null),this.mediaSource=new window.MediaSource,this.objectUrl=URL.createObjectURL(this.mediaSource),r.src=this.objectUrl,this.mediaSource.addEventListener(`sourceopen`,()=>{if(a!==this.srcToken){n(`sourceopen: stale token=${a}, current=${this.srcToken}`);return}if(this.mediaSource?.readyState!==`open`){z({m:`sourceopen`,err:`not open: ${this.mediaSource?.readyState}`}),n(`sourceopen: not open: ${this.mediaSource?.readyState}`);return}z({m:`sourceopen`,c:e.codecs}),n(`sourceopen: codecs=${e.codecs}`),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t()}),this.mediaSource?.addEventListener(`sourceclose`,e=>{z({m:`sourceclose`})}),this.videoPlayStarted=!1;let o=()=>{fa(r,`progress`,()=>{if(a!==this.srcToken){n(`progress: stale token=${a}, current=${this.srcToken}`);return}if(!r.buffered.length)n(`progress: no buffered data yet, re-listening`),o();else{let e=r.buffered.start(0);n(`progress: setting currentTime=${e}, clearing waitingForFirstBufferAfterSrcChange`),r.currentTime=e,this.waitingForFirstBufferAfterSrcChange=!1,i({name:`playing`})}})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ya(Da,Ea,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:n,playerCallback:r}=this.params,i=!1,a=null,o=null,s=null,c=null,l=!1,u=()=>{let e=i&&(!l||l===this.rep);return e||t(`Not running!`),e},d=(e,t,n)=>{s&&s.abort(),s=pa(this.urlResolver.resolve(e,!1),t,n,()=>this._retryCallback()).withTimeout(Ea).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Da).withFinally(()=>{s=null}).send()},f=(e,t,n)=>{aa(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(e,!1),t,n,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},p=e=>{let r=n.playbackRate;n.playbackRate!==e&&(t(`Playback rate switch: ${r}=>${e}`),n.playbackRate=e)},m=e=>{this.lowLatency=e,t(`lowLatency changed to ${e}`),h()},h=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)p(1);else{let e=this._getBufferSizeSec();if(this.bufferStates.length<5){p(1);return}let n=L()-1e4,r=0;for(let t=0;t<this.bufferStates.length;t++){let i=this.bufferStates[t];e=Math.min(e,i.buf),i.ts<n&&r++}this.bufferStates.splice(0,r),t(`update playback rate; minBuffer=${e} drop=${r} jitter=${this.sourceJitter}`);let i=e-Aa;this.sourceJitter>=0?i-=this.sourceJitter/2:--this.sourceJitter,p(i>3?1.15:i>1?1.1:i>.3?1.05:1)}},g=e=>{let n,i=()=>n&&n.start?n.start.length:0,a=e=>n.start[e]/1e3,o=e=>n.dur[e]/1e3,s=e=>n.fragIndex+e,l=(e,t)=>({chunkIdx:s(e),startTS:a(e),dur:o(e),discontinuity:t}),d=()=>{let e=0;if(n&&n.dur){let t=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,r=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,i=t;this.sourceJitter>1&&(i+=this.sourceJitter-1);let a=n.dur.length-1;for(;a>=0&&(i-=n.dur[a],!(i<=0));--a);e=Math.min(a,n.dur.length-1-r),e=Math.max(e,0)}return l(e,!0)},f=e=>{let t=i();if(!(t<=0)){if(ra(e)){for(let n=0;n<t;n++)if(a(n)>e)return l(n)}return d()}},p=e=>{let r=i(),a=e?e.chunkIdx+1:0,o=a-n.fragIndex;if(!(r<=0)){if(!e||o<0||o-r>ka)return t(`Resync: offset=${o} bChunks=${r} chunk=`+JSON.stringify(e)),d();if(!(o>=r))return l(a-n.fragIndex,!1)}},h=(e,t,n)=>{c&&c.abort(),c=pa(this.urlResolver.resolve(e,!0,this.lowLatency),t,n,()=>this._retryCallback()).withTimeout(Ea).withRetryCount(Da).withFinally(()=>{c=null}).withJSONResponse().send()};return{seek:(t,i)=>{h(e,e=>{if(!u())return;n=e;let a=!!n.lowLatency;a!==this.lowLatency&&m(a);let o=0;for(let e=0;e<n.dur.length;++e)o+=n.dur[e];o>0&&(aa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(o/n.dur.length)),r({name:`index`,zeroTime:n.zeroTime,shiftDuration:n.shiftDuration}),this.sourceJitter=n.hasOwnProperty(`jitter`)?Math.min(10,Math.max(.01,n.jitter/1e3)):1,t(f(i))},()=>this._handleNetworkError())},nextChunk:p}},_=()=>{i=!1,o&&o.abort(),s&&s.abort(),c&&c.abort(),aa(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:t=>{let{videoElement:n,logger:o}=this.params,s=g(e.jidxUrl),l,p,m,v,y=0,b,x,S,C=()=>{b&&=(j.clearTimeout(b),void 0);let e=Math.max(ja,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),t=y+e,n=L(),r=Math.min(1e4,t-n);y=n;let i=()=>{c||u()&&s.seek(()=>{u()&&(y=L(),w(),C())})};r>0?b=j.setTimeout(()=>{this.paused?C():i()},r):i()},w=()=>{let t;for(;t=s.nextChunk(v);)v=t,ee(t);let n=s.nextChunk(m);if(n){if(m&&n.discontinuity){o(`Detected discontinuity; restarting playback`),this.paused?C():(_(),z({m:`ldp.fetchChunkIdx.0`}),this._initPlayerWith(e));return}O(n)}else C()},T=(e,t)=>{if(!u()||!this.sourceBuffer){z({m:`ab.0`,c:[!u(),!this.sourceBuffer]});return}let i,a,s,c=n=>{z({m:`ldp.postpone`,t:n}),j.setTimeout(()=>{u()&&T(e,t)},n)};if(this.sourceBuffer.updating)o(`Source buffer is updating; delaying appendBuffer`),z({m:`ldp.ab.1`}),c(100);else{let l=L(),u=n.currentTime;!this.paused&&n.buffered.length>1&&x===u&&l-S>500&&(o(`Stall suspected; trying to fix`),this._fixupStall()),x!==u&&(x=u,S=l);let d=this._getBufferSizeSec();if(d>30)z({m:`ldp.ab.3`}),o(`Buffered ${d} seconds; delaying appendBuffer`),c(2e3);else try{if(this.params.config.useInvalidBufferFix&&R(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(e),this.videoPlayStarted?(z({m:`ldp.ab.5`}),this.bufferStates.push({ts:l,buf:d}),h(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(z({m:`ldp.ab.4`}),this.videoPlayStarted=!0,this._playVideoElement()),t&&t()}catch(e){z({m:`ldp.ab.err`,e:e.name}),e.name===`QuotaExceededError`?(o(`QuotaExceededError; delaying appendBuffer`),s=this.sourceBuffer.buffered.length,s!==0&&(i=this.sourceBuffer.buffered.start(0),a=u,a-i>4&&this.sourceBuffer.remove(i,a-3)),c(1e3)):(o(e.name),r({name:`error`,type:`buffer`,message:`appendBuffer failed due to ${e.name}`}))}}},E=()=>{p&&l&&(o([`Appending chunk, sz=${p.byteLength}:`,JSON.stringify(m)]),T(p,function(){p=null,w()}))},D=t=>e.fragUrlTemplate.replace(`%%id%%`,t.chunkIdx),O=e=>{u()&&f(D(e),(t,n)=>{if(u()){if(n/=1e3,p=t,m=e,a=e.startTS,n){let t=Math.min(10,e.dur/n);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*t:t}E()}},()=>this._handleNetworkError())},ee=e=>{u()&&(aa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(D(e),!1)))},te=t=>{u()&&(e.cachedHeader=t,T(t,()=>{l=!0,E()}))};i=!0,s.seek(e=>{if(u()){if(y=L(),!e){C();return}v=e,!ia(t)||e.startTS>t?O(e):(m=e,w())}},t),e.cachedHeader?te(e.cachedHeader):d(e.headerUrl,te,()=>this._handleNetworkError())},stop:_,getTimestampSec:()=>a},l}_switchToQuality(e){let{logger:t,playerCallback:n}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),ra(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,aa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),n({name:`qualitySwitch`,quality:e}))}_qualityAvailable(e){return ra(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,n=t=>{if(!this.autoQuality)return;let n,r,i;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&t<this.bitrate&&(r=this._getBufferSizeSec(),i=t/this.bitrate,r>10&&i>.8||r>15&&i>.5||r>20&&i>.3)){e(`Not switching: buffer=${Math.floor(r)}; bitrate=${this.bitrate}; newRate=${Math.floor(t)}`);return}n=this._selectQuality(t),n?this._switchToQuality(n):e(`Could not find quality by bitrate ${t}`)},r={updateChunk:(e,n)=>{let r=L();if(this.chunkRateEstimator.addInterval(e,r,n)){let i=this.chunkRateEstimator.getBitRate();return t({name:`bandwidth`,size:n,duration:r-e,speed:i}),!0}},get:()=>{let e=this.chunkRateEstimator.getBitRate();return e?e*.85:0}},i=-1/0,a,o=!0,s=()=>{let e=r.get();if(e&&a&&this.autoQuality){if(o&&e>a&&ua(i)<3e4)return;n(e)}o=this.autoQuality};return{updateChunk:(e,t)=>{let n=r.updateChunk(e,t);return n&&s(),n},notifySwitch:e=>{let t=L();e<a&&(i=t),a=e}}}_fetchManifest(e,t,n){this.manifestRequest=pa(this.urlResolver.resolve(e,!0),t,n,()=>this._retryCallback()).withJSONResponse().withTimeout(Ea).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;na(e,()=>{this.soundProhibitedEvent$.next()}).then(e=>{z({m:`ldp.pve.1`}),e||(z({m:`ldp.pve.2`}),this.params.liveOffset.pause(),this.params.videoState.setState(`paused`))})}_handleManifestUpdate(e){let{logger:t,playerCallback:n,videoElement:r}=this.params,i=e=>{let t=[];return e?.length?(e.forEach((e,n)=>{var i,a;e.video&&r.canPlayType(e.codecs).replace(/no/,``)&&!((i=window.MediaSource)==null||(a=i.isTypeSupported)==null)&&a.call(i,e.codecs)&&(e.index=n,t.push(e))}),t.sort(function(e,t){return e.video&&t.video?t.video.height-e.video.height:t.bitrate-e.bitrate}),t):(n({name:`error`,type:`empty_manifest`}),[])};this.manifest=i(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),n({name:`manifest`,manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&j.clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=j.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Oa))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Wa{constructor(){this.onDroopedVideoFramesLimit$=new Ha,this.subscription=new Ua,this.log=void 0,this.video=void 0,this.droppedFramesChecker=void 0,this.isAuto=void 0,this.playing=!1,this.tracks=[],this.forceChecker$=new Ha,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.currentTimer=void 0,this.limitCounts={},this.currentQuality=void 0,this.maxQualityLimit=void 0,this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:e})=>e?.height===this.video.videoHeight&&e?.width===this.video.videoWidth);e&&!za(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),n=e-this.prevTotalVideoFrames,r=1-(n-(t-this.prevDroppedVideoFrames))/n;!isNaN(r)&&r>0&&this.log({message:`[dropped]. current dropped percent: ${r}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(r)&&r>=this.droppedFramesChecker.percentLimit&&Ra(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&j.clearTimeout(this.currentTimer),this.currentTimer=j.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&&j.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}getMetrics(){if(!this.video||typeof this.video.getVideoPlaybackQuality!=`function`)return{totalVideoFrames:0,droppedVideoFrames:0,droppedPercent:0,stalledFrames:0};let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality();return{totalVideoFrames:e,droppedVideoFrames:t,droppedPercent:e>0?t/e:0,stalledFrames:e-t}}subscribe(){this.subscription.add(Ia(this.video,`resize`).subscribe(this.handleChangeVideoQuality));let e=Va(La(this.droppedFramesChecker.checkTime).pipe(Fa(()=>this.playing),Fa(()=>{let e=!!this.isForceCheckCounter;return e&&--this.isForceCheckCounter,!e})),this.forceChecker$.pipe(Pa(this.droppedFramesChecker.checkTime)));this.subscription.add(e.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:n}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,n),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 t;let n=(t=Na(this.limitCounts).filter(([,e])=>e>=this.droppedFramesChecker.countLimit).sort(([e],[t])=>Ba(e,t)?-1:1))==null||(t=t[0])==null?void 0:t[0];return e??n}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}}var Ga=Wa;var Ya=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement,Xa=(e,t)=>new qa(n=>{if(!window.IntersectionObserver)return;let r=new IntersectionObserver((e,t)=>{e.forEach(e=>n.next(e.isIntersecting||Ya()))},T(T({},{root:null}),t));r.observe(e);let i=Ja(document,`visibilitychange`).pipe(Ka(e=>!document.hidden||Ya())).subscribe(e=>n.next(e));return()=>{r.unobserve(e),i.unsubscribe()}});var $a;(e=>{e.VP9=`vp9`,e.AV1=`av1`,e.NONE=`none`,e.SMOOTH=`smooth`,e.POWER_EFFICIENT=`power_efficient`})($a||={});var eo=e=>{let{webmDecodingInfo:t}=N.video,n=`DASH_WEBM`,r=`DASH_WEBM_AV1`;switch(e){case`vp9`:return[n,r];case`av1`:return[r,n];case`none`:return[];case`smooth`:return t?t[r].smooth?[r,n]:t[n].smooth?[n,r]:[r,n]:[n,r];case`power_efficient`:return t?t[r].powerEfficient?[r,n]:t[n].powerEfficient?[n,r]:[r,n]:[n,r];default:Qa(e)}},to=({webmCodec:e,androidPreferredFormat:t,iosPreferredFormat:n,preferMultiStream:r})=>{let i=[...r?[`DASH_STREAMS`]:[],...eo(e),`DASH_SEP`,`DASH_ONDEMAND`,...r?[]:[`DASH_STREAMS`]],a=[...r?[`DASH_STREAMS`]:[],`DASH_SEP`,`DASH_ONDEMAND`,...r?[]:[`DASH_STREAMS`]];if(N.device.isAndroid)switch(t){case`mpeg`:return[`MPEG`,...i,`HLS`,`HLS_ONDEMAND`];case`hls`:return[`HLS`,`HLS_ONDEMAND`,...i,`MPEG`];case`dash`:return[...i,`HLS`,`HLS_ONDEMAND`,`MPEG`];case`dash_any_mpeg`:return[...a,`MPEG`,...eo(e),`HLS`,`HLS_ONDEMAND`];case`dash_any_webm`:return[...eo(e),`MPEG`,...a,`HLS`,`HLS_ONDEMAND`];case`dash_sep`:return[`DASH_SEP`,`MPEG`,...eo(e),...a,`HLS`,`HLS_ONDEMAND`];default:Qa(t)}if(N.video.nativeHlsSupported)switch(n){case`hls`:return[...i,`HLS`,`HLS_FMP4`,`HLS_ONDEMAND`,`MPEG`];case`hls_fmp4`:return[...i,`HLS_FMP4`,`HLS`,`HLS_ONDEMAND`,`MPEG`];default:Qa(n)}return[...i,`HLS`,`HLS_ONDEMAND`,`MPEG`]},no=({androidPreferredFormat:e,preferCMAF:t,preferWebRTC:n})=>{let r=t?[`DASH_LIVE_CMAF`,`DASH_LIVE`]:[`DASH_LIVE`,`DASH_LIVE_CMAF`],i=t?[`HLS_LIVE_CMAF`,`HLS_LIVE`]:[`HLS_LIVE`,`HLS_LIVE_CMAF`],a=[...r,...i],o=[...i,...r],s,c=N.device.isMac&&N.browser.isSafari;if(N.device.isAndroid)switch(e){case`dash`:case`dash_any_mpeg`:case`dash_any_webm`:case`dash_sep`:s=a;break;case`hls`:case`mpeg`:s=o;break;default:Qa(e)}else s=N.video.nativeHlsSupported&&!c&&!N.browser.isChromiumBased?o:c?t?[`DASH_LIVE_CMAF`,`HLS_LIVE_CMAF`,`HLS_LIVE`,`DASH_LIVE`]:[`HLS_LIVE`,`DASH_LIVE`,`DASH_LIVE_CMAF`,`HLS_LIVE_CMAF`]:a;return n?[`WEB_RTC_LIVE`,...s]:[...s,`WEB_RTC_LIVE`]},ro=e=>e?[`HLS_LIVE`,`HLS_LIVE_CMAF`,`DASH_LIVE_CMAF`]:[`DASH_WEBM`,`DASH_WEBM_AV1`,`DASH_SEP`,`DASH_ONDEMAND`,`HLS`,`HLS_ONDEMAND`,`MPEG`],io=(e,{preferHdr:t})=>{let n=e.filter(e=>e.hdr),r=e.filter(e=>!e.hdr),i=ao(n.map(({codecs:e})=>e)),a=ao(r.map(({codecs:e})=>e)),o=N.display.isHDR&&t&&i.length>0,s=[...i.map(e=>({name:e,hdr:!0})),...a.map(e=>({name:e,hdr:!1}))],c=[...a.map(e=>({name:e,hdr:!1})),...i.map(e=>({name:e,hdr:!0}))];return o?s:c},ao=e=>{let t=e.map(e=>so(e)),{codecs:n}=N.video;return co().filter(e=>{if(Za(t,e))switch(e){case`av1`:return n.av1;case`vp9`:return n.vp9;case`avc1`:return n.h264;case`hev1`:return n.h265;default:return!1}else return!1})},oo=e=>{let t=e.map(e=>so(e)),{codecs:n}=N.video;return lo().filter(e=>{if(Za(t,e))switch(e){case`opus`:return n.opus;case`mp4a`:return n.aac;default:return!1}else return!1})},so=e=>e.split(`.`)[0].replace(`0`,``),co=()=>[`av1`,`vp9`,`hev1`,`avc1`],lo=()=>[`opus`,`mp4a`],uo=(e,t)=>{e.video.forEach(e=>{e.representations.forEach(e=>{e.tvDisabled=e.tvDisabled||po(e,t)})})};function fo(e){return typeof e==`number`&&Number.isInteger(e)}function po({codecs:e,height:t,fps:n},r){let i=r.find(([n,r,i])=>n===`${t}p`&&mo(e,i))?.[1];return fo(i)&&fo(n)&&n>i}function mo(e,t){return Array.isArray(e)?e.some(e=>ho(e,t)):ho(e,t)}function ho(e,t){return so(e)===t}var go=e=>e.match(/codecs="([^"]+)"/)?.[1].split(/\s*,\s*/)??[];function _o(e,t){if(e instanceof HTMLAudioElement)return{target:Kn(e),video:null};let n=Gn(e,t);return{target:n,video:n}}var vo=[`paused`,`playing`,`ready`],yo=[`paused`,`playing`,`ready`];class bo{constructor(e){this.subscription=new Xi,this.volumeSubscription=new Xi,this.allocation=void 0,this.videoState=new mn(`stopped`),this.dash=void 0,this.representations$=new Zi([]),this.textTracksManager=null,this.droppedFramesManager=new Ga,this.maxSeekBackTime$=new Zi(1/0),this.zeroTime$=new Zi(void 0),this.liveOffset=new xr,this.log=void 0,this.params=void 0,this._dashCb=e=>{switch(e.name){case`buffering`:{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case`error`:this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Hi.WTF,message:`LiveDashPlayer reported error${e.message?`: ${e.message}`:``}`});break;case`manifest`:{let t=e.manifest,n=[];for(let e of t){let t=e.name??e.index.toString(10),r=Wr(e.name)??$i(e.video),i=e.bitrate/1e3,a=T({},e.video),o=e.frameRate,s=!1,{videoStreamRepresentaionsFilter:c}=this.params.tuning.dash;if(c.length&&(s=po({codecs:go(e.codecs),height:e.video.height,fps:o},c)),e.tvDisabled=s,!r)continue;let l={id:t,quality:r,bitrate:i,size:a,fps:o,tvDisabled:s};n.push({track:l,representation:e})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.map(({track:e})=>e)),this.videoState.getTransition()?.to===`manifest_ready`&&this.videoState.setState(`manifest_ready`);break}case`qualitySwitch`:{let t=e.quality,n=this.representations$.getValue().find(({representation:e})=>e===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Gi(n)&&this.params.output.currentVideoTrack$.next(n);break}case`bandwidth`:{let{size:t,duration:n}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,n);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(),n=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(i)};`}),n===`stopped`){e!==`stopped`&&(this.videoState.startTransitionTo(`stopped`),this.dash.destroy(),this.allocation.target.removeAttribute(`src`),this.allocation.target.load(),this.videoState.setState(`stopped`));return}if(t)return;let a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(An(yo,e)&&(a||o)){this.prepare();return}if(r?.to!==`paused`&&i.state===`requested`&&An(vo,e)){let e=i.position<0?this.liveOffset.getCurrentPausedTime():0;this.seek(i.position-e);return}switch(e){case`stopped`:this.videoState.startTransitionTo(`manifest_ready`),this.dash.attachSource(k(this.params.source.url));return;case`manifest_ready`:this.videoState.startTransitionTo(`ready`),this.prepare();break;case`ready`:if(n===`paused`)this.videoState.setState(`paused`);else if(n===`playing`){z({m:`dlp.sync.1`}),this.videoState.startTransitionTo(`playing`);let e=r?.from;e&&e===`ready`&&(z({m:`dlp.sync.2`}),this.dash.catchUp()),z({m:`dlp.sync.3`}),this.dash.play()}return;case`playing`:n===`paused`&&(this.videoState.startTransitionTo(`paused`),this.liveOffset.pause(),this.dash.pause());return;case`paused`:if(n===`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 e=this.liveOffset.getTotalOffset();e>=this.maxSeekBackTime$.getValue()&&(e=0,this.liveOffset.resetTo(e)),this.liveOffset.resume(),this.params.output.position$.next(-e/1e3),this.dash.reinit(k(this.params.source.url,e))}return;default:return Ri(e)}},e.tuning.disableSubtitles||(this.textTracksManager=new br(e.source.url)),this.params=e,this.log=this.params.dependencies.logger.createComponentLog(`DashLiveProvider`);let t=t=>{e.output.error$.next({id:`DashLiveProvider`,category:Hi.WTF,message:`DashLiveProvider internal logic error`,thrown:t})};this.subscription.add(qi(this.videoState.stateChangeStarted$.pipe(Ki(e=>({transition:e,type:`start`}))),this.videoState.stateChangeEnded$.pipe(Ki(e=>({transition:e,type:`end`})))).subscribe(({transition:e,type:t})=>{z({m:`dlp.s.1`,t:t+`:${e.from}-${e.to}`}),this.log({message:`[videoState change] ${t}: ${JSON.stringify(e)}`})})),this.allocation=_o(e.container,e.tuning),this.params.output.element$.next(this.allocation.video??void 0),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(Li(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.allocation.video&&this.textTracksManager?.connect(this.allocation.video,this.params.desiredState,this.params.output);let n=Hr(this.allocation.target);this.subscription.add(()=>n.destroy());let r=this.allocation.video;r&&this.subscription.add(this.representations$.pipe(Ki(e=>e.map(({track:e})=>e)),Ui(e=>!!e.length),Yi()).subscribe(e=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:r,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks:e}))),this.subscription.add(n.canplay$.subscribe(()=>{this.videoState.getTransition()?.to===`ready`&&this.videoState.setState(`ready`)},t)).add(n.pause$.subscribe(()=>{this.videoState.setState(`paused`)},t)).add(n.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===`applying`&&this.params.output.seekedEvent$.next(),this.videoState.setState(`playing`)},t)).add(n.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(Wi(),Ki(e=>-e/1e3)).subscribe(this.params.output.duration$)).add(Bi({zeroTime:this.zeroTime$.pipe(Ui(Gi)),position:n.timeUpdate$}).subscribe(({zeroTime:e,position:t})=>{t===0&&this.videoState.getTransition()||this.params.output.liveTime$.next(e+t*1e3)},t)).add(pr(this.allocation.target,this.params.desiredState.isLooped,t)).add(mr(this.allocation.target,this.params.desiredState.volume,n.volumeState$,t,{skipVideoElVolumeSync$:this.params.skipVideoElVolumeSync$})),this.subscription.add(this.params.skipVideoElVolumeSync$.subscribe(e=>{this.volumeSubscription.unsubscribe(),e?this.volumeSubscription.add(this.params.desiredState.volume.stateChangeStarted$.subscribe(({to:e})=>this.params.output.volume$.next(e),t)):this.volumeSubscription.add(n.volumeState$.subscribe(this.params.output.volume$,t))})),this.subscription.add(hr(this.allocation.target,this.params.desiredState.playbackRate,n.playbackRateState$,t)).add(n.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(n.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(n.playing$.subscribe(this.params.output.firstFrameEvent$)).add(n.canplay$.subscribe(this.params.output.canplay$)).add(n.playedTime$.subscribe(this.params.output.playedTime$)).add(n.inPiP$.subscribe(this.params.output.inPiP$)).add(n.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Xa(this.allocation.target).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:e,min:t}})=>{this.dash.setAutoQualityLimits({max:e&&Qi(e),min:t&&Qi(t)}),this.params.output.autoVideoTrackLimits$.next({max:e,min:t})})).add(this.videoState.stateChangeEnded$.subscribe(e=>{switch(e.to){case`stopped`:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),z({m:`dlp.vse.s`}),this.params.desiredState.playbackState.setState(`stopped`);break;case`manifest_ready`:case`ready`:this.params.desiredState.playbackState.getTransition()?.to===`ready`&&(z({m:`dlp.vse.r`}),this.params.desiredState.playbackState.setState(`ready`));break;case`paused`:z({m:`dlp.vse.pa`}),this.params.desiredState.playbackState.setState(`paused`);break;case`playing`:z({m:`dlp.vse.pl`}),this.params.desiredState.playbackState.setState(`playing`);break;default:return Ri(e.to)}},t)).add(qi(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ji([`init`])).pipe(Vi(0)).subscribe(this.syncPlayback,t));let i=!1,{output:a}=this.params;this.params.tuning.live.catchupLiveForMutedInactiveTab&&this.subscription.add(a.elementVisible$.pipe(Wi()).subscribe(e=>{let t=a.position$.getValue(),n=a.volume$.getValue(),r=!n.volume||n.muted;!e&&!t&&r?i=!0:e&&i&&(this.seek(0),i=!1)}))}destroy(){z({m:`dlp.destroy`}),this.subscription.unsubscribe(),this.volumeSubscription.unsubscribe(),this.textTracksManager?.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),qn(this.allocation.target,this.params.tuning)}createLiveDashPlayer(){let e=new Ma({videoElement:this.allocation.target,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:e=>{this.params.dependencies.logger.log({message:String(e),component:`LiveDashPlayer`})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!n&&Gi(t)?t:Ni(e.map(({track:e})=>e),{container:this.allocation.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}),i=r?.id,a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,s=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(a||i!==o)&&this.setVideoTrack(r),s&&this.setAutoQuality(n),a||s||i!==o){let t=e.find(({track:e})=>e.id===i)?.representation;zi(t,`Representations missing`),this.dash.startPlay(t,n)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:t})=>t.id===e.id)?.representation;zi(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(),n=this.videoState.getState(),r=t===`paused`&&n===`paused`,i=-e,a=i<=this.maxSeekBackTime$.getValue()?i:0;this.params.output.position$.next(e/1e3),z({m:`dlp.seek`,p:e,no:a,url:this.params.source.url}),this.dash.reinit(k(this.params.source.url,a)),r&&this.dash.pause(),this.liveOffset.resetTo(a,r)}}var xo=bo;var Uo=({id:e,width:t,height:n,bitrate:r,fps:i,quality:a,streamId:o,tvDisabled:s})=>{let c=(a?Wr(a):void 0)??Ho({width:t,height:n});return c&&{id:e,quality:c,bitrate:r,size:{width:t,height:n},fps:i,streamId:o,tvDisabled:s}},Wo=({id:e,bitrate:t})=>({id:e,bitrate:t}),Go=({language:e,label:t},{id:n,url:r,isAuto:i})=>({id:n,url:r,isAuto:i,type:`internal`,language:e,label:t}),Ko=({language:e,label:t,id:n,url:r,isAuto:i})=>({id:n,url:r,isAuto:i,type:`internal`,language:e,label:t}),qo=({id:e,language:t,label:n,codecs:r,isDefault:i,channels:a})=>({id:e,language:t,label:n,codec:Vo(r.split(`.`),0),isDefault:i,channels:a}),Jo=({id:e,language:t,label:n,hdr:r,codecs:i})=>({id:e,language:t,hdr:r,label:n,codec:Vo(i.split(`.`),0)}),Yo=e=>e.type===`template`;var is=(e,t,n)=>n*t+(1-n)*e,as=(e,t)=>e.reduce((e,t)=>e+t,0)/t,os=(e,t,n,r)=>{let i=0,a=n,o=as(e,t),s=t<r?t:r;for(let t=0;t<s;t++)e[a]>o?i++:i--,a=(e.length+a-1)%e.length;return Math.abs(i)===s},ss=`stalls_manager_metrics`,cs=`stalls_manager_abr_params`,ls=`stalls_manager_default_tuning_abr_params`;class us{constructor(){this.currentStallDuration$=void 0,this.videoLastDataObtainedTimestamp$=void 0,this.throughput$=void 0,this.rtt$=void 0,this.tuning=void 0,this.abrParams=void 0,this.duration=void 0,this.isSeeked$=new es(!1),this.isBuffering$=new es(!1),this.isPaused=!1,this.maxQualityLimit=void 0,this.lastUniqueVideoTrackSelected=void 0,this.currentStallsCount=0,this.sumStallsDuration=0,this.lastStallDuration=0,this.providerStartWatchingTimestamp=0,this.lastUniqueVideoTrackSelectedTimestamp=0,this.predictedThroughputWithoutData=0,this.qualityRestrictionTimer=void 0,this.subscription=new $o,this.severeStallOccurred$=new es(!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 e=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(cs):{};return T(T({},this.abrParams),e)}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Zo(),this.currentStallsCount=0)}destroy(){j.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Zo()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:n}=T({},this.getStoredData(ls)),{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:i,containerSizeFactor:a}=T({},this.abrParams);this.tuning.enabled&&e===r&&t===i&&n===a||(this.removeStoredData(cs),this.setStoredData(ls,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:i,containerSizeFactor:a}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(ss,`[]`);if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let n=t.reduce((e,t)=>e+t.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let r=t.reduce((e,t)=>e+t.stallsDuration,0)/n;e.push(this.calculateOptimalAbrParams(r,n))}if(this.tuning.useAverageStallsDurationPerTvt){let r=t.reduce((e,t)=>e+t.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(r,n))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,n));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(e=>e.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(e=>e.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(e=>e.containerSizeFactor))};this.setStoredData(ss,[]),this.setStoredData(cs,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:n,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:i,abrAdjustingSpeed:a,significantTvt:o}=this.tuning,s=a*Math.min(t/o,1),c=this.abrTuningParams;return e<n-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-s,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-s,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+s,this.abrParams.maxContainerSizeFactor)}:e>n+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+s,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+s,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-s,this.abrParams.minContainerSizeFactor)}),e>i&&(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=`{}`){return JSON.parse(ns.get(e)??t)}setStoredData(e,t){ns.set(e,JSON.stringify(t))}removeStoredData(e){ns.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let n=this.getStoredData(ss,`[]`),r=t/e,i={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:n.length?is(n[n.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r};n.push(i),n.length>this.tuning.stallsMetricsHistoryLength&&n.shift(),this.setStoredData(ss,n)}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(e=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(Qo()).subscribe(e=>this.providerStartWatchingTimestamp=Zo())),this.subscription.add(e.playing$.subscribe(e=>this.isPaused=!1)),this.subscription.add(e.pause$.subscribe(e=>this.isPaused=!0)),this.subscription.add(this.currentStallDuration$.pipe(rs()).subscribe(e=>{let{stallDurationNoDataBeforeQualityDecrease:t,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:r,ignoreStallsOnSeek:i}=this.tuning;if(Xo(this.lastUniqueVideoTrackSelected)||i&&this.isSeeked$.getValue())return;if(this.tuning.ignoreStallsOnPause&&this.isPaused){this.lastStallDuration=e;return}let a=this.rtt$.getValue(),o=this.throughput$.getValue(),s=this.videoLastDataObtainedTimestamp$.getValue(),c=Zo(),l=n&&this.currentStallsCount>=n,u=t&&c-this.lastUniqueVideoTrackSelectedTimestamp>=t+a&&c-s>=t+a&&e>=t;(l||u)&&(this.severeStallOccurred$.next(!0),j.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,ts(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!e&&Zo()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),j.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=j.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},r)),this.lastStallDuration=e}))}}var ds=us;class vs{constructor(){this.subscription=new hs,this.pipSize$=new gs(void 0),this.videoSize$=new gs(void 0),this.elementSize$=new gs(void 0),this.pictureInPictureWindowRemoveEventListener=_s}connect({observableVideo:e,video:t}){let n=e=>{let t=e.target;this.pipSize$.next({width:t.width,height:t.height})};this.subscription.add(ms(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:e})=>{this.pipSize$.next({width:e.width,height:e.height}),e.addEventListener(`resize`,n),this.pictureInPictureWindowRemoveEventListener=()=>{e.removeEventListener(`resize`,n)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(fs({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(ps(({videoSize:e,inPip:t,pipSize:n})=>t?n:e)).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 Ss=({subscription:e,desiredState:t,videoElement$:n,observableVideo:r})=>{if(!N.browser.isSafari)return;let i=0,a=!1;e.add(t.volume.stateChangeStarted$.pipe(bs(()=>{let e=t.volume.getTransition(),r=n.getValue();return!r||!e?!1:!e.to.muted&&r.muted}),ys(e=>!!e),xs()).subscribe(()=>{i=performance.now(),a=!0})),e.add(r.playbackRateState$.pipe(ys(()=>a),xs()).subscribe(()=>{let e=n.getValue(),r=t.playbackRate.getState();e&&r!==e.playbackRate&&performance.now()-i<1e3&&(e.playbackRate=r)}))};class As{constructor(){this.currentStallDuration$=new ks(0),this.videoLastDataObtainedTimestamp$=new ks(0),this.isSeeked$=new ks(!1),this.rtt$=new ks(0),this.tuning=void 0,this.lastUniqueVideoTrackSelectedTimestamp=0,this.lastUniqueVideoTrackSelected=void 0,this.providerStartWatchingTimestamp=0,this.subscription=new Os,this.severeStallOccurred$=new ks(!1),this.totalStallsCount$=new ks(0),this.currentVideoTrackStallsCount$=new ks(0),this.sumStallsDuration$=new ks(0),this.lastStallDuration$=new ks(0)}init(e){this.tuning=e.tuning,this.subscription.add(e.currentStallDuration$.subscribe(this.currentStallDuration$)),this.subscription.add(e.rtt$.subscribe(this.rtt$)),this.subscription.add(e.videoLastDataObtainedTimestamp$.subscribe(this.videoLastDataObtainedTimestamp$)),this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.observableVideo.looped$.subscribe(e=>this.currentVideoTrackStallsCount$.next(0))),this.subscription.add(e.observableVideo.playing$.pipe(Ds()).subscribe(e=>this.providerStartWatchingTimestamp=Es())),this.subscription.add(e.lastVideoTrackSelected$.subscribe(e=>{ws(e)&&this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Es(),this.currentVideoTrackStallsCount$.next(0))})),this.subscription.add(this.currentStallDuration$.pipe(Cs()).subscribe(e=>{let{stallDurationNoDataBeforeQualityDecrease:t,stallCountBeforeQualityDecrease:n,ignoreStallsOnSeek:r}=this.tuning;if(Ts(this.lastUniqueVideoTrackSelected)||r&&this.isSeeked$.getValue())return;let i=this.rtt$.getValue(),a=this.videoLastDataObtainedTimestamp$.getValue(),o=Es(),s=n&&this.currentVideoTrackStallsCount$.getValue()>=n,c=t&&o-this.lastUniqueVideoTrackSelectedTimestamp>=t+i&&o-a>=t+i&&e>=t;(s||c)&&this.severeStallOccurred$.next(!0),!e&&Es()-this.providerStartWatchingTimestamp>this.lastStallDuration$.getValue()&&(this.updateStallData(),this.severeStallOccurred$.next(!1)),this.lastStallDuration$.next(e)}))}destroy(){this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData()}updateStallData(){if(this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&this.lastStallDuration$.getValue()>0){let e=this.sumStallsDuration$.getValue(),t=this.lastStallDuration$.getValue(),n=this.currentVideoTrackStallsCount$.getValue(),r=this.totalStallsCount$.getValue();this.sumStallsDuration$.next(e+Math.min(t,this.tuning.maxPossibleStallDuration)),this.currentVideoTrackStallsCount$.next(n+1),this.totalStallsCount$.next(r+1)}}}var js=e=>`audioTracksAsc`in e;class Ns{constructor(){this.last=void 0,this.history={}}recordSelection(e){this.history[e.id]=Ms()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}var Vs=(e,t)=>(e??0)/(t>0?t:1),Hs=e=>`quality`in e,Us=e=>(t,n)=>e*(Number(t.bitrate)-Number(n.bitrate)),Ws=e=>(t,n)=>e*(Rs(t.quality,n.quality)?-1:1),Gs=e=>(t,n)=>Hs(t)&&Hs(n)?Ws(e)(t,n):Us(e)(t,n),Ks=(e,t)=>Gs(1)(e,t)<0,qs=(e,t)=>Math.log(t)/Math.log(e),Js=(e,t,n)=>(t-n)*2**(-10*e)+n,Ys=(e,t,n,r)=>{if(Bs(e))return n[0];let i=n.filter(t=>zs(t.bitrate)&&zs(e.bitrate)?e.bitrate/t.bitrate>r:!0),a=Is(n,Math.round(n.length*t.indexOf(e)/(t.length+1)))??Is(n,-1);return a&&Ls(i,a)?a:i.length?Is(i,-1):Is(n,0)};class Xs{constructor(){this.history=new Ns,this.rules=[],this._context=void 0}get context(){return this._context}init(e,t){this.rules=e;for(let e of this.rules)e.init(t)}destroy(){for(let e of this.rules)e.destroy()}updateContext(e){this._context=T({},e)}autoSelectTrack(e=this.rules){let{context:t}=this,n=e=>(t,n)=>n.confidence-t.confidence||Gs(e)(t.track,n.track),r=e.map(e=>e.execute(t)),i=r.filter(e=>e.type===`limit_above`).sort(n(1)),a=r.filter(e=>e.type===`limit_below`).sort(n(-1)),o=r[0].track;i.length===0&&a.length?o=a[0].track:i&&a.length===0?o=i[0].track:i.length&&a.length&&(o=Ks(i[0].track,a[0].track)?a[0].track:i[0].track);let s=this.history.last,c=this.selectTrackBasedOnHistory(o);if(c.bitrate!==s?.bitrate){let e=r.map(e=>e.logMessage).join(`
117
117
 
118
118
  `),n=`
119
119
  [${Hs(c)?`VIDEO`:`AUDIO`} TRACKS ABR]
@@ -247,4 +247,4 @@ import{objectEntries as ce}from"@vkontakte/videoplayer-shared/es2015";import{obj
247
247
  `,e.map(({time:e,data:t,stack:n})=>`${e}: ${JSON.stringify(t)}${n?`
248
248
  `+n:``}`).join(`
249
249
  `),`
250
- ===== DASH_LIVE DEBUG END ====`),n){let t=e.reduce((e,{time:t,data:n,stack:r})=>{let i=sn(n).map(([e,t])=>`${e}:${t}`).join(`,`);return e+=`${t}: ${i}${r?`: ${r}`:``};`,e},``);K_.push(`core`,{key:`vp_dash_live_debug`,strings:[t]})}};return e.add(this.providerError$.subscribe(e=>{e.id.startsWith(`ProviderHangup`)&&(z({m:`final.0`,e:e.id}),t())})).add(this.noAvailableProvidersError$.subscribe(()=>{z({m:`final.1`}),t()})),e.add(this.mayday.recommendation$.subscribe(({error:e,recommendation:t})=>{let n=this.current$.getValue(),r=n.destination??`SCREEN`;this.applyErrorSideEffects(e,n.type),this.handleMaydayRecommendation(t,r);let i={error:e,currentDestination:r,action:t.action,reason:t.reason};e.traceAsLog?this.tracer.log(`providerInfo`,G_(i)):this.tracer.error(`providerError`,G_(i))})),e.add(this.providerError$.subscribe(e=>{let{destination:t}=this.current$.getValue();t===`CHROMECAST`?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(`CHROMECAST`),()=>this.params.dependencies.chromecastInitializer.disconnect())):this.mayday.handleError(e)})),e}}var ey=`vk_uvp_throughput`,ty=`vk_uvp_rtt`,ny=`one_video_throughput`,ry=`one_video_rtt`,iy=()=>{let{navigator:e}=$v();if(e)return e.connection},ay=()=>{let e=iy()?.downlink;if(Xv(e)&&e!==10)return e*1e3},oy=()=>{let e=iy()?.rtt;if(Xv(e)&&e!==3e3)return e},sy=(e,t,n)=>{let r=n*8;return r/(r/e+t)};class cy{constructor(e){this.throughput=void 0,this.rtt=void 0,this.subscription=new Kv,this.tuningConfig=void 0,this.concurrentDownloads=new Set,this.throughput$=void 0,this.rtt$=void 0,this.rttAdjustedThroughput$=void 0,this.tuningConfig=e;let t=cy.loadStored(ey,ny,e)||(e.useBrowserEstimation?ay():void 0)||e.initialThroughput,n=cy.loadStored(ty,ry,e)??(e.useBrowserEstimation?oy():void 0)??0;if(this.throughput$=new qv(t),this.rtt$=new qv(n),this.rttAdjustedThroughput$=new qv(sy(t,n,e.rttPenaltyRequestSize)),this.throughput=Dp.getSmoothedValue(t,-1,e),this.rtt=Dp.getSmoothedValue(n,1,e),e.useBrowserEstimation){let e=()=>{let e=ay();e&&this.throughput.next(e);let t=oy();Xv(t)&&this.rtt.next(t)},t=iy();t&&`onchange`in t&&this.subscription.add(Uv(t,`change`).subscribe(e)),e()}this.subscription.add(this.throughput.smoothed$.subscribe(t=>{cy.writeStored(ey,ny,t,e)})),this.subscription.add(this.rtt.smoothed$.subscribe(t=>{cy.writeStored(ty,ry,t,e)})),this.subscription.add(this.throughput.debounced$.pipe(Jv(e=>Math.round(e))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Gv({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Jv(({throughput:t,rtt:n})=>sy(t,n,e.rttPenaltyRequestSize)),Yv(t=>{let n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,n=Zv(),r=new Kv;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Uv(e,`progress`).pipe(Wv()).subscribe(e=>{t=e.loaded,n=Zv()}));break;case 1:case 0:r.add(Uv(e,`loadstart`).subscribe(()=>{t=0,n=Zv()}));break}r.add(Uv(e,`loadend`).subscribe(i=>{if(e.status===200){let e=i.loaded,r=Zv(),a=e-t,o=r-n;this.addRawSpeed(a,o,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){var n=this;let r=e.getReader();if(!r){e.cancel(`Could not get reader`);return}let i=0,a=Zv(),o=0,s=Zv(),c=t=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${t}`).catch(()=>{})},l=function(){var u=w(function*({done:u,value:d}){if(u)!t&&n.addRawSpeed(i,Zv()-a,1),n.concurrentDownloads.delete(e);else if(d){if(t){let e=Zv();if(e-s>n.tuningConfig.lowLatency.continuesByteSequenceInterval||e-a>n.tuningConfig.lowLatency.maxLastEvaluationTimeout){let e=s-a;e&&n.addRawSpeed(o,e,1,t),o=d.byteLength,a=Zv()}else o+=d.byteLength;s=Zv()}else i+=d.byteLength,o+=d.byteLength,o>=n.tuningConfig.streamMinSampleSize&&Zv()-s>=n.tuningConfig.streamMinSampleTime&&(n.addRawSpeed(o,Zv()-s,n.concurrentDownloads.size),o=0,s=Zv());yield r?.read().then(l,c)}});return function(e){return u.apply(this,arguments)}}();this.concurrentDownloads.add(e),r?.read().then(l,c)}addRawSpeed(e,t,n=1,r=!1){if(this.sanityCheck(e,t,r)){let r=e*8/t;this.throughput.next(r*n)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}sanityCheck(e,t,n=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||n&&e<1e4||!n&&e<10*1024&&(!this.tuningConfig.measureNonSegmentRequests||t<this.tuningConfig.smallSampleMinDuration+this.rtt$.getValue())||!n&&!this.tuningConfig.measureFastSamples&&t<=this.tuningConfig.cacheThresholdSize)}get throughputVariance$(){return this.throughput.varianceCoefficient$}static loadStored(e,t,n){if(!n.useThroughputTtl){let e=Qv.get(t);if(!Xv(e))return;let n=parseInt(e,10);return isNaN(n)?void 0:n}let r=Qv.get(e)??Qv.get(t);if(Xv(r))try{let e=JSON.parse(r);if(typeof e==`object`&&e&&typeof e.value==`number`)return cy.validateStored(e,n)}catch{}}static writeStored(e,t,n,r){if(!r.useThroughputTtl){Qv.set(t,n.toFixed(0));return}let i=JSON.stringify({value:Math.round(n),timestamp:Date.now(),networkType:iy()?.effectiveType});Qv.set(e,i)}static validateStored(e,t){if(!t.useThroughputTtl)return e.value;if(Date.now()-e.timestamp>t.storedThroughputTtlMs)return;let n=iy()?.effectiveType;if(!(n!==void 0&&e.networkType!==void 0&&n!==e.networkType))return e.value}}var ly=cy;var fy={mayday:{playingUnstableThresholdMs:3e3,heuristics:[]},allowPlayerReuse:!1,useWorkerTimers:[],throughputEstimator:{type:`EmaAndMa`,emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,initialThroughput:5e3,measureNonSegmentRequests:!1,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,smallSampleMinDuration:100,cacheThresholdSize:20,measureFastSamples:!1,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300},useThroughputTtl:!1,storedThroughputTtlMs:144e5},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:dy.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:dy.Q_720P,trafficSavingLimit:dy.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,ignoreStallsOnPause:!1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:dy.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,audioBufferAheadOfVideoMs:6e4,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:6e4,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,restoreBufferBeforeCrashTimeout:1e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,virtualBufferEmptinessTolerance:100,useBufferQueueVerification:!1,useVirtualBufferImplicitSeek:!1,bufferQueueVerificationMinPosition:2e3,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,stallForceSeekOncePerStall:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,minNativeBufferSize:5e3,removeTimeShiftFromSegment:500,tickMaintainInterval:100,minSafeBufferToPlay:0,useBufferHoldingOnlyOnStall:!0,useNewAbr:!1,useAbrPhases:!1,abrVideoRules:[`fits_container_rule`,`throughput_rule`,`buffer_rule`,`stalls_rule`,`upper_limit_rule`,`lower_limit_rule`],abrAudioRules:[`throughput_rule`,`min_audio_for_video_rule`],useDynamicBirtateRule:!1,useFailoverHostsOnAllProviderCrash:!1,saveData3gQualityLimit:dy.Q_240P,saveData2gQualityLimit:dy.Q_144P,useConnectionDataUpperLimit:!1,abandon:{minElapsedMs:1500,bufferSafetyFactor:.8,minLoadedFraction:.15,minBufferToActivateMs:500},bola:{bufferTargetMs:3e4,minBufferMs:1e4,minBufferPerBitrateLevelMs:2e3,placeholderBufferDecay:.99,fallbackSegmentDurationMs:4e3,finiteThresholdMs:6e4,adaptiveBufferTargetK:.5,adaptiveBufferTargetMaxMs:6e4,trimDetectThresholdMs:1e4,antiCascadeDownshift:!0},insufficientBuffer:{thresholdMs:500,gracePeriodAfterPlaybackResetMs:1e3,budgetFactor:.5,fallbackSegmentDurationMs:6e3},videoStreamRepresentaionsFilter:[],filterOnDemandQualityList:!1,dashMaxTvVideoQuality:!1,checkRepresentationCanPlayType:!1,preloadFirstSegment:!1,maxQualityForFirstSegmentPreload:dy.Q_480P,tracerResumeOnUnexpectedStall:!1},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,catchupLiveForMutedInactiveTab:!1},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:180*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,useDelayedPlaybackHangupWithData:!1,playbackHangupNoDataThreshold:5e3,hangupTimeoutMs:5e3,endGapTolerance:300,stallIgnoreThreshold:33,stallHandlingStrategy:`exclude-threshold`,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,disableHlsOnDesktop:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,alwaysAbortPreviousSwitch:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useSafariOptimisticPositionForLiveEdgeBugfix:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,autoplayOnlyIfVisible:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1,reuseOwnVideoElement:!1,handleExtendedNetworkErrorsSet:!1,useUrlCacheMechanism:!1,useDurationFromSegments:!0,dropUrlCacheWhenProviderCrashed:!1,ignoreForcePlayResultWhenProviderChanged:!1,hls:{filterOnDemandQualityList:!1},disableSubtitles:!1,audioOnly:!1,readyOnLoadedMetadata:!1},py=e=>uy(e,fy);var Wy=({seekState:e,position$:t})=>By(e.stateChangeEnded$.pipe(Vy(({to:e})=>e.state===`none`?void 0:(e.position??NaN)/1e3),Hy(Uy)),t.pipe(Hy(()=>e.getState().state===`none`)));var Ky=e=>{let t=typeof e.container==`string`?document.getElementById(e.container):e.container;return Gy(t,`Wrong container or containerId {${e.container}}`),t};var Yy=(e,t,n,r)=>{e!==void 0&&t.getState()===void 0&&t.getPrevState()===void 0&&n?.getValue().length===0?n.pipe(qy(e=>e.length>0),Jy()).subscribe(n=>{n.find(r)&&t.startTransitionTo(e)}):(e===void 0||n?.getValue().find(r))&&t.startTransitionTo(e)};var tb=()=>{let e=`mediaCapabilities`in eb().navigator?nb:rb,t=Xy(w(function*(){let t=yield Promise.all(Zy(ib).map(function(){var t=w(function*([t,n]){return{codec:t,supported:yield e(n)}});return function(e){return t.apply(this,arguments)}}())),n=[N.browser.current,...t.map(e=>JSON.stringify(e))].slice(0,16);return $y.push(`core`,{key:`videoplayer_decoding_info`,strings:n}),t}));return()=>Qy(t)},nb=function(){var e=w(function*(e){if(!e)return Promise.resolve({supported:!1});let t={[`channels`in e?`audio`:`video`]:e};return yield eb().navigator.mediaCapabilities.decodingInfo(T({type:`media-source`},t))});return function(t){return e.apply(this,arguments)}}(),rb=e=>{if(!e)return Promise.resolve({supported:!1});let t=eb().document,n=`channels`in e?t.createElement(`audio`):t.createElement(`video`);return Promise.resolve({supported:n.canPlayType(e?.contentType??``)===`probably`})},ib={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}},ab={playbackState$:void 0,position$:0,duration$:1/0,playedTime$:0,muted$:!1,volume$:1,availableVideoStreams$:[],currentVideoStream$:void 0,availableVideoTracks$:[],availableQualities$:[],availableQualitiesFps$:{},currentQuality$:void 0,isAutoQualityEnabled$:!0,autoQualityLimitingAvailable$:!1,autoQualityLimits$:{},predefinedQualityLimitType$:`unknown`,availableAudioStreams$:[],currentAudioStream$:void 0,availableAudioTracks$:[],isAudioAvailable$:!0,currentPlaybackRate$:1,currentBuffer$:{start:0,end:0},currentNativeBuffer$:{start:0,end:0},totalBufferDuration$:0,isBuffering$:!0,isStalled$:!1,stallStartTime$:0,isEnded$:!1,isLooped$:!1,isLive$:void 0,isLiveEnded$:null,canPlayLiveTailBuffer$:!1,canChangePlaybackSpeed$:void 0,atLiveEdge$:void 0,atLiveDurationEdge$:void 0,liveTime$:void 0,liveBufferTime$:void 0,liveLatency$:void 0,currentFormat$:void 0,availableTextTracks$:[],currentTextTrack$:void 0,throughputEstimation$:void 0,rttEstimation$:void 0,videoBitrate$:void 0,hostname$:void 0,httpConnectionType$:void 0,httpConnectionReused$:void 0,httpConnectionMetrics$:void 0,httpDownloadMetrics$:void 0,surface$:`none`,chromecastState$:`NOT_AVAILABLE`,chromecastDeviceName$:void 0,intrinsicVideoSize$:void 0,availableSources$:void 0,currentVideoSegmentLength$:0,currentAudioSegmentLength$:0},ob={audioStream:void 0,autoVideoTrackLimits:{},autoVideoTrackSwitching:!0,currentTextTrack:void 0,externalTextTracks:[],internalTextTracks:[],isLooped:!1,isLowLatency:!1,playbackRate:1,playbackState:`stopped`,seekState:{state:`none`},textTrackCuesSettings:{},videoTrack:void 0,videoStream:void 0,volume:{volume:1,muted:!1}};class sb{constructor(e={},t=Ry.createRootTracer(`fake`),n){this.subscription=new Fy,this.persistentSubscription=new Fy,this.domContainer=null,this.providerContainer=void 0,this.chromecastInitializer=void 0,this.logger=new ky,this.tracer=void 0,this.abrLogger=this.logger.createComponentLog(`ABR`),this.config=void 0,this.tuning=void 0,this.throughputEstimator=void 0,this.internalsExposure=null,this.isPlaybackStarted=!1,this.suppressWillStop=!1,this.initedAt=void 0,this.hasLiveOffsetByPaused=new zy(!1),this.hasLiveOffsetByPausedTimer=0,this.playerInitRequest=0,this.playerInited=new zy(!1),this.explicitInitialQuality=void 0,this.wasSetStartedQuality=!1,this.desiredState=ce(ob).reduce((e,[t,n])=>(e[t]=new mn(n),e),{}),this.info=ce(ab).reduce((e,[t,n])=>(e[t]=new zy(n),e),{}),this.events={inited$:new $,ready$:new $,started$:new $,playing$:new $,paused$:new $,stopped$:new $,willReady$:new $,willStart$:new $,willResume$:new $,willPause$:new $,willStop$:new $,willDestruct$:new $,watchCoverageRecord$:new $,watchCoverageLive$:new $,managedError$:new $,fatalError$:new $,fetcherRecoverableError$:new $,ended$:new $,looped$:new $,seeked$:new $,willSeek$:new $,autoplaySoundProhibited$:new $,manifestRequested$:new $,firstBytesManifest$:new $,manifestReceived$:new $,firstBytesRequested$:new $,firstBytesReceived$:new $,firstBytes$:new $,loadedMetadata$:new $,firstFrame$:new $,canplay$:new $,log$:new $,fetcherError$:new $,severeStallOccured$:new $},this.experimental={element$:new zy(void 0),enableDebugTelemetry$:new zy(!1),dumpTelemetry:si,getCurrentTime$:new zy(null),skipVideoElVolumeSync$:new zy(!1)},this.devNullLog=void 0,this.collectDecodingInfoDestroyCb=void 0,this.hasReleasedTimers=!1,this.doInit=e=>{let{container:t}=e,n=O(e,C);this.tracer.log(`initVideo`,vy(n),!0),this.domContainer=Ky(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Hv({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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,skipVideoElVolumeSync$:this.experimental.skipVideoElVolumeSync$,handleNetworkRecoverableErrorAsProviderError:e.handleNetworkRecoverableErrorAsProviderError}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0),this.devNullLog&&this.tuning.devNullLogEnabled?(gy.subscribe(`core`,this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=tb())):gy.destroy(`core`)},this.initLogs(),this.tuning=py(e),this.tracer=t,Py(this.tuning.useWorkerTimers),this.tuning.suppressExceptionsInObservables&&(le(this.info).forEach(e=>e.setSuppressErrors(!0)),le(this.events).forEach(e=>e.setSuppressErrors(!0)));let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new an(r):new Ee(r),this.throughputEstimator=new ly(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new wy(`core`,by(n?.playerId)),this.internalsExposure.expose({player:this,getTimersDiagnostics:xy})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=n?.onDevNullLog,gy.create(`core`),Proxy&&Reflect)return new Proxy(this,{get:(e,t,n)=>{let r=Reflect.get(e,t,n);return typeof r==`function`?(...n)=>{try{return r.apply(e,n)}catch(e){let r=n.map(e=>JSON.stringify(e,(e,t)=>{let n=typeof t;return ue([`number`,`string`,`boolean`],n)?t:t===null?null:`<${n}>`})),i=`Player.${String(t)}`,a=`Exception calling ${i} (${r.join(`, `)})`;throw this.events.fatalError$.next({id:i,category:_y.WTF,message:a,thrown:e}),e}}:r}})}resetDesiredState(){let e=(e,t)=>{e.setState(t)};Object.keys(this.desiredState).forEach(t=>{e(this.desiredState[t],ob[t])})}reset(){this.subscription.unsubscribe(),this.providerContainer?.destroy(),this.providerContainer=void 0,j.clearTimeout(this.hasLiveOffsetByPausedTimer),this.collectDecodingInfoDestroyCb?.call(this),this.playerInited.next(!1),this.resetDesiredState();let e=(e,t)=>{e.next(t)},t=[`muted$`,`volume$`];Object.keys(this.info).forEach(n=>{ue(t,n)?e(this.info[n],this.info[n].getValue()):e(this.info[n],ab[n])})}initAudio(e){return this.initVideo(T(T({},e),{},{container:e.audioElement??document.createElement(`audio`)}))}initVideo(e){let t=Cy();this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let n=()=>{this.tuning.autoplayOnlyIfVisible&&t.requestAnimationFrame?this.playerInitRequest=t.requestAnimationFrame(()=>this.doInit(e)):this.doInit(e)},r=()=>{this.tuning.asyncResolveClientChecker?N.isInited$.pipe(Y(e=>!!e),Q()).subscribe(()=>{console.log(`Core SDK async start`),n()}):n()};return this.isNotActiveTabCase()?(this.tracer.log(`request play from hidden tab`),yy(t.document,`visibilitychange`).pipe(Q()).subscribe(r)):r(),this}destroy(e){let t=Cy();this.tracer.log(`destroy`),j.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&t.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.suppressWillStop=e?.reportStop===!1,this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.persistentSubscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy(),gy.destroy(`core`),this.collectDecodingInfoDestroyCb?.call(this),this.hasReleasedTimers||(this.hasReleasedTimers=!0,Ny())}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(Y(e=>!!e),Q()).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.tuning.allowPlayerReuse&&this.reset())}),this}seekTime(e,t=!0){return this.waitInit(()=>{let n=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),i=e;e>=n&&!r&&(i=n-this.tuning.seekNearDurationBias),i<0&&!r&&(i=0),this.tracer.log(`seekTime`,{duration:n,isLive:r,time:e,calculatedTime:i,forcePrecise:t}),Number.isFinite(i)&&(this.events.willSeek$.next({from:this.getExactTime(),to:i}),this.desiredState.seekState.setState({state:`requested`,position:i*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,n=!1){return this.waitInit(()=>{this.experimental.skipVideoElVolumeSync$.next(n);let r=this.desiredState.volume,i=r.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||i);this.tracer.log(`setVolume`,{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()===`CONNECTED`&&!(this.chromecastInitializer instanceof an)?this.chromecastInitializer.setVolume(e):r.startTransitionTo({volume:e,muted:a})}),this}setMuted(e,t=!1,n=!1){return this.waitInit(()=>{this.experimental.skipVideoElVolumeSync$.next(n);let r=this.desiredState.volume,i=this.tuning.isAudioDisabled&&!t||e,a=r.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log(`setMuted`,{isMuted:e,nextMuted:i,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()===`CONNECTED`&&!(this.chromecastInitializer instanceof an)?this.chromecastInitializer.setMuted(i):r.startTransitionTo({volume:a,muted:i})}),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(()=>{my(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log(`setQuality`,{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Y(e=>e.length>0),Q()).subscribe(t=>{this.setVideoTrackIdByQuality(t,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`,vy(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:n}=this.tuning.autoTrackSelection,r;switch(e){case`high_quality`:r={min:t,max:void 0};break;case`traffic_saving`:r={max:n,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`,vy(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(e=>T({type:`external`},e)))}),this}selectTextTrack(e){return this.waitInit(()=>{Yy(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log(`selectTextTrack`,{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log(`setTextTrackCueSettings`,T({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),n=this.desiredState.isLowLatency.getState();return!t||n===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()}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Oy(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),n=t.state===`none`?void 0:t.position;return Dy(n)?n/1e3:e.currentTime}getExactLiveTime(){if(!this.providerContainer)return 0;let e=this.desiredState.seekState.getState(),t=e.state===`none`?void 0:e.position;return(Dy(t)?t:this.info.liveTime$.getValue()??0)/1e3}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){let t={width:e.reduce((e,{width:t})=>e||t||0,0),height:e.reduce((e,{height:t})=>e||t||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.persistentSubscription.add(jy(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:n}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(hi(e,t,n))})).add(jy(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Y(({from:e})=>e===`stopped`)).subscribe(()=>{this.initedAt=My(),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.suppressWillStop||this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let e=this.desiredState.seekState.getState();this.tracer.log(`willSeekEvent`,vy(e)),e.state===`requested`?this.desiredState.seekState.setState(T(T({},e),{},{state:`applying`})):this.events.managedError$.next({id:`WillSeekIn${e.state}`,category:_y.WTF,message:`Received unexpeceted willSeek$`})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Q()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let e=this.desiredState.seekState.getState();this.tracer.log(`seekedEvent`,vy(e)),e.state===`applying`&&(this.desiredState.seekState.setState({state:`none`}),this.events.seeked$.next())})).add(e.current$.pipe(Z(e=>e.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Z(e=>e.destination),X()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.subscribe(this.info.availableVideoTracks$)).add(hy({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Z(({availableVideoTracks:e,currentVideoStream:t})=>e.filter(e=>t?t.id===e.streamId:!0).map(({quality:e})=>e).sort((e,t)=>Ey(e)?1:Ey(t)?-1:Ty(t,e)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(e=>{let t={};for(let n of e)n.fps&&(t[n.quality]=n.fps);this.info.availableQualitiesFps$.next(t)})).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(X()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(Y(e=>Dy(e))).subscribe(e=>{this.info.currentQuality$.next(e?.quality),this.info.videoBitrate$.next(e?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(X((e,t)=>Math.round(e)===Math.round(t))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(X((e,t)=>Math.round(e)===Math.round(t))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(X()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(X()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(X()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.httpConnectionMetrics$.pipe(X()).subscribe(this.info.httpConnectionMetrics$)).add(e.providerOutput.httpDownloadMetrics$.pipe(X()).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(e=>{this.desiredState.autoVideoTrackLimits.setState(e??{})})).add(e.providerOutput.currentBuffer$.pipe(Z(e=>e?{start:e.from,end:e.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe(Z(e=>e?{start:e.from,end:e.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).add(e.providerOutput.totalBufferDuration$.subscribe(this.info.totalBufferDuration$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.playedTime$.subscribe(this.info.playedTime$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Iy(e=>e&&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$.pipe(X()).subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(hy({hasLiveOffsetByPaused:jy(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Z(e=>e.to),X(),Z(e=>e===`paused`)),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:e,isLowLatency:t})=>{if(j.clearTimeout(this.hasLiveOffsetByPausedTimer),e){this.hasLiveOffsetByPausedTimer=j.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(t));return}this.hasLiveOffsetByPaused.next(!1)})).add(hy({atLiveEdge:hy({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Wy({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Z(({isLive:e,position:t,isLowLatency:n})=>{let r=this.getActiveLiveDelay(n);return e&&Math.abs(t)<r/1e3}),X(),Iy(e=>e&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Z(({atLiveEdge:e,hasPausedTimeoutCase:t})=>e&&!t)).subscribe(this.info.atLiveEdge$)).add(hy({isLive:e.providerOutput.isLive$,position:N.browser.isSafari&&this.tuning.useSafariOptimisticPositionForLiveEdgeBugfix?Wy({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}):e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Z(({isLive:e,position:t,duration:n})=>e&&(Math.abs(n)-Math.abs(t))*1e3<this.tuning.live.activeLiveDelay),X(),Iy(e=>e&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Z(e=>e.muted),X()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Z(e=>e.volume),X()).subscribe(this.info.volume$)).add(Wy({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(jy(e.providerOutput.endedEvent$.pipe(Ay(!0)),e.providerOutput.seekedEvent$.pipe(Ay(!1))).pipe(X()).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.updateDurationError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.pipe(Y(e=>e.category===_y.FATAL)).subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(Z(({forced:e,input:t,supported:n})=>{let r,i;return e?(r=`NoForcedFormat`,i=`${e} was forced but failed or not available`):n.length?(r=`NoFormats`,i=`All formats failed`):t.length?(r=`NoSupportedFormats`,i=`No supported formats`):(r=`NoInputFormats`,i=`No formats supplied`),my(r),{id:r,category:_y.VIDEO_PIPELINE,message:i}})).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(Q()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(Q()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(Q()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(Q()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(Q()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(Q(),Z(e=>e??My()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Q(),Z(()=>My()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Q(),Z(()=>My()-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 zy(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let n=new zy(!0);this.subscription.add(e.current$.subscribe(()=>n.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Y(({to:e})=>e===`playing`),Q()).subscribe(()=>n.next(!1)));let r=0,i=0,a=jy(e.providerOutput.isBuffering$,t,n).pipe(Z(()=>{let r=e.providerOutput.isBuffering$.getValue(),i=t.getValue()||n.getValue();return r&&!i}),X());this.subscription.add(a.subscribe(e=>{let{stallIgnoreThreshold:t,stallHandlingStrategy:n}=this.tuning;e?(i=My(),n===`verbose`&&this.info.stallStartTime$.next(i),r=j.setTimeout(()=>{this.info.isStalled$.next(!0),i&&this.info.stallStartTime$.next(n===`exclude-threshold`?My():i)},t)):(j.clearTimeout(r),this.info.isStalled$.next(!1),i=0,this.info.stallStartTime$.next(0))})),this.subscription.add(jy(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let t=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:t?.videoWidth,height:t?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(t=>{var n,r;let i=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:t==null||(n=t.size)==null?void 0:n.width,height:t==null||(r=t.size)==null?void 0:r.height},{width:i?.videoWidth,height:i?.videoHeight})})),this.subscription.add(jy(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let t=e.providerOutput.inPiP$.getValue(),n=e.providerOutput.inFullscreen$.getValue(),r=e.providerOutput.element$.getValue(),i=e.providerOutput.elementVisible$.getValue(),a=this.chromecastInitializer.castState$.getValue(),o;o=a===`CONNECTED`?`second_screen`:r?i?t?`pip`:n?`fullscreen`:`inline`:`invisible`:`none`,this.info.surface$.getValue()!==o&&this.info.surface$.next(o)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Z(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Fy;this.subscription.add(t),this.subscription.add(e.current$.pipe(X((e,t)=>e.provider===t.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Y(e=>e.length>0),Q()).subscribe(e=>{this.setStartingVideoTrack(e)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let n=this.explicitInitialQuality??this.info.currentQuality$.getValue();n&&(t=e.find(({quality:e,tvDisabled:t})=>e===n&&!t),t||this.setAutoQuality(!0)),!t&&(t=Ni(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.persistentSubscription.add(jy(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.persistentSubscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;my(this.providerContainer),my(e),oi(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(e=>ai(e)),this.providerContainer.current$.subscribe(({type:e})=>ci(`provider`,e)),e.duration$.subscribe(e=>ci(`duration`,e)),e.availableVideoTracks$.pipe(Y(e=>!!e.length),Q()).subscribe(e=>ci(`tracks`,e)),this.events.fatalError$.subscribe(new li(`fatalError`)),this.events.managedError$.subscribe(new li(`managedError`)),e.position$.subscribe(new li(`position`)),e.currentVideoTrack$.pipe(Z(e=>e?.quality)).subscribe(new li(`quality`)),this.info.currentBuffer$.subscribe(new li(`buffer`)),e.isBuffering$.subscribe(new li(`isBuffering`))].forEach(e=>this.subscription.add(e)),ci(`codecs`,N.video.supportedCodecs)}initTracerSubscription(){let e=Sy(this.tracer.log.bind(this.tracer)),t=Sy(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(X()).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(hy({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(Y(({currentQuality:e,videoBitrate:t})=>!!e&&!!t),X((e,t)=>e.currentQuality===t.currentQuality)).subscribe(e(`currentVideoTrack`))).add(this.info.currentVideoSegmentLength$.pipe(Y(e=>e>0),X()).subscribe(e(`currentVideoSegmentLength`))).add(this.info.currentAudioSegmentLength$.pipe(Y(e=>e>0),X()).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(hy({currentBuffer:this.info.currentBuffer$.pipe(Y(e=>e.end>0),X((e,t)=>e.end===t.end&&e.start===t.start)),position:this.info.position$.pipe(X())}).pipe(Ly(1e3)).subscribe(e(`currentBufferAndPosition`))).add(this.info.duration$.pipe(X()).subscribe(e(`duration`))).add(this.info.isBuffering$.subscribe(e(`isBuffering`))).add(this.info.isLive$.pipe(X()).subscribe(e(`isLive`))).add(this.info.canChangePlaybackSpeed$.pipe(X()).subscribe(e(`canChangePlaybackSpeed`))).add(hy({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Y(({liveTime:e,liveBufferTime:t})=>!!e&&!!t),Ly(1e3)).subscribe(e(`liveBufferAndPosition`))).add(this.info.atLiveEdge$.pipe(X(),Y(e=>e===!0)).subscribe(e(`atLiveEdge`))).add(this.info.atLiveDurationEdge$.pipe(X(),Y(e=>e===!0)).subscribe(e(`atLiveDurationEdge`))).add(this.info.muted$.pipe(X()).subscribe(e(`muted`))).add(this.info.volume$.pipe(X()).subscribe(e(`volume`))).add(this.info.isEnded$.pipe(X(),Y(e=>e===!0)).subscribe(e(`isEnded`))).add(this.info.availableSources$.subscribe(e(`availableSources`))).add(hy({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Y(({throughputEstimation:e,rtt:t})=>!!e&&!!t),Ly(3e3)).subscribe(e(`throughputEstimation`))).add(this.info.isStalled$.subscribe(e(`isStalled`))).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(){var e=this;let t=Cy();if(!t.navigator.wakeLock||!this.tuning.enableWakeLock)return;let n,r=()=>{n?.release(),n=void 0},i=function(){var t=w(function*(){r(),n=yield window.navigator.wakeLock.request(`screen`).catch(t=>{t instanceof DOMException&&t.name===`NotAllowedError`||e.events.managedError$.next({id:`WakeLock`,category:_y.DOM,message:String(t)})})});return function(){return t.apply(this,arguments)}}();this.subscription.add(jy(yy(t.document,`visibilitychange`),yy(t.document,`fullscreenchange`),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let e=t.document.visibilityState===`visible`,a=this.desiredState.playbackState.getState()===`playing`,o=!!n&&!n?.released;e&&a?o||i():r()})).add(this.events.willDestruct$.subscribe(r))}setVideoTrackIdByQuality(e,t){let n=e.find(e=>e.quality===t);this.tracer.log(`setVideoTrackIdByQuality`,vy({quality:t,availableTracks:vy(e),track:vy(n),isAutoQuality:!n})),n?n.tvDisabled?(this.setAutoQuality(!0),this.events.managedError$.next({id:`SetQualityTrackTvDisabled`,category:_y.WTF,message:`Set quality was called on track with tvDisabled flag`})):this.desiredState.videoTrack.startTransitionTo(n):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return Cy().document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ya()}}var pb=`@vkontakte/videoplayer-core@${ee}`;;return{lt,N,Lt,$a,fb,ne,re,db,ee,oe,cb,ub,pb,se,sb,te,lb,ae,ie};}();var{lt:_oxcMod2yytt7_lt,N:_oxcMod2yytt7_N,Lt:_oxcMod2yytt7_Lt,$a:_oxcMod2yytt7_$a,fb:_oxcMod2yytt7_fb,ne:_oxcMod2yytt7_ne,re:_oxcMod2yytt7_re,db:_oxcMod2yytt7_db,ee:_oxcMod2yytt7_ee,oe:_oxcMod2yytt7_oe,cb:_oxcMod2yytt7_cb,ub:_oxcMod2yytt7_ub,pb:_oxcMod2yytt7_pb,se:_oxcMod2yytt7_se,sb:_oxcMod2yytt7_sb,te:_oxcMod2yytt7_te,lb:_oxcMod2yytt7_lb,ae:_oxcMod2yytt7_ae,ie:_oxcMod2yytt7_ie}=_oxcMod2yytt7;export{_oxcMod2yytt7_lt as isMobile,_oxcMod2yytt7_N as clientChecker,_oxcMod2yytt7_Lt as areValidLiveRecordSources,_oxcMod2yytt7_$a as WebmCodecStrategy,_oxcMod2yytt7_fb as VideoQuality,_oxcMod2yytt7_ne as VideoFormat,_oxcMod2yytt7_re as VideoCodecName,_oxcMod2yytt7_db as ValueSubject,_oxcMod2yytt7_ee as VERSION,_oxcMod2yytt7_oe as Surface,_oxcMod2yytt7_cb as Subscription,_oxcMod2yytt7_ub as Subject,_oxcMod2yytt7_pb as SDK_VERSION,_oxcMod2yytt7_se as PredefinedQualityLimits,_oxcMod2yytt7_sb as Player,_oxcMod2yytt7_te as PlaybackState,_oxcMod2yytt7_lb as Observable,_oxcMod2yytt7_ae as HttpConnectionType,_oxcMod2yytt7_ie as ChromecastState};
250
+ ===== DASH_LIVE DEBUG END ====`),n){let t=e.reduce((e,{time:t,data:n,stack:r})=>{let i=sn(n).map(([e,t])=>`${e}:${t}`).join(`,`);return e+=`${t}: ${i}${r?`: ${r}`:``};`,e},``);K_.push(`core`,{key:`vp_dash_live_debug`,strings:[t]})}};return e.add(this.providerError$.subscribe(e=>{e.id.startsWith(`ProviderHangup`)&&(z({m:`final.0`,e:e.id}),t())})).add(this.noAvailableProvidersError$.subscribe(()=>{z({m:`final.1`}),t()})),e.add(this.mayday.recommendation$.subscribe(({error:e,recommendation:t})=>{let n=this.current$.getValue(),r=n.destination??`SCREEN`;this.applyErrorSideEffects(e,n.type),this.handleMaydayRecommendation(t,r);let i={error:e,currentDestination:r,action:t.action,reason:t.reason};e.traceAsLog?this.tracer.log(`providerInfo`,G_(i)):this.tracer.error(`providerError`,G_(i))})),e.add(this.providerError$.subscribe(e=>{let{destination:t}=this.current$.getValue();t===`CHROMECAST`?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(`CHROMECAST`),()=>this.params.dependencies.chromecastInitializer.disconnect())):this.mayday.handleError(e)})),e}}var ey=`vk_uvp_throughput`,ty=`vk_uvp_rtt`,ny=`one_video_throughput`,ry=`one_video_rtt`,iy=()=>{let{navigator:e}=$v();if(e)return e.connection},ay=()=>{let e=iy()?.downlink;if(Xv(e)&&e!==10)return e*1e3},oy=()=>{let e=iy()?.rtt;if(Xv(e)&&e!==3e3)return e},sy=(e,t,n)=>{let r=n*8;return r/(r/e+t)};class cy{constructor(e){this.throughput=void 0,this.rtt=void 0,this.subscription=new Kv,this.tuningConfig=void 0,this.concurrentDownloads=new Set,this.throughput$=void 0,this.rtt$=void 0,this.rttAdjustedThroughput$=void 0,this.tuningConfig=e;let t=cy.loadStored(ey,ny,e)||(e.useBrowserEstimation?ay():void 0)||e.initialThroughput,n=cy.loadStored(ty,ry,e)??(e.useBrowserEstimation?oy():void 0)??0;if(this.throughput$=new qv(t),this.rtt$=new qv(n),this.rttAdjustedThroughput$=new qv(sy(t,n,e.rttPenaltyRequestSize)),this.throughput=Dp.getSmoothedValue(t,-1,e),this.rtt=Dp.getSmoothedValue(n,1,e),e.useBrowserEstimation){let e=()=>{let e=ay();e&&this.throughput.next(e);let t=oy();Xv(t)&&this.rtt.next(t)},t=iy();t&&`onchange`in t&&this.subscription.add(Uv(t,`change`).subscribe(e)),e()}this.subscription.add(this.throughput.smoothed$.subscribe(t=>{cy.writeStored(ey,ny,t,e)})),this.subscription.add(this.rtt.smoothed$.subscribe(t=>{cy.writeStored(ty,ry,t,e)})),this.subscription.add(this.throughput.debounced$.pipe(Jv(e=>Math.round(e))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Gv({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Jv(({throughput:t,rtt:n})=>sy(t,n,e.rttPenaltyRequestSize)),Yv(t=>{let n=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-n)/n>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,n=Zv(),r=new Kv;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Uv(e,`progress`).pipe(Wv()).subscribe(e=>{t=e.loaded,n=Zv()}));break;case 1:case 0:r.add(Uv(e,`loadstart`).subscribe(()=>{t=0,n=Zv()}));break}r.add(Uv(e,`loadend`).subscribe(i=>{if(e.status===200){let e=i.loaded,r=Zv(),a=e-t,o=r-n;this.addRawSpeed(a,o,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){var n=this;let r=e.getReader();if(!r){e.cancel(`Could not get reader`);return}let i=0,a=Zv(),o=0,s=Zv(),c=t=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${t}`).catch(()=>{})},l=function(){var u=w(function*({done:u,value:d}){if(u)!t&&n.addRawSpeed(i,Zv()-a,1),n.concurrentDownloads.delete(e);else if(d){if(t){let e=Zv();if(e-s>n.tuningConfig.lowLatency.continuesByteSequenceInterval||e-a>n.tuningConfig.lowLatency.maxLastEvaluationTimeout){let e=s-a;e&&n.addRawSpeed(o,e,1,t),o=d.byteLength,a=Zv()}else o+=d.byteLength;s=Zv()}else i+=d.byteLength,o+=d.byteLength,o>=n.tuningConfig.streamMinSampleSize&&Zv()-s>=n.tuningConfig.streamMinSampleTime&&(n.addRawSpeed(o,Zv()-s,n.concurrentDownloads.size),o=0,s=Zv());yield r?.read().then(l,c)}});return function(e){return u.apply(this,arguments)}}();this.concurrentDownloads.add(e),r?.read().then(l,c)}addRawSpeed(e,t,n=1,r=!1){if(this.sanityCheck(e,t,r)){let r=e*8/t;this.throughput.next(r*n)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}sanityCheck(e,t,n=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||n&&e<1e4||!n&&e<10*1024&&(!this.tuningConfig.measureNonSegmentRequests||t<this.tuningConfig.smallSampleMinDuration+this.rtt$.getValue())||!n&&!this.tuningConfig.measureFastSamples&&t<=this.tuningConfig.cacheThresholdSize)}get throughputVariance$(){return this.throughput.varianceCoefficient$}static loadStored(e,t,n){if(!n.useThroughputTtl){let e=Qv.get(t);if(!Xv(e))return;let n=parseInt(e,10);return isNaN(n)?void 0:n}let r=Qv.get(e)??Qv.get(t);if(Xv(r))try{let e=JSON.parse(r);if(typeof e==`object`&&e&&typeof e.value==`number`)return cy.validateStored(e,n)}catch{}}static writeStored(e,t,n,r){if(!r.useThroughputTtl){Qv.set(t,n.toFixed(0));return}let i=JSON.stringify({value:Math.round(n),timestamp:Date.now(),networkType:iy()?.effectiveType});Qv.set(e,i)}static validateStored(e,t){if(!t.useThroughputTtl)return e.value;if(Date.now()-e.timestamp>t.storedThroughputTtlMs)return;let n=iy()?.effectiveType;if(!(n!==void 0&&e.networkType!==void 0&&n!==e.networkType))return e.value}}var ly=cy;var fy={mayday:{playingUnstableThresholdMs:3e3,heuristics:[]},allowPlayerReuse:!1,useWorkerTimers:[],throughputEstimator:{type:`EmaAndMa`,emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,initialThroughput:5e3,measureNonSegmentRequests:!1,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,smallSampleMinDuration:100,cacheThresholdSize:20,measureFastSamples:!1,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300},useThroughputTtl:!1,storedThroughputTtlMs:144e5},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:dy.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:dy.Q_720P,trafficSavingLimit:dy.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,ignoreStallsOnPause:!1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:dy.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,audioBufferAheadOfVideoMs:6e4,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:6e4,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,restoreBufferBeforeCrashTimeout:1e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,virtualBufferEmptinessTolerance:100,useBufferQueueVerification:!1,useVirtualBufferImplicitSeek:!1,bufferQueueVerificationMinPosition:2e3,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,stallForceSeekOncePerStall:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,minNativeBufferSize:5e3,removeTimeShiftFromSegment:500,tickMaintainInterval:100,minSafeBufferToPlay:0,useBufferHoldingOnlyOnStall:!0,useNewAbr:!1,useAbrPhases:!1,abrVideoRules:[`fits_container_rule`,`throughput_rule`,`buffer_rule`,`stalls_rule`,`upper_limit_rule`,`lower_limit_rule`],abrAudioRules:[`throughput_rule`,`min_audio_for_video_rule`],useDynamicBirtateRule:!1,useFailoverHostsOnAllProviderCrash:!1,saveData3gQualityLimit:dy.Q_240P,saveData2gQualityLimit:dy.Q_144P,useConnectionDataUpperLimit:!1,abandon:{minElapsedMs:1500,bufferSafetyFactor:.8,minLoadedFraction:.15,minBufferToActivateMs:500},bola:{bufferTargetMs:3e4,minBufferMs:1e4,minBufferPerBitrateLevelMs:2e3,placeholderBufferDecay:.99,fallbackSegmentDurationMs:4e3,finiteThresholdMs:6e4,adaptiveBufferTargetK:.5,adaptiveBufferTargetMaxMs:6e4,trimDetectThresholdMs:1e4,antiCascadeDownshift:!0},insufficientBuffer:{thresholdMs:500,gracePeriodAfterPlaybackResetMs:1e3,budgetFactor:.5,fallbackSegmentDurationMs:6e3},videoStreamRepresentaionsFilter:[],filterOnDemandQualityList:!1,dashMaxTvVideoQuality:!1,checkRepresentationCanPlayType:!1,preloadFirstSegment:!1,maxQualityForFirstSegmentPreload:dy.Q_480P,tracerResumeOnUnexpectedStall:!1},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,catchupLiveForMutedInactiveTab:!1},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:180*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,useDelayedPlaybackHangupWithData:!1,playbackHangupNoDataThreshold:5e3,hangupTimeoutMs:5e3,endGapTolerance:300,stallIgnoreThreshold:33,stallHandlingStrategy:`exclude-threshold`,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,disableHlsOnDesktop:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,alwaysAbortPreviousSwitch:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useSafariOptimisticPositionForLiveEdgeBugfix:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,autoplayOnlyIfVisible:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1,reuseOwnVideoElement:!1,handleExtendedNetworkErrorsSet:!1,useUrlCacheMechanism:!1,useDurationFromSegments:!0,dropUrlCacheWhenProviderCrashed:!1,ignoreForcePlayResultWhenProviderChanged:!1,hls:{filterOnDemandQualityList:!1},disableSubtitles:!1,audioOnly:!1,readyOnLoadedMetadata:!1},py=e=>uy(e,fy);var Wy=({seekState:e,position$:t})=>By(e.stateChangeEnded$.pipe(Vy(({to:e})=>e.state===`none`?void 0:(e.position??NaN)/1e3),Hy(Uy)),t.pipe(Hy(()=>e.getState().state===`none`)));var Ky=e=>{let t=typeof e.container==`string`?document.getElementById(e.container):e.container;return Gy(t,`Wrong container or containerId {${e.container}}`),t};var Yy=(e,t,n,r)=>{e!==void 0&&t.getState()===void 0&&t.getPrevState()===void 0&&n?.getValue().length===0?n.pipe(qy(e=>e.length>0),Jy()).subscribe(n=>{n.find(r)&&t.startTransitionTo(e)}):(e===void 0||n?.getValue().find(r))&&t.startTransitionTo(e)};var tb=()=>{let e=`mediaCapabilities`in eb().navigator?nb:rb,t=Xy(w(function*(){let t=yield Promise.all(Zy(ib).map(function(){var t=w(function*([t,n]){return{codec:t,supported:yield e(n)}});return function(e){return t.apply(this,arguments)}}())),n=[N.browser.current,...t.map(e=>JSON.stringify(e))].slice(0,16);return $y.push(`core`,{key:`videoplayer_decoding_info`,strings:n}),t}));return()=>Qy(t)},nb=function(){var e=w(function*(e){if(!e)return Promise.resolve({supported:!1});let t={[`channels`in e?`audio`:`video`]:e};return yield eb().navigator.mediaCapabilities.decodingInfo(T({type:`media-source`},t))});return function(t){return e.apply(this,arguments)}}(),rb=e=>{if(!e)return Promise.resolve({supported:!1});let t=eb().document,n=`channels`in e?t.createElement(`audio`):t.createElement(`video`);return Promise.resolve({supported:n.canPlayType(e?.contentType??``)===`probably`})},ib={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}},ab={playbackState$:void 0,position$:0,duration$:1/0,playedTime$:0,muted$:!1,volume$:1,availableVideoStreams$:[],currentVideoStream$:void 0,availableVideoTracks$:[],availableQualities$:[],availableQualitiesFps$:{},currentQuality$:void 0,isAutoQualityEnabled$:!0,autoQualityLimitingAvailable$:!1,autoQualityLimits$:{},predefinedQualityLimitType$:`unknown`,availableAudioStreams$:[],currentAudioStream$:void 0,availableAudioTracks$:[],isAudioAvailable$:!0,currentPlaybackRate$:1,currentBuffer$:{start:0,end:0},currentNativeBuffer$:{start:0,end:0},totalBufferDuration$:0,isBuffering$:!0,isStalled$:!1,stallStartTime$:0,isEnded$:!1,isLooped$:!1,isLive$:void 0,isLiveEnded$:null,canPlayLiveTailBuffer$:!1,canChangePlaybackSpeed$:void 0,atLiveEdge$:void 0,atLiveDurationEdge$:void 0,liveTime$:void 0,liveBufferTime$:void 0,liveLatency$:void 0,currentFormat$:void 0,availableTextTracks$:[],currentTextTrack$:void 0,throughputEstimation$:void 0,rttEstimation$:void 0,videoBitrate$:void 0,hostname$:void 0,httpConnectionType$:void 0,httpConnectionReused$:void 0,httpConnectionMetrics$:void 0,httpDownloadMetrics$:void 0,surface$:`none`,chromecastState$:`NOT_AVAILABLE`,chromecastDeviceName$:void 0,intrinsicVideoSize$:void 0,availableSources$:void 0,currentVideoSegmentLength$:0,currentAudioSegmentLength$:0},ob={audioStream:void 0,autoVideoTrackLimits:{},autoVideoTrackSwitching:!0,currentTextTrack:void 0,externalTextTracks:[],internalTextTracks:[],isLooped:!1,isLowLatency:!1,playbackRate:1,playbackState:`stopped`,seekState:{state:`none`},textTrackCuesSettings:{},videoTrack:void 0,videoStream:void 0,volume:{volume:1,muted:!1}};class sb{constructor(e={},t=Ry.createRootTracer(`fake`),n){this.subscription=new Fy,this.persistentSubscription=new Fy,this.domContainer=null,this.providerContainer=void 0,this.chromecastInitializer=void 0,this.logger=new ky,this.tracer=void 0,this.abrLogger=this.logger.createComponentLog(`ABR`),this.config=void 0,this.tuning=void 0,this.throughputEstimator=void 0,this.internalsExposure=null,this.isPlaybackStarted=!1,this.suppressWillStop=!1,this.initedAt=void 0,this.hasLiveOffsetByPaused=new zy(!1),this.hasLiveOffsetByPausedTimer=0,this.playerInitRequest=0,this.playerInited=new zy(!1),this.explicitInitialQuality=void 0,this.wasSetStartedQuality=!1,this.desiredState=ce(ob).reduce((e,[t,n])=>(e[t]=new mn(n),e),{}),this.info=ce(ab).reduce((e,[t,n])=>(e[t]=new zy(n),e),{}),this.events={inited$:new $,ready$:new $,started$:new $,playing$:new $,paused$:new $,stopped$:new $,willReady$:new $,willStart$:new $,willResume$:new $,willPause$:new $,willStop$:new $,willDestruct$:new $,watchCoverageRecord$:new $,watchCoverageLive$:new $,managedError$:new $,fatalError$:new $,fetcherRecoverableError$:new $,ended$:new $,looped$:new $,seeked$:new $,willSeek$:new $,autoplaySoundProhibited$:new $,manifestRequested$:new $,firstBytesManifest$:new $,manifestReceived$:new $,firstBytesRequested$:new $,firstBytesReceived$:new $,firstBytes$:new $,loadedMetadata$:new $,firstFrame$:new $,canplay$:new $,log$:new $,fetcherError$:new $,severeStallOccured$:new $},this.experimental={element$:new zy(void 0),enableDebugTelemetry$:new zy(!1),dumpTelemetry:si,getCurrentTime$:new zy(null),skipVideoElVolumeSync$:new zy(!1)},this.devNullLog=void 0,this.collectDecodingInfoDestroyCb=void 0,this.hasReleasedTimers=!1,this.doInit=e=>{let{container:t}=e,n=O(e,C);this.tracer.log(`initVideo`,vy(n),!0),this.domContainer=Ky(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Hv({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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,skipVideoElVolumeSync$:this.experimental.skipVideoElVolumeSync$,handleNetworkRecoverableErrorAsProviderError:e.handleNetworkRecoverableErrorAsProviderError}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0),this.devNullLog&&this.tuning.devNullLogEnabled?(gy.subscribe(`core`,this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=tb())):gy.destroy(`core`)},this.initLogs(),this.tuning=py(e),this.tracer=t,Py(this.tuning.useWorkerTimers),this.tuning.suppressExceptionsInObservables&&(le(this.info).forEach(e=>e.setSuppressErrors(!0)),le(this.events).forEach(e=>e.setSuppressErrors(!0)));let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new an(r):new Ee(r),this.throughputEstimator=new ly(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new wy(`core`,by(n?.playerId)),this.internalsExposure.expose({player:this,getTimersDiagnostics:xy})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=n?.onDevNullLog,gy.create(`core`),Proxy&&Reflect)return new Proxy(this,{get:(e,t,n)=>{let r=Reflect.get(e,t,n);return typeof r==`function`?(...n)=>{try{return r.apply(e,n)}catch(e){let r=n.map(e=>JSON.stringify(e,(e,t)=>{let n=typeof t;return ue([`number`,`string`,`boolean`],n)?t:t===null?null:`<${n}>`})),i=`Player.${String(t)}`,a=`Exception calling ${i} (${r.join(`, `)})`;throw this.events.fatalError$.next({id:i,category:_y.WTF,message:a,thrown:e}),e}}:r}})}resetDesiredState(){let e=(e,t)=>{e.setState(t)};Object.keys(this.desiredState).forEach(t=>{e(this.desiredState[t],ob[t])})}reset(){this.subscription.unsubscribe(),this.providerContainer?.destroy(),this.providerContainer=void 0,j.clearTimeout(this.hasLiveOffsetByPausedTimer),this.collectDecodingInfoDestroyCb?.call(this),this.playerInited.next(!1),this.resetDesiredState();let e=(e,t)=>{e.next(t)},t=[`muted$`,`volume$`];Object.keys(this.info).forEach(n=>{ue(t,n)?e(this.info[n],this.info[n].getValue()):e(this.info[n],ab[n])})}initAudio(e){return this.initVideo(T(T({},e),{},{container:e.audioElement??document.createElement(`audio`)}))}initVideo(e){let t=Cy();this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let n=()=>{this.tuning.autoplayOnlyIfVisible&&t.requestAnimationFrame?this.playerInitRequest=t.requestAnimationFrame(()=>this.doInit(e)):this.doInit(e)},r=()=>{this.tuning.asyncResolveClientChecker?N.isInited$.pipe(Y(e=>!!e),Q()).subscribe(()=>{console.log(`Core SDK async start`),n()}):n()};return this.isNotActiveTabCase()?(this.tracer.log(`request play from hidden tab`),yy(t.document,`visibilitychange`).pipe(Q()).subscribe(r)):r(),this}destroy(e){let t=Cy();this.tracer.log(`destroy`),j.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&t.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.suppressWillStop=e?.reportStop===!1,this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.persistentSubscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy(),gy.destroy(`core`),this.collectDecodingInfoDestroyCb?.call(this),this.hasReleasedTimers||(this.hasReleasedTimers=!0,Ny())}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(Y(e=>!!e),Q()).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.tuning.allowPlayerReuse&&this.reset())}),this}seekTime(e,t=!0){return this.waitInit(()=>{let n=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),i=e;e>=n&&!r&&(i=n-this.tuning.seekNearDurationBias),i<0&&!r&&(i=0),this.tracer.log(`seekTime`,{duration:n,isLive:r,time:e,calculatedTime:i,forcePrecise:t}),Number.isFinite(i)&&(this.events.willSeek$.next({from:this.getExactTime(),to:i}),this.desiredState.seekState.setState({state:`requested`,position:i*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,n=!1){return this.waitInit(()=>{this.experimental.skipVideoElVolumeSync$.next(n);let r=this.desiredState.volume,i=r.getTransition()?.to.muted??this.info.muted$.getValue(),a=t??(this.tuning.isAudioDisabled||i);this.tracer.log(`setVolume`,{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:a}),this.chromecastInitializer.castState$.getValue()===`CONNECTED`&&!(this.chromecastInitializer instanceof an)?this.chromecastInitializer.setVolume(e):r.startTransitionTo({volume:e,muted:a})}),this}setMuted(e,t=!1,n=!1){return this.waitInit(()=>{this.experimental.skipVideoElVolumeSync$.next(n);let r=this.desiredState.volume,i=this.tuning.isAudioDisabled&&!t||e,a=r.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log(`setMuted`,{isMuted:e,nextMuted:i,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()===`CONNECTED`&&!(this.chromecastInitializer instanceof an)?this.chromecastInitializer.setMuted(i):r.startTransitionTo({volume:a,muted:i})}),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(()=>{my(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log(`setQuality`,{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Y(e=>e.length>0),Q()).subscribe(t=>{this.setVideoTrackIdByQuality(t,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`,vy(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:n}=this.tuning.autoTrackSelection,r;switch(e){case`high_quality`:r={min:t,max:void 0};break;case`traffic_saving`:r={max:n,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`,vy(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(e=>T({type:`external`},e)))}),this}selectTextTrack(e){return this.waitInit(()=>{Yy(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log(`selectTextTrack`,{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log(`setTextTrackCueSettings`,T({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),n=this.desiredState.isLowLatency.getState();return!t||n===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()}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Oy(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),n=t.state===`none`?void 0:t.position;return Dy(n)?n/1e3:e.currentTime}getExactLiveTime(){if(!this.providerContainer)return 0;let e=this.desiredState.seekState.getState(),t=e.state===`none`?void 0:e.position;return(Dy(t)?t:this.info.liveTime$.getValue()??0)/1e3}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){let t={width:e.reduce((e,{width:t})=>e||t||0,0),height:e.reduce((e,{height:t})=>e||t||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.persistentSubscription.add(jy(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:n}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(hi(e,t,n))})).add(jy(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Y(({from:e})=>e===`stopped`)).subscribe(()=>{this.initedAt=My(),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.suppressWillStop||this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let e=this.desiredState.seekState.getState();this.tracer.log(`willSeekEvent`,vy(e)),e.state===`requested`?this.desiredState.seekState.setState(T(T({},e),{},{state:`applying`})):this.events.managedError$.next({id:`WillSeekIn${e.state}`,category:_y.WTF,message:`Received unexpeceted willSeek$`})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Q()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let e=this.desiredState.seekState.getState();this.tracer.log(`seekedEvent`,vy(e)),e.state===`applying`&&(this.desiredState.seekState.setState({state:`none`}),this.events.seeked$.next())})).add(e.current$.pipe(Z(e=>e.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Z(e=>e.destination),X()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.subscribe(this.info.availableVideoTracks$)).add(hy({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Z(({availableVideoTracks:e,currentVideoStream:t})=>e.filter(e=>t?t.id===e.streamId:!0).map(({quality:e})=>e).sort((e,t)=>Ey(e)?1:Ey(t)?-1:Ty(t,e)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(e=>{let t={};for(let n of e)n.fps&&(t[n.quality]=n.fps);this.info.availableQualitiesFps$.next(t)})).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(X()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(Y(e=>Dy(e))).subscribe(e=>{this.info.currentQuality$.next(e?.quality),this.info.videoBitrate$.next(e?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(X((e,t)=>Math.round(e)===Math.round(t))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(X((e,t)=>Math.round(e)===Math.round(t))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(X()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(X()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(X()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.httpConnectionMetrics$.pipe(X()).subscribe(this.info.httpConnectionMetrics$)).add(e.providerOutput.httpDownloadMetrics$.pipe(X()).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(e=>{this.desiredState.autoVideoTrackLimits.setState(e??{})})).add(e.providerOutput.currentBuffer$.pipe(Z(e=>e?{start:e.from,end:e.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.currentNativeBuffer$.pipe(Z(e=>e?{start:e.from,end:e.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).add(e.providerOutput.totalBufferDuration$.subscribe(this.info.totalBufferDuration$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.playedTime$.subscribe(this.info.playedTime$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Iy(e=>e&&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$.pipe(X()).subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(hy({hasLiveOffsetByPaused:jy(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Z(e=>e.to),X(),Z(e=>e===`paused`)),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:e,isLowLatency:t})=>{if(j.clearTimeout(this.hasLiveOffsetByPausedTimer),e){this.hasLiveOffsetByPausedTimer=j.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(t));return}this.hasLiveOffsetByPaused.next(!1)})).add(hy({atLiveEdge:hy({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Wy({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Z(({isLive:e,position:t,isLowLatency:n})=>{let r=this.getActiveLiveDelay(n);return e&&Math.abs(t)<r/1e3}),X(),Iy(e=>e&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Z(({atLiveEdge:e,hasPausedTimeoutCase:t})=>e&&!t)).subscribe(this.info.atLiveEdge$)).add(hy({isLive:e.providerOutput.isLive$,position:N.browser.isSafari&&this.tuning.useSafariOptimisticPositionForLiveEdgeBugfix?Wy({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}):e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Z(({isLive:e,position:t,duration:n})=>e&&(Math.abs(n)-Math.abs(t))*1e3<this.tuning.live.activeLiveDelay),X(),Iy(e=>e&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Z(e=>e.muted),X()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Z(e=>e.volume),X()).subscribe(this.info.volume$)).add(Wy({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(jy(e.providerOutput.endedEvent$.pipe(Ay(!0)),e.providerOutput.seekedEvent$.pipe(Ay(!1))).pipe(X()).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.updateDurationError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.pipe(Y(e=>e.category===_y.FATAL)).subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(Z(({forced:e,input:t,supported:n})=>{let r,i;return e?(r=`NoForcedFormat`,i=`${e} was forced but failed or not available`):n.length?(r=`NoFormats`,i=`All formats failed`):t.length?(r=`NoSupportedFormats`,i=`No supported formats`):(r=`NoInputFormats`,i=`No formats supplied`),my(r),{id:r,category:_y.VIDEO_PIPELINE,message:i}})).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(Q()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(Q()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(Q()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(Q()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(Q()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(Q(),Z(e=>e??My()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Q(),Z(()=>My()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Q(),Z(()=>My()-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 zy(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let n=new zy(!0);this.subscription.add(e.current$.subscribe(()=>n.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Y(({to:e})=>e===`playing`),Q()).subscribe(()=>n.next(!1)));let r=0,i=0,a=jy(e.providerOutput.isBuffering$,t,n).pipe(Z(()=>{let r=e.providerOutput.isBuffering$.getValue(),i=t.getValue()||n.getValue();return r&&!i}),X());this.subscription.add(a.subscribe(e=>{let{stallIgnoreThreshold:t,stallHandlingStrategy:n}=this.tuning;e?(i=My(),n===`verbose`&&this.info.stallStartTime$.next(i),r=j.setTimeout(()=>{this.info.isStalled$.next(!0),i&&this.info.stallStartTime$.next(n===`exclude-threshold`?My():i)},t)):(j.clearTimeout(r),this.info.isStalled$.next(!1),i=0,this.info.stallStartTime$.next(0))})),this.subscription.add(jy(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let t=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:t?.videoWidth,height:t?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(t=>{var n,r;let i=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:t==null||(n=t.size)==null?void 0:n.width,height:t==null||(r=t.size)==null?void 0:r.height},{width:i?.videoWidth,height:i?.videoHeight})})),this.subscription.add(jy(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let t=e.providerOutput.inPiP$.getValue(),n=e.providerOutput.inFullscreen$.getValue(),r=e.providerOutput.element$.getValue(),i=e.providerOutput.elementVisible$.getValue(),a=this.chromecastInitializer.castState$.getValue(),o;o=a===`CONNECTED`?`second_screen`:r?i?t?`pip`:n?`fullscreen`:`inline`:`invisible`:`none`,this.info.surface$.getValue()!==o&&this.info.surface$.next(o)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Z(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Fy;this.subscription.add(t),this.subscription.add(e.current$.pipe(X((e,t)=>e.provider===t.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Y(e=>e.length>0),Q()).subscribe(e=>{this.setStartingVideoTrack(e)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let n=this.explicitInitialQuality??this.info.currentQuality$.getValue();n&&(t=e.find(({quality:e,tvDisabled:t})=>e===n&&!t),t||this.setAutoQuality(!0)),!t&&(t=Ni(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.persistentSubscription.add(jy(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.persistentSubscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;my(this.providerContainer),my(e),oi(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(e=>ai(e)),this.providerContainer.current$.subscribe(({type:e})=>ci(`provider`,e)),e.duration$.subscribe(e=>ci(`duration`,e)),e.availableVideoTracks$.pipe(Y(e=>!!e.length),Q()).subscribe(e=>ci(`tracks`,e)),this.events.fatalError$.subscribe(new li(`fatalError`)),this.events.managedError$.subscribe(new li(`managedError`)),e.position$.subscribe(new li(`position`)),e.currentVideoTrack$.pipe(Z(e=>e?.quality)).subscribe(new li(`quality`)),this.info.currentBuffer$.subscribe(new li(`buffer`)),e.isBuffering$.subscribe(new li(`isBuffering`))].forEach(e=>this.subscription.add(e)),ci(`codecs`,N.video.supportedCodecs)}initTracerSubscription(){let e=Sy(this.tracer.log.bind(this.tracer)),t=Sy(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(X()).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(hy({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(Y(({currentQuality:e,videoBitrate:t})=>!!e&&!!t),X((e,t)=>e.currentQuality===t.currentQuality)).subscribe(e(`currentVideoTrack`))).add(this.info.currentVideoSegmentLength$.pipe(Y(e=>e>0),X()).subscribe(e(`currentVideoSegmentLength`))).add(this.info.currentAudioSegmentLength$.pipe(Y(e=>e>0),X()).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(hy({currentBuffer:this.info.currentBuffer$.pipe(Y(e=>e.end>0),X((e,t)=>e.end===t.end&&e.start===t.start)),position:this.info.position$.pipe(X())}).pipe(Ly(1e3)).subscribe(e(`currentBufferAndPosition`))).add(this.info.duration$.pipe(X()).subscribe(e(`duration`))).add(this.info.isBuffering$.subscribe(e(`isBuffering`))).add(this.info.isLive$.pipe(X()).subscribe(e(`isLive`))).add(this.info.canChangePlaybackSpeed$.pipe(X()).subscribe(e(`canChangePlaybackSpeed`))).add(hy({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Y(({liveTime:e,liveBufferTime:t})=>!!e&&!!t),Ly(1e3)).subscribe(e(`liveBufferAndPosition`))).add(this.info.atLiveEdge$.pipe(X(),Y(e=>e===!0)).subscribe(e(`atLiveEdge`))).add(this.info.atLiveDurationEdge$.pipe(X(),Y(e=>e===!0)).subscribe(e(`atLiveDurationEdge`))).add(this.info.muted$.pipe(X()).subscribe(e(`muted`))).add(this.info.volume$.pipe(X()).subscribe(e(`volume`))).add(this.info.isEnded$.pipe(X(),Y(e=>e===!0)).subscribe(e(`isEnded`))).add(this.info.availableSources$.subscribe(e(`availableSources`))).add(hy({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Y(({throughputEstimation:e,rtt:t})=>!!e&&!!t),Ly(3e3)).subscribe(e(`throughputEstimation`))).add(this.info.isStalled$.subscribe(e(`isStalled`))).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(){var e=this;let t=Cy();if(!t.navigator.wakeLock||!this.tuning.enableWakeLock)return;let n,r=()=>{n?.release(),n=void 0},i=function(){var t=w(function*(){r(),n=yield window.navigator.wakeLock.request(`screen`).catch(t=>{t instanceof DOMException&&t.name===`NotAllowedError`||e.events.managedError$.next({id:`WakeLock`,category:_y.DOM,message:String(t)})})});return function(){return t.apply(this,arguments)}}();this.subscription.add(jy(yy(t.document,`visibilitychange`),yy(t.document,`fullscreenchange`),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let e=t.document.visibilityState===`visible`,a=this.desiredState.playbackState.getState()===`playing`,o=!!n&&!n?.released;e&&a?o||i():r()})).add(this.events.willDestruct$.subscribe(r))}setVideoTrackIdByQuality(e,t){let n=e.find(e=>e.quality===t);this.tracer.log(`setVideoTrackIdByQuality`,vy({quality:t,availableTracks:vy(e),track:vy(n),isAutoQuality:!n})),n?n.tvDisabled?(this.setAutoQuality(!0),this.events.managedError$.next({id:`SetQualityTrackTvDisabled`,category:_y.WTF,message:`Set quality was called on track with tvDisabled flag`})):this.desiredState.videoTrack.startTransitionTo(n):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return Cy().document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ya()}}var pb=`@vkontakte/videoplayer-core@${ee}`;;return{lt,N,Lt,$a,fb,ne,re,db,ee,oe,cb,ub,pb,se,sb,te,lb,ae,ie};}();var{lt:_oxcModehgni7_lt,N:_oxcModehgni7_N,Lt:_oxcModehgni7_Lt,$a:_oxcModehgni7_$a,fb:_oxcModehgni7_fb,ne:_oxcModehgni7_ne,re:_oxcModehgni7_re,db:_oxcModehgni7_db,ee:_oxcModehgni7_ee,oe:_oxcModehgni7_oe,cb:_oxcModehgni7_cb,ub:_oxcModehgni7_ub,pb:_oxcModehgni7_pb,se:_oxcModehgni7_se,sb:_oxcModehgni7_sb,te:_oxcModehgni7_te,lb:_oxcModehgni7_lb,ae:_oxcModehgni7_ae,ie:_oxcModehgni7_ie}=_oxcModehgni7;export{_oxcModehgni7_lt as isMobile,_oxcModehgni7_N as clientChecker,_oxcModehgni7_Lt as areValidLiveRecordSources,_oxcModehgni7_$a as WebmCodecStrategy,_oxcModehgni7_fb as VideoQuality,_oxcModehgni7_ne as VideoFormat,_oxcModehgni7_re as VideoCodecName,_oxcModehgni7_db as ValueSubject,_oxcModehgni7_ee as VERSION,_oxcModehgni7_oe as Surface,_oxcModehgni7_cb as Subscription,_oxcModehgni7_ub as Subject,_oxcModehgni7_pb as SDK_VERSION,_oxcModehgni7_se as PredefinedQualityLimits,_oxcModehgni7_sb as Player,_oxcModehgni7_te as PlaybackState,_oxcModehgni7_lb as Observable,_oxcModehgni7_ae as HttpConnectionType,_oxcModehgni7_ie as ChromecastState};