@vkontakte/videoplayer-core 2.0.85 → 2.0.86

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/es2018.cjs.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.85
3
- * Fri, 28 Apr 2023 10:45:06 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-85/doc/
2
+ * @vkontakte/videoplayer-core v2.0.86
3
+ * Thu, 11 May 2023 16:24:35 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-86/doc/
5
5
  */
6
- "use strict";var lo=Object.create;var ca=Object.defineProperty;var uo=Object.getOwnPropertyDescriptor;var co=Object.getOwnPropertyNames;var ho=Object.getPrototypeOf,fo=Object.prototype.hasOwnProperty;var po=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of co(e))!fo.call(s,a)&&a!==t&&ca(s,a,{get:()=>e[a],enumerable:!(i=uo(e,a))||i.enumerable});return s};var ha=(s,e,t)=>(t=s!=null?lo(ho(s)):{},po(e||!s||!s.__esModule?ca(t,"default",{value:s,enumerable:!0}):t,s));var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),mo=require("lodash/debounce.js");const bo="2.0.85",vo="es2018.cjs.js";exports.PlaybackState=void 0;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var le;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(le||(le={}));exports.ChromecastState=void 0;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var N;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(N||(N={}));var So=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class go{constructor(e){var t;this.connection$=new r.ValueSubject(void 0),this.castState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new r.Subject,this.realCastState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const a=r.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);a?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||So("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:r.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,a,n;(n=(a=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){r.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();r.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();r.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(r.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var n,o;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=i.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.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 r.assertNever(a.sessionState)}})).add(r.merge(r.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(r.tap(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),r.map(a=>a.castState)),r.observableFrom([i.getCastState()])).pipe(r.filterChanged(),r.map(yo),r.tap(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var n;const o=a===exports.ChromecastState.CONNECTED,l=r.isNonNullable(this.connection$.getValue());if(o&&!l){const d=i.getCurrentSession();r.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(r.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?r.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)}))}initializeCastApi(){var e;let t,i,a;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,a=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:a}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:r.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const yo=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return r.assertNever(s)}};var fa=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Le=function(s){try{return!!s()}catch(e){return!0}},To=Le,_i=!To(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Or=_i,Br=Function.prototype,ws=Br.call,Eo=Or&&Br.bind.bind(ws,ws),xe=Or?Eo:function(s){return function(){return ws.apply(s,arguments)}},Mr=xe,$o=Mr({}.toString),ko=Mr("".slice),Ri=function(s){return ko($o(s),8,-1)},Ao=xe,Po=Le,wo=Ri,ji=Object,_o=Ao("".split),Ro=Po(function(){return!ji("z").propertyIsEnumerable(0)})?function(s){return wo(s)=="String"?_o(s,""):ji(s)}:ji,Ii=function(s){return s==null},Io=Ii,No=TypeError,Vs=function(s){if(Io(s))throw No("Can't call method on "+s);return s},Do=Ro,Co=Vs,Ft=function(s){return Do(Co(s))},Lo=function(){},yt={},Jt=function(s){return s&&s.Math==Math&&s},Ae=Jt(typeof globalThis=="object"&&globalThis)||Jt(typeof window=="object"&&window)||Jt(typeof self=="object"&&self)||Jt(typeof fa=="object"&&fa)||function(){return this}()||Function("return this")(),_s=typeof document=="object"&&document.all,xo=typeof _s=="undefined"&&_s!==void 0,Vr={all:_s,IS_HTMLDDA:xo},Fr=Vr,Oo=Fr.all,me=Fr.IS_HTMLDDA?function(s){return typeof s=="function"||s===Oo}:function(s){return typeof s=="function"},Bo=Ae,Mo=me,pa=Bo.WeakMap,Vo=Mo(pa)&&/native code/.test(String(pa)),ma=me,Ur=Vr,Fo=Ur.all,it=Ur.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:ma(s)||s===Fo}:function(s){return typeof s=="object"?s!==null:ma(s)},Uo=Le,Ye=!Uo(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Tt={},jo=Ae,ba=it,Rs=jo.document,Ho=ba(Rs)&&ba(Rs.createElement),jr=function(s){return Ho?Rs.createElement(s):{}},Go=Ye,Yo=Le,qo=jr,Hr=!Go&&!Yo(function(){return Object.defineProperty(qo("div"),"a",{get:function(){return 7}}).a!=7}),zo=Ye,Wo=Le,Gr=zo&&Wo(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Qo=it,Jo=String,Ko=TypeError,st=function(s){if(Qo(s))return s;throw Ko(Jo(s)+" is not an object")},Xo=_i,Kt=Function.prototype.call,Oe=Xo?Kt.bind(Kt):function(){return Kt.apply(Kt,arguments)},Fs={},Hi=Fs,Gi=Ae,Zo=me,va=function(s){return Zo(s)?s:void 0},Us=function(s,e){return arguments.length<2?va(Hi[s])||va(Gi[s]):Hi[s]&&Hi[s][e]||Gi[s]&&Gi[s][e]},el=xe,js=el({}.isPrototypeOf),tl=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Yr=Ae,Yi=tl,Sa=Yr.process,ga=Yr.Deno,ya=Sa&&Sa.versions||ga&&ga.version,Ta=ya&&ya.v8,be,Si;Ta&&(be=Ta.split("."),Si=be[0]>0&&be[0]<4?1:+(be[0]+be[1]));!Si&&Yi&&(be=Yi.match(/Edge\/(\d+)/),(!be||be[1]>=74)&&(be=Yi.match(/Chrome\/(\d+)/),be&&(Si=+be[1])));var il=Si,Ea=il,sl=Le,qr=!!Object.getOwnPropertySymbols&&!sl(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Ea&&Ea<41}),al=qr,zr=al&&!Symbol.sham&&typeof Symbol.iterator=="symbol",rl=Us,nl=me,ol=js,ll=zr,ul=Object,Wr=ll?function(s){return typeof s=="symbol"}:function(s){var e=rl("Symbol");return nl(e)&&ol(e.prototype,ul(s))},dl=String,Hs=function(s){try{return dl(s)}catch(e){return"Object"}},cl=me,hl=Hs,fl=TypeError,Gs=function(s){if(cl(s))return s;throw fl(hl(s)+" is not a function")},pl=Gs,ml=Ii,Ni=function(s,e){var t=s[e];return ml(t)?void 0:pl(t)},qi=Oe,zi=me,Wi=it,bl=TypeError,vl=function(s,e){var t,i;if(e==="string"&&zi(t=s.toString)&&!Wi(i=qi(t,s))||zi(t=s.valueOf)&&!Wi(i=qi(t,s))||e!=="string"&&zi(t=s.toString)&&!Wi(i=qi(t,s)))return i;throw bl("Can't convert object to primitive value")},gi={},Sl={get exports(){return gi},set exports(s){gi=s}},gl=!0,$a=Ae,yl=Object.defineProperty,Tl=function(s,e){try{yl($a,s,{value:e,configurable:!0,writable:!0})}catch(t){$a[s]=e}return e},El=Ae,$l=Tl,ka="__core-js_shared__",kl=El[ka]||$l(ka,{}),Qr=kl,Aa=Qr;(Sl.exports=function(s,e){return Aa[s]||(Aa[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var Al=Vs,Pl=Object,Di=function(s){return Pl(Al(s))},wl=xe,_l=Di,Rl=wl({}.hasOwnProperty),Be=Object.hasOwn||function(e,t){return Rl(_l(e),t)},Il=xe,Nl=0,Dl=Math.random(),Cl=Il(1 .toString),Jr=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Cl(++Nl+Dl,36)},Ll=Ae,xl=gi,Pa=Be,Ol=Jr,Bl=qr,Ml=zr,ft=Ll.Symbol,Qi=xl("wks"),Vl=Ml?ft.for||ft:ft&&ft.withoutSetter||Ol,Se=function(s){return Pa(Qi,s)||(Qi[s]=Bl&&Pa(ft,s)?ft[s]:Vl("Symbol."+s)),Qi[s]},Fl=Oe,wa=it,_a=Wr,Ul=Ni,jl=vl,Hl=Se,Gl=TypeError,Yl=Hl("toPrimitive"),ql=function(s,e){if(!wa(s)||_a(s))return s;var t=Ul(s,Yl),i;if(t){if(e===void 0&&(e="default"),i=Fl(t,s,e),!wa(i)||_a(i))return i;throw Gl("Can't convert object to primitive value")}return e===void 0&&(e="number"),jl(s,e)},zl=ql,Wl=Wr,Ys=function(s){var e=zl(s,"string");return Wl(e)?e:e+""},Ql=Ye,Jl=Hr,Kl=Gr,Xt=st,Ra=Ys,Xl=TypeError,Ji=Object.defineProperty,Zl=Object.getOwnPropertyDescriptor,Ki="enumerable",Xi="configurable",Zi="writable";Tt.f=Ql?Kl?function(e,t,i){if(Xt(e),t=Ra(t),Xt(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Zi in i&&!i[Zi]){var a=Zl(e,t);a&&a[Zi]&&(e[t]=i.value,i={configurable:Xi in i?i[Xi]:a[Xi],enumerable:Ki in i?i[Ki]:a[Ki],writable:!1})}return Ji(e,t,i)}:Ji:function(e,t,i){if(Xt(e),t=Ra(t),Xt(i),Jl)try{return Ji(e,t,i)}catch(a){}if("get"in i||"set"in i)throw Xl("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Ci=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},eu=Ye,tu=Tt,iu=Ci,Ut=eu?function(s,e,t){return tu.f(s,e,iu(1,t))}:function(s,e,t){return s[e]=t,s},su=gi,au=Jr,Ia=su("keys"),qs=function(s){return Ia[s]||(Ia[s]=au(s))},zs={},ru=Vo,Kr=Ae,nu=it,ou=Ut,es=Be,ts=Qr,lu=qs,uu=zs,Na="Object already initialized",Is=Kr.TypeError,du=Kr.WeakMap,yi,Vt,Ti,cu=function(s){return Ti(s)?Vt(s):yi(s,{})},hu=function(s){return function(e){var t;if(!nu(e)||(t=Vt(e)).type!==s)throw Is("Incompatible receiver, "+s+" required");return t}};if(ru||ts.state){var Ee=ts.state||(ts.state=new du);Ee.get=Ee.get,Ee.has=Ee.has,Ee.set=Ee.set,yi=function(s,e){if(Ee.has(s))throw Is(Na);return e.facade=s,Ee.set(s,e),e},Vt=function(s){return Ee.get(s)||{}},Ti=function(s){return Ee.has(s)}}else{var lt=lu("state");uu[lt]=!0,yi=function(s,e){if(es(s,lt))throw Is(Na);return e.facade=s,ou(s,lt,e),e},Vt=function(s){return es(s,lt)?s[lt]:{}},Ti=function(s){return es(s,lt)}}var fu={set:yi,get:Vt,has:Ti,enforce:cu,getterFor:hu},pu=_i,Xr=Function.prototype,Da=Xr.apply,Ca=Xr.call,mu=typeof Reflect=="object"&&Reflect.apply||(pu?Ca.bind(Da):function(){return Ca.apply(Da,arguments)}),bu=Ri,vu=xe,Zr=function(s){if(bu(s)==="Function")return vu(s)},en={},tn={},sn={}.propertyIsEnumerable,an=Object.getOwnPropertyDescriptor,Su=an&&!sn.call({1:2},1);tn.f=Su?function(e){var t=an(this,e);return!!t&&t.enumerable}:sn;var gu=Ye,yu=Oe,Tu=tn,Eu=Ci,$u=Ft,ku=Ys,Au=Be,Pu=Hr,La=Object.getOwnPropertyDescriptor;en.f=gu?La:function(e,t){if(e=$u(e),t=ku(t),Pu)try{return La(e,t)}catch(i){}if(Au(e,t))return Eu(!yu(Tu.f,e,t),e[t])};var wu=Le,_u=me,Ru=/#|\.prototype\./,jt=function(s,e){var t=Nu[Iu(s)];return t==Cu?!0:t==Du?!1:_u(e)?wu(e):!!e},Iu=jt.normalize=function(s){return String(s).replace(Ru,".").toLowerCase()},Nu=jt.data={},Du=jt.NATIVE="N",Cu=jt.POLYFILL="P",Lu=jt,xa=Zr,xu=Gs,Ou=_i,Bu=xa(xa.bind),rn=function(s,e){return xu(s),e===void 0?s:Ou?Bu(s,e):function(){return s.apply(e,arguments)}},Zt=Ae,Mu=mu,Vu=Zr,Fu=me,Uu=en.f,ju=Lu,ut=Fs,Hu=rn,dt=Ut,Oa=Be,Gu=function(s){var e=function(t,i,a){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,a)}return Mu(s,this,arguments)};return e.prototype=s.prototype,e},Li=function(s,e){var t=s.target,i=s.global,a=s.stat,n=s.proto,o=i?Zt:a?Zt[t]:(Zt[t]||{}).prototype,l=i?ut:ut[t]||dt(ut,t,{})[t],d=l.prototype,u,c,h,f,m,b,p,v,S;for(f in e)u=ju(i?f:t+(a?".":"#")+f,s.forced),c=!u&&o&&Oa(o,f),b=l[f],c&&(s.dontCallGetSet?(S=Uu(o,f),p=S&&S.value):p=o[f]),m=c&&p?p:e[f],!(c&&typeof b==typeof m)&&(s.bind&&c?v=Hu(m,Zt):s.wrap&&c?v=Gu(m):n&&Fu(m)?v=Vu(m):v=m,(s.sham||m&&m.sham||b&&b.sham)&&dt(v,"sham",!0),dt(l,f,v),n&&(h=t+"Prototype",Oa(ut,h)||dt(ut,h,{}),dt(ut[h],f,m),s.real&&d&&(u||!d[f])&&dt(d,f,m)))},Ns=Ye,Yu=Be,nn=Function.prototype,qu=Ns&&Object.getOwnPropertyDescriptor,Ws=Yu(nn,"name"),zu=Ws&&function(){}.name==="something",Wu=Ws&&(!Ns||Ns&&qu(nn,"name").configurable),Qu={EXISTS:Ws,PROPER:zu,CONFIGURABLE:Wu},on={},Ju=Math.ceil,Ku=Math.floor,Xu=Math.trunc||function(e){var t=+e;return(t>0?Ku:Ju)(t)},Zu=Xu,Qs=function(s){var e=+s;return e!==e||e===0?0:Zu(e)},ed=Qs,td=Math.max,id=Math.min,sd=function(s,e){var t=ed(s);return t<0?td(t+e,0):id(t,e)},ad=Qs,rd=Math.min,nd=function(s){return s>0?rd(ad(s),9007199254740991):0},od=nd,Js=function(s){return od(s.length)},ld=Ft,ud=sd,dd=Js,Ba=function(s){return function(e,t,i){var a=ld(e),n=dd(a),o=ud(i,n),l;if(s&&t!=t){for(;n>o;)if(l=a[o++],l!=l)return!0}else for(;n>o;o++)if((s||o in a)&&a[o]===t)return s||o||0;return!s&&-1}},cd={includes:Ba(!0),indexOf:Ba(!1)},hd=xe,is=Be,fd=Ft,pd=cd.indexOf,md=zs,Ma=hd([].push),bd=function(s,e){var t=fd(s),i=0,a=[],n;for(n in t)!is(md,n)&&is(t,n)&&Ma(a,n);for(;e.length>i;)is(t,n=e[i++])&&(~pd(a,n)||Ma(a,n));return a},ln=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],vd=bd,Sd=ln,gd=Object.keys||function(e){return vd(e,Sd)},yd=Ye,Td=Gr,Ed=Tt,$d=st,kd=Ft,Ad=gd;on.f=yd&&!Td?Object.defineProperties:function(e,t){$d(e);for(var i=kd(t),a=Ad(t),n=a.length,o=0,l;n>o;)Ed.f(e,l=a[o++],i[l]);return e};var Pd=Us,wd=Pd("document","documentElement"),_d=st,Rd=on,Va=ln,Id=zs,Nd=wd,Dd=jr,Cd=qs,Fa=">",Ua="<",Ds="prototype",Cs="script",un=Cd("IE_PROTO"),ss=function(){},dn=function(s){return Ua+Cs+Fa+s+Ua+"/"+Cs+Fa},ja=function(s){s.write(dn("")),s.close();var e=s.parentWindow.Object;return s=null,e},Ld=function(){var s=Dd("iframe"),e="java"+Cs+":",t;return s.style.display="none",Nd.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(dn("document.F=Object")),t.close(),t.F},ei,fi=function(){try{ei=new ActiveXObject("htmlfile")}catch(e){}fi=typeof document!="undefined"?document.domain&&ei?ja(ei):Ld():ja(ei);for(var s=Va.length;s--;)delete fi[Ds][Va[s]];return fi()};Id[un]=!0;var cn=Object.create||function(e,t){var i;return e!==null?(ss[Ds]=_d(e),i=new ss,ss[Ds]=null,i[un]=e):i=fi(),t===void 0?i:Rd.f(i,t)},xd=Le,Od=!xd(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Bd=Be,Md=me,Vd=Di,Fd=qs,Ud=Od,Ha=Fd("IE_PROTO"),Ls=Object,jd=Ls.prototype,hn=Ud?Ls.getPrototypeOf:function(s){var e=Vd(s);if(Bd(e,Ha))return e[Ha];var t=e.constructor;return Md(t)&&e instanceof t?t.prototype:e instanceof Ls?jd:null},Hd=Ut,fn=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Hd(s,e,t),s},Gd=Le,Yd=me,qd=it,zd=cn,Ga=hn,Wd=fn,Qd=Se,xs=Qd("iterator"),pn=!1,De,as,rs;[].keys&&(rs=[].keys(),"next"in rs?(as=Ga(Ga(rs)),as!==Object.prototype&&(De=as)):pn=!0);var Jd=!qd(De)||Gd(function(){var s={};return De[xs].call(s)!==s});Jd?De={}:De=zd(De);Yd(De[xs])||Wd(De,xs,function(){return this});var mn={IteratorPrototype:De,BUGGY_SAFARI_ITERATORS:pn},Kd=Se,Xd=Kd("toStringTag"),bn={};bn[Xd]="z";var Ks=String(bn)==="[object z]",Zd=Ks,ec=me,pi=Ri,tc=Se,ic=tc("toStringTag"),sc=Object,ac=pi(function(){return arguments}())=="Arguments",rc=function(s,e){try{return s[e]}catch(t){}},xi=Zd?pi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=rc(e=sc(s),ic))=="string"?t:ac?pi(e):(i=pi(e))=="Object"&&ec(e.callee)?"Arguments":i},nc=Ks,oc=xi,lc=nc?{}.toString:function(){return"[object "+oc(this)+"]"},uc=Ks,dc=Tt.f,cc=Ut,hc=Be,fc=lc,pc=Se,Ya=pc("toStringTag"),vn=function(s,e,t,i){if(s){var a=t?s:s.prototype;hc(a,Ya)||dc(a,Ya,{configurable:!0,value:e}),i&&!uc&&cc(a,"toString",fc)}},mc=mn.IteratorPrototype,bc=cn,vc=Ci,Sc=vn,gc=yt,yc=function(){return this},Tc=function(s,e,t,i){var a=e+" Iterator";return s.prototype=bc(mc,{next:vc(+!i,t)}),Sc(s,a,!1,!0),gc[a]=yc,s},Ec=Li,$c=Oe,Sn=Qu,kc=Tc,Ac=hn,Pc=vn,qa=fn,wc=Se,za=yt,gn=mn,_c=Sn.PROPER;Sn.CONFIGURABLE;gn.IteratorPrototype;var ti=gn.BUGGY_SAFARI_ITERATORS,ns=wc("iterator"),Wa="keys",ii="values",Qa="entries",Rc=function(){return this},Ic=function(s,e,t,i,a,n,o){kc(t,e,i);var l=function(S){if(S===a&&f)return f;if(!ti&&S in c)return c[S];switch(S){case Wa:return function(){return new t(this,S)};case ii:return function(){return new t(this,S)};case Qa:return function(){return new t(this,S)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[ns]||c["@@iterator"]||a&&c[a],f=!ti&&h||l(a),m=e=="Array"&&c.entries||h,b,p,v;if(m&&(b=Ac(m.call(new s)),b!==Object.prototype&&b.next&&(Pc(b,d,!0,!0),za[d]=Rc)),_c&&a==ii&&h&&h.name!==ii&&(u=!0,f=function(){return $c(h,this)}),a)if(p={values:l(ii),keys:n?f:l(Wa),entries:l(Qa)},o)for(v in p)(ti||u||!(v in c))&&qa(c,v,p[v]);else Ec({target:e,proto:!0,forced:ti||u},p);return o&&c[ns]!==f&&qa(c,ns,f,{name:a}),za[e]=f,p},Nc=function(s,e){return{value:s,done:e}},Dc=Ft,Xs=Lo,Ja=yt,yn=fu,Cc=Tt.f,Lc=Ic,si=Nc,xc=gl,Oc=Ye,Tn="Array Iterator",Bc=yn.set,Mc=yn.getterFor(Tn);Lc(Array,"Array",function(s,e){Bc(this,{type:Tn,target:Dc(s),index:0,kind:e})},function(){var s=Mc(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,si(void 0,!0)):t=="keys"?si(i,!1):t=="values"?si(e[i],!1):si([i,e[i]],!1)},"values");var Ka=Ja.Arguments=Ja.Array;Xs();Xs();Xs();if(!xc&&Oc&&Ka.name!=="values")try{Cc(Ka,"name",{value:"values"})}catch(s){}var Vc=Se,Fc=yt,Uc=Vc("iterator"),jc=Array.prototype,Hc=function(s){return s!==void 0&&(Fc.Array===s||jc[Uc]===s)},Gc=xi,Xa=Ni,Yc=Ii,qc=yt,zc=Se,Wc=zc("iterator"),En=function(s){if(!Yc(s))return Xa(s,Wc)||Xa(s,"@@iterator")||qc[Gc(s)]},Qc=Oe,Jc=Gs,Kc=st,Xc=Hs,Zc=En,eh=TypeError,th=function(s,e){var t=arguments.length<2?Zc(s):e;if(Jc(t))return Kc(Qc(t,s));throw eh(Xc(s)+" is not iterable")},ih=Oe,Za=st,sh=Ni,ah=function(s,e,t){var i,a;Za(s);try{if(i=sh(s,"return"),!i){if(e==="throw")throw t;return t}i=ih(i,s)}catch(n){a=!0,i=n}if(e==="throw")throw t;if(a)throw i;return Za(i),t},rh=rn,nh=Oe,oh=st,lh=Hs,uh=Hc,dh=Js,er=js,ch=th,hh=En,tr=ah,fh=TypeError,mi=function(s,e){this.stopped=s,this.result=e},ir=mi.prototype,ph=function(s,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=rh(e,i),u,c,h,f,m,b,p,v=function(g){return u&&tr(u,"normal",g),new mi(!0,g)},S=function(g){return a?(oh(g),l?d(g[0],g[1],v):d(g[0],g[1])):l?d(g,v):d(g)};if(n)u=s.iterator;else if(o)u=s;else{if(c=hh(s),!c)throw fh(lh(s)+" is not iterable");if(uh(c)){for(h=0,f=dh(s);f>h;h++)if(m=S(s[h]),m&&er(ir,m))return m;return new mi(!1)}u=ch(s,c)}for(b=n?s.next:u.next;!(p=nh(b,u)).done;){try{m=S(p.value)}catch(g){tr(u,"throw",g)}if(typeof m=="object"&&m&&er(ir,m))return m}return new mi(!1)},mh=Ys,bh=Tt,vh=Ci,Sh=function(s,e,t){var i=mh(e);i in s?bh.f(s,i,vh(0,t)):s[i]=t},gh=Li,yh=ph,Th=Sh;gh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return yh(e,function(i,a){Th(t,i,a)},{AS_ENTRIES:!0}),t}});var Eh=Fs,$h=Eh.Object.fromEntries,kh={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},Ah=kh,Ph=Ae,wh=xi,_h=Ut,sr=yt,Rh=Se,ar=Rh("toStringTag");for(var os in Ah){var rr=Ph[os],ls=rr&&rr.prototype;ls&&wh(ls)!==ar&&_h(ls,ar,os),sr[os]=sr.Array}var Ih=$h,Nh=Ih,Dh=Nh,Ch=Dh,Ht=Ch,mt;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(mt||(mt={}));var bt=(s,e=0,t=mt.OFFSET_P)=>{switch(t){case mt.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case mt.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:r.assertNever(t)}return s},k=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};exports.VideoQuality=void 0;(function(s){s.INVARIANT="Invariant quality",s.Q_144P="144p",s.Q_240P="240p",s.Q_360P="360p",s.Q_480P="480p",s.Q_720P="720p",s.Q_1080P="1080p",s.Q_1440P="1440p",s.Q_2160P="2160p",s.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const ve={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},bi=(s,e)=>ve[s].height>ve[e].height,Lh=(s,e)=>ve[s].height>=ve[e].height,Ot=(s,e)=>ve[s].height<ve[e].height,xh=(s,e)=>ve[s].height<=ve[e].height,Oh=s=>s.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:Ot(e,t)?1:-1)[0],Bh=Object.keys(ve).sort((s,e)=>Ot(s,e)?-1:1),at=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return Bh.find(a=>{const n=ve[a];return n.width>=i&&n.height>=t})},Mh=s=>ve[s].height,Ei=s=>s===exports.VideoQuality.INVARIANT;class W{constructor(e){this.transitionStarted$=new r.Subject,this.transitionEnded$=new r.Subject,this.transitionUpdated$=new r.Subject,this.forceChanged$=new r.Subject,this.stateChangeStarted$=r.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=r.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||r.isNonNullable(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const Vh=s=>{switch(s){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return r.assertNever(s)}};var L;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(L||(L={}));const Fh=5,Uh=5,jh=500,nr=7e3;class Hh{constructor(e){this.subscription=new r.Subscription,this.loadMediaTimeoutSubscription=new r.Subscription,this.videoState=new W(L.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){i!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!a){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===N.Requested&&i!==L.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(i){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PLAYING:{switch(i){case L.PLAYING:break;case L.PAUSED:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.READY:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case L.PLAYING:this.videoState.startTransitionTo(L.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case L.PAUSED:break;case L.READY:this.videoState.startTransitionTo(L.PAUSED),this.videoState.setState(L.PAUSED);break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(i)}break}default:r.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Vh(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const 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);const e=new r.Subscription;this.subscription.add(e),this.subscription.add(r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(r.map(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));const t=(a,n)=>this.subscription.add(a.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const a=new r.Subject;e.add(a.pipe(r.debounce(jh)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===N.Applying||Math.abs(l-n)>Fh)&&a.next(l),n=l})),e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);const{remotePlayer:n}=this.params.connection,o=a.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Uh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,exports.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:r.assertNever(o)}}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});const i=r.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(L.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(L.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:N.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PAUSED||e===L.PLAYING)&&(this.videoState.setState(L.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PLAYING||e===L.PAUSED)&&(this.videoState.setState(L.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===L.READY&&this.videoState.setState(L.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==L.STOPPED&&this.videoState.setState(L.STOPPED)}handleRemoteVolumeChange(e){var t,i;const a=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:a.volume,muted:(i=e.muted)!==null&&i!==void 0?i:a.muted};(n.volume!==a.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let a,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=i[e];r.assertNonNullable(c);const h=Oh(Object.keys(c));r.assertNonNullable(h);const f=c[h];r.assertNonNullable(f),a=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=i[e];r.assertNonNullable(c),a=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const c=i[e];r.assertNonNullable(c),a=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=i[e];r.assertNonNullable(c),a=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=i[e];r.assertNonNullable(c),a=bt(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:r.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:a,n);l.contentUrl=a,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return r.isNonNullable(d)&&(l.metadata.title=d),r.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===N.Applying||i.state===N.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((a,n)=>{this.loadMediaTimeoutSubscription.add(r.timeout(nr).subscribe(()=>n(`timeout(${nr})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===N.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:r.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:a})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class or{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let a=0,n=i.length;a<n;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let a=0,n=i.length;a<n;a++){const o=i[a];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class $n extends or{constructor(){super(),this.listeners||or.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let kn=class{constructor(){Object.defineProperty(this,"signal",{value:new $n,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(a){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(kn.prototype[Symbol.toStringTag]="AbortController",$n.prototype[Symbol.toStringTag]="AbortSignal");function An(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Gh(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=s;if(!An({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||a)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(m){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((m,b)=>{c.addEventListener("abort",()=>b(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Oi=An({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Pn=Oi?Gh({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,vt=Oi?Pn.fetch:window.fetch;Oi?Pn.Request:window.Request;const et=Oi?kn:window.AbortController,Ct=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class Bt{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,a=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];a.push(e),this.dashJsRequestQueue.set(i,a)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const a=t[0];if(!a||!a.request.range)continue;const[n,o]=Ct(a.request);if(n>=i.from&&o<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const a=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,a)}}}abort(e){var t;if(e){const{request:i}=e,a=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(i.url);a&&n&&n.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(Ct),a=i[0][0];let n=i[0][1];for(let f=1;f<i.length&&n<this.params.minDataSize;f++){const m=i[f][1];m-a<=2*this.params.minDataSize&&(n=Math.max(n,m))}a===0?n=Math.max(n,a+this.params.minInitSize):n=Math.max(n,a+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${a}-${n}`);const l=o.toString(),d=new et,u=d.signal,c={url:e,from:a,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var m,b;throw(b=(m=this.params).onError)===null||b===void 0||b.call(m,{id:"BigRequestParsing",category:r.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return vt(l,{signal:u}).then(f=>{var m,b,p;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[v,S]=f.body.tee();(b=(m=this.params).onDownloadStream)===null||b===void 0||b.call(m,S);const g=v.getReader(),A=parseInt((p=f.headers.get("Content-Length"))!==null&&p!==void 0?p:"",10)||n-a+1;c.data=new ArrayBuffer(A);const E=new Uint8Array(c.data),T=async({done:w,value:V})=>{w?this.onBigRequestProgress(c):V&&(E.set(V,c.loaded),c.loaded+=V.byteLength,this.onBigRequestProgress(c),await(g==null?void 0:g.read().then(T,Bt.suppressStreamErrors).catch(h)))};g==null||g.read().then(T,Bt.suppressStreamErrors).catch(h)},Bt.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:i,loaded:a,data:n,response:o}){var l,d,u,c,h,f,m,b;if(!this.activeRequests.has(e)||!n)return;const p=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const v of p){const{request:S}=v,[g,A]=Ct(S),E=g>=t&&A<=t+a,T=t>=g&&t+a<A,w=n.slice(g-t,Math.min(A-t+1,a));if((E||T)&&(S.requestStartDate=(d=S.requestStartDate)!==null&&d!==void 0?d:new Date,S.firstByteDate=(u=S.firstByteDate)!==null&&u!==void 0?u:new Date,S.bytesLoaded=w.byteLength,S.bytesTotal=i-t),E){S.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(C=>C!==v)),(h=v.success)===null||h===void 0||h.call(v,w,"",e);const V=o?Array.from(o.headers.entries()).map(([C,R])=>`${C}: ${R}`).join(`\r
7
- `):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(S,e,(m=o==null?void 0:o.status)!==null&&m!==void 0?m:200,V,[])}else T&&((b=v.progress)===null||b===void 0||b.call(v,{loaded:a,total:i-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:i},a){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:r.ErrorCategory.NETWORK,message:"Download error",thrown:a}),!this.activeRequests.has(e))return;const u=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const c of u){const[h,f]=Ct(c.request);(h>=t&&h<i||f>t&&f<=i)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(a)))}if(this.activeRequests.delete(e),a)throw a}onBigRequestAbort({url:e,from:t,to:i}){var a,n;if(!this.activeRequests.has(e))return;const o=(a=this.dashJsRequestQueue.get(e))!==null&&a!==void 0?a:[];for(const l of o){const[d,u]=Ct(l.request);(d>=t&&d<i||u>t&&u<=i)&&((n=l==null?void 0:l.abort)===null||n===void 0||n.call(l,l.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class $i{constructor(e,t,i){this.baseLoader=e,this.config=i,this.bigRequest=t,t.setMetrics(i.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if($i.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;$i.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Yh=(s,e)=>t=>({create:i=>{const a=s(t).create(i);return new $i(a,e,i)}}),qh=(s,e)=>{const t=new Bt(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,a=i.getLoader;return{getLoader:n=>{const o=a(n);return Yh(o,t)}}},!0),()=>t.destroy()};var zh=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:a})=>{i=a<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:a}=this,n=a.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&(e==null||e())}}},!0)},Wh=s=>{const e=new r.ValueSubject(1/0),t=new r.Subject,i=new r.ValueSubject(void 0),a=new r.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,m,b,p;const v=Ht(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(A=>A.split(": ")));if("x-playback-duration"in v||"x-playback-duration-millis"in v){const A=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),E=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),T=(m=E!=null?E:A*1e3)!==null&&m!==void 0?m:NaN;r.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const S=(b=v["x-delivery-type"])!==null&&b!==void 0?b:exports.HttpConnectionType.HTTP1,g=(p={1:!0,0:!1}[v["x-reused"]])!==null&&p!==void 0?p:void 0;i.next(S),a.next(g)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return s.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const m=f.onload,b=f.progress;f.onload=function(...p){return d(this),m(...p)},f.progress=function(...p){return u(this),b(...p)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:a,connectionType$:i}},St=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Qh=s=>s.extend("RequestModifier",()=>({modifyRequestURL:St}),!0),Jh=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[a,n]=i.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${a}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const ke=(s,e,t,{equal:i=(o,l)=>o===l,changed$:a,onError:n}={})=>{const o=s.getState(),l=e(),d=r.isNullable(a),u=new r.Subscription;return a&&u.add(a.subscribe(c=>{const h=s.getState();i(c,h)&&s.setState(c)},n)),i(l,o)||(t(o),d&&s.setState(o)),u.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),d&&s.setState(c.to)},n)),u},rt=(s,e,t)=>ke(e,()=>s.loop,i=>{r.isNonNullable(i)&&(s.loop=i)},{onError:t}),Me=(s,e,t,i)=>ke(e,()=>({muted:s.muted,volume:s.volume}),a=>{r.isNonNullable(a)&&(s.muted=a.muted,s.volume=a.volume)},{equal:(a,n)=>a===n||(a==null?void 0:a.muted)===(n==null?void 0:n.muted)&&(a==null?void 0:a.volume)===(n==null?void 0:n.volume),changed$:t,onError:i}),qe=(s,e,t,i)=>ke(e,()=>s.playbackRate,a=>{r.isNonNullable(a)&&(s.playbackRate=a)},{changed$:t,onError:i}),Kh=s=>["__",s.language,s.label].join("|"),Xh=(s,e)=>{if(s.id===e)return!0;const[t,i,a]=e.split("|");return s.language===i&&s.label===a};class Pe{constructor(){this.available$=new r.Subject,this.current$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.subscription=new r.Subscription,this.externalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const a=n=>{this.error$.next({id:"TextTracksManager",category:r.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ke(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{r.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),this.subscription.add(ke(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:a})),this.subscription.add(ke(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){r.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(r.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();this.select(i)})),this.subscription.add(r.merge(r.fromEvent(e,"addtrack"),r.fromEvent(e,"removetrack"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),r.filterChanged((i,a)=>i.length===a.length&&i.every(({id:n},o)=>n===a[o].id))).subscribe(this.available$)),this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),r.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),r.filterChanged()).subscribe(this.current$));const t=i=>{var a,n;return this.applyCueSettings((n=(a=i.target)===null||a===void 0?void 0:a.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(r.fromEvent(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)===null||a===void 0||a.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const m=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;m&&m.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(r.fromEvent(e,"removetrack").subscribe(i=>{var a;(a=i.track)===null||a===void 0||a.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const a=i;r.isNonNullable(t.align)&&(a.align=t.align),r.isNonNullable(t.position)&&(a.position=t.position),r.isNonNullable(t.size)&&(a.size=t.size),r.isNonNullable(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){r.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Pe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,a=e.id!==""?e.id:Kh(e);return this.externalTracks.has(a)?{id:a,type:"external",language:t,label:i,url:this.externalTracks.get(a).url}:{id:a,type:"internal",language:t,label:i}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(i=>i.id===t)).forEach(t=>this.detach(t))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))r.isNonNullable(e)&&Xh(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){r.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){r.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var Ve=s=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),s.appendChild(e),e};class Zs{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){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var wn=()=>{const{userAgent:s}=window.navigator;return!/chrome/i.test(s)&&/webkit|safari|khtml/i.test(s)};const Os=3;class Zh{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let a=this._source.buffered.start(t);const n=this._source.buffered.end(t);a>e&&a-e<Os&&(a=e),this._buffer.push({from:a,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Os))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:a,to:n})=>{const o=a>=e&&a<t,l=n>=e&&n<t;o&&l||(o?i(t,n):l?i(a,e):a<e&&n>t?(i(t,n),i(a,e)):i(a,n))})}destroy(){this._buffer=[]}}var _n=(s,e,t=Os)=>{let i=0,a=0;for(let n=0;n<s.length;n++){const o=s.start(n),l=s.end(n);if(o<=e&&e<=l){if(i=o,a=l,!t)return{from:i,to:a};for(let d=n-1;d>=0;d--)s.end(d)+t>=i&&(i=s.start(d));for(let d=n+1;d<s.length;d++)s.start(d)-t<=a&&(a=s.end(d))}}return{from:i,to:a}};const ef=50,tf=s=>s.webkitAudioDecodedByteCount!==void 0?!!s.webkitAudioDecodedByteCount:s.mozHasAudio!==void 0?s.mozHasAudio:s.audioTracks?!!s.audioTracks.length:!0,Fe=s=>{const e=b=>r.fromEvent(s,b).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=r.merge(...t.map(b=>r.fromEvent(s,b))).pipe(r.map(b=>b.type==="ended"?s.readyState<2:s.readyState<3),r.filterChanged()),a=r.merge(r.fromEvent(s,"progress"),r.fromEvent(s,"timeupdate")).pipe(r.map(()=>_n(s.buffered,s.currentTime))),n=wn()?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),o=r.fromEvent(s,"playing").pipe(r.debounce(ef),r.map(()=>tf(s))),l=r.fromEvent(s,"volumechange").pipe(r.map(()=>({muted:s.muted,volume:s.volume}))),d=r.fromEvent(s,"ratechange").pipe(r.map(()=>s.playbackRate)),u=r.fromEvent(s,"error").pipe(r.filter(()=>Boolean(s.error||s.played.length)),r.map(()=>{var b;const p=s.error;return{id:p?`MediaError#${p.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:p?p.message:"Error event from HTML video element",thrown:(b=s.error)!==null&&b!==void 0?b:void 0}})),c=r.fromEvent(s,"timeupdate").pipe(r.map(()=>s.currentTime)),h=new r.Subject,f=.3;let m;return c.subscribe(b=>{s.loop&&r.isNonNullable(m)&&r.isNonNullable(b)&&m>=s.duration-f&&b<=f&&h.next(m),m=b}),{playing$:n,pause$:e("pause").pipe(r.filter(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:r.fromEvent(s,"durationchange").pipe(r.map(()=>s.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:l,isAudioAvailable$:o,playbackRateState$:d}},ea=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var sf=Li,af=Di,rf=Js,nf=Qs;sf({target:"Array",proto:!0},{at:function(e){var t=af(this),i=rf(t),a=nf(e),n=a>=0?a:i+a;return n<0||n>=i?void 0:t[n]}});var of=Us,Rn=of,lf=Rn,uf=lf("Array","at"),df=uf,cf=df,hf=cf,ff=hf,Re=ff;let ta=!1,Ie={};const pf=s=>{ta=s},mf=()=>{Ie={}},bf=s=>{s(Ie)},ai=(s,e)=>{var t;ta&&(Ie.meta=(t=Ie.meta)!==null&&t!==void 0?t:{},Ie.meta[s]=e)};class $e{constructor(e){this.name=e}next(e){var t,i;if(!ta)return;Ie.series=(t=Ie.series)!==null&&t!==void 0?t:{};const a=(i=Ie.series[this.name])!==null&&i!==void 0?i:[];a.push([Date.now(),e]),Ie.series[this.name]=a}}const vf=new $e("best_bitrate"),Sf=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class gf{constructor(){this.history={}}recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Gt=(s,{container:e,throughput:t,tuning:i,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,m;const b=i.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*b*i.containerSizeFactor,height:e.height*b*i.containerSizeFactor},v=p&&at(p),S=i.considerPlaybackRate&&r.isNonNullable(l)?l:1,g=s.filter(I=>!Ei(I.quality)).sort((I,_)=>bi(I.quality,_.quality)?-1:1),A=(h=Re(g,-1))===null||h===void 0?void 0:h.quality,E=(f=Re(g,0))===null||f===void 0?void 0:f.quality,T=r.isNullable(a)||r.isNonNullable(a.min)&&r.isNonNullable(a.max)&&Ot(a.max,a.min)||r.isNonNullable(a.min)&&E&&bi(a.min,E)||r.isNonNullable(a.max)&&A&&Ot(a.max,A),w=S*Sf(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),C=g.filter(I=>{const _=v?Ot(I.quality,v):!0,H=r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(I.bitrate)?t-n>=I.bitrate*w:!0,Q=i.lazyQualitySwitch&&r.isNonNullable(i.minBufferToSwitchUp)&&d&&!Ei(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&bi(I.quality,d.quality),Z=T||(r.isNullable(a.max)||xh(I.quality,a.max))&&(r.isNullable(a.min)||Lh(I.quality,a.min));return _&&H&&!Q&&Z})[0];C&&C.bitrate&&vf.next(C.bitrate);const R=(m=C!=null?C:g[Math.ceil((g.length-1)/2)])!==null&&m!==void 0?m:s[0],F=R&&u&&u.history[R.id]&&r.now()-u.history[R.id]<=i.trackCooldown&&(!u.last||R.id!==u.last.id);if(R!=null&&R.id&&u&&!F&&u.recordSelection(R),F&&(u!=null&&u.last)){const I=u.last;return u==null||u.recordSwitch(I),I}return u==null||u.recordSwitch(R),R};var ne=s=>new URL(s).hostname;const yf=300,ki=(s,e=yf)=>new r.Observable(t=>{const{width:i,height:a}=s.getBoundingClientRect();if(t.next({width:i,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(mo(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),r.isNonNullable(d)&&r.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(s),()=>n.disconnect()}),Ue=s=>{try{s.pause(),s.playbackRate=0,s.removeAttribute("src"),s.load(),s.remove()}catch(e){console.error(e)}},Tf=5e3,Lt={};var x;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(x||(x={}));const te=(s,e)=>new r.Observable(t=>{const i=a=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class lr{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(x.DOWNLOADING_LIB),this.textTracksManager=new Pe,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new r.ValueSubject(void 0),this.maxSeekBackTime$=new r.ValueSubject(1/0),this.availableFrom$=new r.ValueSubject(void 0),this.elementSize$=new r.ValueSubject(void 0),this.liveOffset=new Zs,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===x.DOWNLOADING_LIB||t===x.STREAM_INITIALIZED))switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===N.Requested&&t!==x.STOPPED&&i!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),i){case exports.PlaybackState.STOPPED:{switch(t){case x.STOPPED:break;case x.PLAYING:case x.PAUSED:case x.READY:this.stop();break;default:r.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case x.STOPPED:this.prepare();break;case x.PLAYING:case x.PAUSED:case x.READY:break;default:r.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case x.PLAYING:break;case x.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case x.READY:this.play();break;case x.STOPPED:this.prepare();break;default:r.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case x.PLAYING:this.pause(),this.liveOffset.pause();break;case x.PAUSED:break;case x.READY:this.videoState.setState(x.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case x.STOPPED:this.prepare();break;default:r.assertNever(t)}break}default:r.assertNever(i)}},this.video=Ve(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=a=>{var n;e||this.params.output.error$.next({id:a==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:r.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=a==null?void 0:a.toString)===null||n===void 0?void 0:n.call(a)}`,thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),Tf);import("dashjs/dist/dash.mediaplayer.min.js").then(a=>{e||(Lt.MediaPlayer=a.MediaPlayer,Lt.Debug=a.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(Lt.MediaPlayer,"dashjs not loaded"),r.assertNonNullable(Lt.Debug,"dashjs not loaded"),this.player=Lt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?ea(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=qh(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&Jh(this.player),zh(this.player),this.params.tuning.requestQuick&&Qh(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(x.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=p=>{e.error$.next({id:"DashIFProvider",category:r.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:p})},a=(p,v)=>this.subscription.add(p.subscribe(v,i));a(ki(this.video),this.elementSize$),a(te(this.player,"error").pipe(r.map(p=>{const v=typeof p.error=="object"?p.error.code:p.error,S=typeof p.error=="object"?p.error.message:void 0;return{id:`DashJS#${v}`,message:S}})),e.error$),a(te(this.player,"playbackError").pipe(r.map(p=>({id:"DashJSPlayback",message:p.error}))),e.error$);const n=te(this.player,"qualityChangeRendered").pipe(r.filter(({mediaType:p})=>p==="video"),r.map(({newQuality:p})=>{var v;return(v=this.videoTracks.find(({bitrateInfo:S})=>S.qualityIndex===p))===null||v===void 0?void 0:v.track}));n.pipe(r.filter(r.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(r.filter(({to:p})=>p===x.STREAM_INITIALIZED),r.once()).subscribe(()=>{this.subscription.add(ke(t.videoTrack,()=>{var p,v;const S=this.player.getQualityFor("video");return(v=(p=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===S))===null||p===void 0?void 0:p.track)===null||v===void 0?void 0:v.id},p=>{var v;if(r.isNullable(p))return;const S=(v=this.videoTracks.find(({track:g})=>g.id===p))===null||v===void 0?void 0:v.bitrateInfo;S&&this.player.setQualityFor("video",S.qualityIndex)},{changed$:n.pipe(r.map(p=>p==null?void 0:p.id)),onError:i}))},i)),this.subscription.add(ke(t.autoVideoTrackSwitching,()=>{var p,v,S;return(S=(v=(p=this.player.getSettings().streaming)===null||p===void 0?void 0:p.abr)===null||v===void 0?void 0:v.autoSwitchBitrate)===null||S===void 0?void 0:S.video},p=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:p}}}}),{onError:i})),a(te(this.player,"bufferStateChanged").pipe(r.filter(({mediaType:p})=>p==="video"),r.map(({state:p})=>p==="bufferStalled")),e.isBuffering$),a(te(this.player,"fragmentLoadingStarted"),({mediaType:p,request:{url:v}})=>{var S,g;const A=this.player.getDashMetrics(),E=A.getLatestFragmentRequestHeaderValueByID(p,"X-Reused"),T=(S=A.getLatestFragmentRequestHeaderValueByID(p,"X-Delivery-Type"))!==null&&S!==void 0?S:exports.HttpConnectionType.HTTP1,w=(g={1:!0,0:!1}[E])!==null&&g!==void 0?g:void 0;this.params.output.httpConnectionType$.next(T),this.params.output.httpConnectionReused$.next(w),e.hostname$.next(ne(v))}),a(te(this.player,"streamInitialized"),({streamInfo:{duration:p,manifestInfo:{isDynamic:v,availableFrom:S}}})=>{this.isLive$.next(v),this.availableFrom$.next(S.getTime()),v||e.duration$.next(p),this.videoTracks=[];const g=this.player.getQualityFor("video");let A;for(const E of this.player.getBitrateInfoListFor("video")){const T=E.qualityIndex.toString(10),w=at(E),V=E.bitrate/1e3,C={width:E.width,height:E.height},R=this.frameRatesByFrameHeight[E.height];if(w){const F={id:T,quality:w,bitrate:V,size:C,fps:R};this.videoTracks.push({track:F,bitrateInfo:E}),E.qualityIndex===g&&(A=F)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:E})=>E)),A&&e.currentVideoTrack$.next(A),this.videoState.setState(x.STREAM_INITIALIZED),this.videoState.startTransitionTo(x.READY)}),a(te(this.player,"fragmentLoadingCompleted"),({request:p})=>{if(!p.requestEndDate||!p.firstByteDate||!p.bytesLoaded)return;const v=p.requestEndDate.getTime()-p.firstByteDate.getTime(),S=p.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(S,v)}),a(r.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const p=this.params.dependencies.throughputEstimator.throughput$.getValue(),v=Gt(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:p,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),S=this.videoTracks.find(({track:g})=>g===v);S!=null&&S.bitrateInfo&&this.player.setQualityFor("video",S==null?void 0:S.bitrateInfo.qualityIndex,!1)}),a(r.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(r.filter(r.isNonNullable))}).pipe(r.filter(({isLive:p})=>p),r.map(({maxSeekBackTime:p})=>-p/1e3)),this.params.output.duration$);const o=te(this.player,"playbackTimeUpdated").pipe(r.map(({time:p})=>p!=null?p:0));a(r.combine({availableFrom:this.availableFrom$.pipe(r.filter(r.isNonNullable)),currentTime:o}),({availableFrom:p,currentTime:v})=>this.params.output.liveTime$.next(p+v*1e3)),a(o.pipe(r.filter(()=>this.isLive$.getValue()===!1)),e.position$),a(te(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),a(te(this.player,"playbackEnded"),e.endedEvent$),a(te(this.player,"playbackProgress").pipe(r.map(()=>_n(this.video.buffered,this.video.currentTime))),e.currentBuffer$),a(te(this.player,"playbackPlaying"),()=>{this.videoState.setState(x.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),a(te(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(x.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),a(te(this.player,"playbackPaused"),()=>{this.videoState.setState(x.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),a(te(this.player,"canPlay"),()=>{var p;((p=this.videoState.getTransition())===null||p===void 0?void 0:p.to)===x.READY&&this.videoState.setState(x.READY)}),a(this.isLive$,e.isLive$),a(ki(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));a(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=Wh(this.player);a(c,this.params.output.httpConnectionType$),a(h,this.params.output.httpConnectionReused$),a(d,this.maxSeekBackTime$),a(u.pipe(r.once()),e.firstBytesEvent$),a(te(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(r.combine({isLive:this.isLive$,isShort:e.duration$.pipe(r.map(p=>p<60))}),({isLive:p,isShort:v})=>{const S=!p&&v;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:S}}})}),a(o.pipe(r.filter(p=>p>this.params.tuning.insufficientBufferRuleMargin),r.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(te(this.player,"manifestLoaded").pipe(r.once()).subscribe(()=>{this.subscription.add(te(this.player,"playbackPlaying").pipe(r.once(),r.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),this.subscription.add(rt(this.video,t.isLooped,i));const{volumeState$:f,looped$:m,playbackRateState$:b}=Fe(this.video);this.subscription.add(Me(this.video,t.volume,f,i)),this.subscription.add(f.subscribe(e.volume$,i)),this.subscription.add(m.subscribe(e.loopedEvent$)),this.subscription.add(qe(this.video,t.playbackRate,b,i))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(x.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(x.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const a=bt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,mt.PLAYBACK_SHIFT);this.player.attachSource(a)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(x.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(x.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(i){}Ue(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Yt=s=>{switch(s){case"mobile":return exports.VideoQuality.Q_144P;case"lowest":return exports.VideoQuality.Q_240P;case"low":return exports.VideoQuality.Q_360P;case"sd":case"medium":return exports.VideoQuality.Q_480P;case"hd":case"high":return exports.VideoQuality.Q_720P;case"fullhd":case"full":return exports.VideoQuality.Q_1080P;case"quadhd":case"quad":return exports.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return exports.VideoQuality.Q_2160P}},ze=async s=>{const e=s.muted;try{await s.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return s.muted=!1,console.warn(i),!1}}return!0};function ae(){return r.now()}function In(s){return ae()-s}function ur(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=o=>i.test(o);return{resolve:(o,l,d=!1)=>{a(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function Ef(s,e,t){const i=(...a)=>{t.apply(null,a),s.removeEventListener(e,i)};s.addEventListener(e,i)}function vi(s,e,t,i){const a=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,m="arraybuffer",b=7e3,p=2e3,v=()=>{if(d)return;r.assertNonNullable(c);const _=In(c);let H;if(_<p){H=p-_,setTimeout(v,H);return}p*=2,p>b&&(p=b),o&&o.abort(),o=new a,w()};const S=_=>(n=_,I),g=_=>(h=_,I),A=()=>(m="json",I),E=()=>{if(!d){if(--u>=0){v(),i&&i();return}d=!0,h&&h(),t&&t()}},T=_=>(f=_,I),w=()=>{c=ae(),o=new a,o.open("get",s);let _=0,H,Q=0;const Z=()=>(r.assertNonNullable(c),Math.max(c,Math.max(H||0,Q||0)));if(n&&o.addEventListener("progress",$=>{const D=ae();n.updateChunk&&$.loaded>_&&(n.updateChunk(Z(),$.loaded-_),_=$.loaded,H=D)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(d)return;r.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const D=o.response.byteLength-_;D&&n.updateChunk&&n.updateChunk(Z(),D)}h&&h(),o&&e(o.response)}else E()}),o.addEventListener("error",()=>{E()}),f){const $=()=>{r.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=ae(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=m,o.send(),I},I={withBitrateReporting:S,withParallel:T,withJSONResponse:A,withRetryCount:_=>(u=_,I),withRetryInterval:(_,H)=>(r.isNonNullable(_)&&(p=_),r.isNonNullable(H)&&(b=H),I),withTimeout:_=>(l=_,I),withFinally:g,send:w,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return I}const $f=100,kf=2e3,Af=500;let Pf=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-Af;if(t-e>kf){let i=0,a=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,a+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;i+=o;const d=n.bytes*o/l;a+=d,n.start=t,n.bytes-=d}}}if(a>0&&i>0){const n=a*8/(i/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>$f&&(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 wf{constructor(e,t,i,a,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=a,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const 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){const i=ae(),a=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=ae()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=vi(t,n,()=>a("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ae()}_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(){const e=this._getParallelRequestCount(),t=ae();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const 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(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,a){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,o._retryCB=a,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=i,n._retryCB=a,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}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}}const ri=1e4,ni=3,_f=300,Rf=2e3,If=6e4,Nf=10,Df=1,Cf=500;class Lf{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new Pf(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ur(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ur(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){const{videoElement:t}=this.params;let i,a,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!a||n.bitrate>a.bitrate)&&(a=n):(!i||i.bitrate>n.bitrate)&&(i=n));return a||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||r.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:a,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{Ef(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new wf(ni,ri,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:a}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const E=n&&(!c||c===this.rep);return E||t("Not running!"),E},f=(E,T,w)=>{d&&d.abort(),d=vi(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withTimeout(ri).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ni).withFinally(()=>{d=null}).send()},m=(E,T,w)=>{r.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},b=E=>{const T=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${T}=>${E}`),i.playbackRate=E)},p=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}const w=ae()-1e4;let V=0;for(let R=0;R<this.bufferStates.length;R++){const F=this.bufferStates[R];E=Math.min(E,F.buf),F.ts<w&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${E} drop=${V} jitter=${this.sourceJitter}`);let C=E-Df;this.sourceJitter>=0?C-=this.sourceJitter/2:this.sourceJitter-=1,C>3?b(1.15):C>1?b(1.1):C>.3?b(1.05):b(1)}},S=E=>{let T;const w=()=>T&&T.start?T.start.length:0,V=$=>T.start[$]/1e3,C=$=>T.dur[$]/1e3,R=$=>T.fragIndex+$,F=($,D)=>({chunkIdx:R($),startTS:V($),dur:C($),discontinuity:D}),I=()=>{let $=0;if(T&&T.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,X=D;this.sourceJitter>1&&(X+=this.sourceJitter-1);let ee=T.dur.length-1;for(;ee>=0&&(X-=T.dur[ee],!(X<=0));--ee);$=Math.min(ee,T.dur.length-1-q),$=Math.max($,0)}return F($,!0)},_=$=>{const D=w();if(!(D<=0)){if(r.isNonNullable($)){for(let q=0;q<D;q++)if(V(q)>$)return F(q)}return I()}},H=$=>{const D=w(),q=$?$.chunkIdx+1:0,X=q-T.fragIndex;if(!(D<=0)){if(!$||X<0||X-D>Nf)return t(`Resync: offset=${X} bChunks=${D} chunk=`+JSON.stringify($)),I();if(!(X>=D))return F(q-T.fragIndex,!1)}},Q=($,D,q)=>{u&&u.abort(),u=vi(this.urlResolver.resolve($,!0,this.lowLatency),D,q,()=>this._retryCallback()).withTimeout(ri).withRetryCount(ni).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,D)=>{Q(E,q=>{if(!h())return;T=q;const X=Boolean(T.lowLatency);X!==this.lowLatency&&p(X);let ee=0;for(let oe=0;oe<T.dur.length;++oe)ee+=T.dur[oe];ee>0&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ee/T.dur.length)),a({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,$(_(D))},()=>this._handleNetworkError())},nextChunk:H}},g=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),r.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{const{videoElement:T,logger:w}=this.params;let V=S(e.jidxUrl),C,R,F,I,_=0,H,Q,Z;const $=()=>{H&&(clearTimeout(H),H=void 0);const U=Math.max(Cf,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=_+U,re=ae(),ue=Math.min(1e4,ie-re);_=re;const We=()=>{u||h()&&V.seek(()=>{h()&&(_=ae(),D(),$())})};ue>0?H=window.setTimeout(()=>{this.paused?$():We()},ue):We()},D=()=>{let U;for(;U=V.nextChunk(I);)I=U,ge(U);const ie=V.nextChunk(F);if(ie){if(F&&ie.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?$():(g(),this._initPlayerWith(e));return}oe(ie)}else $()},q=(U,ie)=>{if(!h()||!this.sourceBuffer)return;let re,ue,We;const ye=je=>{window.setTimeout(()=>{h()&&q(U,ie)},je)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),ye(100);else{const je=ae(),Qe=T.currentTime;!this.paused&&T.buffered.length>1&&Q===Qe&&je-Z>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),Q!==Qe&&(Q=Qe,Z=je);const $t=this._getBufferSizeSec();if($t>30)w(`Buffered ${$t} seconds; delaying appendBuffer`),ye(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:je,buf:$t}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch(nt){if(nt.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),We=this.sourceBuffer.buffered.length,We!==0&&(re=this.sourceBuffer.buffered.start(0),ue=Qe,ue-re>4&&this.sourceBuffer.remove(re,ue-3)),ye(1e3);else throw nt}}},X=()=>{R&&C&&(w([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(F)]),q(R,function(){R=null,D()}))},ee=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),oe=U=>{h()&&m(ee(U),(ie,re)=>{if(h()){if(re/=1e3,R=ie,F=U,o=U.startTS,re){const ue=Math.min(10,U.dur/re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ue:ue}X()}},()=>this._handleNetworkError())},ge=U=>{h()&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(U),!1)))},Et=U=>{h()&&(e.cachedHeader=U,q(U,()=>{C=!0,X()}))};n=!0,V.seek(U=>{if(h()){if(_=ae(),!U){$();return}I=U,!r.isNullable(E)||U.startTS>E?oe(U):(F=U,D())}},E),e.cachedHeader?Et(e.cachedHeader):f(e.headerUrl,Et,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),r.isNonNullable(a)&&(a+=.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,r.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return r.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=h=>{if(!this.autoQuality)return;let f,m,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(m=this._getBufferSizeSec(),b=h/this.bitrate,m>10&&b>.8||m>15&&b>.5||m>20&&b>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,m)=>{const b=ae();if(this.chunkRateEstimator.addInterval(f,b,m)){const v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:b-f,speed:v}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&In(o)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const m=n.updateChunk(h,f);return m&&u(),m},notifySwitch:h=>{const f=ae();h<l&&(o=f),l=h}}}_fetchManifest(e,t,i){this.manifestRequest=vi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ri).withRetryCount(ni).withRetryInterval(_f,Rf).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;ze(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:a}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&a.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},If))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var O;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(O||(O={}));const xf=[O.PAUSED,O.PLAYING,O.READY],Of=[O.PAUSED,O.PLAYING,O.READY];class Bf{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(O.STOPPED),this.representations$=new r.ValueSubject([]),this.textTracksManager=new Pe,this.maxSeekBackTime$=new r.ValueSubject(1/0),this.zeroTime$=new r.ValueSubject(void 0),this.liveOffset=new Zs,this._dashCb=a=>{var n,o,l,d;switch(a.name){case"buffering":{const u=a.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${a.type}`,category:r.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=a.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),m=(o=Yt(h.name))!==null&&o!==void 0?o:at(h.video),b=h.bitrate/1e3,p={...h.video};if(!m)continue;const v={id:f,quality:m,bitrate:b,size:p};c.push({track:v,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===O.MANIFEST_READY&&this.videoState.setState(O.MANIFEST_READY);break}case"qualitySwitch":{const u=a.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),r.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=a;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(a.shiftDuration),this.zeroTime$.next(a.zeroTime);break}}},this.syncPlayback=()=>{var a;const n=this.videoState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.playbackState.getState(),d=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${n}; videoTransition: ${JSON.stringify(o)}; desiredPlaybackState: ${l}; seekState: ${JSON.stringify(u)};`}),l===exports.PlaybackState.STOPPED){n!==O.STOPPED&&(this.videoState.startTransitionTo(O.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(O.STOPPED));return}if(!o){if(Of.includes(n)){const c=(a=this.params.desiredState.videoTrack.getTransition())===null||a===void 0?void 0:a.to;r.isNonNullable(c)&&this.setVideoTrack(c);const h=this.params.desiredState.autoVideoTrackSwitching.getTransition();h&&this.setAutoQuality(h.to)}if((d==null?void 0:d.to)!==exports.PlaybackState.PAUSED&&u.state===N.Requested&&xf.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case O.STOPPED:this.videoState.startTransitionTo(O.MANIFEST_READY),this.dash.attachSource(bt(this.params.source.url));return;case O.MANIFEST_READY:this.videoState.startTransitionTo(O.READY),this.prepare();break;case O.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(O.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(O.PLAYING);const c=d==null?void 0:d.from;c&&c===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)})}return;case O.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(O.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case O.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(O.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return r.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=a=>{e.output.error$.next({id:"DashLiveProvider",category:r.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}),this.video=Ve(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ne(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.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=Fe(this.video);this.subscription.add(i.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())===null||a===void 0?void 0:a.to)===O.READY&&this.videoState.setState(O.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(O.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===N.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(O.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(r.combine({zeroTime:this.zeroTime$.pipe(r.filter(r.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(rt(this.video,this.params.desiredState.isLooped,t)).add(Me(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(qe(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:a}})=>{const n=a&&Mh(a);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var n;switch(a.to){case O.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case O.MANIFEST_READY:case O.READY:((n=this.params.desiredState.playbackState.getTransition())===null||n===void 0?void 0:n.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case O.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case O.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(a.to)}},t)).add(r.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}createLiveDashPlayer(){const e=new Lf({videoElement:this.video,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},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,i,a,n,o;const l=this.representations$.getValue(),d=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(a=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&a!==void 0?a:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&r.isNonNullable(d)?d:(n=Gt(l.map(({track:f})=>f),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))===null||n===void 0?void 0:n.id,h=(o=l.find(({track:f})=>f.id===c))===null||o===void 0?void 0:o.representation;r.assertNonNullable(h,"Representations missing"),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(c),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:a})=>a.id===e))===null||t===void 0?void 0:t.representation;r.assertNonNullable(i,`No such representation ${e}`),this.dash.switchByName(i.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();const t=-e,i=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(i),this.dash.reinit(bt(this.params.source.url,i))}}var Nn=s=>{var e,t;const i=s.get("X-Delivery-Type"),a=s.get("X-Reused"),n=i===null?exports.HttpConnectionType.HTTP1:(e=i)!==null&&e!==void 0?e:void 0,o=a===null?void 0:(t={1:!0,0:!1}[a])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},Ze=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const a=s.start(i)*1e3,n=s.end(i)*1e3;a<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Mf=s=>{const e=document.createElement("a");return e.href=s,e.origin},Vf=s=>{const e=document.createElement("a");return e.href=s,e.host};class Dn{constructor(e,t=[],i,a,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=a,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,i,a,n,o,l,d,u;if(r.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.call(this,`Http${(a=this._xhr)===null||a===void 0?void 0:a.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=Ht(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let a;this._failoverIndex>=this._failoverHosts.length?(a=this._url,this._failoverIndex=0):(a=this._url.replace(Vf(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",a,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Ai{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const a=this._sourceBuffer.buffered;let n=0;for(let o=0,l=a.length;o<l;o++)n+=a.end(o)-a.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,a,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const m=p=>{a(Ai._str2ua(p.substr(d))),d=p.length};let b=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(b=St(b)),this._lastXhr=new Dn(b,e.failoverHosts,p=>{this._lastXhr=void 0,m(p);const v=Date.now()-u;this._params.onBandwidthChange({size:p.length,duration:v,speed:8*p.length/(v/1e3)}),this._onDashCallback("loading",{size:p.length,done:!0}),n==null||n()},p=>{if(p.length-d>l&&m(p),h===0){h=Date.now();return}f=p.length-c;const v=Date.now()-h;f>=100*1024&&v>=1e3&&(this._params.onBandwidthChange({size:f,duration:v,speed:8*f/(v/1e3)}),f=0,c=p.length,h=Date.now()),this._onDashCallback("loading",{size:p.length,done:!1})},o,(p,v,S)=>this._params.onError(p,v,S))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Ai._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class Ff{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},a=t.exec(e),n=(a==null?void 0:a[1])==="-"?-1:1,o={years:i(a==null?void 0:a[2],n),months:i(a==null?void 0:a[3],n),weeks:i(a==null?void 0:a[4],n),days:i(a==null?void 0:a[5],n),hours:i(a==null?void 0:a[6],n),minutes:i(a==null?void 0:a[7],n),seconds:i(a==null?void 0:a[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=St(i)),new Dn(i,t,a=>{this.attachManifest(a,t,Mf(i))},void 0,a=>{this._params.onResponseHeaders(a)},(a,n,o)=>this._params.onError(a,n,o))}attachManifest(e,t,i){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,m,b,p,v,S,g,A,E,T,w,V,C,R,F,I,_;const H=u.getElementsByTagName("SegmentBase")[0],Q=H&&o(H,"indexRange").split("-"),Z=H&&H.getElementsByTagName("Initialization")[0],$=Z&&o(Z,"range").split("-");if(!$||!Q){const ge=u.parentElement;if((ge==null?void 0:ge.getAttribute("contentType"))==="text"){const Et=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,U=(i?i+"/":"")+((b=(m=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||m===void 0?void 0:m[0])===null||b===void 0?void 0:b.data),ie=(p=ge.getAttribute("lang"))!==null&&p!==void 0?p:void 0;U&&d.push({id:Et,url:U,language:ie})}return}const D=.1,q=Number((v=u.attributes.getNamedItem("bandwidth"))===null||v===void 0?void 0:v.value),X=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ee;const oe=(g=(S=u.attributes.getNamedItem("frameRate"))===null||S===void 0?void 0:S.value)!==null&&g!==void 0?g:void 0;ee=oe?ea(oe):void 0,l.push({width:Number((A=u.attributes.getNamedItem("width"))===null||A===void 0?void 0:A.value),height:Number((E=u.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:q,baseURL:X,failoverHosts:t,indexFrom:Number(Q[0]),indexTo:Number(Q[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(w=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&w!==void 0?w:void 0,mimeType:(C=(V=u.attributes.getNamedItem("mimeType"))===null||V===void 0?void 0:V.value)!==null&&C!==void 0?C:void 0,fps:ee,bufferSize:D*q/8,bufferLength:D,name:(F=(R=u.attributes.getNamedItem("okQuality"))===null||R===void 0?void 0:R.value)!==null&&F!==void 0?F:void 0,id:(_=(I=u.attributes.getNamedItem("id"))===null||I===void 0?void 0:I.value)!==null&&_!==void 0?_:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,a=>{let n=e.initTo-e.initFrom+1;if(!a.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(a.buffer,0,n);const o=new DataView(a.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const m=u+(o.getUint32(n,!1)&2147483647),b=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:b/l,fromOffset:u,toOffset:m-1}),u=m,d=b}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,a=>{this._params.onResponseHeaders(a),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let a,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const m=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),m)}const c=this._appendVector[String(u.fromTime)];c!==a&&(a=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const m=this._buffer.getByTime(this._video.currentTime);if(!m){this._onDashCallback("buffering");return}h=m.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==m.to&&(n=m.to,window.setTimeout(()=>{try{const b=this._buffer.getNextWithGap(m);b&&(this._video.currentTime=b.from)}catch(b){throw this._params.onError("GapSyncError",`Seek Error ${String(b)}`,b),b}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Ai({mediaSource:i,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||l(),i.removeEventListener("sourceopen",d),i.removeEventListener("webkitsourceopen",d)};i.addEventListener("sourceopen",d,!1),i.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,a=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(i){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=a||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),a=this._findRef(this._video.currentTime);if(!i||!a){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(a.toTime<i.to+n){const o=this._findRef(a.toTime);o&&o.toTime<i.to+n?(this._buffer.smartRemove(a.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(a.fromTime-n,a.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,a.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||r.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let a;for(let n=0;n<i.length;n++){const o=i[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!a||o.fromTime<a.fromTime)&&(a=o)}if(!a){const n=i[i.length-1];if(e>n.toTime)return n}return a}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const a=i[i.length-1];return e.fromTime===a.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),a=this._video.buffered.end(t);if(e>i&&e<a)return Math.round(a*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var B;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(B||(B={}));const Uf=[B.PAUSED,B.PLAYING];class jf{constructor(e){this.videoState=new W(B.STOPPED),this.subscription=new r.Subscription,this.representations$=new r.ValueSubject([]),this.currentRepresentation$=new r.ValueSubject(void 0),this.textTracksManager=new Pe,this.elementSize$=new r.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new r.Subject,responseHeaders$:new r.Subject,manifestReady$:new r.Subject,representationPlay$:new r.Subject,error$:new r.Subject},this.handleManifestReady=t=>{var i,a,n;const o=[];for(const l of t){const d=(a=(i=l.name)!==null&&i!==void 0?i:l.id)!==null&&a!==void 0?a:l.height.toString(10),u=(n=l.name&&Yt(l.name))!==null&&n!==void 0?n:at(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const m={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:m,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(B.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const a=(i=this.representations$.getValue().find(({representation:n})=>n===t))===null||i===void 0?void 0:i.track;a&&(this.params.output.currentVideoTrack$.next(a),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return r.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${a}; seekState: ${JSON.stringify(o)};`}),a===exports.PlaybackState.STOPPED){t!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(B.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!i)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===N.Requested&&Uf.includes(t)&&this.seek(o.position,o.forcePrecise),t){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_LOADED),this.prepare();return;case B.MANIFEST_LOADED:this.videoState.startTransitionTo(B.INITIAL_REPRESENTATION_SELECTED);return;case B.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(B.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case B.METADATA_LOADED:this.videoState.startTransitionTo(B.READY),this.dash.updateRefsForCurrentTime();return;case B.READY:a===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed());return;case B.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(B.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case B.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),r.merge(this.videoState.stateChangeStarted$.pipe(r.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=Ve(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Zh(this.video),this.dash=new Ff({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,a)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:a,category:r.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"DashProvider",category:r.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},a=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=Fe(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,i));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(n.seeking$.subscribe(()=>{r.isNullable(this.params.desiredState.seekState.getState().state!==N.Applying)&&(this.videoState.getState()===B.PLAYING||this.videoState.getState()===B.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Me(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,t.playbackRate,n.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),o(ki(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===B.READY&&this.videoState.setState(B.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(B.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(B.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},i)).add(this.dashLiteEvents.error$.pipe(r.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:r.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(r.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,r.fromEvent(this.video,"progress")).pipe(r.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),m=this.params.desiredState.videoTrack.getState(),b=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),v=a();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let S;if(!v&&r.isNonNullable(m))S=m;else{const g=Ze(this.video.buffered,this.video.currentTime*1e3),A=v?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(g/A,1);S=(d=Gt(h.map(({track:T})=>T),{container:p,throughput:b,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:T})=>T===c))===null||l===void 0?void 0:l.track}))===null||d===void 0?void 0:d.id}return r.isNonNullable(S)?(u=h.find(({track:g})=>g.id===S))===null||u===void 0?void 0:u.representation:void 0}),r.filterChanged()).subscribe(this.currentRepresentation$,i)).add(r.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(r.filter(l=>l.to===B.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(r.filter(r.isNonNullable))}).pipe(r.once()).subscribe(()=>this.videoState.setState(B.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(r.filter(r.isNonNullable),r.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?l.height<=d.height:l===d)).subscribe(l=>{const d=Ze(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!a())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(ne(l.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Nn(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(r.once(),r.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(r.filter(r.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return r.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var he;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(he||(he={}));var Pi;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Pi||(Pi={}));var fe;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(fe||(fe={}));var j;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(j||(j={}));var gt;(function(s){s.MP4="mp4",s.WEBM="webm"})(gt||(gt={}));var Bs=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const Hf=(s,e={})=>{const i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},Gf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",dr=Gf?Hf:window.requestIdleCallback;var us,ds;let Cn=!1;try{Cn=wn()&&parseInt((ds=(us=navigator.userAgent.match(/Version\/(\d+)/))===null||us===void 0?void 0:us[1])!==null&&ds!==void 0?ds:"",10)<16}catch(s){console.error(s)}class Yf{constructor(e){this.bufferFull$=new r.Subject,this.error$=new r.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{const n={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;Cn&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:a}of this.queue)a(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask);try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"&&i==="remove"||this.error$.next({id:`BufferTaskQueue:${i}`,category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:r.assertNever(t)}}}var cr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};const Ln=new TextDecoder("ascii"),xn=s=>{let e=0,t=s.getUint32(e);e+=4;const i=new DataView(s.buffer,s.byteOffset+e,4),a=Ln.decode(i);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,s.byteLength)-e,o=new DataView(s.buffer,s.byteOffset+e,n);return{id:a,size:t,contents:o}},qf=s=>Ln.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",zf=(s,e,t)=>{const i=xn(s),a=[];let n=0;const o=()=>{const p=i.contents.getUint32(n);return n+=4,p};if((o()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");o();const u=o(),c=o(),h=o(),f=o()&4294967295;let m=c/u*1e3,b=(t?t.to+1:s.byteOffset+s.byteLength)+h;for(let p=0;p<f;p++){const v=o(),S=v>>>31,g=v<<1>>>1,A=o();if(o(),S!==0)throw new Error("Unsupported multilevel sidx");const E=A/u*1e3;a.push({status:j.NONE,time:{from:m,to:m+E},byte:{from:b,to:b+g-1}}),m+=E,b+=g}return a},Wf=s=>{let e=0,t=!1,i=!1;for(;e<=s.byteLength&&!t;){const a=new DataView(s.buffer,s.byteOffset+e);try{const n=xn(a);if(i||(i=n.id==="mdat"),e+n.size<=s.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=s.byteLength&&i?new DataView(s.buffer,s.byteOffset,e):null},Qf={validateData:qf,parseInit:()=>null,getIndexRange:()=>{},parseSegments:zf,parseFeedableSegmentChunk:Wf};var y;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(y||(y={}));var P;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(P||(P={}));const hr={[y.EBML]:{type:P.Master},[y.EBMLVersion]:{type:P.UnsignedInteger},[y.EBMLReadVersion]:{type:P.UnsignedInteger},[y.EBMLMaxIDLength]:{type:P.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:P.UnsignedInteger},[y.DocType]:{type:P.String},[y.DocTypeVersion]:{type:P.UnsignedInteger},[y.DocTypeReadVersion]:{type:P.UnsignedInteger},[y.Void]:{type:P.Binary},[y.Segment]:{type:P.Master},[y.SeekHead]:{type:P.Master},[y.Seek]:{type:P.Master},[y.SeekID]:{type:P.Binary},[y.SeekPosition]:{type:P.UnsignedInteger},[y.Info]:{type:P.Master},[y.TimestampScale]:{type:P.UnsignedInteger},[y.Duration]:{type:P.Float},[y.Tracks]:{type:P.Master},[y.Chapters]:{type:P.Master},[y.Cluster]:{type:P.Master},[y.Timestamp]:{type:P.UnsignedInteger},[y.SilentTracks]:{type:P.Master},[y.SilentTrackNumber]:{type:P.UnsignedInteger},[y.Position]:{type:P.UnsignedInteger},[y.PrevSize]:{type:P.UnsignedInteger},[y.SimpleBlock]:{type:P.Binary},[y.BlockGroup]:{type:P.Master},[y.EncryptedBlock]:{type:P.Binary},[y.Attachments]:{type:P.Master},[y.Tags]:{type:P.Master},[y.Cues]:{type:P.Master},[y.CuePoint]:{type:P.Master},[y.CueTime]:{type:P.UnsignedInteger},[y.CueTrackPositions]:{type:P.Master},[y.CueTrack]:{type:P.UnsignedInteger},[y.CueClusterPosition]:{type:P.UnsignedInteger},[y.CueRelativePosition]:{type:P.UnsignedInteger},[y.CueDuration]:{type:P.UnsignedInteger},[y.CueBlockNumber]:{type:P.UnsignedInteger},[y.CueCodecState]:{type:P.UnsignedInteger},[y.CueReference]:{type:P.Master},[y.CueRefTime]:{type:P.UnsignedInteger}},On=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=wi(s,t),a=i in hr,n=a?hr[i].type:P.Binary,o=s.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(s.buffer,s.byteOffset+t+1,l-1),u=o&255>>l,c=wi(d),h=u*2**((l-1)*8)+c,f=t+l;let m;return f+h>s.byteLength?m=new DataView(s.buffer,s.byteOffset+f):m=new DataView(s.buffer,s.byteOffset+f,h),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:m,valueSize:h}},wi=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ne=(s,e)=>{switch(e){case P.SignedInteger:return s.getInt8(0);case P.UnsignedInteger:return wi(s);case P.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case P.String:return new TextDecoder("ascii").decode(s);case P.UTF8:return new TextDecoder("utf-8").decode(s);case P.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case P.Master:return s;case P.Binary:return s;default:r.assertNever(e)}},qt=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),a=On(i);if(!e(a))return;a.type===P.Master&&qt(a.value,e),t=a.value.byteOffset-s.byteOffset+a.valueSize}},Jf=s=>{if(s.getUint32(0)!==y.EBML)return!1;let e,t,i;const a=On(s);return qt(a.value,({tag:n,type:o,value:l})=>(n===y.EBMLReadVersion?e=Ne(l,o):n===y.DocType?t=Ne(l,o):n===y.DocTypeReadVersion&&(i=Ne(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Bn=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],Kf=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],Xf=s=>{let e,t,i,a,n=!1,o=!1,l=!1,d,u;return qt(s,({tag:c,type:h,value:f,valueSize:m})=>{if(c===y.SeekID){const b=Ne(f,h);u=wi(b)}else c!==y.SeekPosition&&(u=void 0);return c===y.Segment?(e=f.byteOffset,t=f.byteOffset+m):c===y.Info?n=!0:c===y.SeekHead?o=!0:c===y.TimestampScale?i=Ne(f,h):c===y.Duration?a=Ne(f,h):c===y.SeekPosition&&u===y.Cues?d=Ne(f,h):n&&o&&Bn.includes(c)&&(l=!0),!l}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(a,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*1e3),cuesSeekPosition:d}},Zf=s=>{if(r.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ep=(s,e)=>{let t=!1,i=!1;const a=l=>r.isNonNullable(l.time)&&r.isNonNullable(l.position),n=[];let o;return qt(s,({tag:l,type:d,value:u})=>{switch(l){case y.Cues:t=!0;break;case y.CuePoint:o&&a(o)&&n.push(o),o={};break;case y.CueTime:o&&(o.time=Ne(u,d));break;case y.CueTrackPositions:break;case y.CueClusterPosition:o&&(o.position=Ne(u,d));break;default:t&&Bn.includes(l)&&(i=!0)}return!(t&&i)}),o&&a(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:j.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},tp=s=>{let e=0,t=!1;try{qt(s,i=>i.tag===y.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Kf.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},ip={validateData:Jf,parseInit:Xf,getIndexRange:Zf,parseSegments:ep,parseFeedableSegmentChunk:tp};class fr{constructor(e,t,i,a,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new r.ValueSubject(!1),this.fullyBuffered$=new r.ValueSubject(!1),this.playingRepresentation$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.gaps=[],this.subscription=new r.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new et,this.destroyAbortController=new et,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=r.abortable(this.destroyAbortController.signal,async function*(u){const c=this.representations.get(u);r.assertNonNullable(c,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new Yf(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const p=Math.min(this.bufferLimit,cr(this.sourceBuffer.buffered)*.8);this.bufferLimit=p,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield this.loadInit(c,"high",!0);const h=this.initData.get(c.id),f=this.segments.get(c.id);if(r.assertNonNullable(h,"No init buffer for starting representation"),r.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return;let m=0;for(const b of f)b.time.from-m>0&&this.gaps.push({representation:c.id,from:m,to:b.time.from}),m=b.time.to;r.isNonNullable(c.duration)&&c.duration-m>0&&this.gaps.push({representation:c.id,from:m,to:c.duration}),yield this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=r.abortable(this.destroyAbortController.signal,async function*(u){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return;this.switchingToRepresentationId=u;const c=this.representations.get(u);r.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(r.isNullable(h)?yield this.loadInit(c,"high",!1):h instanceof Promise&&(yield h),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal);const f=this.getCurrentPosition();r.isNonNullable(f)&&this.maintain(f)}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.container=i,i){case gt.MP4:this.containerParser=Qf;break;case gt.WEBM:this.containerParser=ip;break;default:r.assertNever(i)}this.initData=new Map(a.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(a.map(u=>[u.id,u])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new et,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const a=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=Ze(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&c>=a.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&cr(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Ze(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(i,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(l.includes(a))u="high";else{const c=Re(l,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===j.FED&&!l.length&&Ze(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Re(i,-1);d&&d.status===j.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===d))}findSegmentStartTime(e){var t,i,a;const n=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(a=l==null?void 0:l.time.from)!==null&&a!==void 0?a:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&(this.mediaSource.readyState==="open"&&this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const a=e.findIndex(({status:h,time:{from:f,to:m}},b)=>{const p=f<=i&&m>=i,v=f>i||p||b===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&f<=i+S||m<=i+S;return(h===j.NONE||h===j.PARTIALLY_EJECTED&&v&&g&&this.sourceBuffer&&!Bs(this.sourceBuffer.buffered,i))&&v&&g});if(a===-1)return[];if(t!==fe.BYTE_RANGE)return e.slice(a,a+1);const n=e;let o=0,l=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=a;h<n.length&&(o<=u||l<=c);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===j.NONE||f.status===j.PARTIALLY_EJECTED)d.push(f);else break}return d}async loadSegments(e,t,i="auto"){if(!e.length)return;let a,n,o=e;const{type:l}=t.segmentReference;switch(l){case fe.BYTE_RANGE:{a=t.segmentReference.url,n={from:Re(e,0).byte.from,to:Re(e,-1).byte.to};break}case fe.TEMPLATE:{const u=Re(e,0);a=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:r.assertNever(l)}for(const u of o)u.status=j.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await r.abortable(d,async function*(){const u=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(a,{range:n,onProgress:(u,c)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,c,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:i}).then(()=>this.failedDownloads=0,u=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)})}onSegmentDownloadError(e){var t;let i=!1;const a=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(a)&&(i=Ze((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,a)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,a,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},l=h=>{var f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),h.segment.status=j.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const m of this.representations.values())if(m.id!==t)for(const b of(f=this.segments.get(m.id))!==null&&f!==void 0?f:[])b.status===j.FED&&b.time.from===h.segment.time.from&&b.time.to===h.segment.time.to&&(b.status=j.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,m=u===fe.BYTE_RANGE,b=m?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!m||f.byte.from>=i&&f.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const v=m?f.byte.from-i:0,S=m?f.byte.to-i:e.byteLength,g=v<a,A=S<=a;if(f.status===j.DOWNLOADING&&g&&A){f.status=j.DOWNLOADED,this.activeSegments.delete(h);const E=new DataView(e.buffer,e.byteOffset+v,b);this.sourceBufferTaskQueue.append(E,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(h.loadedBytes=Math.min(b,a-v),h.loadedBytes>h.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+v+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===b?E:this.containerParser.parseFeedableSegmentChunk(E);T!=null&&T.byteLength&&(f.status=j.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(w=>{if(n.aborted)o();else if(w)h.fedBytes+=T.byteLength,h.fedBytes===b&&l(h);else{if(h.feedingBytes<b)return;o()}}))}}}abortSegment(e){e.status===j.PARTIALLY_FED||e.status===j.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=j.NONE),e.status=j.PARTIALLY_EJECTED):e.status=j.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[a,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=dr(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const a=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const l=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(l=>{if(!l)return;const{dataView:d,segments:u}=l,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:r.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||r.isNullable(e)||this.sourceBuffer.updating)return!1;let a=0,n=1/0,o=-1/0,l=!1;const d=u=>{var c;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h="size"in u?(c=u.size)!==null&&c!==void 0?c:0:u.byte.to-u.byte.from;a+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status===j.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){a=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status===j.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const m of f)if(m.status===j.NONE&&Math.round(m.time.from)<=Math.round(c)&&Math.round(m.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&i){a=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===j.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let a={representation:e,from:i.time.from,to:i.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&l>=i.time.to){a=void 0;break}l>i.time.from&&l<i.time.to&&(a.from=l),o<i.time.to&&o>i.time.from&&(a.to=o)}}a&&a.to-a.from>=1&&!this.gaps.some(n=>a&&n.from===a.from&&n.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=dr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const a=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:n})}const t=1;for(const i of this.segments.values())for(const a of i){const{status:n}=a;if(n!==j.FED&&n!==j.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),l=Math.ceil(a.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.filter(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u.length===1?a.status=j.PARTIALLY_EJECTED:a.status=j.NONE)}}}var pt;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(pt||(pt={}));class sp{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.abortAllController=new et,this.subscription=new r.Subscription,this.fetchManifest=r.abortable(this.abortAllController.signal,async function*(a){let n=a;this.requestQuic&&(n=St(n));const o=yield vt(n,{signal:this.abortAllController.signal}).catch(xt);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=r.abortable(this.abortAllController.signal,async function*(a,{rangeMethod:n=this.compatibilityMode?pt.HEADER:pt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,m,b;let p=a;const v=new Headers;if(o)switch(n){case pt.HEADER:{v.append("Range",`bytes=${o.from}-${o.to}`);break}case pt.PARAM:{const $=new URL(p,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),p=$.toString();break}default:r.assertNever(n)}this.requestQuic&&(p=St(p));let S=this.abortAllController.signal;if(u){const $=new et;if(this.subscription.add(r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(u,"abort")).subscribe(()=>{try{$.abort()}catch(D){xt(D)}})),this.abortAllController.signal.aborted||u.aborted)try{$.abort()}catch(D){xt(D)}S=$.signal}const g=r.now(),A=yield vt(p,{priority:d,headers:v,signal:S}).catch(xt),E=r.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-g),!A)return null;if(!A.ok||!A.body)return Promise.reject(new Error(`Fetch error ${A.status}: ${A.statusText}`));this.onHeadersReceived(A.headers);const T=parseInt((f=A.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!T){const $=yield A.arrayBuffer();return(m=this.throughputEstimator)===null||m===void 0||m.addRawSpeed($.byteLength,r.now()-E),l==null||l(new DataView($),$.byteLength),$}if(!l&&!c)return A.arrayBuffer();const[w,V]=A.body.tee(),C=w.getReader();c&&((b=this.throughputEstimator)===null||b===void 0||b.trackStream(V));let R=0;const F=new ArrayBuffer(T),I=new Uint8Array(F),_=new DataView(F);let H=!1;const Q=$=>{H=!0,xt($)},Z=r.abortable(S,async function*({done:$,value:D}){R===0&&this.lastRequestFirstBytes$.next(r.now()-g),!S.aborted&&($?l==null||l(_,R):D&&(I.set(D,R),R+=D.byteLength,l==null||l(_,R),yield C==null?void 0:C.read().then(Z,Q)))}.bind(this));return yield C==null?void 0:C.read().then(Z,Q),H?null:F}.bind(this)),this.fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n,o){var l;if(a.type!==fe.BYTE_RANGE)return null;const{from:d,to:u}=a.initRange;let c=d,h=u,f=!1,m,b;a.indexRange&&(m=a.indexRange.from,b=a.indexRange.to,f=u+1===m,f&&(c=Math.min(m,d),h=Math.max(b,u))),c=Math.min(c,0);const p=yield this.fetch(a.url,{range:{from:c,to:h},priority:o,measureThroughput:!1});if(!p)return null;const v=new DataView(p,d-c,u-c+1);if(!n.validateData(v))throw new Error("Invalid media file");const S=n.parseInit(v),g=(l=a.indexRange)!==null&&l!==void 0?l:n.getIndexRange(S);if(!g)throw new ReferenceError("No way to load representation index");let A;if(f)A=new DataView(p,g.from-c,g.to-g.from+1);else{const T=yield this.fetch(a.url,{range:g,priority:o,measureThroughput:!1});if(!T)return null;A=new DataView(T)}const E=n.parseSegments(A,S,g);return{dataView:new DataView(p),segments:E}}.bind(this)),this.fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n){if(a.type!==fe.TEMPLATE)return null;const o=new URL(a.initUrl,a.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{segments:a.segments.map(u=>({...u,status:j.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Nn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;const{type:o}=e;switch(o){case fe.BYTE_RANGE:return(a=await this.fetchByteRangeRepresentation(e,t,i))!==null&&a!==void 0?a:null;case fe.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:r.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const xt=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var ap=it,rp=Ri,np=Se,op=np("match"),lp=function(s){var e;return ap(s)&&((e=s[op])!==void 0?!!e:rp(s)=="RegExp")},up=xi,dp=String,cp=function(s){if(up(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return dp(s)},hp=st,fp=function(){var s=hp(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e},pp=Oe,mp=Be,bp=js,vp=fp,pr=RegExp.prototype,Sp=function(s){var e=s.flags;return e===void 0&&!("flags"in pr)&&!mp(s,"flags")&&bp(pr,s)?pp(vp,s):e},ia=xe,gp=Di,yp=Math.floor,cs=ia("".charAt),Tp=ia("".replace),hs=ia("".slice),Ep=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,$p=/\$([$&'`]|\d{1,2})/g,kp=function(s,e,t,i,a,n){var o=t+s.length,l=i.length,d=$p;return a!==void 0&&(a=gp(a),d=Ep),Tp(n,d,function(u,c){var h;switch(cs(c,0)){case"$":return"$";case"&":return s;case"`":return hs(e,0,t);case"'":return hs(e,o);case"<":h=a[hs(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var m=yp(f/10);return m===0?u:m<=l?i[m-1]===void 0?cs(c,1):i[m-1]+cs(c,1):u}h=i[f-1]}return h===void 0?"":h})},Ap=Li,Pp=Oe,sa=xe,mr=Vs,wp=me,_p=Ii,Rp=lp,ct=cp,Ip=Ni,Np=Sp,Dp=kp,Cp=Se,Lp=Cp("replace"),xp=TypeError,Mn=sa("".indexOf),Op=sa("".replace),br=sa("".slice),Bp=Math.max,vr=function(s,e,t){return t>s.length?-1:e===""?t:Mn(s,e,t)};Ap({target:"String",proto:!0},{replaceAll:function(e,t){var i=mr(this),a,n,o,l,d,u,c,h,f,m=0,b=0,p="";if(!_p(e)){if(a=Rp(e),a&&(n=ct(mr(Np(e))),!~Mn(n,"g")))throw xp("`.replaceAll` does not allow non-global regexes");if(o=Ip(e,Lp),o)return Pp(o,e,i,t);if(a)return Op(ct(i),e,t)}for(l=ct(i),d=ct(e),u=wp(t),u||(t=ct(t)),c=d.length,h=Bp(1,c),m=vr(l,d,0);m!==-1;)f=u?ct(t(d,m,l)):Dp(d,l,m,[],void 0,t),p+=br(l,b,m)+f,b=m+c,m=vr(l,d,m+h);return b<l.length&&(p+=br(l,b)),p}});var Mp=Rn,Vp=Mp("String","replaceAll"),Fp=Vp,Up=Fp,jp=Up,Hp=jp,Sr=Hp;const gr=s=>{if(!s.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),a=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],a),hours:e(i==null?void 0:i[6],a),minutes:e(i==null?void 0:i[7],a),seconds:e(i==null?void 0:i[8],a)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},fs=(s,e)=>{let t=s;t=Sr(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[a,n]of Object.entries(i)){const o=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=Sr(t,o,(l,d)=>r.isNullable(n)?l:r.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Gp=(s,e)=>{var t,i,a,n,o,l,d,u,c,h,f,m,b,p,v,S,g,A,E,T,w,V,C,R,F,I,_,H,Q,Z,$,D,q,X,ee,oe,ge;const U=new DOMParser().parseFromString(s,"application/xml"),ie={video:[],audio:[],text:[]},re=U.children[0],ue=re.getElementsByTagName("Period")[0],We=ue.children;let ye;const je=re.getAttribute("mediaPresentationDuration"),Qe=ue.getAttribute("duration");if(je)ye=gr(je);else if(Qe){const Te=gr(Qe);r.isNonNullable(Te)&&(ye=Te)}let $t=0;const nt=(i=(t=re.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],Gn=nt.includes(Pi.WEBM_AS_IN_FFMPEG)||nt.includes(Pi.WEBM_AS_IN_SPEC)?gt.WEBM:gt.MP4;for(const Te of We){const zt=Te.getAttribute("mimeType"),Yn=Te.getAttribute("codecs"),aa=(a=Te.getAttribute("contentType"))!==null&&a!==void 0?a:zt==null?void 0:zt.split("/")[0],qn=(o=(n=Te.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],zn=Te.querySelectorAll("Representation"),Wn=Te.querySelector("SegmentTemplate");if(aa!=="text")for(const se of zn){const kt=(l=se.getAttribute("mimeType"))!==null&&l!==void 0?l:zt,ra=(u=(d=se.getAttribute("codecs"))!==null&&d!==void 0?d:Yn)!==null&&u!==void 0?u:"",Wt=(h=(c=se.getAttribute("contentType"))!==null&&c!==void 0?c:kt==null?void 0:kt.split("/")[0])!==null&&h!==void 0?h:aa,Qn=(m=(f=Te.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&m!==void 0?m:[],Jn=parseInt((b=se.getAttribute("width"))!==null&&b!==void 0?b:"",10),na=parseInt((p=se.getAttribute("height"))!==null&&p!==void 0?p:"",10),oa=parseInt((v=se.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,la=(S=se.getAttribute("frameRate"))!==null&&S!==void 0?S:"",Kn=(g=se.getAttribute("quality"))!==null&&g!==void 0?g:void 0,Xn=la?ea(la):void 0,Zn=(A=se.getAttribute("id"))!==null&&A!==void 0?A:($t++).toString(10),eo=Wt==="video"?`${na}p`:Wt==="audio"?`${oa}Kbps`:ra,to=`${Zn}@${eo}`,io=(w=(T=(E=se.querySelector("BaseURL"))===null||E===void 0?void 0:E.textContent)===null||T===void 0?void 0:T.trim())!==null&&w!==void 0?w:"",ua=new URL(io,e).toString(),so=[...nt,...qn,...Qn];let Mi;const ao=se.querySelector("SegmentBase"),Je=(V=se.querySelector("SegmentTemplate"))!==null&&V!==void 0?V:Wn;if(ao){const At=(R=(C=se.querySelector("SegmentBase Initialization"))===null||C===void 0?void 0:C.getAttribute("range"))!==null&&R!==void 0?R:"",[Pt,Fi]=At.split("-").map(Ke=>parseInt(Ke,10)),wt={from:Pt,to:Fi},_t=(F=se.querySelector("SegmentBase"))===null||F===void 0?void 0:F.getAttribute("indexRange"),[Ui,Qt]=_t?_t.split("-").map(Ke=>parseInt(Ke,10)):[],Rt=_t?{from:Ui,to:Qt}:void 0;Mi={type:fe.BYTE_RANGE,url:ua,initRange:wt,indexRange:Rt}}else if(Je){const At={representationId:(I=se.getAttribute("id"))!==null&&I!==void 0?I:void 0,bandwidth:(_=se.getAttribute("bandwidth"))!==null&&_!==void 0?_:void 0},Pt=parseInt((H=Je.getAttribute("timescale"))!==null&&H!==void 0?H:"",10),Fi=(Q=Je.getAttribute("initialization"))!==null&&Q!==void 0?Q:"",wt=Je.getAttribute("media"),_t=($=parseInt((Z=Je.getAttribute("startNumber"))!==null&&Z!==void 0?Z:"",10))!==null&&$!==void 0?$:1,Ui=fs(Fi,At);if(!wt)throw new ReferenceError("No media attribute in SegmentTemplate");const Qt=(D=Je.querySelectorAll("SegmentTimeline S"))!==null&&D!==void 0?D:[],Rt=[];if(Qt.length){let Ke=_t,Xe=0;for(const It of Qt){const ot=parseInt((q=It.getAttribute("d"))!==null&&q!==void 0?q:"",10)*1e3,Nt=parseInt((X=It.getAttribute("r"))!==null&&X!==void 0?X:"",10)||0,Dt=(oe=parseInt((ee=It.getAttribute("t"))!==null&&ee!==void 0?ee:"",10))!==null&&oe!==void 0?oe:void 0;for(let da=0;da<Nt+1;da++){const ro=fs(wt,{...At,segmentNumber:Ke.toString(10),segmentTime:Dt.toString(10)}),no=Dt?Dt/Pt:Xe;Xe+=ot/Pt;const oo=Xe;Ke++,Rt.push({time:{from:no,to:oo},url:ro})}}}else if(r.isNonNullable(ye)){const Xe=parseInt((ge=Je.getAttribute("duration"))!==null&&ge!==void 0?ge:"",10)/Pt*1e3,It=Math.ceil(ye/Xe);let ot=0;for(let Nt=1;Nt<It;Nt++){const Dt=fs(wt,{...At,segmentNumber:Nt.toString(10),segmentTime:ot.toString(10)});Rt.push({time:{from:ot,to:ot+Xe},url:Dt}),ot+=Xe}}Mi={type:fe.TEMPLATE,baseUrl:ua,initUrl:Ui,segments:Rt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Wt||!kt)continue;const Vi={video:he.VIDEO,audio:he.AUDIO,text:he.TEXT}[Wt];Vi&&ie[Vi].push({id:to,kind:Vi,segmentReference:Mi,profiles:so,duration:ye,bitrate:oa,mime:kt,codecs:ra,width:Jn,height:na,fps:Xn,quality:Kn})}}return{duration:ye,container:Gn,representations:ie}},Yp=["timeupdate","progress","play","seeked","stalled","waiting"];var ce;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(ce||(ce={}));let qp=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new r.Subscription,this.state$=new W(ce.NONE),this.currentVideoRepresentation$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.forceEnded$=new r.Subject,this.gapWatchdogStarted=!1,this.destroyController=new et,this.initManifest=r.abortable(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(ce.MANIFEST_READY);const a=yield this.fetcher.fetchManifest(i).catch(l=>this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l}));if(!a)return;let n;try{n=Gp(a!=null?a:"",i)}catch(l){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return;const o=({mime:l,codecs:d})=>{var u,c,h;return Boolean(((u=t.canPlayType)===null||u===void 0?void 0:u.call(t,l))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${l}; codecs="${d}"`)))};this.manifest={...n,representations:Ht(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))},this.manifest.representations.video.length?this.state$.setState(ce.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this)),this.initRepresentations=r.abortable(this.destroyController.signal,async function*(t,i){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.state$.startTransitionTo(ce.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new fr(he.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,a),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(i)&&(this.audioBufferManager=new fr(he.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,a),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const n=r.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=r.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.subscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:n,someBufferEnded:o}).pipe(r.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(r.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)})),r.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&r.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(ce.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const a=this.element.currentTime*1e3;this.videoBufferManager.maintain(a),(t=this.audioBufferManager)===null||t===void 0||t.maintain(a),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),n=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new sp({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){r.assertNonNullable(this.element),this.state$.setState(ce.RUNNING),this.subscription.add(r.merge(...Yp.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Bs(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[he.VIDEO]:this.videoBufferManager,[he.AUDIO]:this.audioBufferManager,[he.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,a,n,o,l;r.assertNonNullable(this.element),r.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(n=(a=this.audioBufferManager)===null||a===void 0?void 0:a.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Bs(this.element.buffered,d)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(d),(l=this.audioBufferManager)===null||l===void 0||l.maintain(d),this.element.currentTime=d/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(ce.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const i of this.bufferManagers)for(const a of i.gaps)i.playingRepresentation$.getValue()===a.representation&&a.from<=e&&a.to>e&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?t.push(1/0):t.push(a.to));if(t.length){const i=Math.max(...t);i===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=i/1e3}}};var J;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(J||(J={}));const zp=({id:s,width:e,height:t,bitrate:i,fps:a,quality:n})=>{var o;const l=(o=n?Yt(n):void 0)!==null&&o!==void 0?o:at({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:a}},Wp=({id:s,bitrate:e})=>({id:s,bitrate:e}),Qp=(s,e,t)=>{var i;const a=e.indexOf(t);return(i=Re(s,Math.round(s.length*a/e.length)))!==null&&i!==void 0?i:Re(s,-1)};class Jp{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(J.STOPPED),this.elementSize$=new r.ValueSubject(void 0),this.textTracksManager=new Pe,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new gf,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===N.Requested&&(a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&t!==J.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),i===exports.PlaybackState.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(t){case J.STOPPED:this.videoState.startTransitionTo(J.READY),this.prepare();return;case J.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case J.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}}},this.params=e,this.video=Ve(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new qp({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=Fe(this.video),a=u=>{e.error$.next({id:"DashVKProvider",category:r.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,c)=>this.subscription.add(u.subscribe(c,a));n(i.timeUpdate$,e.position$),n(i.durationChange$,e.duration$),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.isAudioAvailable$,e.isAudioAvailable$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once(),r.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(rt(this.video,t.isLooped,a)),this.subscription.add(Me(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,a)),n(ki(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},a)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===ce.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const h=this.player.getRepresentations();r.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((p,v)=>v.bitrate-p.bitrate),m=Array.from(h.video).sort((p,v)=>v.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of f){const v=Wp(p);v&&this.audioTracks.push({track:v,representation:p})}for(const p of m){const v=zp(p);if(v){this.videoTracks.push({track:v,representation:p});const S=!this.params.tuning.isAudioDisabled&&Qp(f,m,p);S&&this.audioRepresentations.set(p.id,S)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:p})=>p)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:p})=>p)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const b=this.selectVideoRepresentation();r.assertNonNullable(b),this.player.initRepresentations(b.id,(c=this.audioRepresentations.get(b.id))===null||c===void 0?void 0:c.id)}else u===ce.REPRESENTATIOS_READY&&(this.videoState.setState(J.READY),this.player.initBuffer())},a));const o=u=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,r.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==ce.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(he.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(he.AUDIO,f.id).catch(o)}},a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(u=>{var c;return u&&((c=this.videoTracks.find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(r.map(({to:u})=>u===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(r.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var e,t,i,a,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks.find(({track:{id:S}})=>S===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=Ze(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=Math.max(u&&!l&&(i=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&i!==void 0?i:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),p=Gt(this.videoTracks.map(({track:S})=>S),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),v=l?p!=null?p:u:u!=null?u:p;return v&&((o=this.videoTracks.find(({track:S})=>S===v))===null||o===void 0?void 0:o.representation)}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const Kp=5e3,we={};var M;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(M||(M={}));const oi=(s,e)=>new r.Observable(t=>{const i=(a,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class Xp{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(M.INITIALIZING),this.textTracksManager=new Pe,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==M.INITIALIZING)switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===N.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case M.STOPPED:break;case M.READY:case M.PLAYING:case M.PAUSED:this.stop();break;default:r.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case M.STOPPED:this.prepare();break;case M.READY:case M.PLAYING:case M.PAUSED:break;default:r.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case M.PLAYING:break;case M.STOPPED:this.prepare();break;case M.READY:case M.PAUSED:this.playIfAllowed();break;default:r.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case M.PAUSED:break;case M.STOPPED:this.prepare();break;case M.READY:this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case M.PLAYING:this.pause();break;default:r.assertNever(t)}break;default:r.assertNever(i)}},this.video=Ve(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}loadHlsJs(){let e=!1;const t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:r.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),Kp);import("hls.js").then(a=>{e||(we.Hls=a.default,we.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(we.Hls,"hls.js not loaded"),this.hls=new we.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){r.assertNonNullable(we.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:r.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=Fe(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,i));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadStart$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),n(a.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(rt(this.video,e.isLooped,i)),this.subscription.add(Me(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(oi(this.hls,we.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:r.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)===null||c===void 0?void 0:c.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===M.READY&&this.videoState.setState(M.READY),this.videoState.getState()===M.PLAYING&&this.playIfAllowed()},i)),n(oi(this.hls,we.Events.MANIFEST_PARSED).pipe(r.map(({levels:u})=>u.reduce((c,h)=>{var f,m;const b=h.name||h.height.toString(10),{width:p,height:v}=h,S=(m=Yt((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&m!==void 0?m:at({width:p,height:v});if(!S)return c;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,A={id:b.toString(),quality:S,bitrate:h.bitrate/1e3,size:{width:p,height:v},fps:g};return this.trackLevels.set(b,{track:A,level:h}),c.push(A),c},[]))),t.availableVideoTracks$),n(oi(this.hls,we.Events.LEVEL_LOADING).pipe(r.map(({url:u})=>ne(u))),t.hostname$),this.subscription.add(ke(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=oi(this.hls,we.Events.LEVEL_SWITCHED).pipe(r.map(({level:u})=>o(this.hls.levels[u])));l.pipe(r.filter(r.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(ke(e.videoTrack,()=>{var u;return(u=o(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var c;if(r.isNullable(u))return;const h=(c=this.trackLevels.get(u))===null||c===void 0?void 0:c.level;if(!h)return;const f=this.hls.levels.indexOf(h),m=this.hls.currentLevel,b=this.hls.levels[m];!b||h.bitrate>b.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(r.map(u=>u==null?void 0:u.id)),onError:i})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=r.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(M.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(M.PLAYING),await ze(this.video)||(this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(M.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(M.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const yr="X-Playback-Duration";var Tr=async s=>{const e=await vt(s,{method:"HEAD"});return e.headers.has(yr)?parseInt(e.headers.get(yr),10):void 0};const Zp=s=>{let e=null;if(s.QUALITY&&(e=Yt(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(a=>parseInt(a,10));e=at({width:t,height:i})}return e!=null?e:null},Vn=async(s,e=s)=>{var t;const n=(await(await vt(s)).text()).split(`
8
- `),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=Ht(u[1].split(",").map(S=>S.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Zp(c);let m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const b=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let p;if(c.RESOLUTION){const[S,g]=c.RESOLUTION.split("x").map(A=>parseInt(A,10));S&&g&&(p={width:S,height:g})}const v=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:v,bandwidth:m,size:p,fps:b})}return o};var G;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(G||(G={}));class em{constructor(e){var t;this.subscription=new r.Subscription,this.videoState=new W(G.STOPPED),this.textTracksManager=new Pe,this.manifests$=new r.ValueSubject([]),this.liveOffset=new Zs,this.manifestStartTime$=new r.ValueSubject(void 0),this.syncPlayback=()=>{const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===exports.PlaybackState.STOPPED){a!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(G.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(a===G.STOPPED){this.videoState.startTransitionTo(G.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(G.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===N.Requested){this.videoState.startTransitionTo(G.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){case G.READY:n===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(G.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed());return;case G.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(G.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case G.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(G.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case G.CHANGING_MANIFEST:break;default:return r.assertNever(a)}},this.params=e,this.video=Ve(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),Vn(bt(this.params.source.url),this.params.source.url).then(a=>{this.manifests$.next([i,...a])},a=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:a})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.maxSeekBackTime$=new r.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:a}=this.params.desiredState,n=i.getState(),o=a.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:a.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&a.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsLiveProvider",category:r.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},a=Fe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(a.ended$,e.endedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Me(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===G.READY&&this.videoState.setState(G.READY),this.videoState.getState()===G.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(l=>-l/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&r.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===G.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===N.Requested&&this.seek(l.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},i)),this.subscription.add(r.combine({startTime:this.manifestStartTime$.pipe(r.filter(r.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),i)),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=bt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Tr(t).then(i=>{var a;if(!r.isNullable(i))this.maxSeekBackTime$.next(i);else{const n=(a=this.params.source.maxSeekBackTime)!==null&&a!==void 0?a:this.maxSeekBackTime$.getValue();if(r.isNullable(n)||!isFinite(n))try{vt(t).then(o=>o.text()).then(o=>{var l;const d=(l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||l===void 0?void 0:l[1];if(d){const u=new URL(d,t).toString();Tr(u).then(c=>{r.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(G.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var z;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(z||(z={}));class tm{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(z.STOPPED),this.textTracksManager=new Pe,this.manifests$=new r.ValueSubject([]),this.syncPlayback=()=>{const i=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===exports.PlaybackState.STOPPED){i!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(z.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(i===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(z.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===N.Requested&&this.seek(u.position),i){case z.READY:a===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case z.CHANGING_MANIFEST:break;default:return r.assertNever(i)}},this.params=e,this.video=Ve(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),Vn(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:a}=this.params.desiredState,n=i.getState(),o=a.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:a.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&a.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsProvider",category:r.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},a=Fe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Me(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&r.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===N.Requested&&this.seek(l.position)},i))),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}prepare(){const e=this.selectManifest();r.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var K;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));class im{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(K.STOPPED),this.trackUrls={},this.textTracksManager=new Pe,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(K.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(t===K.STOPPED){this.videoState.startTransitionTo(K.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:d*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&l.state===N.Requested&&this.seek(l.position),t){case K.READY:i===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(K.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case K.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.params=e,this.video=Ve(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,i],a)=>{const n=a.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"MpegProvider",category:r.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},a=Fe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Me(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===K.READY&&this.videoState.setState(K.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&r.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ue(this.video)}prepare(){var e,t;const i=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState();r.assertNonNullable(i,"MpegProvider: track is not selected");let{url:a}=this.trackUrls[i];r.assertNonNullable(a,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(a=St(a)),this.video.setAttribute("src",a),this.video.load(),this.params.output.hostname$.next(ne(a))}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const Er=["stun:videostun.mycdn.me:80"],sm=1e3,am=3,ps=()=>null;class rm{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=ps,this.externalStopCallback=ps,this.externalErrorCallback=ps,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Er}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:r.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),sm)}normalizeOptions(e={}){const t={stunServerList:Er,maxRetryNumber:am,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));class nm{constructor(e){this.videoState=new W(Y.STOPPED),this.maxSeekBackTime$=new r.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Y.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case Y.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ve(e.container),this.liveStreamClient=new rm(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ue(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:r.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const a=Fe(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,i));n(a.timeUpdate$,e.liveTime$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(a.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===Y.READY&&this.videoState.setState(Y.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED)},i)).add(a.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING)},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Me(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case Y.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case Y.READY:break;case Y.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case Y.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(o.to)}},i)).add(r.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Y.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:r.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class $r{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return Boolean(this.current.done)}}var om=()=>{var s,e;const t=window.navigator;return t.userAgentData?((e=(s=t.userAgentData)===null||s===void 0?void 0:s.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},ms,bs,vs,Ss,gs,ys,li,Ts,ui,Es,di,$s,ci,ks,hi,As;const Fn=om(),He=document.createElement("video"),_e={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((bs=(ms=window.SourceBuffer)===null||ms===void 0?void 0:ms.prototype)===null||bs===void 0?void 0:bs.appendBuffer)),hls:Boolean(((vs=He.canPlayType)===null||vs===void 0?void 0:vs.call(He,"application/x-mpegurl"))||((Ss=He.canPlayType)===null||Ss===void 0?void 0:Ss.call(He,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},de={mp4:Boolean((gs=He.canPlayType)===null||gs===void 0?void 0:gs.call(He,"video/mp4")),webm:Boolean((ys=He.canPlayType)===null||ys===void 0?void 0:ys.call(He,"video/webm")),cmaf:!0},Ge={h264:Boolean((Ts=(li=window.MediaSource)===null||li===void 0?void 0:li.isTypeSupported)===null||Ts===void 0?void 0:Ts.call(li,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((Es=(ui=window.MediaSource)===null||ui===void 0?void 0:ui.isTypeSupported)===null||Es===void 0?void 0:Es.call(ui,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(($s=(di=window.MediaSource)===null||di===void 0?void 0:di.isTypeSupported)===null||$s===void 0?void 0:$s.call(di,'video/webm; codecs="vp9"')),aac:Boolean((ks=(ci=window.MediaSource)===null||ci===void 0?void 0:ci.isTypeSupported)===null||ks===void 0?void 0:ks.call(ci,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((As=(hi=window.MediaSource)===null||hi===void 0?void 0:hi.isTypeSupported)===null||As===void 0?void 0:As.call(hi,'audio/webm; codecs="opus"'))},ht=(Ge.h264||Ge.h265)&&Ge.aac,Bi=_e.hls&&de.mp4,lm=Boolean(window.WebSocket),um=()=>Object.keys(Ge).filter(s=>Ge[s]),dm=(s,e=!1)=>s.filter(t=>{switch(t){case exports.VideoFormat.DASH:return _e.mse&&de.mp4&&ht;case exports.VideoFormat.DASH_SEP:return _e.mse&&de.mp4&&ht;case exports.VideoFormat.DASH_WEBM:return _e.mse&&de.webm&&Ge.vp9&&Ge.opus;case exports.VideoFormat.DASH_LIVE:return _e.mse&&de.mp4&&ht;case exports.VideoFormat.DASH_LIVE_CMAF:return _e.mse&&de.mp4&&ht&&de.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return _e.mse&&de.mp4&&ht;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return Bi||e&&_e.mse&&de.mp4&&ht;case exports.VideoFormat.MPEG:return de.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return _e.webrtc&&lm&&Ge.h264&&(de.mp4||de.webm);default:return r.assertNever(t)}}),cm=()=>Fn?[exports.VideoFormat.MPEG,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:Bi?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],hm=()=>Fn?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:Bi?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],kr=s=>s?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var fm=s=>new r.Observable(e=>{const t=new r.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(r.map(({from:u,to:c})=>`${u}-${c}`)),a=s.desiredPlaybackState$.stateChangeEnded$,n=s.providerChanged$,o=new r.Subject;let l=0,d="unknown";return t.add(i.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),s.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(l),d="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),s.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const Ar={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},pm={cacheDuration:12e4},mm={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},bm={maxPausedTime:3e4},Pr={maxPausedTime:3e4};class vm{constructor(e){this.current$=new r.ValueSubject({type:void 0}),this.providerError$=new r.Subject,this.noAvailableProvidersError$=new r.Subject,this.providerOutput={position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),volume$:new r.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new r.ValueSubject(void 0),availableVideoTracks$:new r.ValueSubject([]),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new r.ValueSubject(!1),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$:new r.Subject,willSeekEvent$:new r.Subject,seekedEvent$:new r.Subject,loopedEvent$:new r.Subject,endedEvent$:new r.Subject,firstBytesEvent$:new r.Subject,firstFrameEvent$:new r.Subject,canplay$:new r.Subject,isLive$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),element$:new r.ValueSubject(void 0)},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=dm([...hm(),...cm()],this.params.tuning.useHlsJs).filter(o=>r.isNonNullable(e.sources[o])),{formatsToAvoid:i}=this.params.tuning,a=i.length?[...t.filter(o=>!i.includes(o)),...t.filter(o=>i.includes(o))]:t;this.screenFormatsIterator=new $r(a);const n=[...kr(!0),...kr(!1)];this.chromecastFormatsIterator=new $r(n.filter(o=>r.isNonNullable(e.sources[o])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(r.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:r.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;r.assertNonNullable(e,"No current provider"),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!==N.None;this.params.desiredState.seekState.setState({state:N.Requested,position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case le.SCREEN:return this.createScreenProvider(t);case le.CHROMECAST:return this.createChromecastProvider(t);default:return r.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new jf({...o,source:l,config:pm})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),this.params.tuning.useDashJs?new lr({...o,source:l,format:e,config:Pr}):new Jp({...o,source:l})}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new lr({...o,source:l,format:e,config:Pr})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),Bi||!this.params.tuning.useHlsJs?new tm({...o,source:l}):new Xp({...o,source:l})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new em({...o,source:l,config:bm})}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new im({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Bf({...o,source:l,config:mm})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new nm({container:i,source:l,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:a,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return r.assertNonNullable(l),new Hh({connection:l,meta:n,container:i,source:t,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?le.CHROMECAST:le.SCREEN}chooseFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case le.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.next();case le.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case le.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case le.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return r.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=a=>{const n=new URL(a);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Ht(Object.entries(e).map(([a,n])=>[a,i(n)]))}initProviderErrorHandling(){const e=new r.Subscription;let t=!1,i=0;return e.add(r.merge(this.providerOutput.error$,fm({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Ar.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(r.filter(({type:a})=>a!==void 0))}).pipe(r.map(a=>({id:`ProviderHangup:${a}`,category:r.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(r.filter(({to:n})=>n===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{if(this.current$.getValue().destination===le.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=a.category===r.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<Ar.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(i++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var pe;(function(s){s[s.LOCAL_STORAGE=0]="LOCAL_STORAGE",s[s.SESSION_STORAGE=1]="SESSION_STORAGE",s[s.RUNTIME=2]="RUNTIME"})(pe||(pe={}));const Un=new Map;let tt=pe.RUNTIME;const Ps=`vk-videoplayer-dummy-key-${Math.random()}`,Sm=()=>{try{localStorage.setItem(Ps,"test"),localStorage.removeItem(Ps),tt=pe.LOCAL_STORAGE}catch(s){if(s instanceof DOMException||s instanceof TypeError)try{sessionStorage.getItem(Ps),tt=pe.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)tt=pe.RUNTIME;else throw e}else throw s}};Sm();const gm=s=>{var e,t;switch(tt){case pe.LOCAL_STORAGE:return(e=localStorage.getItem(s))!==null&&e!==void 0?e:void 0;case pe.SESSION_STORAGE:return(t=sessionStorage.getItem(s))!==null&&t!==void 0?t:void 0;case pe.RUNTIME:return Un.get(s);default:r.assertNever(tt)}},wr=(s,e)=>{switch(tt){case pe.LOCAL_STORAGE:try{localStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case pe.SESSION_STORAGE:try{sessionStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case pe.RUNTIME:return void Un.set(s,e);default:r.assertNever(tt)}},Ms=(s,e,t)=>t*e+(1-t)*s,jn=(s,e)=>s.reduce((t,i)=>t+i,0)/e,ym=(s,e,t,i)=>{let a=0,n=t;const o=jn(s,e),l=e<i?e:i;for(let d=0;d<l;d++)s[n]>o?a++:a--,n=(s.length+n-1)%s.length;return Math.abs(a)===l};class Hn{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new r.ValueSubject(e.initial),this.debounced$=new r.ValueSubject(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new $e(`raw_${i}`),this.smoothedSeries$=new $e(`smoothed_${i}`),this.reportedSeries$=new $e(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=(this.pastMeasures[l]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const a=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(r.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Tm extends Hn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ms(this.slow,e,this.params.emaAlphaSlow),this.fast=Ms(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Em extends Hn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=jn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ms(this.emaSmoothed,e,this.params.emaAlpha);const i=ym(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class _r{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Tm({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Em({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const $m=5e3,Rr="one_video_throughput",Ir="one_video_rtt",Ce=window.navigator.connection,Nr=()=>{const s=Ce==null?void 0:Ce.downlink;if(r.isNonNullable(s)&&s!==10)return s*1e3},Dr=()=>{const s=Ce==null?void 0:Ce.rtt;if(r.isNonNullable(s)&&s!==3e3)return s},Cr=(s,e,t)=>{const i=t*8,a=i/s;return i/(a+e)};class Mt{constructor(e){var t,i;this.subscription=new r.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=Mt.load(Rr)||(e.useBrowserEstimation?Nr():void 0)||$m,n=(i=(t=Mt.load(Ir))!==null&&t!==void 0?t:e.useBrowserEstimation?Dr():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new r.ValueSubject(a),this.rtt$=new r.ValueSubject(n),this.rttAdjustedThroughput$=new r.ValueSubject(Cr(a,n,e.rttPenaltyRequestSize)),this.throughput=_r.getSmoothedValue(a,-1,e),this.rtt=_r.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Nr();d&&this.throughput.next(d);const u=Dr();r.isNonNullable(u)&&this.rtt.next(u)};Ce&&"onchange"in Ce&&this.subscription.add(r.fromEvent(Ce,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{wr(Rr,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{wr(Ir,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(r.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(r.map(({throughput:o,rtt:l})=>Cr(o,l,e.rttPenaltyRequestSize)),r.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=r.now();const a=new r.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(r.fromEvent(e,"progress").pipe(r.once()).subscribe(n=>{t=n.loaded,i=r.now()}));break;case 1:case 0:a.add(r.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=r.now()}));break}a.add(r.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=r.now(),d=o-t,u=l-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const a=r.now();let n=0,o=r.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=async({done:u,value:c})=>{u?(this.addRawSpeed(i,r.now()-a,1),this.concurrentDownloads.delete(e)):c&&(i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&r.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,r.now()-o,this.concurrentDownloads.size),n=0,o=r.now()),await(t==null?void 0:t.read().then(d,l)))};this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,i=1){if(Mt.sanityCheck(e,t)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=gm(e);if(r.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Lr={throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},km=s=>{const e={};for(const t of Object.keys(Lr)){const i=Lr[t],a=s[t];Array.isArray(i)&&Array.isArray(a)?e[t]=a:typeof i=="object"&&typeof a=="object"?e[t]={...i,...a}:e[t]=a!=null?a:i}return e};var Am=({seekState:s,position$:e})=>r.merge(s.stateChangeEnded$.pipe(r.map(({to:t})=>{var i;return t.state===N.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>s.getState().state===N.None))),Pm=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return r.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};const xr=({playbackState:s,seekState:e,playbackAbort$:t,looped$:i,position$:a})=>new r.Observable(n=>{let o;const l=s.transitionEnded$.pipe(r.filter(m=>(m.from===exports.PlaybackState.PAUSED||m.from===exports.PlaybackState.STOPPED)&&m.to===exports.PlaybackState.PLAYING)),d=s.stateChangeEnded$.pipe(r.filter(m=>m.from===exports.PlaybackState.PLAYING&&m.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(r.filter(({to:m})=>{var b,p;return m.state===N.Requested&&((p=(b=s.getTransition())===null||b===void 0?void 0:b.from)!==null&&p!==void 0?p:s.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(r.filter(({from:m,to:b})=>{var p,v;return m.state===N.Applying&&b.state===N.None&&((v=(p=s.getTransition())===null||p===void 0?void 0:p.from)!==null&&v!==void 0?v:s.getState())===exports.PlaybackState.PLAYING})),h=r.merge(l,c).pipe(r.map(()=>a.getValue()),r.filter(r.isNonNullable)),f=r.merge(r.merge(d,u,t),i).pipe(r.map(()=>a.getValue()),r.filter(r.isNonNullable));return new r.Subscription().add(h.subscribe(m=>{o=m})).add(f.subscribe(m=>{if(r.isNullable(o)||o===m)return;const b={from:o,to:m};o=void 0,n.next(b)}))});class wm{constructor(e={}){if(this.subscription=new r.Subscription,this.logger=new r.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new W(exports.PlaybackState.STOPPED),seekState:new W({state:N.None}),volume:new W({volume:1,muted:!1}),videoTrack:new W(void 0),autoVideoTrackSwitching:new W(!0),autoVideoTrackLimits:new W({}),isLooped:new W(!1),playbackRate:new W(1),externalTextTracks:new W([]),currentTextTrack:new W(void 0),textTrackCuesSettings:new W({})},this.info={playbackState$:new r.ValueSubject(exports.PlaybackState.STOPPED),position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),muted$:new r.ValueSubject(!1),volume$:new r.ValueSubject(1),availableQualities$:new r.ValueSubject([]),availableQualitiesFps$:new r.ValueSubject({}),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),currentQuality$:new r.ValueSubject(void 0),isAutoQualityEnabled$:new r.ValueSubject(!0),autoQualityLimitingAvailable$:new r.ValueSubject(!1),autoQualityLimits$:new r.ValueSubject({}),currentPlaybackRate$:new r.ValueSubject(1),currentBuffer$:new r.ValueSubject({start:0,end:0}),isBuffering$:new r.ValueSubject(!0),isStalled$:new r.ValueSubject(!1),isEnded$:new r.ValueSubject(!1),isLooped$:new r.ValueSubject(!1),isLive$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),currentFormat$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),throughputEstimation$:new r.ValueSubject(void 0),rttEstimation$:new r.ValueSubject(void 0),videoBitrate$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0)},this.events={inited$:new r.Subject,started$:new r.Subject,willPause$:new r.Subject,willResume$:new r.Subject,willDestruct$:new r.Subject,watchCoverageRecord$:new r.Subject,watchCoverageLive$:new r.Subject,managedError$:new r.Subject,fatalError$:new r.Subject,ended$:new r.Subject,looped$:new r.Subject,seeked$:new r.Subject,willSeek$:new r.Subject,firstBytes$:new r.Subject,firstFrame$:new r.Subject,canplay$:new r.Subject,log$:new r.Subject},this.experimental={element$:new r.ValueSubject(void 0),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:bf},this.initLogs(),this.tuning=km(e),this.chromecastInitializer=new go({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Mt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,a)=>{const n=Reflect.get(t,i,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,m)=>{const b=typeof m;return["number","string","boolean"].includes(b)?m:m===null?null:`<${b}>`})),u=`Player.${String(i)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:r.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,i,a;return this.config=e,this.domContainer=Pm(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new vm({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(a=e.failoverHosts)!==null&&a!==void 0?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:N.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){r.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(a=>a.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;r.assertNonNullable(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(i=>i.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){r.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(r.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===N.None?void 0:t.position;return r.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(r.filter(({from:e})=>e===exports.PlaybackState.STOPPED),r.once()).subscribe(()=>{this.initedAt=r.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(()=>!this.isPlaybackStarted),r.filter(e=>e.to===exports.PlaybackState.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const d=this.desiredState.seekState.getState();d.state===N.Requested?this.desiredState.seekState.setState({...d,state:N.Applying}):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===N.Applying&&(this.desiredState.seekState.setState({state:N.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(d=>d.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(d=>d.map(({quality:u})=>u).sort((u,c)=>Ei(u)?1:Ei(c)?-1:bi(c,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(d=>{const u={};for(const c of d)c.fps&&(u[c.quality]=c.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{this.info.currentQuality$.next(d==null?void 0:d.quality),this.info.videoBitrate$.next(d==null?void 0:d.bitrate)})).add(e.providerOutput.hostname$.pipe(r.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(r.map(d=>d?{start:d.from,end:d.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(r.map(d=>d.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(d=>d.volume),r.filterChanged()).subscribe(this.info.volume$)).add(Am({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(r.merge(e.providerOutput.endedEvent$.pipe(r.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(r.mapTo(!1))).pipe(r.filterChanged()).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.noAvailableProvidersError$.pipe(r.map(d=>({id:"NoProviders",category:r.ErrorCategory.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new r.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new r.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(({to:d})=>d===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>i.next(!1)));let a=0;const n=r.merge(e.providerOutput.isBuffering$,t,i).pipe(r.map(()=>{const d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return d&&!u}),r.filterChanged());this.subscription.add(n.subscribe(d=>{d?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))}));const o=new r.Subscription;this.subscription.add(o);const l=r.merge(r.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(r.filter(d=>Boolean(d==null?void 0:d.provider))));e.providerOutput.isLive$.pipe(r.filterChanged()).subscribe(d=>{switch(r.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new r.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>u.next(c&&Math.floor(c/1e3)))),o.add(xr({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:l,looped$:this.events.looped$,position$:u}).pipe(r.map(({from:c,to:h})=>({start:c,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(xr({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:l,position$:this.providerContainer.providerOutput.position$}).pipe(r.map(({from:u,to:c})=>({start:u,end:c}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(r.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{var u,c;const h=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=d==null?void 0:d.size)===null||u===void 0?void 0:u.width,height:(c=d==null?void 0:d.size)===null||c===void 0?void 0:c.height},{width:h==null?void 0:h.videoWidth,height:h==null?void 0:h.videoHeight})}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(r.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new r.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(r.filterChanged((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(r.filter(i=>i.length>0),r.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Gt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(r.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(r.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;r.assertNonNullable(this.providerContainer),r.assertNonNullable(t),mf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>pf(i)),this.providerContainer.current$.subscribe(({type:i})=>ai("provider",i)),t.duration$.subscribe(i=>ai("duration",i)),t.availableVideoTracks$.pipe(r.filter(i=>!!i.length),r.once()).subscribe(i=>ai("tracks",i)),this.events.fatalError$.subscribe(new $e("fatalError")),this.events.managedError$.subscribe(new $e("managedError")),t.position$.subscribe(new $e("position")),t.currentVideoTrack$.pipe(r.map(i=>i==null?void 0:i.quality)).subscribe(new $e("quality")),this.info.currentBuffer$.subscribe(new $e("buffer")),t.isBuffering$.subscribe(new $e("isBuffering"))].forEach(i=>this.subscription.add(i)),ai("codecs",um())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:r.ErrorCategory.DOM,message:String(a)})})};this.subscription.add(r.merge(r.fromEvent(document,"visibilitychange"),r.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=Boolean(e)&&!(e!=null&&e.released);a&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const _m=`${vo}@${bo}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return r.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return r.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return r.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return r.ValueSubject}});exports.Player=wm;exports.SDK_VERSION=_m;
6
+ "use strict";var uo=Object.create;var ca=Object.defineProperty;var co=Object.getOwnPropertyDescriptor;var ho=Object.getOwnPropertyNames;var fo=Object.getPrototypeOf,po=Object.prototype.hasOwnProperty;var mo=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ho(e))!po.call(s,a)&&a!==t&&ca(s,a,{get:()=>e[a],enumerable:!(i=co(e,a))||i.enumerable});return s};var ha=(s,e,t)=>(t=s!=null?uo(fo(s)):{},mo(e||!s||!s.__esModule?ca(t,"default",{value:s,enumerable:!0}):t,s));var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),bo=require("lodash/debounce.js");const So="2.0.86",vo="es2018.cjs.js";exports.PlaybackState=void 0;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var le;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(le||(le={}));exports.ChromecastState=void 0;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var N;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(N||(N={}));var go=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class yo{constructor(e){var t;this.connection$=new r.ValueSubject(void 0),this.castState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new r.Subject,this.realCastState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const a=r.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);a?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||go("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:r.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,a,n;(n=(a=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){r.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();r.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();r.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(r.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var n,o;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=i.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.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 r.assertNever(a.sessionState)}})).add(r.merge(r.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(r.tap(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),r.map(a=>a.castState)),r.observableFrom([i.getCastState()])).pipe(r.filterChanged(),r.map(To),r.tap(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var n;const o=a===exports.ChromecastState.CONNECTED,l=r.isNonNullable(this.connection$.getValue());if(o&&!l){const d=i.getCurrentSession();r.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(r.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?r.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)}))}initializeCastApi(){var e;let t,i,a;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,a=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:a}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:r.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const To=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return r.assertNever(s)}};var fa=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Le=function(s){try{return!!s()}catch(e){return!0}},Eo=Le,_i=!Eo(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Br=_i,Mr=Function.prototype,ws=Mr.call,$o=Br&&Mr.bind.bind(ws,ws),xe=Br?$o:function(s){return function(){return ws.apply(s,arguments)}},Vr=xe,ko=Vr({}.toString),Ao=Vr("".slice),Ri=function(s){return Ao(ko(s),8,-1)},Po=xe,wo=Le,_o=Ri,ji=Object,Ro=Po("".split),Io=wo(function(){return!ji("z").propertyIsEnumerable(0)})?function(s){return _o(s)=="String"?Ro(s,""):ji(s)}:ji,Ii=function(s){return s==null},No=Ii,Do=TypeError,Vs=function(s){if(No(s))throw Do("Can't call method on "+s);return s},Co=Io,Lo=Vs,Ft=function(s){return Co(Lo(s))},xo=function(){},yt={},Jt=function(s){return s&&s.Math==Math&&s},Ae=Jt(typeof globalThis=="object"&&globalThis)||Jt(typeof window=="object"&&window)||Jt(typeof self=="object"&&self)||Jt(typeof fa=="object"&&fa)||function(){return this}()||Function("return this")(),_s=typeof document=="object"&&document.all,Oo=typeof _s=="undefined"&&_s!==void 0,Fr={all:_s,IS_HTMLDDA:Oo},Ur=Fr,Bo=Ur.all,me=Ur.IS_HTMLDDA?function(s){return typeof s=="function"||s===Bo}:function(s){return typeof s=="function"},Mo=Ae,Vo=me,pa=Mo.WeakMap,Fo=Vo(pa)&&/native code/.test(String(pa)),ma=me,jr=Fr,Uo=jr.all,it=jr.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:ma(s)||s===Uo}:function(s){return typeof s=="object"?s!==null:ma(s)},jo=Le,Ye=!jo(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Tt={},Ho=Ae,ba=it,Rs=Ho.document,Go=ba(Rs)&&ba(Rs.createElement),Hr=function(s){return Go?Rs.createElement(s):{}},Yo=Ye,qo=Le,zo=Hr,Gr=!Yo&&!qo(function(){return Object.defineProperty(zo("div"),"a",{get:function(){return 7}}).a!=7}),Wo=Ye,Qo=Le,Yr=Wo&&Qo(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Jo=it,Ko=String,Xo=TypeError,st=function(s){if(Jo(s))return s;throw Xo(Ko(s)+" is not an object")},Zo=_i,Kt=Function.prototype.call,Oe=Zo?Kt.bind(Kt):function(){return Kt.apply(Kt,arguments)},Fs={},Hi=Fs,Gi=Ae,el=me,Sa=function(s){return el(s)?s:void 0},Us=function(s,e){return arguments.length<2?Sa(Hi[s])||Sa(Gi[s]):Hi[s]&&Hi[s][e]||Gi[s]&&Gi[s][e]},tl=xe,js=tl({}.isPrototypeOf),il=typeof navigator!="undefined"&&String(navigator.userAgent)||"",qr=Ae,Yi=il,va=qr.process,ga=qr.Deno,ya=va&&va.versions||ga&&ga.version,Ta=ya&&ya.v8,be,vi;Ta&&(be=Ta.split("."),vi=be[0]>0&&be[0]<4?1:+(be[0]+be[1]));!vi&&Yi&&(be=Yi.match(/Edge\/(\d+)/),(!be||be[1]>=74)&&(be=Yi.match(/Chrome\/(\d+)/),be&&(vi=+be[1])));var sl=vi,Ea=sl,al=Le,zr=!!Object.getOwnPropertySymbols&&!al(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Ea&&Ea<41}),rl=zr,Wr=rl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",nl=Us,ol=me,ll=js,ul=Wr,dl=Object,Qr=ul?function(s){return typeof s=="symbol"}:function(s){var e=nl("Symbol");return ol(e)&&ll(e.prototype,dl(s))},cl=String,Hs=function(s){try{return cl(s)}catch(e){return"Object"}},hl=me,fl=Hs,pl=TypeError,Gs=function(s){if(hl(s))return s;throw pl(fl(s)+" is not a function")},ml=Gs,bl=Ii,Ni=function(s,e){var t=s[e];return bl(t)?void 0:ml(t)},qi=Oe,zi=me,Wi=it,Sl=TypeError,vl=function(s,e){var t,i;if(e==="string"&&zi(t=s.toString)&&!Wi(i=qi(t,s))||zi(t=s.valueOf)&&!Wi(i=qi(t,s))||e!=="string"&&zi(t=s.toString)&&!Wi(i=qi(t,s)))return i;throw Sl("Can't convert object to primitive value")},gi={},gl={get exports(){return gi},set exports(s){gi=s}},yl=!0,$a=Ae,Tl=Object.defineProperty,El=function(s,e){try{Tl($a,s,{value:e,configurable:!0,writable:!0})}catch(t){$a[s]=e}return e},$l=Ae,kl=El,ka="__core-js_shared__",Al=$l[ka]||kl(ka,{}),Jr=Al,Aa=Jr;(gl.exports=function(s,e){return Aa[s]||(Aa[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var Pl=Vs,wl=Object,Di=function(s){return wl(Pl(s))},_l=xe,Rl=Di,Il=_l({}.hasOwnProperty),Be=Object.hasOwn||function(e,t){return Il(Rl(e),t)},Nl=xe,Dl=0,Cl=Math.random(),Ll=Nl(1 .toString),Kr=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Ll(++Dl+Cl,36)},xl=Ae,Ol=gi,Pa=Be,Bl=Kr,Ml=zr,Vl=Wr,ft=xl.Symbol,Qi=Ol("wks"),Fl=Vl?ft.for||ft:ft&&ft.withoutSetter||Bl,ve=function(s){return Pa(Qi,s)||(Qi[s]=Ml&&Pa(ft,s)?ft[s]:Fl("Symbol."+s)),Qi[s]},Ul=Oe,wa=it,_a=Qr,jl=Ni,Hl=vl,Gl=ve,Yl=TypeError,ql=Gl("toPrimitive"),zl=function(s,e){if(!wa(s)||_a(s))return s;var t=jl(s,ql),i;if(t){if(e===void 0&&(e="default"),i=Ul(t,s,e),!wa(i)||_a(i))return i;throw Yl("Can't convert object to primitive value")}return e===void 0&&(e="number"),Hl(s,e)},Wl=zl,Ql=Qr,Ys=function(s){var e=Wl(s,"string");return Ql(e)?e:e+""},Jl=Ye,Kl=Gr,Xl=Yr,Xt=st,Ra=Ys,Zl=TypeError,Ji=Object.defineProperty,eu=Object.getOwnPropertyDescriptor,Ki="enumerable",Xi="configurable",Zi="writable";Tt.f=Jl?Xl?function(e,t,i){if(Xt(e),t=Ra(t),Xt(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Zi in i&&!i[Zi]){var a=eu(e,t);a&&a[Zi]&&(e[t]=i.value,i={configurable:Xi in i?i[Xi]:a[Xi],enumerable:Ki in i?i[Ki]:a[Ki],writable:!1})}return Ji(e,t,i)}:Ji:function(e,t,i){if(Xt(e),t=Ra(t),Xt(i),Kl)try{return Ji(e,t,i)}catch(a){}if("get"in i||"set"in i)throw Zl("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Ci=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},tu=Ye,iu=Tt,su=Ci,Ut=tu?function(s,e,t){return iu.f(s,e,su(1,t))}:function(s,e,t){return s[e]=t,s},au=gi,ru=Kr,Ia=au("keys"),qs=function(s){return Ia[s]||(Ia[s]=ru(s))},zs={},nu=Fo,Xr=Ae,ou=it,lu=Ut,es=Be,ts=Jr,uu=qs,du=zs,Na="Object already initialized",Is=Xr.TypeError,cu=Xr.WeakMap,yi,Vt,Ti,hu=function(s){return Ti(s)?Vt(s):yi(s,{})},fu=function(s){return function(e){var t;if(!ou(e)||(t=Vt(e)).type!==s)throw Is("Incompatible receiver, "+s+" required");return t}};if(nu||ts.state){var Ee=ts.state||(ts.state=new cu);Ee.get=Ee.get,Ee.has=Ee.has,Ee.set=Ee.set,yi=function(s,e){if(Ee.has(s))throw Is(Na);return e.facade=s,Ee.set(s,e),e},Vt=function(s){return Ee.get(s)||{}},Ti=function(s){return Ee.has(s)}}else{var lt=uu("state");du[lt]=!0,yi=function(s,e){if(es(s,lt))throw Is(Na);return e.facade=s,lu(s,lt,e),e},Vt=function(s){return es(s,lt)?s[lt]:{}},Ti=function(s){return es(s,lt)}}var pu={set:yi,get:Vt,has:Ti,enforce:hu,getterFor:fu},mu=_i,Zr=Function.prototype,Da=Zr.apply,Ca=Zr.call,bu=typeof Reflect=="object"&&Reflect.apply||(mu?Ca.bind(Da):function(){return Ca.apply(Da,arguments)}),Su=Ri,vu=xe,en=function(s){if(Su(s)==="Function")return vu(s)},tn={},sn={},an={}.propertyIsEnumerable,rn=Object.getOwnPropertyDescriptor,gu=rn&&!an.call({1:2},1);sn.f=gu?function(e){var t=rn(this,e);return!!t&&t.enumerable}:an;var yu=Ye,Tu=Oe,Eu=sn,$u=Ci,ku=Ft,Au=Ys,Pu=Be,wu=Gr,La=Object.getOwnPropertyDescriptor;tn.f=yu?La:function(e,t){if(e=ku(e),t=Au(t),wu)try{return La(e,t)}catch(i){}if(Pu(e,t))return $u(!Tu(Eu.f,e,t),e[t])};var _u=Le,Ru=me,Iu=/#|\.prototype\./,jt=function(s,e){var t=Du[Nu(s)];return t==Lu?!0:t==Cu?!1:Ru(e)?_u(e):!!e},Nu=jt.normalize=function(s){return String(s).replace(Iu,".").toLowerCase()},Du=jt.data={},Cu=jt.NATIVE="N",Lu=jt.POLYFILL="P",xu=jt,xa=en,Ou=Gs,Bu=_i,Mu=xa(xa.bind),nn=function(s,e){return Ou(s),e===void 0?s:Bu?Mu(s,e):function(){return s.apply(e,arguments)}},Zt=Ae,Vu=bu,Fu=en,Uu=me,ju=tn.f,Hu=xu,ut=Fs,Gu=nn,dt=Ut,Oa=Be,Yu=function(s){var e=function(t,i,a){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,a)}return Vu(s,this,arguments)};return e.prototype=s.prototype,e},Li=function(s,e){var t=s.target,i=s.global,a=s.stat,n=s.proto,o=i?Zt:a?Zt[t]:(Zt[t]||{}).prototype,l=i?ut:ut[t]||dt(ut,t,{})[t],d=l.prototype,u,c,h,f,m,b,p,S,v;for(f in e)u=Hu(i?f:t+(a?".":"#")+f,s.forced),c=!u&&o&&Oa(o,f),b=l[f],c&&(s.dontCallGetSet?(v=ju(o,f),p=v&&v.value):p=o[f]),m=c&&p?p:e[f],!(c&&typeof b==typeof m)&&(s.bind&&c?S=Gu(m,Zt):s.wrap&&c?S=Yu(m):n&&Uu(m)?S=Fu(m):S=m,(s.sham||m&&m.sham||b&&b.sham)&&dt(S,"sham",!0),dt(l,f,S),n&&(h=t+"Prototype",Oa(ut,h)||dt(ut,h,{}),dt(ut[h],f,m),s.real&&d&&(u||!d[f])&&dt(d,f,m)))},Ns=Ye,qu=Be,on=Function.prototype,zu=Ns&&Object.getOwnPropertyDescriptor,Ws=qu(on,"name"),Wu=Ws&&function(){}.name==="something",Qu=Ws&&(!Ns||Ns&&zu(on,"name").configurable),Ju={EXISTS:Ws,PROPER:Wu,CONFIGURABLE:Qu},ln={},Ku=Math.ceil,Xu=Math.floor,Zu=Math.trunc||function(e){var t=+e;return(t>0?Xu:Ku)(t)},ed=Zu,Qs=function(s){var e=+s;return e!==e||e===0?0:ed(e)},td=Qs,id=Math.max,sd=Math.min,ad=function(s,e){var t=td(s);return t<0?id(t+e,0):sd(t,e)},rd=Qs,nd=Math.min,od=function(s){return s>0?nd(rd(s),9007199254740991):0},ld=od,Js=function(s){return ld(s.length)},ud=Ft,dd=ad,cd=Js,Ba=function(s){return function(e,t,i){var a=ud(e),n=cd(a),o=dd(i,n),l;if(s&&t!=t){for(;n>o;)if(l=a[o++],l!=l)return!0}else for(;n>o;o++)if((s||o in a)&&a[o]===t)return s||o||0;return!s&&-1}},hd={includes:Ba(!0),indexOf:Ba(!1)},fd=xe,is=Be,pd=Ft,md=hd.indexOf,bd=zs,Ma=fd([].push),Sd=function(s,e){var t=pd(s),i=0,a=[],n;for(n in t)!is(bd,n)&&is(t,n)&&Ma(a,n);for(;e.length>i;)is(t,n=e[i++])&&(~md(a,n)||Ma(a,n));return a},un=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],vd=Sd,gd=un,yd=Object.keys||function(e){return vd(e,gd)},Td=Ye,Ed=Yr,$d=Tt,kd=st,Ad=Ft,Pd=yd;ln.f=Td&&!Ed?Object.defineProperties:function(e,t){kd(e);for(var i=Ad(t),a=Pd(t),n=a.length,o=0,l;n>o;)$d.f(e,l=a[o++],i[l]);return e};var wd=Us,_d=wd("document","documentElement"),Rd=st,Id=ln,Va=un,Nd=zs,Dd=_d,Cd=Hr,Ld=qs,Fa=">",Ua="<",Ds="prototype",Cs="script",dn=Ld("IE_PROTO"),ss=function(){},cn=function(s){return Ua+Cs+Fa+s+Ua+"/"+Cs+Fa},ja=function(s){s.write(cn("")),s.close();var e=s.parentWindow.Object;return s=null,e},xd=function(){var s=Cd("iframe"),e="java"+Cs+":",t;return s.style.display="none",Dd.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(cn("document.F=Object")),t.close(),t.F},ei,fi=function(){try{ei=new ActiveXObject("htmlfile")}catch(e){}fi=typeof document!="undefined"?document.domain&&ei?ja(ei):xd():ja(ei);for(var s=Va.length;s--;)delete fi[Ds][Va[s]];return fi()};Nd[dn]=!0;var hn=Object.create||function(e,t){var i;return e!==null?(ss[Ds]=Rd(e),i=new ss,ss[Ds]=null,i[dn]=e):i=fi(),t===void 0?i:Id.f(i,t)},Od=Le,Bd=!Od(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Md=Be,Vd=me,Fd=Di,Ud=qs,jd=Bd,Ha=Ud("IE_PROTO"),Ls=Object,Hd=Ls.prototype,fn=jd?Ls.getPrototypeOf:function(s){var e=Fd(s);if(Md(e,Ha))return e[Ha];var t=e.constructor;return Vd(t)&&e instanceof t?t.prototype:e instanceof Ls?Hd:null},Gd=Ut,pn=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Gd(s,e,t),s},Yd=Le,qd=me,zd=it,Wd=hn,Ga=fn,Qd=pn,Jd=ve,xs=Jd("iterator"),mn=!1,De,as,rs;[].keys&&(rs=[].keys(),"next"in rs?(as=Ga(Ga(rs)),as!==Object.prototype&&(De=as)):mn=!0);var Kd=!zd(De)||Yd(function(){var s={};return De[xs].call(s)!==s});Kd?De={}:De=Wd(De);qd(De[xs])||Qd(De,xs,function(){return this});var bn={IteratorPrototype:De,BUGGY_SAFARI_ITERATORS:mn},Xd=ve,Zd=Xd("toStringTag"),Sn={};Sn[Zd]="z";var Ks=String(Sn)==="[object z]",ec=Ks,tc=me,pi=Ri,ic=ve,sc=ic("toStringTag"),ac=Object,rc=pi(function(){return arguments}())=="Arguments",nc=function(s,e){try{return s[e]}catch(t){}},xi=ec?pi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=nc(e=ac(s),sc))=="string"?t:rc?pi(e):(i=pi(e))=="Object"&&tc(e.callee)?"Arguments":i},oc=Ks,lc=xi,uc=oc?{}.toString:function(){return"[object "+lc(this)+"]"},dc=Ks,cc=Tt.f,hc=Ut,fc=Be,pc=uc,mc=ve,Ya=mc("toStringTag"),vn=function(s,e,t,i){if(s){var a=t?s:s.prototype;fc(a,Ya)||cc(a,Ya,{configurable:!0,value:e}),i&&!dc&&hc(a,"toString",pc)}},bc=bn.IteratorPrototype,Sc=hn,vc=Ci,gc=vn,yc=yt,Tc=function(){return this},Ec=function(s,e,t,i){var a=e+" Iterator";return s.prototype=Sc(bc,{next:vc(+!i,t)}),gc(s,a,!1,!0),yc[a]=Tc,s},$c=Li,kc=Oe,gn=Ju,Ac=Ec,Pc=fn,wc=vn,qa=pn,_c=ve,za=yt,yn=bn,Rc=gn.PROPER;gn.CONFIGURABLE;yn.IteratorPrototype;var ti=yn.BUGGY_SAFARI_ITERATORS,ns=_c("iterator"),Wa="keys",ii="values",Qa="entries",Ic=function(){return this},Nc=function(s,e,t,i,a,n,o){Ac(t,e,i);var l=function(v){if(v===a&&f)return f;if(!ti&&v in c)return c[v];switch(v){case Wa:return function(){return new t(this,v)};case ii:return function(){return new t(this,v)};case Qa:return function(){return new t(this,v)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[ns]||c["@@iterator"]||a&&c[a],f=!ti&&h||l(a),m=e=="Array"&&c.entries||h,b,p,S;if(m&&(b=Pc(m.call(new s)),b!==Object.prototype&&b.next&&(wc(b,d,!0,!0),za[d]=Ic)),Rc&&a==ii&&h&&h.name!==ii&&(u=!0,f=function(){return kc(h,this)}),a)if(p={values:l(ii),keys:n?f:l(Wa),entries:l(Qa)},o)for(S in p)(ti||u||!(S in c))&&qa(c,S,p[S]);else $c({target:e,proto:!0,forced:ti||u},p);return o&&c[ns]!==f&&qa(c,ns,f,{name:a}),za[e]=f,p},Dc=function(s,e){return{value:s,done:e}},Cc=Ft,Xs=xo,Ja=yt,Tn=pu,Lc=Tt.f,xc=Nc,si=Dc,Oc=yl,Bc=Ye,En="Array Iterator",Mc=Tn.set,Vc=Tn.getterFor(En);xc(Array,"Array",function(s,e){Mc(this,{type:En,target:Cc(s),index:0,kind:e})},function(){var s=Vc(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,si(void 0,!0)):t=="keys"?si(i,!1):t=="values"?si(e[i],!1):si([i,e[i]],!1)},"values");var Ka=Ja.Arguments=Ja.Array;Xs();Xs();Xs();if(!Oc&&Bc&&Ka.name!=="values")try{Lc(Ka,"name",{value:"values"})}catch(s){}var Fc=ve,Uc=yt,jc=Fc("iterator"),Hc=Array.prototype,Gc=function(s){return s!==void 0&&(Uc.Array===s||Hc[jc]===s)},Yc=xi,Xa=Ni,qc=Ii,zc=yt,Wc=ve,Qc=Wc("iterator"),$n=function(s){if(!qc(s))return Xa(s,Qc)||Xa(s,"@@iterator")||zc[Yc(s)]},Jc=Oe,Kc=Gs,Xc=st,Zc=Hs,eh=$n,th=TypeError,ih=function(s,e){var t=arguments.length<2?eh(s):e;if(Kc(t))return Xc(Jc(t,s));throw th(Zc(s)+" is not iterable")},sh=Oe,Za=st,ah=Ni,rh=function(s,e,t){var i,a;Za(s);try{if(i=ah(s,"return"),!i){if(e==="throw")throw t;return t}i=sh(i,s)}catch(n){a=!0,i=n}if(e==="throw")throw t;if(a)throw i;return Za(i),t},nh=nn,oh=Oe,lh=st,uh=Hs,dh=Gc,ch=Js,er=js,hh=ih,fh=$n,tr=rh,ph=TypeError,mi=function(s,e){this.stopped=s,this.result=e},ir=mi.prototype,mh=function(s,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=nh(e,i),u,c,h,f,m,b,p,S=function(g){return u&&tr(u,"normal",g),new mi(!0,g)},v=function(g){return a?(lh(g),l?d(g[0],g[1],S):d(g[0],g[1])):l?d(g,S):d(g)};if(n)u=s.iterator;else if(o)u=s;else{if(c=fh(s),!c)throw ph(uh(s)+" is not iterable");if(dh(c)){for(h=0,f=ch(s);f>h;h++)if(m=v(s[h]),m&&er(ir,m))return m;return new mi(!1)}u=hh(s,c)}for(b=n?s.next:u.next;!(p=oh(b,u)).done;){try{m=v(p.value)}catch(g){tr(u,"throw",g)}if(typeof m=="object"&&m&&er(ir,m))return m}return new mi(!1)},bh=Ys,Sh=Tt,vh=Ci,gh=function(s,e,t){var i=bh(e);i in s?Sh.f(s,i,vh(0,t)):s[i]=t},yh=Li,Th=mh,Eh=gh;yh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Th(e,function(i,a){Eh(t,i,a)},{AS_ENTRIES:!0}),t}});var $h=Fs,kh=$h.Object.fromEntries,Ah={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},Ph=Ah,wh=Ae,_h=xi,Rh=Ut,sr=yt,Ih=ve,ar=Ih("toStringTag");for(var os in Ph){var rr=wh[os],ls=rr&&rr.prototype;ls&&_h(ls)!==ar&&Rh(ls,ar,os),sr[os]=sr.Array}var Nh=kh,Dh=Nh,Ch=Dh,Lh=Ch,Ht=Lh,mt;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(mt||(mt={}));var bt=(s,e=0,t=mt.OFFSET_P)=>{switch(t){case mt.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case mt.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:r.assertNever(t)}return s},k=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};exports.VideoQuality=void 0;(function(s){s.INVARIANT="Invariant quality",s.Q_144P="144p",s.Q_240P="240p",s.Q_360P="360p",s.Q_480P="480p",s.Q_720P="720p",s.Q_1080P="1080p",s.Q_1440P="1440p",s.Q_2160P="2160p",s.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const Se={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},bi=(s,e)=>Se[s].height>Se[e].height,xh=(s,e)=>Se[s].height>=Se[e].height,Ot=(s,e)=>Se[s].height<Se[e].height,Oh=(s,e)=>Se[s].height<=Se[e].height,Bh=s=>s.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:Ot(e,t)?1:-1)[0],Mh=Object.keys(Se).sort((s,e)=>Ot(s,e)?-1:1),at=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return Mh.find(a=>{const n=Se[a];return n.width>=i&&n.height>=t})},Vh=s=>Se[s].height,Ei=s=>s===exports.VideoQuality.INVARIANT;class W{constructor(e){this.transitionStarted$=new r.Subject,this.transitionEnded$=new r.Subject,this.transitionUpdated$=new r.Subject,this.forceChanged$=new r.Subject,this.stateChangeStarted$=r.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=r.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||r.isNonNullable(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const Fh=s=>{switch(s){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return r.assertNever(s)}};var L;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(L||(L={}));const Uh=5,jh=5,Hh=500,nr=7e3;class Gh{constructor(e){this.subscription=new r.Subscription,this.loadMediaTimeoutSubscription=new r.Subscription,this.videoState=new W(L.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){i!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!a){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===N.Requested&&i!==L.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(i){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PLAYING:{switch(i){case L.PLAYING:break;case L.PAUSED:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.READY:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case L.PLAYING:this.videoState.startTransitionTo(L.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case L.PAUSED:break;case L.READY:this.videoState.startTransitionTo(L.PAUSED),this.videoState.setState(L.PAUSED);break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(i)}break}default:r.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Fh(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const 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);const e=new r.Subscription;this.subscription.add(e),this.subscription.add(r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(r.map(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));const t=(a,n)=>this.subscription.add(a.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const a=new r.Subject;e.add(a.pipe(r.debounce(Hh)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===N.Applying||Math.abs(l-n)>Uh)&&a.next(l),n=l})),e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);const{remotePlayer:n}=this.params.connection,o=a.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<jh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,exports.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:r.assertNever(o)}}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});const i=r.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(L.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(L.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:N.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PAUSED||e===L.PLAYING)&&(this.videoState.setState(L.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PLAYING||e===L.PAUSED)&&(this.videoState.setState(L.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===L.READY&&this.videoState.setState(L.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==L.STOPPED&&this.videoState.setState(L.STOPPED)}handleRemoteVolumeChange(e){var t,i;const a=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:a.volume,muted:(i=e.muted)!==null&&i!==void 0?i:a.muted};(n.volume!==a.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let a,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=i[e];r.assertNonNullable(c);const h=Bh(Object.keys(c));r.assertNonNullable(h);const f=c[h];r.assertNonNullable(f),a=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=i[e];r.assertNonNullable(c),a=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const c=i[e];r.assertNonNullable(c),a=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=i[e];r.assertNonNullable(c),a=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=i[e];r.assertNonNullable(c),a=bt(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:r.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:a,n);l.contentUrl=a,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return r.isNonNullable(d)&&(l.metadata.title=d),r.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===N.Applying||i.state===N.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((a,n)=>{this.loadMediaTimeoutSubscription.add(r.timeout(nr).subscribe(()=>n(`timeout(${nr})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===N.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:r.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:a})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class or{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let a=0,n=i.length;a<n;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let a=0,n=i.length;a<n;a++){const o=i[a];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class kn extends or{constructor(){super(),this.listeners||or.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let An=class{constructor(){Object.defineProperty(this,"signal",{value:new kn,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(a){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(An.prototype[Symbol.toStringTag]="AbortController",kn.prototype[Symbol.toStringTag]="AbortSignal");function Pn(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Yh(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=s;if(!Pn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||a)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(m){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((m,b)=>{c.addEventListener("abort",()=>b(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Oi=Pn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),wn=Oi?Yh({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,St=Oi?wn.fetch:window.fetch;Oi?wn.Request:window.Request;const et=Oi?An:window.AbortController,Ct=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class Bt{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,a=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];a.push(e),this.dashJsRequestQueue.set(i,a)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const a=t[0];if(!a||!a.request.range)continue;const[n,o]=Ct(a.request);if(n>=i.from&&o<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const a=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,a)}}}abort(e){var t;if(e){const{request:i}=e,a=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(i.url);a&&n&&n.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(Ct),a=i[0][0];let n=i[0][1];for(let f=1;f<i.length&&n<this.params.minDataSize;f++){const m=i[f][1];m-a<=2*this.params.minDataSize&&(n=Math.max(n,m))}a===0?n=Math.max(n,a+this.params.minInitSize):n=Math.max(n,a+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${a}-${n}`);const l=o.toString(),d=new et,u=d.signal,c={url:e,from:a,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var m,b;throw(b=(m=this.params).onError)===null||b===void 0||b.call(m,{id:"BigRequestParsing",category:r.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return St(l,{signal:u}).then(f=>{var m,b,p;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[S,v]=f.body.tee();(b=(m=this.params).onDownloadStream)===null||b===void 0||b.call(m,v);const g=S.getReader(),A=parseInt((p=f.headers.get("Content-Length"))!==null&&p!==void 0?p:"",10)||n-a+1;c.data=new ArrayBuffer(A);const E=new Uint8Array(c.data),T=async({done:w,value:V})=>{w?this.onBigRequestProgress(c):V&&(E.set(V,c.loaded),c.loaded+=V.byteLength,this.onBigRequestProgress(c),await(g==null?void 0:g.read().then(T,Bt.suppressStreamErrors).catch(h)))};g==null||g.read().then(T,Bt.suppressStreamErrors).catch(h)},Bt.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:i,loaded:a,data:n,response:o}){var l,d,u,c,h,f,m,b;if(!this.activeRequests.has(e)||!n)return;const p=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const S of p){const{request:v}=S,[g,A]=Ct(v),E=g>=t&&A<=t+a,T=t>=g&&t+a<A,w=n.slice(g-t,Math.min(A-t+1,a));if((E||T)&&(v.requestStartDate=(d=v.requestStartDate)!==null&&d!==void 0?d:new Date,v.firstByteDate=(u=v.firstByteDate)!==null&&u!==void 0?u:new Date,v.bytesLoaded=w.byteLength,v.bytesTotal=i-t),E){v.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(C=>C!==S)),(h=S.success)===null||h===void 0||h.call(S,w,"",e);const V=o?Array.from(o.headers.entries()).map(([C,R])=>`${C}: ${R}`).join(`\r
7
+ `):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(v,e,(m=o==null?void 0:o.status)!==null&&m!==void 0?m:200,V,[])}else T&&((b=S.progress)===null||b===void 0||b.call(S,{loaded:a,total:i-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:i},a){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:r.ErrorCategory.NETWORK,message:"Download error",thrown:a}),!this.activeRequests.has(e))return;const u=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const c of u){const[h,f]=Ct(c.request);(h>=t&&h<i||f>t&&f<=i)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(a)))}if(this.activeRequests.delete(e),a)throw a}onBigRequestAbort({url:e,from:t,to:i}){var a,n;if(!this.activeRequests.has(e))return;const o=(a=this.dashJsRequestQueue.get(e))!==null&&a!==void 0?a:[];for(const l of o){const[d,u]=Ct(l.request);(d>=t&&d<i||u>t&&u<=i)&&((n=l==null?void 0:l.abort)===null||n===void 0||n.call(l,l.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class $i{constructor(e,t,i){this.baseLoader=e,this.config=i,this.bigRequest=t,t.setMetrics(i.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if($i.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;$i.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const qh=(s,e)=>t=>({create:i=>{const a=s(t).create(i);return new $i(a,e,i)}}),zh=(s,e)=>{const t=new Bt(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,a=i.getLoader;return{getLoader:n=>{const o=a(n);return qh(o,t)}}},!0),()=>t.destroy()};var Wh=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:a})=>{i=a<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:a}=this,n=a.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&(e==null||e())}}},!0)},Qh=s=>{const e=new r.ValueSubject(1/0),t=new r.Subject,i=new r.ValueSubject(void 0),a=new r.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,m,b,p;const S=Ht(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(A=>A.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const A=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),E=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),T=(m=E!=null?E:A*1e3)!==null&&m!==void 0?m:NaN;r.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const v=(b=S["x-delivery-type"])!==null&&b!==void 0?b:exports.HttpConnectionType.HTTP1,g=(p={1:!0,0:!1}[S["x-reused"]])!==null&&p!==void 0?p:void 0;i.next(v),a.next(g)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return s.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const m=f.onload,b=f.progress;f.onload=function(...p){return d(this),m(...p)},f.progress=function(...p){return u(this),b(...p)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:a,connectionType$:i}},vt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Jh=s=>s.extend("RequestModifier",()=>({modifyRequestURL:vt}),!0),Kh=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[a,n]=i.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${a}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const ke=(s,e,t,{equal:i=(o,l)=>o===l,changed$:a,onError:n}={})=>{const o=s.getState(),l=e(),d=r.isNullable(a),u=new r.Subscription;return a&&u.add(a.subscribe(c=>{const h=s.getState();i(c,h)&&s.setState(c)},n)),i(l,o)||(t(o),d&&s.setState(o)),u.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),d&&s.setState(c.to)},n)),u},rt=(s,e,t)=>ke(e,()=>s.loop,i=>{r.isNonNullable(i)&&(s.loop=i)},{onError:t}),Me=(s,e,t,i)=>ke(e,()=>({muted:s.muted,volume:s.volume}),a=>{r.isNonNullable(a)&&(s.muted=a.muted,s.volume=a.volume)},{equal:(a,n)=>a===n||(a==null?void 0:a.muted)===(n==null?void 0:n.muted)&&(a==null?void 0:a.volume)===(n==null?void 0:n.volume),changed$:t,onError:i}),qe=(s,e,t,i)=>ke(e,()=>s.playbackRate,a=>{r.isNonNullable(a)&&(s.playbackRate=a)},{changed$:t,onError:i}),Xh=s=>["__",s.language,s.label].join("|"),Zh=(s,e)=>{if(s.id===e)return!0;const[t,i,a]=e.split("|");return s.language===i&&s.label===a};class Pe{constructor(){this.available$=new r.Subject,this.current$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.subscription=new r.Subscription,this.externalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const a=n=>{this.error$.next({id:"TextTracksManager",category:r.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ke(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{r.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),this.subscription.add(ke(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:a})),this.subscription.add(ke(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){r.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(r.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();this.select(i)})),this.subscription.add(r.merge(r.fromEvent(e,"addtrack"),r.fromEvent(e,"removetrack"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),r.filterChanged((i,a)=>i.length===a.length&&i.every(({id:n},o)=>n===a[o].id))).subscribe(this.available$)),this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),r.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),r.filterChanged()).subscribe(this.current$));const t=i=>{var a,n;return this.applyCueSettings((n=(a=i.target)===null||a===void 0?void 0:a.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(r.fromEvent(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)===null||a===void 0||a.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const m=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;m&&m.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(r.fromEvent(e,"removetrack").subscribe(i=>{var a;(a=i.track)===null||a===void 0||a.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const a=i;r.isNonNullable(t.align)&&(a.align=t.align),r.isNonNullable(t.position)&&(a.position=t.position),r.isNonNullable(t.size)&&(a.size=t.size),r.isNonNullable(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){r.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Pe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,a=e.id!==""?e.id:Xh(e);return this.externalTracks.has(a)?{id:a,type:"external",language:t,label:i,url:this.externalTracks.get(a).url}:{id:a,type:"internal",language:t,label:i}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(i=>i.id===t)).forEach(t=>this.detach(t))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))r.isNonNullable(e)&&Zh(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){r.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){r.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var Ve=s=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),s.appendChild(e),e};class Zs{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 _n=()=>{const{userAgent:s}=window.navigator;return!/chrome/i.test(s)&&/webkit|safari|khtml/i.test(s)};const Os=3;class ef{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let a=this._source.buffered.start(t);const n=this._source.buffered.end(t);a>e&&a-e<Os&&(a=e),this._buffer.push({from:a,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Os))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:a,to:n})=>{const o=a>=e&&a<t,l=n>=e&&n<t;o&&l||(o?i(t,n):l?i(a,e):a<e&&n>t?(i(t,n),i(a,e)):i(a,n))})}destroy(){this._buffer=[]}}var Rn=(s,e,t=Os)=>{let i=0,a=0;for(let n=0;n<s.length;n++){const o=s.start(n),l=s.end(n);if(o<=e&&e<=l){if(i=o,a=l,!t)return{from:i,to:a};for(let d=n-1;d>=0;d--)s.end(d)+t>=i&&(i=s.start(d));for(let d=n+1;d<s.length;d++)s.start(d)-t<=a&&(a=s.end(d))}}return{from:i,to:a}};const tf=50,sf=s=>s.webkitAudioDecodedByteCount!==void 0?!!s.webkitAudioDecodedByteCount:s.mozHasAudio!==void 0?s.mozHasAudio:s.audioTracks?!!s.audioTracks.length:!0,Fe=s=>{const e=b=>r.fromEvent(s,b).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=r.merge(...t.map(b=>r.fromEvent(s,b))).pipe(r.map(b=>b.type==="ended"?s.readyState<2:s.readyState<3),r.filterChanged()),a=r.merge(r.fromEvent(s,"progress"),r.fromEvent(s,"timeupdate")).pipe(r.map(()=>Rn(s.buffered,s.currentTime))),n=_n()?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),o=r.fromEvent(s,"playing").pipe(r.debounce(tf),r.map(()=>sf(s))),l=r.fromEvent(s,"volumechange").pipe(r.map(()=>({muted:s.muted,volume:s.volume}))),d=r.fromEvent(s,"ratechange").pipe(r.map(()=>s.playbackRate)),u=r.fromEvent(s,"error").pipe(r.filter(()=>Boolean(s.error||s.played.length)),r.map(()=>{var b;const p=s.error;return{id:p?`MediaError#${p.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:p?p.message:"Error event from HTML video element",thrown:(b=s.error)!==null&&b!==void 0?b:void 0}})),c=r.fromEvent(s,"timeupdate").pipe(r.map(()=>s.currentTime)),h=new r.Subject,f=.3;let m;return c.subscribe(b=>{s.loop&&r.isNonNullable(m)&&r.isNonNullable(b)&&m>=s.duration-f&&b<=f&&h.next(m),m=b}),{playing$:n,pause$:e("pause").pipe(r.filter(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:r.fromEvent(s,"durationchange").pipe(r.map(()=>s.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:l,isAudioAvailable$:o,playbackRateState$:d}},ea=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var af=Li,rf=Di,nf=Js,of=Qs;af({target:"Array",proto:!0},{at:function(e){var t=rf(this),i=nf(t),a=of(e),n=a>=0?a:i+a;return n<0||n>=i?void 0:t[n]}});var lf=Us,In=lf,uf=In,df=uf("Array","at"),cf=df,hf=cf,ff=hf,pf=ff,Re=pf;let ta=!1,Ie={};const mf=s=>{ta=s},bf=()=>{Ie={}},Sf=s=>{s(Ie)},ai=(s,e)=>{var t;ta&&(Ie.meta=(t=Ie.meta)!==null&&t!==void 0?t:{},Ie.meta[s]=e)};class $e{constructor(e){this.name=e}next(e){var t,i;if(!ta)return;Ie.series=(t=Ie.series)!==null&&t!==void 0?t:{};const a=(i=Ie.series[this.name])!==null&&i!==void 0?i:[];a.push([Date.now(),e]),Ie.series[this.name]=a}}const vf=new $e("best_bitrate"),gf=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class yf{constructor(){this.history={}}recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Gt=(s,{container:e,throughput:t,tuning:i,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,m;const b=i.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*b*i.containerSizeFactor,height:e.height*b*i.containerSizeFactor},S=p&&at(p),v=i.considerPlaybackRate&&r.isNonNullable(l)?l:1,g=s.filter(I=>!Ei(I.quality)).sort((I,_)=>bi(I.quality,_.quality)?-1:1),A=(h=Re(g,-1))===null||h===void 0?void 0:h.quality,E=(f=Re(g,0))===null||f===void 0?void 0:f.quality,T=r.isNullable(a)||r.isNonNullable(a.min)&&r.isNonNullable(a.max)&&Ot(a.max,a.min)||r.isNonNullable(a.min)&&E&&bi(a.min,E)||r.isNonNullable(a.max)&&A&&Ot(a.max,A),w=v*gf(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),C=g.filter(I=>{const _=S?Ot(I.quality,S):!0,H=r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(I.bitrate)?t-n>=I.bitrate*w:!0,Q=i.lazyQualitySwitch&&r.isNonNullable(i.minBufferToSwitchUp)&&d&&!Ei(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&bi(I.quality,d.quality),Z=T||(r.isNullable(a.max)||Oh(I.quality,a.max))&&(r.isNullable(a.min)||xh(I.quality,a.min));return _&&H&&!Q&&Z})[0];C&&C.bitrate&&vf.next(C.bitrate);const R=(m=C!=null?C:g[Math.ceil((g.length-1)/2)])!==null&&m!==void 0?m:s[0],F=R&&u&&u.history[R.id]&&r.now()-u.history[R.id]<=i.trackCooldown&&(!u.last||R.id!==u.last.id);if(R!=null&&R.id&&u&&!F&&u.recordSelection(R),F&&(u!=null&&u.last)){const I=u.last;return u==null||u.recordSwitch(I),I}return u==null||u.recordSwitch(R),R};var ne=s=>new URL(s).hostname;const Tf=300,ki=(s,e=Tf)=>new r.Observable(t=>{const{width:i,height:a}=s.getBoundingClientRect();if(t.next({width:i,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(bo(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),r.isNonNullable(d)&&r.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(s),()=>n.disconnect()}),Ue=s=>{try{s.pause(),s.playbackRate=0,s.removeAttribute("src"),s.load(),s.remove()}catch(e){console.error(e)}},Ef=5e3,Lt={};var O;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(O||(O={}));const te=(s,e)=>new r.Observable(t=>{const i=a=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class lr{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(O.DOWNLOADING_LIB),this.textTracksManager=new Pe,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new r.ValueSubject(void 0),this.maxSeekBackTime$=new r.ValueSubject(1/0),this.availableFrom$=new r.ValueSubject(void 0),this.elementSize$=new r.ValueSubject(void 0),this.liveOffset=new Zs,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===O.DOWNLOADING_LIB||t===O.STREAM_INITIALIZED))switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===N.Requested&&t!==O.STOPPED&&i!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),i){case exports.PlaybackState.STOPPED:{switch(t){case O.STOPPED:break;case O.PLAYING:case O.PAUSED:case O.READY:this.stop();break;default:r.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case O.STOPPED:this.prepare();break;case O.PLAYING:case O.PAUSED:case O.READY:break;default:r.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case O.PLAYING:break;case O.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case O.READY:this.play();break;case O.STOPPED:this.prepare();break;default:r.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case O.PLAYING:this.pause(),this.liveOffset.pause();break;case O.PAUSED:break;case O.READY:this.videoState.setState(O.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case O.STOPPED:this.prepare();break;default:r.assertNever(t)}break}default:r.assertNever(i)}},this.video=Ve(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=a=>{var n;e||this.params.output.error$.next({id:a==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:r.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=a==null?void 0:a.toString)===null||n===void 0?void 0:n.call(a)}`,thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),Ef);import("dashjs/dist/dash.mediaplayer.min.js").then(a=>{e||(Lt.MediaPlayer=a.MediaPlayer,Lt.Debug=a.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(Lt.MediaPlayer,"dashjs not loaded"),r.assertNonNullable(Lt.Debug,"dashjs not loaded"),this.player=Lt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?ea(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=zh(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&Kh(this.player),Wh(this.player),this.params.tuning.requestQuick&&Jh(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(O.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=p=>{e.error$.next({id:"DashIFProvider",category:r.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:p})},a=(p,S)=>this.subscription.add(p.subscribe(S,i));a(ki(this.video),this.elementSize$),a(te(this.player,"error").pipe(r.map(p=>{const S=typeof p.error=="object"?p.error.code:p.error,v=typeof p.error=="object"?p.error.message:void 0;return{id:`DashJS#${S}`,message:v}})),e.error$),a(te(this.player,"playbackError").pipe(r.map(p=>({id:"DashJSPlayback",message:p.error}))),e.error$);const n=te(this.player,"qualityChangeRendered").pipe(r.filter(({mediaType:p})=>p==="video"),r.map(({newQuality:p})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:v})=>v.qualityIndex===p))===null||S===void 0?void 0:S.track}));n.pipe(r.filter(r.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(r.filter(({to:p})=>p===O.STREAM_INITIALIZED),r.once()).subscribe(()=>{this.subscription.add(ke(t.videoTrack,()=>{var p,S;const v=this.player.getQualityFor("video");return(S=(p=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===v))===null||p===void 0?void 0:p.track)===null||S===void 0?void 0:S.id},p=>{var S;if(r.isNullable(p))return;const v=(S=this.videoTracks.find(({track:g})=>g.id===p))===null||S===void 0?void 0:S.bitrateInfo;v&&this.player.setQualityFor("video",v.qualityIndex)},{changed$:n.pipe(r.map(p=>p==null?void 0:p.id)),onError:i}))},i)),this.subscription.add(ke(t.autoVideoTrackSwitching,()=>{var p,S,v;return(v=(S=(p=this.player.getSettings().streaming)===null||p===void 0?void 0:p.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||v===void 0?void 0:v.video},p=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:p}}}}),{onError:i})),a(te(this.player,"bufferStateChanged").pipe(r.filter(({mediaType:p})=>p==="video"),r.map(({state:p})=>p==="bufferStalled")),e.isBuffering$),a(te(this.player,"fragmentLoadingStarted"),({mediaType:p,request:{url:S}})=>{var v,g;const A=this.player.getDashMetrics(),E=A.getLatestFragmentRequestHeaderValueByID(p,"X-Reused"),T=(v=A.getLatestFragmentRequestHeaderValueByID(p,"X-Delivery-Type"))!==null&&v!==void 0?v:exports.HttpConnectionType.HTTP1,w=(g={1:!0,0:!1}[E])!==null&&g!==void 0?g:void 0;this.params.output.httpConnectionType$.next(T),this.params.output.httpConnectionReused$.next(w),e.hostname$.next(ne(S))}),a(te(this.player,"streamInitialized"),({streamInfo:{duration:p,manifestInfo:{isDynamic:S,availableFrom:v}}})=>{this.isLive$.next(S),this.availableFrom$.next(v.getTime()),S||e.duration$.next(p),this.videoTracks=[];const g=this.player.getQualityFor("video");let A;for(const E of this.player.getBitrateInfoListFor("video")){const T=E.qualityIndex.toString(10),w=at(E),V=E.bitrate/1e3,C={width:E.width,height:E.height},R=this.frameRatesByFrameHeight[E.height];if(w){const F={id:T,quality:w,bitrate:V,size:C,fps:R};this.videoTracks.push({track:F,bitrateInfo:E}),E.qualityIndex===g&&(A=F)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:E})=>E)),A&&e.currentVideoTrack$.next(A),this.videoState.setState(O.STREAM_INITIALIZED),this.videoState.startTransitionTo(O.READY)}),a(te(this.player,"fragmentLoadingCompleted"),({request:p})=>{if(!p.requestEndDate||!p.firstByteDate||!p.bytesLoaded)return;const S=p.requestEndDate.getTime()-p.firstByteDate.getTime(),v=p.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(v,S)}),a(r.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const p=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=Gt(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:p,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),v=this.videoTracks.find(({track:g})=>g===S);v!=null&&v.bitrateInfo&&this.player.setQualityFor("video",v==null?void 0:v.bitrateInfo.qualityIndex,!1)}),a(r.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(r.filter(r.isNonNullable))}).pipe(r.filter(({isLive:p})=>p),r.map(({maxSeekBackTime:p})=>-p/1e3)),this.params.output.duration$);const o=te(this.player,"playbackTimeUpdated").pipe(r.map(({time:p})=>p!=null?p:0));a(r.combine({availableFrom:this.availableFrom$.pipe(r.filter(r.isNonNullable)),currentTime:o}),({availableFrom:p,currentTime:S})=>this.params.output.liveTime$.next(p+S*1e3)),a(o.pipe(r.filter(()=>this.isLive$.getValue()===!1)),e.position$),a(te(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),a(te(this.player,"playbackEnded"),e.endedEvent$),a(te(this.player,"playbackProgress").pipe(r.map(()=>Rn(this.video.buffered,this.video.currentTime))),e.currentBuffer$),a(te(this.player,"playbackPlaying"),()=>{this.videoState.setState(O.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),a(te(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(O.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),a(te(this.player,"playbackPaused"),()=>{this.videoState.setState(O.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),a(te(this.player,"canPlay"),()=>{var p;((p=this.videoState.getTransition())===null||p===void 0?void 0:p.to)===O.READY&&this.videoState.setState(O.READY)}),a(this.isLive$,e.isLive$),a(ki(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));a(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=Qh(this.player);a(c,this.params.output.httpConnectionType$),a(h,this.params.output.httpConnectionReused$),a(d,this.maxSeekBackTime$),a(u.pipe(r.once()),e.firstBytesEvent$),a(te(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(r.combine({isLive:this.isLive$,isShort:e.duration$.pipe(r.map(p=>p<60))}),({isLive:p,isShort:S})=>{const v=!p&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:v}}})}),a(o.pipe(r.filter(p=>p>this.params.tuning.insufficientBufferRuleMargin),r.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(te(this.player,"manifestLoaded").pipe(r.once()).subscribe(()=>{this.subscription.add(te(this.player,"playbackPlaying").pipe(r.once(),r.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),this.subscription.add(rt(this.video,t.isLooped,i));const{volumeState$:f,looped$:m,playbackRateState$:b}=Fe(this.video);this.subscription.add(Me(this.video,t.volume,f,i)),this.subscription.add(f.subscribe(e.volume$,i)),this.subscription.add(m.subscribe(e.loopedEvent$)),this.subscription.add(qe(this.video,t.playbackRate,b,i))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(O.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(O.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const a=bt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,mt.PLAYBACK_SHIFT);this.player.attachSource(a)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(O.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(O.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(i){}Ue(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Yt=s=>{switch(s){case"mobile":return exports.VideoQuality.Q_144P;case"lowest":return exports.VideoQuality.Q_240P;case"low":return exports.VideoQuality.Q_360P;case"sd":case"medium":return exports.VideoQuality.Q_480P;case"hd":case"high":return exports.VideoQuality.Q_720P;case"fullhd":case"full":return exports.VideoQuality.Q_1080P;case"quadhd":case"quad":return exports.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return exports.VideoQuality.Q_2160P}};const ur=s=>{if(s instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))};var ze=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!ur(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return ur(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function ae(){return r.now()}function Nn(s){return ae()-s}function dr(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=o=>i.test(o);return{resolve:(o,l,d=!1)=>{a(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function $f(s,e,t){const i=(...a)=>{t.apply(null,a),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Si(s,e,t,i){const a=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,m="arraybuffer",b=7e3,p=2e3,S=()=>{if(d)return;r.assertNonNullable(c);const _=Nn(c);let H;if(_<p){H=p-_,setTimeout(S,H);return}p*=2,p>b&&(p=b),o&&o.abort(),o=new a,w()};const v=_=>(n=_,I),g=_=>(h=_,I),A=()=>(m="json",I),E=()=>{if(!d){if(--u>=0){S(),i&&i();return}d=!0,h&&h(),t&&t()}},T=_=>(f=_,I),w=()=>{c=ae(),o=new a,o.open("get",s);let _=0,H,Q=0;const Z=()=>(r.assertNonNullable(c),Math.max(c,Math.max(H||0,Q||0)));if(n&&o.addEventListener("progress",$=>{const D=ae();n.updateChunk&&$.loaded>_&&(n.updateChunk(Z(),$.loaded-_),_=$.loaded,H=D)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(d)return;r.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const D=o.response.byteLength-_;D&&n.updateChunk&&n.updateChunk(Z(),D)}h&&h(),o&&e(o.response)}else E()}),o.addEventListener("error",()=>{E()}),f){const $=()=>{r.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=ae(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=m,o.send(),I},I={withBitrateReporting:v,withParallel:T,withJSONResponse:A,withRetryCount:_=>(u=_,I),withRetryInterval:(_,H)=>(r.isNonNullable(_)&&(p=_),r.isNonNullable(H)&&(b=H),I),withTimeout:_=>(l=_,I),withFinally:g,send:w,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return I}const kf=100,Af=2e3,Pf=500;let wf=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-Pf;if(t-e>Af){let i=0,a=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,a+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;i+=o;const d=n.bytes*o/l;a+=d,n.start=t,n.bytes-=d}}}if(a>0&&i>0){const n=a*8/(i/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>kf&&(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 _f{constructor(e,t,i,a,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=a,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const 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){const i=ae(),a=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=ae()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Si(t,n,()=>a("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ae()}_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(){const e=this._getParallelRequestCount(),t=ae();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const 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(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,a){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,o._retryCB=a,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=i,n._retryCB=a,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}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}}const ri=1e4,ni=3,Rf=300,If=2e3,Nf=6e4,Df=10,Cf=1,Lf=500;class xf{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new wf(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=dr(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=dr(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){const{videoElement:t}=this.params;let i,a,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!a||n.bitrate>a.bitrate)&&(a=n):(!i||i.bitrate>n.bitrate)&&(i=n));return a||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||r.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:a,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{$f(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new _f(ni,ri,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:a}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const E=n&&(!c||c===this.rep);return E||t("Not running!"),E},f=(E,T,w)=>{d&&d.abort(),d=Si(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withTimeout(ri).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ni).withFinally(()=>{d=null}).send()},m=(E,T,w)=>{r.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},b=E=>{const T=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${T}=>${E}`),i.playbackRate=E)},p=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}const w=ae()-1e4;let V=0;for(let R=0;R<this.bufferStates.length;R++){const F=this.bufferStates[R];E=Math.min(E,F.buf),F.ts<w&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${E} drop=${V} jitter=${this.sourceJitter}`);let C=E-Cf;this.sourceJitter>=0?C-=this.sourceJitter/2:this.sourceJitter-=1,C>3?b(1.15):C>1?b(1.1):C>.3?b(1.05):b(1)}},v=E=>{let T;const w=()=>T&&T.start?T.start.length:0,V=$=>T.start[$]/1e3,C=$=>T.dur[$]/1e3,R=$=>T.fragIndex+$,F=($,D)=>({chunkIdx:R($),startTS:V($),dur:C($),discontinuity:D}),I=()=>{let $=0;if(T&&T.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,X=D;this.sourceJitter>1&&(X+=this.sourceJitter-1);let ee=T.dur.length-1;for(;ee>=0&&(X-=T.dur[ee],!(X<=0));--ee);$=Math.min(ee,T.dur.length-1-q),$=Math.max($,0)}return F($,!0)},_=$=>{const D=w();if(!(D<=0)){if(r.isNonNullable($)){for(let q=0;q<D;q++)if(V(q)>$)return F(q)}return I()}},H=$=>{const D=w(),q=$?$.chunkIdx+1:0,X=q-T.fragIndex;if(!(D<=0)){if(!$||X<0||X-D>Df)return t(`Resync: offset=${X} bChunks=${D} chunk=`+JSON.stringify($)),I();if(!(X>=D))return F(q-T.fragIndex,!1)}},Q=($,D,q)=>{u&&u.abort(),u=Si(this.urlResolver.resolve($,!0,this.lowLatency),D,q,()=>this._retryCallback()).withTimeout(ri).withRetryCount(ni).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,D)=>{Q(E,q=>{if(!h())return;T=q;const X=Boolean(T.lowLatency);X!==this.lowLatency&&p(X);let ee=0;for(let oe=0;oe<T.dur.length;++oe)ee+=T.dur[oe];ee>0&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ee/T.dur.length)),a({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,$(_(D))},()=>this._handleNetworkError())},nextChunk:H}},g=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),r.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{const{videoElement:T,logger:w}=this.params;let V=v(e.jidxUrl),C,R,F,I,_=0,H,Q,Z;const $=()=>{H&&(clearTimeout(H),H=void 0);const U=Math.max(Lf,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=_+U,re=ae(),ue=Math.min(1e4,ie-re);_=re;const We=()=>{u||h()&&V.seek(()=>{h()&&(_=ae(),D(),$())})};ue>0?H=window.setTimeout(()=>{this.paused?$():We()},ue):We()},D=()=>{let U;for(;U=V.nextChunk(I);)I=U,ge(U);const ie=V.nextChunk(F);if(ie){if(F&&ie.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?$():(g(),this._initPlayerWith(e));return}oe(ie)}else $()},q=(U,ie)=>{if(!h()||!this.sourceBuffer)return;let re,ue,We;const ye=je=>{window.setTimeout(()=>{h()&&q(U,ie)},je)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),ye(100);else{const je=ae(),Qe=T.currentTime;!this.paused&&T.buffered.length>1&&Q===Qe&&je-Z>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),Q!==Qe&&(Q=Qe,Z=je);const $t=this._getBufferSizeSec();if($t>30)w(`Buffered ${$t} seconds; delaying appendBuffer`),ye(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:je,buf:$t}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch(nt){if(nt.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),We=this.sourceBuffer.buffered.length,We!==0&&(re=this.sourceBuffer.buffered.start(0),ue=Qe,ue-re>4&&this.sourceBuffer.remove(re,ue-3)),ye(1e3);else throw nt}}},X=()=>{R&&C&&(w([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(F)]),q(R,function(){R=null,D()}))},ee=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),oe=U=>{h()&&m(ee(U),(ie,re)=>{if(h()){if(re/=1e3,R=ie,F=U,o=U.startTS,re){const ue=Math.min(10,U.dur/re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ue:ue}X()}},()=>this._handleNetworkError())},ge=U=>{h()&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(U),!1)))},Et=U=>{h()&&(e.cachedHeader=U,q(U,()=>{C=!0,X()}))};n=!0,V.seek(U=>{if(h()){if(_=ae(),!U){$();return}I=U,!r.isNullable(E)||U.startTS>E?oe(U):(F=U,D())}},E),e.cachedHeader?Et(e.cachedHeader):f(e.headerUrl,Et,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),r.isNonNullable(a)&&(a+=.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,r.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return r.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=h=>{if(!this.autoQuality)return;let f,m,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(m=this._getBufferSizeSec(),b=h/this.bitrate,m>10&&b>.8||m>15&&b>.5||m>20&&b>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,m)=>{const b=ae();if(this.chunkRateEstimator.addInterval(f,b,m)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:b-f,speed:S}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&Nn(o)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const m=n.updateChunk(h,f);return m&&u(),m},notifySwitch:h=>{const f=ae();h<l&&(o=f),l=h}}}_fetchManifest(e,t,i){this.manifestRequest=Si(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ri).withRetryCount(ni).withRetryInterval(Rf,If).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;ze(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:a}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&a.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Nf))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var x;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(x||(x={}));const Of=[x.PAUSED,x.PLAYING,x.READY],Bf=[x.PAUSED,x.PLAYING,x.READY];class Mf{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(x.STOPPED),this.representations$=new r.ValueSubject([]),this.textTracksManager=new Pe,this.maxSeekBackTime$=new r.ValueSubject(1/0),this.zeroTime$=new r.ValueSubject(void 0),this.liveOffset=new Zs,this._dashCb=a=>{var n,o,l,d;switch(a.name){case"buffering":{const u=a.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${a.type}`,category:r.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=a.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),m=(o=Yt(h.name))!==null&&o!==void 0?o:at(h.video),b=h.bitrate/1e3,p={...h.video};if(!m)continue;const S={id:f,quality:m,bitrate:b,size:p};c.push({track:S,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===x.MANIFEST_READY&&this.videoState.setState(x.MANIFEST_READY);break}case"qualitySwitch":{const u=a.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),r.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=a;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(a.shiftDuration),this.zeroTime$.next(a.zeroTime);break}}},this.syncPlayback=()=>{var a;const n=this.videoState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.playbackState.getState(),d=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${n}; videoTransition: ${JSON.stringify(o)}; desiredPlaybackState: ${l}; seekState: ${JSON.stringify(u)};`}),l===exports.PlaybackState.STOPPED){n!==x.STOPPED&&(this.videoState.startTransitionTo(x.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(x.STOPPED));return}if(!o){if(Bf.includes(n)){const c=(a=this.params.desiredState.videoTrack.getTransition())===null||a===void 0?void 0:a.to;r.isNonNullable(c)&&this.setVideoTrack(c);const h=this.params.desiredState.autoVideoTrackSwitching.getTransition();h&&this.setAutoQuality(h.to)}if((d==null?void 0:d.to)!==exports.PlaybackState.PAUSED&&u.state===N.Requested&&Of.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case x.STOPPED:this.videoState.startTransitionTo(x.MANIFEST_READY),this.dash.attachSource(bt(this.params.source.url));return;case x.MANIFEST_READY:this.videoState.startTransitionTo(x.READY),this.prepare();break;case x.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(x.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(x.PLAYING);const c=d==null?void 0:d.from;c&&c===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(x.PAUSED)})}return;case x.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(x.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case x.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(x.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(x.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return r.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=a=>{e.output.error$.next({id:"DashLiveProvider",category:r.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}),this.video=Ve(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ne(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.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=Fe(this.video);this.subscription.add(i.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())===null||a===void 0?void 0:a.to)===x.READY&&this.videoState.setState(x.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(x.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===N.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(x.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(r.combine({zeroTime:this.zeroTime$.pipe(r.filter(r.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(rt(this.video,this.params.desiredState.isLooped,t)).add(Me(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(qe(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:a}})=>{const n=a&&Vh(a);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var n;switch(a.to){case x.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case x.MANIFEST_READY:case x.READY:((n=this.params.desiredState.playbackState.getTransition())===null||n===void 0?void 0:n.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case x.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case x.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(a.to)}},t)).add(r.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}createLiveDashPlayer(){const e=new xf({videoElement:this.video,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},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,i,a,n,o;const l=this.representations$.getValue(),d=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(a=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&a!==void 0?a:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&r.isNonNullable(d)?d:(n=Gt(l.map(({track:f})=>f),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))===null||n===void 0?void 0:n.id,h=(o=l.find(({track:f})=>f.id===c))===null||o===void 0?void 0:o.representation;r.assertNonNullable(h,"Representations missing"),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(c),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:a})=>a.id===e))===null||t===void 0?void 0:t.representation;r.assertNonNullable(i,`No such representation ${e}`),this.dash.switchByName(i.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();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&i===x.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(bt(this.params.source.url,o)),a&&this.dash.pause(),this.liveOffset.resetTo(o,a)}}var Dn=s=>{var e,t;const i=s.get("X-Delivery-Type"),a=s.get("X-Reused"),n=i===null?exports.HttpConnectionType.HTTP1:(e=i)!==null&&e!==void 0?e:void 0,o=a===null?void 0:(t={1:!0,0:!1}[a])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},Ze=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const a=s.start(i)*1e3,n=s.end(i)*1e3;a<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Vf=s=>{const e=document.createElement("a");return e.href=s,e.origin},Ff=s=>{const e=document.createElement("a");return e.href=s,e.host};class Cn{constructor(e,t=[],i,a,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=a,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,i,a,n,o,l,d,u;if(r.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.call(this,`Http${(a=this._xhr)===null||a===void 0?void 0:a.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=Ht(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let a;this._failoverIndex>=this._failoverHosts.length?(a=this._url,this._failoverIndex=0):(a=this._url.replace(Ff(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",a,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Ai{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const a=this._sourceBuffer.buffered;let n=0;for(let o=0,l=a.length;o<l;o++)n+=a.end(o)-a.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,a,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const m=p=>{a(Ai._str2ua(p.substr(d))),d=p.length};let b=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(b=vt(b)),this._lastXhr=new Cn(b,e.failoverHosts,p=>{this._lastXhr=void 0,m(p);const S=Date.now()-u;this._params.onBandwidthChange({size:p.length,duration:S,speed:8*p.length/(S/1e3)}),this._onDashCallback("loading",{size:p.length,done:!0}),n==null||n()},p=>{if(p.length-d>l&&m(p),h===0){h=Date.now();return}f=p.length-c;const S=Date.now()-h;f>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:f,duration:S,speed:8*f/(S/1e3)}),f=0,c=p.length,h=Date.now()),this._onDashCallback("loading",{size:p.length,done:!1})},o,(p,S,v)=>this._params.onError(p,S,v))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Ai._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class Uf{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},a=t.exec(e),n=(a==null?void 0:a[1])==="-"?-1:1,o={years:i(a==null?void 0:a[2],n),months:i(a==null?void 0:a[3],n),weeks:i(a==null?void 0:a[4],n),days:i(a==null?void 0:a[5],n),hours:i(a==null?void 0:a[6],n),minutes:i(a==null?void 0:a[7],n),seconds:i(a==null?void 0:a[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=vt(i)),new Cn(i,t,a=>{this.attachManifest(a,t,Vf(i))},void 0,a=>{this._params.onResponseHeaders(a)},(a,n,o)=>this._params.onError(a,n,o))}attachManifest(e,t,i){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,m,b,p,S,v,g,A,E,T,w,V,C,R,F,I,_;const H=u.getElementsByTagName("SegmentBase")[0],Q=H&&o(H,"indexRange").split("-"),Z=H&&H.getElementsByTagName("Initialization")[0],$=Z&&o(Z,"range").split("-");if(!$||!Q){const ge=u.parentElement;if((ge==null?void 0:ge.getAttribute("contentType"))==="text"){const Et=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,U=(i?i+"/":"")+((b=(m=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||m===void 0?void 0:m[0])===null||b===void 0?void 0:b.data),ie=(p=ge.getAttribute("lang"))!==null&&p!==void 0?p:void 0;U&&d.push({id:Et,url:U,language:ie})}return}const D=.1,q=Number((S=u.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),X=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ee;const oe=(g=(v=u.attributes.getNamedItem("frameRate"))===null||v===void 0?void 0:v.value)!==null&&g!==void 0?g:void 0;ee=oe?ea(oe):void 0,l.push({width:Number((A=u.attributes.getNamedItem("width"))===null||A===void 0?void 0:A.value),height:Number((E=u.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:q,baseURL:X,failoverHosts:t,indexFrom:Number(Q[0]),indexTo:Number(Q[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(w=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&w!==void 0?w:void 0,mimeType:(C=(V=u.attributes.getNamedItem("mimeType"))===null||V===void 0?void 0:V.value)!==null&&C!==void 0?C:void 0,fps:ee,bufferSize:D*q/8,bufferLength:D,name:(F=(R=u.attributes.getNamedItem("okQuality"))===null||R===void 0?void 0:R.value)!==null&&F!==void 0?F:void 0,id:(_=(I=u.attributes.getNamedItem("id"))===null||I===void 0?void 0:I.value)!==null&&_!==void 0?_:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,a=>{let n=e.initTo-e.initFrom+1;if(!a.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(a.buffer,0,n);const o=new DataView(a.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const m=u+(o.getUint32(n,!1)&2147483647),b=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:b/l,fromOffset:u,toOffset:m-1}),u=m,d=b}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,a=>{this._params.onResponseHeaders(a),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let a,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const m=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),m)}const c=this._appendVector[String(u.fromTime)];c!==a&&(a=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const m=this._buffer.getByTime(this._video.currentTime);if(!m){this._onDashCallback("buffering");return}h=m.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==m.to&&(n=m.to,window.setTimeout(()=>{try{const b=this._buffer.getNextWithGap(m);b&&(this._video.currentTime=b.from)}catch(b){throw this._params.onError("GapSyncError",`Seek Error ${String(b)}`,b),b}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Ai({mediaSource:i,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||l(),i.removeEventListener("sourceopen",d),i.removeEventListener("webkitsourceopen",d)};i.addEventListener("sourceopen",d,!1),i.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,a=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(i){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=a||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),a=this._findRef(this._video.currentTime);if(!i||!a){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(a.toTime<i.to+n){const o=this._findRef(a.toTime);o&&o.toTime<i.to+n?(this._buffer.smartRemove(a.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(a.fromTime-n,a.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,a.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||r.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let a;for(let n=0;n<i.length;n++){const o=i[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!a||o.fromTime<a.fromTime)&&(a=o)}if(!a){const n=i[i.length-1];if(e>n.toTime)return n}return a}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const a=i[i.length-1];return e.fromTime===a.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),a=this._video.buffered.end(t);if(e>i&&e<a)return Math.round(a*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var B;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(B||(B={}));const jf=[B.PAUSED,B.PLAYING];class Hf{constructor(e){this.videoState=new W(B.STOPPED),this.subscription=new r.Subscription,this.representations$=new r.ValueSubject([]),this.currentRepresentation$=new r.ValueSubject(void 0),this.textTracksManager=new Pe,this.elementSize$=new r.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new r.Subject,responseHeaders$:new r.Subject,manifestReady$:new r.Subject,representationPlay$:new r.Subject,error$:new r.Subject},this.handleManifestReady=t=>{var i,a,n;const o=[];for(const l of t){const d=(a=(i=l.name)!==null&&i!==void 0?i:l.id)!==null&&a!==void 0?a:l.height.toString(10),u=(n=l.name&&Yt(l.name))!==null&&n!==void 0?n:at(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const m={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:m,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(B.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const a=(i=this.representations$.getValue().find(({representation:n})=>n===t))===null||i===void 0?void 0:i.track;a&&(this.params.output.currentVideoTrack$.next(a),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return r.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${a}; seekState: ${JSON.stringify(o)};`}),a===exports.PlaybackState.STOPPED){t!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(B.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!i)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===N.Requested&&jf.includes(t)&&this.seek(o.position,o.forcePrecise),t){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_LOADED),this.prepare();return;case B.MANIFEST_LOADED:this.videoState.startTransitionTo(B.INITIAL_REPRESENTATION_SELECTED);return;case B.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(B.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case B.METADATA_LOADED:this.videoState.startTransitionTo(B.READY),this.dash.updateRefsForCurrentTime();return;case B.READY:a===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed());return;case B.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(B.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case B.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),r.merge(this.videoState.stateChangeStarted$.pipe(r.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=Ve(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ef(this.video),this.dash=new Uf({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,a)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:a,category:r.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"DashProvider",category:r.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},a=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=Fe(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,i));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(n.seeking$.subscribe(()=>{r.isNullable(this.params.desiredState.seekState.getState().state!==N.Applying)&&(this.videoState.getState()===B.PLAYING||this.videoState.getState()===B.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Me(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,t.playbackRate,n.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),o(ki(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===B.READY&&this.videoState.setState(B.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(B.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(B.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},i)).add(this.dashLiteEvents.error$.pipe(r.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:r.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(r.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,r.fromEvent(this.video,"progress")).pipe(r.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),m=this.params.desiredState.videoTrack.getState(),b=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),S=a();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let v;if(!S&&r.isNonNullable(m))v=m;else{const g=Ze(this.video.buffered,this.video.currentTime*1e3),A=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(g/A,1);v=(d=Gt(h.map(({track:T})=>T),{container:p,throughput:b,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:T})=>T===c))===null||l===void 0?void 0:l.track}))===null||d===void 0?void 0:d.id}return r.isNonNullable(v)?(u=h.find(({track:g})=>g.id===v))===null||u===void 0?void 0:u.representation:void 0}),r.filterChanged()).subscribe(this.currentRepresentation$,i)).add(r.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(r.filter(l=>l.to===B.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(r.filter(r.isNonNullable))}).pipe(r.once()).subscribe(()=>this.videoState.setState(B.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(r.filter(r.isNonNullable),r.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?l.height<=d.height:l===d)).subscribe(l=>{const d=Ze(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!a())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(ne(l.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Dn(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(r.once(),r.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(r.filter(r.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return r.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}}var he;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(he||(he={}));var Pi;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Pi||(Pi={}));var fe;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(fe||(fe={}));var j;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(j||(j={}));var gt;(function(s){s.MP4="mp4",s.WEBM="webm"})(gt||(gt={}));var Bs=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const Gf=(s,e={})=>{const i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},Yf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",cr=Yf?Gf:window.requestIdleCallback;var us,ds;let Ln=!1;try{Ln=_n()&&parseInt((ds=(us=navigator.userAgent.match(/Version\/(\d+)/))===null||us===void 0?void 0:us[1])!==null&&ds!==void 0?ds:"",10)<16}catch(s){console.error(s)}class qf{constructor(e){this.bufferFull$=new r.Subject,this.error$=new r.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{const n={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;Ln&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:a}of this.queue)a(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask);try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:r.assertNever(t)}}}var hr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};const xn=new TextDecoder("ascii"),On=s=>{let e=0,t=s.getUint32(e);e+=4;const i=new DataView(s.buffer,s.byteOffset+e,4),a=xn.decode(i);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,s.byteLength)-e,o=new DataView(s.buffer,s.byteOffset+e,n);return{id:a,size:t,contents:o}},zf=s=>xn.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",Wf=(s,e,t)=>{const i=On(s),a=[];let n=0;const o=()=>{const p=i.contents.getUint32(n);return n+=4,p};if((o()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");o();const u=o(),c=o(),h=o(),f=o()&4294967295;let m=c/u*1e3,b=(t?t.to+1:s.byteOffset+s.byteLength)+h;for(let p=0;p<f;p++){const S=o(),v=S>>>31,g=S<<1>>>1,A=o();if(o(),v!==0)throw new Error("Unsupported multilevel sidx");const E=A/u*1e3;a.push({status:j.NONE,time:{from:m,to:m+E},byte:{from:b,to:b+g-1}}),m+=E,b+=g}return a},Qf=s=>{let e=0,t=!1,i=!1;for(;e<=s.byteLength&&!t;){const a=new DataView(s.buffer,s.byteOffset+e);try{const n=On(a);if(i||(i=n.id==="mdat"),e+n.size<=s.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=s.byteLength&&i?new DataView(s.buffer,s.byteOffset,e):null},Jf={validateData:zf,parseInit:()=>null,getIndexRange:()=>{},parseSegments:Wf,parseFeedableSegmentChunk:Qf};var y;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(y||(y={}));var P;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(P||(P={}));const fr={[y.EBML]:{type:P.Master},[y.EBMLVersion]:{type:P.UnsignedInteger},[y.EBMLReadVersion]:{type:P.UnsignedInteger},[y.EBMLMaxIDLength]:{type:P.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:P.UnsignedInteger},[y.DocType]:{type:P.String},[y.DocTypeVersion]:{type:P.UnsignedInteger},[y.DocTypeReadVersion]:{type:P.UnsignedInteger},[y.Void]:{type:P.Binary},[y.Segment]:{type:P.Master},[y.SeekHead]:{type:P.Master},[y.Seek]:{type:P.Master},[y.SeekID]:{type:P.Binary},[y.SeekPosition]:{type:P.UnsignedInteger},[y.Info]:{type:P.Master},[y.TimestampScale]:{type:P.UnsignedInteger},[y.Duration]:{type:P.Float},[y.Tracks]:{type:P.Master},[y.Chapters]:{type:P.Master},[y.Cluster]:{type:P.Master},[y.Timestamp]:{type:P.UnsignedInteger},[y.SilentTracks]:{type:P.Master},[y.SilentTrackNumber]:{type:P.UnsignedInteger},[y.Position]:{type:P.UnsignedInteger},[y.PrevSize]:{type:P.UnsignedInteger},[y.SimpleBlock]:{type:P.Binary},[y.BlockGroup]:{type:P.Master},[y.EncryptedBlock]:{type:P.Binary},[y.Attachments]:{type:P.Master},[y.Tags]:{type:P.Master},[y.Cues]:{type:P.Master},[y.CuePoint]:{type:P.Master},[y.CueTime]:{type:P.UnsignedInteger},[y.CueTrackPositions]:{type:P.Master},[y.CueTrack]:{type:P.UnsignedInteger},[y.CueClusterPosition]:{type:P.UnsignedInteger},[y.CueRelativePosition]:{type:P.UnsignedInteger},[y.CueDuration]:{type:P.UnsignedInteger},[y.CueBlockNumber]:{type:P.UnsignedInteger},[y.CueCodecState]:{type:P.UnsignedInteger},[y.CueReference]:{type:P.Master},[y.CueRefTime]:{type:P.UnsignedInteger}},Bn=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=wi(s,t),a=i in fr,n=a?fr[i].type:P.Binary,o=s.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(s.buffer,s.byteOffset+t+1,l-1),u=o&255>>l,c=wi(d),h=u*2**((l-1)*8)+c,f=t+l;let m;return f+h>s.byteLength?m=new DataView(s.buffer,s.byteOffset+f):m=new DataView(s.buffer,s.byteOffset+f,h),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:m,valueSize:h}},wi=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ne=(s,e)=>{switch(e){case P.SignedInteger:return s.getInt8(0);case P.UnsignedInteger:return wi(s);case P.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case P.String:return new TextDecoder("ascii").decode(s);case P.UTF8:return new TextDecoder("utf-8").decode(s);case P.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case P.Master:return s;case P.Binary:return s;default:r.assertNever(e)}},qt=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),a=Bn(i);if(!e(a))return;a.type===P.Master&&qt(a.value,e),t=a.value.byteOffset-s.byteOffset+a.valueSize}},Kf=s=>{if(s.getUint32(0)!==y.EBML)return!1;let e,t,i;const a=Bn(s);return qt(a.value,({tag:n,type:o,value:l})=>(n===y.EBMLReadVersion?e=Ne(l,o):n===y.DocType?t=Ne(l,o):n===y.DocTypeReadVersion&&(i=Ne(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Mn=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],Xf=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],Zf=s=>{let e,t,i,a,n=!1,o=!1,l=!1,d,u;return qt(s,({tag:c,type:h,value:f,valueSize:m})=>{if(c===y.SeekID){const b=Ne(f,h);u=wi(b)}else c!==y.SeekPosition&&(u=void 0);return c===y.Segment?(e=f.byteOffset,t=f.byteOffset+m):c===y.Info?n=!0:c===y.SeekHead?o=!0:c===y.TimestampScale?i=Ne(f,h):c===y.Duration?a=Ne(f,h):c===y.SeekPosition&&u===y.Cues?d=Ne(f,h):n&&o&&Mn.includes(c)&&(l=!0),!l}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(a,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*1e3),cuesSeekPosition:d}},ep=s=>{if(r.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},tp=(s,e)=>{let t=!1,i=!1;const a=l=>r.isNonNullable(l.time)&&r.isNonNullable(l.position),n=[];let o;return qt(s,({tag:l,type:d,value:u})=>{switch(l){case y.Cues:t=!0;break;case y.CuePoint:o&&a(o)&&n.push(o),o={};break;case y.CueTime:o&&(o.time=Ne(u,d));break;case y.CueTrackPositions:break;case y.CueClusterPosition:o&&(o.position=Ne(u,d));break;default:t&&Mn.includes(l)&&(i=!0)}return!(t&&i)}),o&&a(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:j.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},ip=s=>{let e=0,t=!1;try{qt(s,i=>i.tag===y.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Xf.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},sp={validateData:Kf,parseInit:Zf,getIndexRange:ep,parseSegments:tp,parseFeedableSegmentChunk:ip};class pr{constructor(e,t,i,a,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new r.ValueSubject(!1),this.fullyBuffered$=new r.ValueSubject(!1),this.playingRepresentation$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.gaps=[],this.subscription=new r.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new et,this.destroyAbortController=new et,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=r.abortable(this.destroyAbortController.signal,async function*(u){const c=this.representations.get(u);r.assertNonNullable(c,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new qf(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const p=Math.min(this.bufferLimit,hr(this.sourceBuffer.buffered)*.8);this.bufferLimit=p,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield this.loadInit(c,"high",!0);const h=this.initData.get(c.id),f=this.segments.get(c.id);if(r.assertNonNullable(h,"No init buffer for starting representation"),r.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return;let m=0;for(const b of f)b.time.from-m>0&&this.gaps.push({representation:c.id,from:m,to:b.time.from}),m=b.time.to;r.isNonNullable(c.duration)&&c.duration-m>0&&this.gaps.push({representation:c.id,from:m,to:c.duration}),yield this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=r.abortable(this.destroyAbortController.signal,async function*(u){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return;this.switchingToRepresentationId=u;const c=this.representations.get(u);r.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(r.isNullable(h)?yield this.loadInit(c,"high",!1):h instanceof Promise&&(yield h),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal);const f=this.getCurrentPosition();r.isNonNullable(f)&&this.maintain(f)}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.container=i,i){case gt.MP4:this.containerParser=Jf;break;case gt.WEBM:this.containerParser=sp;break;default:r.assertNever(i)}this.initData=new Map(a.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(a.map(u=>[u.id,u])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new et,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const a=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=Ze(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&c>=a.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&hr(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Ze(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(i,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(l.includes(a))u="high";else{const c=Re(l,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===j.FED&&!l.length&&Ze(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Re(i,-1);d&&d.status===j.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===d))}findSegmentStartTime(e){var t,i,a;const n=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(a=l==null?void 0:l.time.from)!==null&&a!==void 0?a:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const a=e.findIndex(({status:h,time:{from:f,to:m}},b)=>{const p=f<=i&&m>=i,S=f>i||p||b===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&f<=i+v||m<=i+v;return(h===j.NONE||h===j.PARTIALLY_EJECTED&&S&&g&&this.sourceBuffer&&!Bs(this.sourceBuffer.buffered,i))&&S&&g});if(a===-1)return[];if(t!==fe.BYTE_RANGE)return e.slice(a,a+1);const n=e;let o=0,l=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=a;h<n.length&&(o<=u||l<=c);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===j.NONE||f.status===j.PARTIALLY_EJECTED)d.push(f);else break}return d}async loadSegments(e,t,i="auto"){if(!e.length)return;let a,n,o=e;const{type:l}=t.segmentReference;switch(l){case fe.BYTE_RANGE:{a=t.segmentReference.url,n={from:Re(e,0).byte.from,to:Re(e,-1).byte.to};break}case fe.TEMPLATE:{const u=Re(e,0);a=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:r.assertNever(l)}for(const u of o)u.status=j.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await r.abortable(d,async function*(){const u=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(a,{range:n,onProgress:(u,c)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,c,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:i}).then(()=>this.failedDownloads=0,u=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)})}onSegmentDownloadError(e){var t;let i=!1;const a=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(a)&&(i=Ze((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,a)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,a,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},l=h=>{var f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),h.segment.status=j.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const m of this.representations.values())if(m.id!==t)for(const b of(f=this.segments.get(m.id))!==null&&f!==void 0?f:[])b.status===j.FED&&b.time.from===h.segment.time.from&&b.time.to===h.segment.time.to&&(b.status=j.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,m=u===fe.BYTE_RANGE,b=m?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!m||f.byte.from>=i&&f.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const S=m?f.byte.from-i:0,v=m?f.byte.to-i:e.byteLength,g=S<a,A=v<=a;if(f.status===j.DOWNLOADING&&g&&A){f.status=j.DOWNLOADED,this.activeSegments.delete(h);const E=new DataView(e.buffer,e.byteOffset+S,b);this.sourceBufferTaskQueue.append(E,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(h.loadedBytes=Math.min(b,a-S),h.loadedBytes>h.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+S+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===b?E:this.containerParser.parseFeedableSegmentChunk(E);T!=null&&T.byteLength&&(f.status=j.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(w=>{if(n.aborted)o();else if(w)h.fedBytes+=T.byteLength,h.fedBytes===b&&l(h);else{if(h.feedingBytes<b)return;o()}}))}}}abortSegment(e){e.status===j.PARTIALLY_FED||e.status===j.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=j.NONE),e.status=j.PARTIALLY_EJECTED):e.status=j.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[a,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=cr(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const a=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const l=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(l=>{if(!l)return;const{dataView:d,segments:u}=l,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:r.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||r.isNullable(e)||this.sourceBuffer.updating)return!1;let a=0,n=1/0,o=-1/0,l=!1;const d=u=>{var c;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h="size"in u?(c=u.size)!==null&&c!==void 0?c:0:u.byte.to-u.byte.from;a+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status===j.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){a=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status===j.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const m of f)if(m.status===j.NONE&&Math.round(m.time.from)<=Math.round(c)&&Math.round(m.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&i){a=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===j.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let a={representation:e,from:i.time.from,to:i.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&l>=i.time.to){a=void 0;break}l>i.time.from&&l<i.time.to&&(a.from=l),o<i.time.to&&o>i.time.from&&(a.to=o)}}a&&a.to-a.from>=1&&!this.gaps.some(n=>a&&n.from===a.from&&n.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=cr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const a=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:n})}const t=1;for(const i of this.segments.values())for(const a of i){const{status:n}=a;if(n!==j.FED&&n!==j.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),l=Math.ceil(a.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.filter(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u.length===1?a.status=j.PARTIALLY_EJECTED:a.status=j.NONE)}}}var pt;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(pt||(pt={}));class ap{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.abortAllController=new et,this.subscription=new r.Subscription,this.fetchManifest=r.abortable(this.abortAllController.signal,async function*(a){let n=a;this.requestQuic&&(n=vt(n));const o=yield St(n,{signal:this.abortAllController.signal}).catch(xt);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=r.abortable(this.abortAllController.signal,async function*(a,{rangeMethod:n=this.compatibilityMode?pt.HEADER:pt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,m,b;let p=a;const S=new Headers;if(o)switch(n){case pt.HEADER:{S.append("Range",`bytes=${o.from}-${o.to}`);break}case pt.PARAM:{const $=new URL(p,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),p=$.toString();break}default:r.assertNever(n)}this.requestQuic&&(p=vt(p));let v=this.abortAllController.signal;if(u){const $=new et;if(this.subscription.add(r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(u,"abort")).subscribe(()=>{try{$.abort()}catch(D){xt(D)}})),this.abortAllController.signal.aborted||u.aborted)try{$.abort()}catch(D){xt(D)}v=$.signal}const g=r.now(),A=yield St(p,{priority:d,headers:S,signal:v}).catch(xt),E=r.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-g),!A)return null;if(!A.ok||!A.body)return Promise.reject(new Error(`Fetch error ${A.status}: ${A.statusText}`));this.onHeadersReceived(A.headers);const T=parseInt((f=A.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!T){const $=yield A.arrayBuffer();return(m=this.throughputEstimator)===null||m===void 0||m.addRawSpeed($.byteLength,r.now()-E),l==null||l(new DataView($),$.byteLength),$}if(!l&&!c)return A.arrayBuffer();const[w,V]=A.body.tee(),C=w.getReader();c&&((b=this.throughputEstimator)===null||b===void 0||b.trackStream(V));let R=0;const F=new ArrayBuffer(T),I=new Uint8Array(F),_=new DataView(F);let H=!1;const Q=$=>{H=!0,xt($)},Z=r.abortable(v,async function*({done:$,value:D}){R===0&&this.lastRequestFirstBytes$.next(r.now()-g),!v.aborted&&($?l==null||l(_,R):D&&(I.set(D,R),R+=D.byteLength,l==null||l(_,R),yield C==null?void 0:C.read().then(Z,Q)))}.bind(this));return yield C==null?void 0:C.read().then(Z,Q),H?null:F}.bind(this)),this.fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n,o){var l;if(a.type!==fe.BYTE_RANGE)return null;const{from:d,to:u}=a.initRange;let c=d,h=u,f=!1,m,b;a.indexRange&&(m=a.indexRange.from,b=a.indexRange.to,f=u+1===m,f&&(c=Math.min(m,d),h=Math.max(b,u))),c=Math.min(c,0);const p=yield this.fetch(a.url,{range:{from:c,to:h},priority:o,measureThroughput:!1});if(!p)return null;const S=new DataView(p,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const v=n.parseInit(S),g=(l=a.indexRange)!==null&&l!==void 0?l:n.getIndexRange(v);if(!g)throw new ReferenceError("No way to load representation index");let A;if(f)A=new DataView(p,g.from-c,g.to-g.from+1);else{const T=yield this.fetch(a.url,{range:g,priority:o,measureThroughput:!1});if(!T)return null;A=new DataView(T)}const E=n.parseSegments(A,v,g);return{dataView:new DataView(p),segments:E}}.bind(this)),this.fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n){if(a.type!==fe.TEMPLATE)return null;const o=new URL(a.initUrl,a.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{segments:a.segments.map(u=>({...u,status:j.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Dn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;const{type:o}=e;switch(o){case fe.BYTE_RANGE:return(a=await this.fetchByteRangeRepresentation(e,t,i))!==null&&a!==void 0?a:null;case fe.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:r.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const xt=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var rp=it,np=Ri,op=ve,lp=op("match"),up=function(s){var e;return rp(s)&&((e=s[lp])!==void 0?!!e:np(s)=="RegExp")},dp=xi,cp=String,hp=function(s){if(dp(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return cp(s)},fp=st,pp=function(){var s=fp(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e},mp=Oe,bp=Be,Sp=js,vp=pp,mr=RegExp.prototype,gp=function(s){var e=s.flags;return e===void 0&&!("flags"in mr)&&!bp(s,"flags")&&Sp(mr,s)?mp(vp,s):e},ia=xe,yp=Di,Tp=Math.floor,cs=ia("".charAt),Ep=ia("".replace),hs=ia("".slice),$p=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,kp=/\$([$&'`]|\d{1,2})/g,Ap=function(s,e,t,i,a,n){var o=t+s.length,l=i.length,d=kp;return a!==void 0&&(a=yp(a),d=$p),Ep(n,d,function(u,c){var h;switch(cs(c,0)){case"$":return"$";case"&":return s;case"`":return hs(e,0,t);case"'":return hs(e,o);case"<":h=a[hs(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var m=Tp(f/10);return m===0?u:m<=l?i[m-1]===void 0?cs(c,1):i[m-1]+cs(c,1):u}h=i[f-1]}return h===void 0?"":h})},Pp=Li,wp=Oe,sa=xe,br=Vs,_p=me,Rp=Ii,Ip=up,ct=hp,Np=Ni,Dp=gp,Cp=Ap,Lp=ve,xp=Lp("replace"),Op=TypeError,Vn=sa("".indexOf),Bp=sa("".replace),Sr=sa("".slice),Mp=Math.max,vr=function(s,e,t){return t>s.length?-1:e===""?t:Vn(s,e,t)};Pp({target:"String",proto:!0},{replaceAll:function(e,t){var i=br(this),a,n,o,l,d,u,c,h,f,m=0,b=0,p="";if(!Rp(e)){if(a=Ip(e),a&&(n=ct(br(Dp(e))),!~Vn(n,"g")))throw Op("`.replaceAll` does not allow non-global regexes");if(o=Np(e,xp),o)return wp(o,e,i,t);if(a)return Bp(ct(i),e,t)}for(l=ct(i),d=ct(e),u=_p(t),u||(t=ct(t)),c=d.length,h=Mp(1,c),m=vr(l,d,0);m!==-1;)f=u?ct(t(d,m,l)):Cp(d,l,m,[],void 0,t),p+=Sr(l,b,m)+f,b=m+c,m=vr(l,d,m+h);return b<l.length&&(p+=Sr(l,b)),p}});var Vp=In,Fp=Vp("String","replaceAll"),Up=Fp,jp=Up,Hp=jp,Gp=Hp,gr=Gp;const yr=s=>{if(!s.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),a=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],a),hours:e(i==null?void 0:i[6],a),minutes:e(i==null?void 0:i[7],a),seconds:e(i==null?void 0:i[8],a)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},fs=(s,e)=>{let t=s;t=gr(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[a,n]of Object.entries(i)){const o=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=gr(t,o,(l,d)=>r.isNullable(n)?l:r.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Yp=(s,e)=>{var t,i,a,n,o,l,d,u,c,h,f,m,b,p,S,v,g,A,E,T,w,V,C,R,F,I,_,H,Q,Z,$,D,q,X,ee,oe,ge;const U=new DOMParser().parseFromString(s,"application/xml"),ie={video:[],audio:[],text:[]},re=U.children[0],ue=re.getElementsByTagName("Period")[0],We=ue.children;let ye;const je=re.getAttribute("mediaPresentationDuration"),Qe=ue.getAttribute("duration");if(je)ye=yr(je);else if(Qe){const Te=yr(Qe);r.isNonNullable(Te)&&(ye=Te)}let $t=0;const nt=(i=(t=re.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],Yn=nt.includes(Pi.WEBM_AS_IN_FFMPEG)||nt.includes(Pi.WEBM_AS_IN_SPEC)?gt.WEBM:gt.MP4;for(const Te of We){const zt=Te.getAttribute("mimeType"),qn=Te.getAttribute("codecs"),aa=(a=Te.getAttribute("contentType"))!==null&&a!==void 0?a:zt==null?void 0:zt.split("/")[0],zn=(o=(n=Te.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Wn=Te.querySelectorAll("Representation"),Qn=Te.querySelector("SegmentTemplate");if(aa!=="text")for(const se of Wn){const kt=(l=se.getAttribute("mimeType"))!==null&&l!==void 0?l:zt,ra=(u=(d=se.getAttribute("codecs"))!==null&&d!==void 0?d:qn)!==null&&u!==void 0?u:"",Wt=(h=(c=se.getAttribute("contentType"))!==null&&c!==void 0?c:kt==null?void 0:kt.split("/")[0])!==null&&h!==void 0?h:aa,Jn=(m=(f=Te.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&m!==void 0?m:[],Kn=parseInt((b=se.getAttribute("width"))!==null&&b!==void 0?b:"",10),na=parseInt((p=se.getAttribute("height"))!==null&&p!==void 0?p:"",10),oa=parseInt((S=se.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,la=(v=se.getAttribute("frameRate"))!==null&&v!==void 0?v:"",Xn=(g=se.getAttribute("quality"))!==null&&g!==void 0?g:void 0,Zn=la?ea(la):void 0,eo=(A=se.getAttribute("id"))!==null&&A!==void 0?A:($t++).toString(10),to=Wt==="video"?`${na}p`:Wt==="audio"?`${oa}Kbps`:ra,io=`${eo}@${to}`,so=(w=(T=(E=se.querySelector("BaseURL"))===null||E===void 0?void 0:E.textContent)===null||T===void 0?void 0:T.trim())!==null&&w!==void 0?w:"",ua=new URL(so,e).toString(),ao=[...nt,...zn,...Jn];let Mi;const ro=se.querySelector("SegmentBase"),Je=(V=se.querySelector("SegmentTemplate"))!==null&&V!==void 0?V:Qn;if(ro){const At=(R=(C=se.querySelector("SegmentBase Initialization"))===null||C===void 0?void 0:C.getAttribute("range"))!==null&&R!==void 0?R:"",[Pt,Fi]=At.split("-").map(Ke=>parseInt(Ke,10)),wt={from:Pt,to:Fi},_t=(F=se.querySelector("SegmentBase"))===null||F===void 0?void 0:F.getAttribute("indexRange"),[Ui,Qt]=_t?_t.split("-").map(Ke=>parseInt(Ke,10)):[],Rt=_t?{from:Ui,to:Qt}:void 0;Mi={type:fe.BYTE_RANGE,url:ua,initRange:wt,indexRange:Rt}}else if(Je){const At={representationId:(I=se.getAttribute("id"))!==null&&I!==void 0?I:void 0,bandwidth:(_=se.getAttribute("bandwidth"))!==null&&_!==void 0?_:void 0},Pt=parseInt((H=Je.getAttribute("timescale"))!==null&&H!==void 0?H:"",10),Fi=(Q=Je.getAttribute("initialization"))!==null&&Q!==void 0?Q:"",wt=Je.getAttribute("media"),_t=($=parseInt((Z=Je.getAttribute("startNumber"))!==null&&Z!==void 0?Z:"",10))!==null&&$!==void 0?$:1,Ui=fs(Fi,At);if(!wt)throw new ReferenceError("No media attribute in SegmentTemplate");const Qt=(D=Je.querySelectorAll("SegmentTimeline S"))!==null&&D!==void 0?D:[],Rt=[];if(Qt.length){let Ke=_t,Xe=0;for(const It of Qt){const ot=parseInt((q=It.getAttribute("d"))!==null&&q!==void 0?q:"",10)*1e3,Nt=parseInt((X=It.getAttribute("r"))!==null&&X!==void 0?X:"",10)||0,Dt=(oe=parseInt((ee=It.getAttribute("t"))!==null&&ee!==void 0?ee:"",10))!==null&&oe!==void 0?oe:void 0;for(let da=0;da<Nt+1;da++){const no=fs(wt,{...At,segmentNumber:Ke.toString(10),segmentTime:Dt.toString(10)}),oo=Dt?Dt/Pt:Xe;Xe+=ot/Pt;const lo=Xe;Ke++,Rt.push({time:{from:oo,to:lo},url:no})}}}else if(r.isNonNullable(ye)){const Xe=parseInt((ge=Je.getAttribute("duration"))!==null&&ge!==void 0?ge:"",10)/Pt*1e3,It=Math.ceil(ye/Xe);let ot=0;for(let Nt=1;Nt<It;Nt++){const Dt=fs(wt,{...At,segmentNumber:Nt.toString(10),segmentTime:ot.toString(10)});Rt.push({time:{from:ot,to:ot+Xe},url:Dt}),ot+=Xe}}Mi={type:fe.TEMPLATE,baseUrl:ua,initUrl:Ui,segments:Rt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Wt||!kt)continue;const Vi={video:he.VIDEO,audio:he.AUDIO,text:he.TEXT}[Wt];Vi&&ie[Vi].push({id:io,kind:Vi,segmentReference:Mi,profiles:ao,duration:ye,bitrate:oa,mime:kt,codecs:ra,width:Kn,height:na,fps:Zn,quality:Xn})}}return{duration:ye,container:Yn,representations:ie}},qp=["timeupdate","progress","play","seeked","stalled","waiting"];var ce;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(ce||(ce={}));let zp=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new r.Subscription,this.state$=new W(ce.NONE),this.currentVideoRepresentation$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.forceEnded$=new r.Subject,this.gapWatchdogStarted=!1,this.destroyController=new et,this.initManifest=r.abortable(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(ce.MANIFEST_READY);const a=yield this.fetcher.fetchManifest(i).catch(l=>this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l}));if(!a)return;let n;try{n=Yp(a!=null?a:"",i)}catch(l){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return;const o=({mime:l,codecs:d})=>{var u,c,h;return Boolean(((u=t.canPlayType)===null||u===void 0?void 0:u.call(t,l))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${l}; codecs="${d}"`)))};this.manifest={...n,representations:Ht(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))},this.manifest.representations.video.length?this.state$.setState(ce.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this)),this.initRepresentations=r.abortable(this.destroyController.signal,async function*(t,i){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.state$.startTransitionTo(ce.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new pr(he.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,a),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(i)&&(this.audioBufferManager=new pr(he.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,a),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const n=r.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=r.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.subscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:n,someBufferEnded:o}).pipe(r.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(r.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)})),r.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&r.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(ce.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const a=this.element.currentTime*1e3;this.videoBufferManager.maintain(a),(t=this.audioBufferManager)===null||t===void 0||t.maintain(a),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),n=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ap({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){r.assertNonNullable(this.element),this.state$.setState(ce.RUNNING),this.subscription.add(r.merge(...qp.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Bs(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[he.VIDEO]:this.videoBufferManager,[he.AUDIO]:this.audioBufferManager,[he.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,a,n,o,l;r.assertNonNullable(this.element),r.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(n=(a=this.audioBufferManager)===null||a===void 0?void 0:a.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Bs(this.element.buffered,d)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(d),(l=this.audioBufferManager)===null||l===void 0||l.maintain(d),this.element.currentTime=d/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(ce.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const i of this.bufferManagers)for(const a of i.gaps)i.playingRepresentation$.getValue()===a.representation&&a.from<=e&&a.to>e&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?t.push(1/0):t.push(a.to));if(t.length){const i=Math.max(...t);i===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=i/1e3}}};var J;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(J||(J={}));const Wp=({id:s,width:e,height:t,bitrate:i,fps:a,quality:n})=>{var o;const l=(o=n?Yt(n):void 0)!==null&&o!==void 0?o:at({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:a}},Qp=({id:s,bitrate:e})=>({id:s,bitrate:e}),Jp=(s,e,t)=>{var i;const a=e.indexOf(t);return(i=Re(s,Math.round(s.length*a/e.length)))!==null&&i!==void 0?i:Re(s,-1)};class Kp{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(J.STOPPED),this.elementSize$=new r.ValueSubject(void 0),this.textTracksManager=new Pe,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new yf,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===N.Requested&&(a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&t!==J.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),i===exports.PlaybackState.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(t){case J.STOPPED:this.videoState.startTransitionTo(J.READY),this.prepare();return;case J.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case J.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}}},this.params=e,this.video=Ve(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new zp({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=Fe(this.video),a=u=>{e.error$.next({id:"DashVKProvider",category:r.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,c)=>this.subscription.add(u.subscribe(c,a));n(i.timeUpdate$,e.position$),n(i.durationChange$,e.duration$),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.isAudioAvailable$,e.isAudioAvailable$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once(),r.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(rt(this.video,t.isLooped,a)),this.subscription.add(Me(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,a)),n(ki(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},a)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===ce.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const h=this.player.getRepresentations();r.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((p,S)=>S.bitrate-p.bitrate),m=Array.from(h.video).sort((p,S)=>S.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of f){const S=Qp(p);S&&this.audioTracks.push({track:S,representation:p})}for(const p of m){const S=Wp(p);if(S){this.videoTracks.push({track:S,representation:p});const v=!this.params.tuning.isAudioDisabled&&Jp(f,m,p);v&&this.audioRepresentations.set(p.id,v)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:p})=>p)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:p})=>p)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const b=this.selectVideoRepresentation();r.assertNonNullable(b),this.player.initRepresentations(b.id,(c=this.audioRepresentations.get(b.id))===null||c===void 0?void 0:c.id)}else u===ce.REPRESENTATIOS_READY&&(this.videoState.setState(J.READY),this.player.initBuffer())},a));const o=u=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,r.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==ce.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(he.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(he.AUDIO,f.id).catch(o)}},a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(u=>{var c;return u&&((c=this.videoTracks.find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,a)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(r.map(({to:u})=>u===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(r.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var e,t,i,a,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks.find(({track:{id:v}})=>v===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=Ze(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=Math.max(u&&!l&&(i=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&i!==void 0?i:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),p=Gt(this.videoTracks.map(({track:v})=>v),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=l?p!=null?p:u:u!=null?u:p;return S&&((o=this.videoTracks.find(({track:v})=>v===S))===null||o===void 0?void 0:o.representation)}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}}const Xp=5e3,we={};var M;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(M||(M={}));const oi=(s,e)=>new r.Observable(t=>{const i=(a,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class Zp{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(M.INITIALIZING),this.textTracksManager=new Pe,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==M.INITIALIZING)switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===N.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case M.STOPPED:break;case M.READY:case M.PLAYING:case M.PAUSED:this.stop();break;default:r.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case M.STOPPED:this.prepare();break;case M.READY:case M.PLAYING:case M.PAUSED:break;default:r.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case M.PLAYING:break;case M.STOPPED:this.prepare();break;case M.READY:case M.PAUSED:this.playIfAllowed();break;default:r.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case M.PAUSED:break;case M.STOPPED:this.prepare();break;case M.READY:this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case M.PLAYING:this.pause();break;default:r.assertNever(t)}break;default:r.assertNever(i)}},this.video=Ve(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}loadHlsJs(){let e=!1;const t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:r.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),Xp);import("hls.js").then(a=>{e||(we.Hls=a.default,we.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(we.Hls,"hls.js not loaded"),this.hls=new we.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){r.assertNonNullable(we.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:r.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=Fe(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,i));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadStart$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),n(a.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(rt(this.video,e.isLooped,i)),this.subscription.add(Me(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(oi(this.hls,we.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:r.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)===null||c===void 0?void 0:c.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===M.READY&&this.videoState.setState(M.READY),this.videoState.getState()===M.PLAYING&&this.playIfAllowed()},i)),n(oi(this.hls,we.Events.MANIFEST_PARSED).pipe(r.map(({levels:u})=>u.reduce((c,h)=>{var f,m;const b=h.name||h.height.toString(10),{width:p,height:S}=h,v=(m=Yt((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&m!==void 0?m:at({width:p,height:S});if(!v)return c;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,A={id:b.toString(),quality:v,bitrate:h.bitrate/1e3,size:{width:p,height:S},fps:g};return this.trackLevels.set(b,{track:A,level:h}),c.push(A),c},[]))),t.availableVideoTracks$),n(oi(this.hls,we.Events.LEVEL_LOADING).pipe(r.map(({url:u})=>ne(u))),t.hostname$),this.subscription.add(ke(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=oi(this.hls,we.Events.LEVEL_SWITCHED).pipe(r.map(({level:u})=>o(this.hls.levels[u])));l.pipe(r.filter(r.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(ke(e.videoTrack,()=>{var u;return(u=o(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var c;if(r.isNullable(u))return;const h=(c=this.trackLevels.get(u))===null||c===void 0?void 0:c.level;if(!h)return;const f=this.hls.levels.indexOf(h),m=this.hls.currentLevel,b=this.hls.levels[m];!b||h.bitrate>b.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(r.map(u=>u==null?void 0:u.id)),onError:i})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=r.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(M.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(M.PLAYING),await ze(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(M.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(M.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Tr="X-Playback-Duration";var Er=async s=>{const e=await St(s,{method:"HEAD"});return e.headers.has(Tr)?parseInt(e.headers.get(Tr),10):void 0};const em=s=>{let e=null;if(s.QUALITY&&(e=Yt(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(a=>parseInt(a,10));e=at({width:t,height:i})}return e!=null?e:null},Fn=async(s,e=s)=>{var t;const n=(await(await St(s)).text()).split(`
8
+ `),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=Ht(u[1].split(",").map(v=>v.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=em(c);let m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const b=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let p;if(c.RESOLUTION){const[v,g]=c.RESOLUTION.split("x").map(A=>parseInt(A,10));v&&g&&(p={width:v,height:g})}const S=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:S,bandwidth:m,size:p,fps:b})}return o};var G;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(G||(G={}));class tm{constructor(e){var t;this.subscription=new r.Subscription,this.videoState=new W(G.STOPPED),this.textTracksManager=new Pe,this.manifests$=new r.ValueSubject([]),this.liveOffset=new Zs,this.manifestStartTime$=new r.ValueSubject(void 0),this.syncPlayback=()=>{const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===exports.PlaybackState.STOPPED){a!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(G.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(a===G.STOPPED){this.videoState.startTransitionTo(G.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(G.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===N.Requested){this.videoState.startTransitionTo(G.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){case G.READY:n===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(G.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed());return;case G.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(G.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case G.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(G.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case G.CHANGING_MANIFEST:break;default:return r.assertNever(a)}},this.params=e,this.video=Ve(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),Fn(bt(this.params.source.url),this.params.source.url).then(a=>{this.manifests$.next([i,...a])},a=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:a})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.maxSeekBackTime$=new r.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:a}=this.params.desiredState,n=i.getState(),o=a.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:a.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&a.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsLiveProvider",category:r.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},a=Fe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(a.ended$,e.endedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Me(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===G.READY&&this.videoState.setState(G.READY),this.videoState.getState()===G.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(l=>-l/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&r.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===G.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===N.Requested&&this.seek(l.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},i)),this.subscription.add(r.combine({startTime:this.manifestStartTime$.pipe(r.filter(r.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),i)),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=bt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Er(t).then(i=>{var a;if(!r.isNullable(i))this.maxSeekBackTime$.next(i);else{const n=(a=this.params.source.maxSeekBackTime)!==null&&a!==void 0?a:this.maxSeekBackTime$.getValue();if(r.isNullable(n)||!isFinite(n))try{St(t).then(o=>o.text()).then(o=>{var l;const d=(l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||l===void 0?void 0:l[1];if(d){const u=new URL(d,t).toString();Er(u).then(c=>{r.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(G.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var z;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(z||(z={}));class im{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(z.STOPPED),this.textTracksManager=new Pe,this.manifests$=new r.ValueSubject([]),this.syncPlayback=()=>{const i=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===exports.PlaybackState.STOPPED){i!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(z.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(i===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(z.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===N.Requested&&this.seek(u.position),i){case z.READY:a===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case z.CHANGING_MANIFEST:break;default:return r.assertNever(i)}},this.params=e,this.video=Ve(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),Fn(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:a}=this.params.desiredState,n=i.getState(),o=a.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:a.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&a.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsProvider",category:r.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},a=Fe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Me(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&r.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===N.Requested&&this.seek(l.position)},i))),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}prepare(){const e=this.selectManifest();r.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var K;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));class sm{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(K.STOPPED),this.trackUrls={},this.textTracksManager=new Pe,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(K.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(t===K.STOPPED){this.videoState.startTransitionTo(K.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:d*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&l.state===N.Requested&&this.seek(l.position),t){case K.READY:i===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(K.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case K.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.params=e,this.video=Ve(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,i],a)=>{const n=a.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"MpegProvider",category:r.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},a=Fe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Me(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===K.READY&&this.videoState.setState(K.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&r.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ue(this.video)}prepare(){var e,t;const i=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState();r.assertNonNullable(i,"MpegProvider: track is not selected");let{url:a}=this.trackUrls[i];r.assertNonNullable(a,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(a=vt(a)),this.video.setAttribute("src",a),this.video.load(),this.params.output.hostname$.next(ne(a))}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const $r=["stun:videostun.mycdn.me:80"],am=1e3,rm=3,ps=()=>null;class nm{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=ps,this.externalStopCallback=ps,this.externalErrorCallback=ps,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:$r}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:r.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),am)}normalizeOptions(e={}){const t={stunServerList:$r,maxRetryNumber:rm,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));class om{constructor(e){this.videoState=new W(Y.STOPPED),this.maxSeekBackTime$=new r.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Y.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case Y.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ve(e.container),this.liveStreamClient=new nm(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ue(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:r.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const a=Fe(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,i));n(a.timeUpdate$,e.liveTime$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(a.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===Y.READY&&this.videoState.setState(Y.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED)},i)).add(a.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING)},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Me(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case Y.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case Y.READY:break;case Y.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case Y.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(o.to)}},i)).add(r.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Y.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:r.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class kr{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return Boolean(this.current.done)}}var lm=()=>{var s,e;const t=window.navigator;return t.userAgentData?((e=(s=t.userAgentData)===null||s===void 0?void 0:s.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},ms,bs,Ss,vs,gs,ys,li,Ts,ui,Es,di,$s,ci,ks,hi,As;const Un=lm(),He=document.createElement("video"),_e={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((bs=(ms=window.SourceBuffer)===null||ms===void 0?void 0:ms.prototype)===null||bs===void 0?void 0:bs.appendBuffer)),hls:Boolean(((Ss=He.canPlayType)===null||Ss===void 0?void 0:Ss.call(He,"application/x-mpegurl"))||((vs=He.canPlayType)===null||vs===void 0?void 0:vs.call(He,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},de={mp4:Boolean((gs=He.canPlayType)===null||gs===void 0?void 0:gs.call(He,"video/mp4")),webm:Boolean((ys=He.canPlayType)===null||ys===void 0?void 0:ys.call(He,"video/webm")),cmaf:!0},Ge={h264:Boolean((Ts=(li=window.MediaSource)===null||li===void 0?void 0:li.isTypeSupported)===null||Ts===void 0?void 0:Ts.call(li,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((Es=(ui=window.MediaSource)===null||ui===void 0?void 0:ui.isTypeSupported)===null||Es===void 0?void 0:Es.call(ui,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(($s=(di=window.MediaSource)===null||di===void 0?void 0:di.isTypeSupported)===null||$s===void 0?void 0:$s.call(di,'video/webm; codecs="vp9"')),aac:Boolean((ks=(ci=window.MediaSource)===null||ci===void 0?void 0:ci.isTypeSupported)===null||ks===void 0?void 0:ks.call(ci,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((As=(hi=window.MediaSource)===null||hi===void 0?void 0:hi.isTypeSupported)===null||As===void 0?void 0:As.call(hi,'audio/webm; codecs="opus"'))},ht=(Ge.h264||Ge.h265)&&Ge.aac,Bi=_e.hls&&de.mp4,um=Boolean(window.WebSocket),dm=()=>Object.keys(Ge).filter(s=>Ge[s]),cm=(s,e=!1)=>s.filter(t=>{switch(t){case exports.VideoFormat.DASH:return _e.mse&&de.mp4&&ht;case exports.VideoFormat.DASH_SEP:return _e.mse&&de.mp4&&ht;case exports.VideoFormat.DASH_WEBM:return _e.mse&&de.webm&&Ge.vp9&&Ge.opus;case exports.VideoFormat.DASH_LIVE:return _e.mse&&de.mp4&&ht;case exports.VideoFormat.DASH_LIVE_CMAF:return _e.mse&&de.mp4&&ht&&de.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return _e.mse&&de.mp4&&ht;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return Bi||e&&_e.mse&&de.mp4&&ht;case exports.VideoFormat.MPEG:return de.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return _e.webrtc&&um&&Ge.h264&&(de.mp4||de.webm);default:return r.assertNever(t)}}),hm=()=>Un?[exports.VideoFormat.MPEG,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:Bi?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],fm=()=>Un?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:Bi?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],Ar=s=>s?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var pm=s=>new r.Observable(e=>{const t=new r.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(r.map(({from:u,to:c})=>`${u}-${c}`)),a=s.desiredPlaybackState$.stateChangeEnded$,n=s.providerChanged$,o=new r.Subject;let l=0,d="unknown";return t.add(i.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),s.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(l),d="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),s.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const Pr={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},mm={cacheDuration:12e4},bm={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Sm={maxPausedTime:3e4},wr={maxPausedTime:3e4};class vm{constructor(e){this.current$=new r.ValueSubject({type:void 0}),this.providerError$=new r.Subject,this.noAvailableProvidersError$=new r.Subject,this.providerOutput={position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),volume$:new r.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new r.ValueSubject(void 0),availableVideoTracks$:new r.ValueSubject([]),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new r.ValueSubject(!1),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$:new r.Subject,willSeekEvent$:new r.Subject,seekedEvent$:new r.Subject,loopedEvent$:new r.Subject,endedEvent$:new r.Subject,firstBytesEvent$:new r.Subject,firstFrameEvent$:new r.Subject,canplay$:new r.Subject,isLive$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),element$:new r.ValueSubject(void 0)},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=cm([...fm(),...hm()],this.params.tuning.useHlsJs).filter(o=>r.isNonNullable(e.sources[o])),{formatsToAvoid:i}=this.params.tuning,a=i.length?[...t.filter(o=>!i.includes(o)),...t.filter(o=>i.includes(o))]:t;this.screenFormatsIterator=new kr(a);const n=[...Ar(!0),...Ar(!1)];this.chromecastFormatsIterator=new kr(n.filter(o=>r.isNonNullable(e.sources[o])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(r.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:r.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;r.assertNonNullable(e,"No current provider"),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!==N.None;this.params.desiredState.seekState.setState({state:N.Requested,position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case le.SCREEN:return this.createScreenProvider(t);case le.CHROMECAST:return this.createChromecastProvider(t);default:return r.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Hf({...o,source:l,config:mm})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),this.params.tuning.useDashJs?new lr({...o,source:l,format:e,config:wr}):new Kp({...o,source:l})}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new lr({...o,source:l,format:e,config:wr})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),Bi||!this.params.tuning.useHlsJs?new im({...o,source:l}):new Zp({...o,source:l})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new tm({...o,source:l,config:Sm})}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new sm({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Mf({...o,source:l,config:bm})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new om({container:i,source:l,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:a,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return r.assertNonNullable(l),new Gh({connection:l,meta:n,container:i,source:t,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?le.CHROMECAST:le.SCREEN}chooseFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case le.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.next();case le.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case le.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case le.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return r.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=a=>{const n=new URL(a);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Ht(Object.entries(e).map(([a,n])=>[a,i(n)]))}initProviderErrorHandling(){const e=new r.Subscription;let t=!1,i=0;return e.add(r.merge(this.providerOutput.error$,pm({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Pr.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(r.filter(({type:a})=>a!==void 0))}).pipe(r.map(a=>({id:`ProviderHangup:${a}`,category:r.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(r.filter(({to:n})=>n===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{if(this.current$.getValue().destination===le.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=a.category===r.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<Pr.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(i++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var pe;(function(s){s[s.LOCAL_STORAGE=0]="LOCAL_STORAGE",s[s.SESSION_STORAGE=1]="SESSION_STORAGE",s[s.RUNTIME=2]="RUNTIME"})(pe||(pe={}));const jn=new Map;let tt=pe.RUNTIME;const Ps=`vk-videoplayer-dummy-key-${Math.random()}`,gm=()=>{try{localStorage.setItem(Ps,"test"),localStorage.removeItem(Ps),tt=pe.LOCAL_STORAGE}catch(s){if(s instanceof DOMException||s instanceof TypeError)try{sessionStorage.getItem(Ps),tt=pe.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)tt=pe.RUNTIME;else throw e}else throw s}};gm();const ym=s=>{var e,t;switch(tt){case pe.LOCAL_STORAGE:return(e=localStorage.getItem(s))!==null&&e!==void 0?e:void 0;case pe.SESSION_STORAGE:return(t=sessionStorage.getItem(s))!==null&&t!==void 0?t:void 0;case pe.RUNTIME:return jn.get(s);default:r.assertNever(tt)}},_r=(s,e)=>{switch(tt){case pe.LOCAL_STORAGE:try{localStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case pe.SESSION_STORAGE:try{sessionStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case pe.RUNTIME:return void jn.set(s,e);default:r.assertNever(tt)}},Ms=(s,e,t)=>t*e+(1-t)*s,Hn=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Tm=(s,e,t,i)=>{let a=0,n=t;const o=Hn(s,e),l=e<i?e:i;for(let d=0;d<l;d++)s[n]>o?a++:a--,n=(s.length+n-1)%s.length;return Math.abs(a)===l};class Gn{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new r.ValueSubject(e.initial),this.debounced$=new r.ValueSubject(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new $e(`raw_${i}`),this.smoothedSeries$=new $e(`smoothed_${i}`),this.reportedSeries$=new $e(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=(this.pastMeasures[l]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const a=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(r.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Em extends Gn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ms(this.slow,e,this.params.emaAlphaSlow),this.fast=Ms(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class $m extends Gn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Hn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ms(this.emaSmoothed,e,this.params.emaAlpha);const i=Tm(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Rr{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Em({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new $m({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const km=5e3,Ir="one_video_throughput",Nr="one_video_rtt",Ce=window.navigator.connection,Dr=()=>{const s=Ce==null?void 0:Ce.downlink;if(r.isNonNullable(s)&&s!==10)return s*1e3},Cr=()=>{const s=Ce==null?void 0:Ce.rtt;if(r.isNonNullable(s)&&s!==3e3)return s},Lr=(s,e,t)=>{const i=t*8,a=i/s;return i/(a+e)};class Mt{constructor(e){var t,i;this.subscription=new r.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=Mt.load(Ir)||(e.useBrowserEstimation?Dr():void 0)||km,n=(i=(t=Mt.load(Nr))!==null&&t!==void 0?t:e.useBrowserEstimation?Cr():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new r.ValueSubject(a),this.rtt$=new r.ValueSubject(n),this.rttAdjustedThroughput$=new r.ValueSubject(Lr(a,n,e.rttPenaltyRequestSize)),this.throughput=Rr.getSmoothedValue(a,-1,e),this.rtt=Rr.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Dr();d&&this.throughput.next(d);const u=Cr();r.isNonNullable(u)&&this.rtt.next(u)};Ce&&"onchange"in Ce&&this.subscription.add(r.fromEvent(Ce,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{_r(Ir,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{_r(Nr,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(r.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(r.map(({throughput:o,rtt:l})=>Lr(o,l,e.rttPenaltyRequestSize)),r.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=r.now();const a=new r.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(r.fromEvent(e,"progress").pipe(r.once()).subscribe(n=>{t=n.loaded,i=r.now()}));break;case 1:case 0:a.add(r.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=r.now()}));break}a.add(r.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=r.now(),d=o-t,u=l-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const a=r.now();let n=0,o=r.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=async({done:u,value:c})=>{u?(this.addRawSpeed(i,r.now()-a,1),this.concurrentDownloads.delete(e)):c&&(i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&r.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,r.now()-o,this.concurrentDownloads.size),n=0,o=r.now()),await(t==null?void 0:t.read().then(d,l)))};this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,i=1){if(Mt.sanityCheck(e,t)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=ym(e);if(r.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const xr={throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},Am=s=>{const e={};for(const t of Object.keys(xr)){const i=xr[t],a=s[t];Array.isArray(i)&&Array.isArray(a)?e[t]=a:typeof i=="object"&&typeof a=="object"?e[t]={...i,...a}:e[t]=a!=null?a:i}return e};var Pm=({seekState:s,position$:e})=>r.merge(s.stateChangeEnded$.pipe(r.map(({to:t})=>{var i;return t.state===N.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>s.getState().state===N.None))),wm=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return r.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};const Or=({playbackState:s,seekState:e,playbackAbort$:t,looped$:i,position$:a})=>new r.Observable(n=>{let o;const l=s.transitionEnded$.pipe(r.filter(m=>(m.from===exports.PlaybackState.PAUSED||m.from===exports.PlaybackState.STOPPED)&&m.to===exports.PlaybackState.PLAYING)),d=s.stateChangeEnded$.pipe(r.filter(m=>m.from===exports.PlaybackState.PLAYING&&m.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(r.filter(({to:m})=>{var b,p;return m.state===N.Requested&&((p=(b=s.getTransition())===null||b===void 0?void 0:b.from)!==null&&p!==void 0?p:s.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(r.filter(({from:m,to:b})=>{var p,S;return m.state===N.Applying&&b.state===N.None&&((S=(p=s.getTransition())===null||p===void 0?void 0:p.from)!==null&&S!==void 0?S:s.getState())===exports.PlaybackState.PLAYING})),h=r.merge(l,c).pipe(r.map(()=>a.getValue()),r.filter(r.isNonNullable)),f=r.merge(r.merge(d,u,t),i).pipe(r.map(()=>a.getValue()),r.filter(r.isNonNullable));return new r.Subscription().add(h.subscribe(m=>{o=m})).add(f.subscribe(m=>{if(r.isNullable(o)||o===m)return;const b={from:o,to:m};o=void 0,n.next(b)}))});class _m{constructor(e={}){if(this.subscription=new r.Subscription,this.logger=new r.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new W(exports.PlaybackState.STOPPED),seekState:new W({state:N.None}),volume:new W({volume:1,muted:!1}),videoTrack:new W(void 0),autoVideoTrackSwitching:new W(!0),autoVideoTrackLimits:new W({}),isLooped:new W(!1),playbackRate:new W(1),externalTextTracks:new W([]),currentTextTrack:new W(void 0),textTrackCuesSettings:new W({})},this.info={playbackState$:new r.ValueSubject(exports.PlaybackState.STOPPED),position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),muted$:new r.ValueSubject(!1),volume$:new r.ValueSubject(1),availableQualities$:new r.ValueSubject([]),availableQualitiesFps$:new r.ValueSubject({}),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),currentQuality$:new r.ValueSubject(void 0),isAutoQualityEnabled$:new r.ValueSubject(!0),autoQualityLimitingAvailable$:new r.ValueSubject(!1),autoQualityLimits$:new r.ValueSubject({}),currentPlaybackRate$:new r.ValueSubject(1),currentBuffer$:new r.ValueSubject({start:0,end:0}),isBuffering$:new r.ValueSubject(!0),isStalled$:new r.ValueSubject(!1),isEnded$:new r.ValueSubject(!1),isLooped$:new r.ValueSubject(!1),isLive$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),currentFormat$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),throughputEstimation$:new r.ValueSubject(void 0),rttEstimation$:new r.ValueSubject(void 0),videoBitrate$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0)},this.events={inited$:new r.Subject,started$:new r.Subject,willPause$:new r.Subject,willResume$:new r.Subject,willDestruct$:new r.Subject,watchCoverageRecord$:new r.Subject,watchCoverageLive$:new r.Subject,managedError$:new r.Subject,fatalError$:new r.Subject,ended$:new r.Subject,looped$:new r.Subject,seeked$:new r.Subject,willSeek$:new r.Subject,firstBytes$:new r.Subject,firstFrame$:new r.Subject,canplay$:new r.Subject,log$:new r.Subject},this.experimental={element$:new r.ValueSubject(void 0),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:Sf},this.initLogs(),this.tuning=Am(e),this.chromecastInitializer=new yo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Mt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,a)=>{const n=Reflect.get(t,i,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,m)=>{const b=typeof m;return["number","string","boolean"].includes(b)?m:m===null?null:`<${b}>`})),u=`Player.${String(i)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:r.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,i,a;return this.config=e,this.domContainer=wm(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new vm({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(a=e.failoverHosts)!==null&&a!==void 0?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:N.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){r.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(a=>a.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;r.assertNonNullable(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(i=>i.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){r.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(r.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===N.None?void 0:t.position;return r.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(r.filter(({from:e})=>e===exports.PlaybackState.STOPPED),r.once()).subscribe(()=>{this.initedAt=r.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(()=>!this.isPlaybackStarted),r.filter(e=>e.to===exports.PlaybackState.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const d=this.desiredState.seekState.getState();d.state===N.Requested?this.desiredState.seekState.setState({...d,state:N.Applying}):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===N.Applying&&(this.desiredState.seekState.setState({state:N.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(d=>d.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(d=>d.map(({quality:u})=>u).sort((u,c)=>Ei(u)?1:Ei(c)?-1:bi(c,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(d=>{const u={};for(const c of d)c.fps&&(u[c.quality]=c.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{this.info.currentQuality$.next(d==null?void 0:d.quality),this.info.videoBitrate$.next(d==null?void 0:d.bitrate)})).add(e.providerOutput.hostname$.pipe(r.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(r.map(d=>d?{start:d.from,end:d.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(r.map(d=>d.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(d=>d.volume),r.filterChanged()).subscribe(this.info.volume$)).add(Pm({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(r.merge(e.providerOutput.endedEvent$.pipe(r.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(r.mapTo(!1))).pipe(r.filterChanged()).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.noAvailableProvidersError$.pipe(r.map(d=>({id:"NoProviders",category:r.ErrorCategory.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new r.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new r.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(({to:d})=>d===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>i.next(!1)));let a=0;const n=r.merge(e.providerOutput.isBuffering$,t,i).pipe(r.map(()=>{const d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return d&&!u}),r.filterChanged());this.subscription.add(n.subscribe(d=>{d?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))}));const o=new r.Subscription;this.subscription.add(o);const l=r.merge(r.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(r.filter(d=>Boolean(d==null?void 0:d.provider))));e.providerOutput.isLive$.pipe(r.filterChanged()).subscribe(d=>{switch(r.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new r.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>u.next(c&&Math.floor(c/1e3)))),o.add(Or({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:l,looped$:this.events.looped$,position$:u}).pipe(r.map(({from:c,to:h})=>({start:c,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(Or({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:l,position$:this.providerContainer.providerOutput.position$}).pipe(r.map(({from:u,to:c})=>({start:u,end:c}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(r.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{var u,c;const h=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=d==null?void 0:d.size)===null||u===void 0?void 0:u.width,height:(c=d==null?void 0:d.size)===null||c===void 0?void 0:c.height},{width:h==null?void 0:h.videoWidth,height:h==null?void 0:h.videoHeight})}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(r.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new r.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(r.filterChanged((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(r.filter(i=>i.length>0),r.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Gt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(r.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(r.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;r.assertNonNullable(this.providerContainer),r.assertNonNullable(t),bf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>mf(i)),this.providerContainer.current$.subscribe(({type:i})=>ai("provider",i)),t.duration$.subscribe(i=>ai("duration",i)),t.availableVideoTracks$.pipe(r.filter(i=>!!i.length),r.once()).subscribe(i=>ai("tracks",i)),this.events.fatalError$.subscribe(new $e("fatalError")),this.events.managedError$.subscribe(new $e("managedError")),t.position$.subscribe(new $e("position")),t.currentVideoTrack$.pipe(r.map(i=>i==null?void 0:i.quality)).subscribe(new $e("quality")),this.info.currentBuffer$.subscribe(new $e("buffer")),t.isBuffering$.subscribe(new $e("isBuffering"))].forEach(i=>this.subscription.add(i)),ai("codecs",dm())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:r.ErrorCategory.DOM,message:String(a)})})};this.subscription.add(r.merge(r.fromEvent(document,"visibilitychange"),r.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=Boolean(e)&&!(e!=null&&e.released);a&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const Rm=`${vo}@${So}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return r.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return r.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return r.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return r.ValueSubject}});exports.Player=_m;exports.SDK_VERSION=Rm;