@vkontakte/videoplayer-core 2.0.83 → 2.0.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.cjs.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.83
3
- * Fri, 21 Apr 2023 09:48:43 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-83/doc/
2
+ * @vkontakte/videoplayer-core v2.0.84
3
+ * Mon, 24 Apr 2023 14:02:41 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-84/doc/
5
5
  */
6
- "use strict";var gu=Object.create;var ka=Object.defineProperty;var yu=Object.getOwnPropertyDescriptor;var Tu=Object.getOwnPropertyNames;var Eu=Object.getPrototypeOf,$u=Object.prototype.hasOwnProperty;var ku=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Tu(e))!$u.call(i,s)&&s!==t&&ka(i,s,{get:()=>e[s],enumerable:!(r=yu(e,s))||r.enumerable});return i};var Pa=(i,e,t)=>(t=i!=null?gu(Eu(i)):{},ku(e||!i||!i.__esModule?ka(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),Pu=require("lodash/debounce.js");const Au="2.0.83",wu="es2015.cjs.js";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var fe;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(fe||(fe={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var C;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(C||(C={}));function Q(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(c){try{u(r.next(c))}catch(h){o(h)}}function d(c){try{u(r.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):s(c.value).then(l,d)}u((r=r.apply(i,e||[])).next())})}function R(i){return this instanceof R?(this.v=i,this):new R(i)}function Pe(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(m,v){n.push([f,p,m,v])>1||l(f,p)})})}function l(f,p){try{d(r[f](p))}catch(m){h(n[0][3],m)}}function d(f){f.value instanceof R?Promise.resolve(f.value.v).then(u,c):h(n[0][2],f)}function u(f){l("next",f)}function c(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}var _u=i=>new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});class Ru{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const r="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${r}`}),e.isDisabled||!r)return;const s=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||_u("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.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 r,s,n;(n=(s=(r=cast.framework.CastContext.getInstance())===null||r===void 0?void 0:r.getCurrentSession())===null||s===void 0?void 0:s.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.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),r=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{var n,o;switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=r.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 a.assertNever(s.sessionState)}})).add(a.merge(a.fromEvent(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),a.map(s=>s.castState)),a.observableFrom([r.getCastState()])).pipe(a.filterChanged(),a.map(Iu),a.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{var n;const o=s===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=r.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.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(s===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){var e;let t,r,s;try{t=cast.framework.CastContext.getInstance(),r=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:r,autoJoinPolicy:s}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Iu=i=>{switch(i){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 a.assertNever(i)}};var Aa=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Ee=function(i){try{return!!i()}catch(e){return!0}},Nu=Ee,ar=!Nu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),yo=ar,To=Function.prototype,gs=To.call,Cu=yo&&To.bind.bind(gs,gs),$e=yo?Cu:function(i){return function(){return gs.apply(i,arguments)}},Eo=$e,Du=Eo({}.toString),Ou=Eo("".slice),ni=function(i){return Ou(Du(i),8,-1)},Lu=$e,xu=Ee,Bu=ni,Er=Object,Mu=Lu("".split),Vu=xu(function(){return!Er("z").propertyIsEnumerable(0)})?function(i){return Bu(i)=="String"?Mu(i,""):Er(i)}:Er,oi=function(i){return i==null},Fu=oi,Uu=TypeError,js=function(i){if(Fu(i))throw Uu("Can't call method on "+i);return i},ju=Vu,Hu=js,li=function(i){return ju(Hu(i))},Gu=function(){},Lt={},Ti=function(i){return i&&i.Math==Math&&i},le=Ti(typeof globalThis=="object"&&globalThis)||Ti(typeof window=="object"&&window)||Ti(typeof self=="object"&&self)||Ti(typeof Aa=="object"&&Aa)||function(){return this}()||Function("return this")(),ys=typeof document=="object"&&document.all,Yu=typeof ys=="undefined"&&ys!==void 0,$o={all:ys,IS_HTMLDDA:Yu},ko=$o,qu=ko.all,se=ko.IS_HTMLDDA?function(i){return typeof i=="function"||i===qu}:function(i){return typeof i=="function"},zu=le,Wu=se,wa=zu.WeakMap,Qu=Wu(wa)&&/native code/.test(String(wa)),_a=se,Po=$o,Ju=Po.all,He=Po.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:_a(i)||i===Ju}:function(i){return typeof i=="object"?i!==null:_a(i)},Ku=Ee,Ge=!Ku(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ht={},Xu=le,Ra=He,Ts=Xu.document,Zu=Ra(Ts)&&Ra(Ts.createElement),Hs=function(i){return Zu?Ts.createElement(i):{}},ed=Ge,td=Ee,id=Hs,Ao=!ed&&!td(function(){return Object.defineProperty(id("div"),"a",{get:function(){return 7}}).a!=7}),rd=Ge,sd=Ee,wo=rd&&sd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),ad=He,nd=String,od=TypeError,Ye=function(i){if(ad(i))return i;throw od(nd(i)+" is not an object")},ld=ar,Ei=Function.prototype.call,ve=ld?Ei.bind(Ei):function(){return Ei.apply(Ei,arguments)},Gs={},$r=Gs,kr=le,ud=se,Ia=function(i){return ud(i)?i:void 0},ft=function(i,e){return arguments.length<2?Ia($r[i])||Ia(kr[i]):$r[i]&&$r[i][e]||kr[i]&&kr[i][e]},dd=$e,nr=dd({}.isPrototypeOf),or=typeof navigator!="undefined"&&String(navigator.userAgent)||"",_o=le,Pr=or,Na=_o.process,Ca=_o.Deno,Da=Na&&Na.versions||Ca&&Ca.version,Oa=Da&&Da.v8,ke,Wi;Oa&&(ke=Oa.split("."),Wi=ke[0]>0&&ke[0]<4?1:+(ke[0]+ke[1]));!Wi&&Pr&&(ke=Pr.match(/Edge\/(\d+)/),(!ke||ke[1]>=74)&&(ke=Pr.match(/Chrome\/(\d+)/),ke&&(Wi=+ke[1])));var Ro=Wi,La=Ro,cd=Ee,Io=!!Object.getOwnPropertySymbols&&!cd(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&La&&La<41}),hd=Io,No=hd&&!Symbol.sham&&typeof Symbol.iterator=="symbol",fd=ft,pd=se,vd=nr,md=No,bd=Object,Co=md?function(i){return typeof i=="symbol"}:function(i){var e=fd("Symbol");return pd(e)&&vd(e.prototype,bd(i))},Sd=String,lr=function(i){try{return Sd(i)}catch(e){return"Object"}},gd=se,yd=lr,Td=TypeError,pt=function(i){if(gd(i))return i;throw Td(yd(i)+" is not a function")},Ed=pt,$d=oi,ur=function(i,e){var t=i[e];return $d(t)?void 0:Ed(t)},Ar=ve,wr=se,_r=He,kd=TypeError,Pd=function(i,e){var t,r;if(e==="string"&&wr(t=i.toString)&&!_r(r=Ar(t,i))||wr(t=i.valueOf)&&!_r(r=Ar(t,i))||e!=="string"&&wr(t=i.toString)&&!_r(r=Ar(t,i)))return r;throw kd("Can't convert object to primitive value")},Qi={},Ad={get exports(){return Qi},set exports(i){Qi=i}},Do=!0,xa=le,wd=Object.defineProperty,_d=function(i,e){try{wd(xa,i,{value:e,configurable:!0,writable:!0})}catch(t){xa[i]=e}return e},Rd=le,Id=_d,Ba="__core-js_shared__",Nd=Rd[Ba]||Id(Ba,{}),Ys=Nd,Ma=Ys;(Ad.exports=function(i,e){return Ma[i]||(Ma[i]=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 Cd=js,Dd=Object,dr=function(i){return Dd(Cd(i))},Od=$e,Ld=dr,xd=Od({}.hasOwnProperty),Oe=Object.hasOwn||function(e,t){return xd(Ld(e),t)},Bd=$e,Md=0,Vd=Math.random(),Fd=Bd(1 .toString),Oo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Fd(++Md+Vd,36)},Ud=le,jd=Qi,Va=Oe,Hd=Oo,Gd=Io,Yd=No,Pt=Ud.Symbol,Rr=jd("wks"),qd=Yd?Pt.for||Pt:Pt&&Pt.withoutSetter||Hd,ue=function(i){return Va(Rr,i)||(Rr[i]=Gd&&Va(Pt,i)?Pt[i]:qd("Symbol."+i)),Rr[i]},zd=ve,Fa=He,Ua=Co,Wd=ur,Qd=Pd,Jd=ue,Kd=TypeError,Xd=Jd("toPrimitive"),Zd=function(i,e){if(!Fa(i)||Ua(i))return i;var t=Wd(i,Xd),r;if(t){if(e===void 0&&(e="default"),r=zd(t,i,e),!Fa(r)||Ua(r))return r;throw Kd("Can't convert object to primitive value")}return e===void 0&&(e="number"),Qd(i,e)},ec=Zd,tc=Co,qs=function(i){var e=ec(i,"string");return tc(e)?e:e+""},ic=Ge,rc=Ao,sc=wo,$i=Ye,ja=qs,ac=TypeError,Ir=Object.defineProperty,nc=Object.getOwnPropertyDescriptor,Nr="enumerable",Cr="configurable",Dr="writable";ht.f=ic?sc?function(e,t,r){if($i(e),t=ja(t),$i(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Dr in r&&!r[Dr]){var s=nc(e,t);s&&s[Dr]&&(e[t]=r.value,r={configurable:Cr in r?r[Cr]:s[Cr],enumerable:Nr in r?r[Nr]:s[Nr],writable:!1})}return Ir(e,t,r)}:Ir:function(e,t,r){if($i(e),t=ja(t),$i(r),rc)try{return Ir(e,t,r)}catch(s){}if("get"in r||"set"in r)throw ac("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var cr=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},oc=Ge,lc=ht,uc=cr,ui=oc?function(i,e,t){return lc.f(i,e,uc(1,t))}:function(i,e,t){return i[e]=t,i},dc=Qi,cc=Oo,Ha=dc("keys"),zs=function(i){return Ha[i]||(Ha[i]=cc(i))},Ws={},hc=Qu,Lo=le,fc=He,pc=ui,Or=Oe,Lr=Ys,vc=zs,mc=Ws,Ga="Object already initialized",Es=Lo.TypeError,bc=Lo.WeakMap,Ji,si,Ki,Sc=function(i){return Ki(i)?si(i):Ji(i,{})},gc=function(i){return function(e){var t;if(!fc(e)||(t=si(e)).type!==i)throw Es("Incompatible receiver, "+i+" required");return t}};if(hc||Lr.state){var Ne=Lr.state||(Lr.state=new bc);Ne.get=Ne.get,Ne.has=Ne.has,Ne.set=Ne.set,Ji=function(i,e){if(Ne.has(i))throw Es(Ga);return e.facade=i,Ne.set(i,e),e},si=function(i){return Ne.get(i)||{}},Ki=function(i){return Ne.has(i)}}else{var gt=vc("state");mc[gt]=!0,Ji=function(i,e){if(Or(i,gt))throw Es(Ga);return e.facade=i,pc(i,gt,e),e},si=function(i){return Or(i,gt)?i[gt]:{}},Ki=function(i){return Or(i,gt)}}var xo={set:Ji,get:si,has:Ki,enforce:Sc,getterFor:gc},yc=ar,Bo=Function.prototype,Ya=Bo.apply,qa=Bo.call,Mo=typeof Reflect=="object"&&Reflect.apply||(yc?qa.bind(Ya):function(){return qa.apply(Ya,arguments)}),Tc=ni,Ec=$e,Vo=function(i){if(Tc(i)==="Function")return Ec(i)},Qs={},Fo={},Uo={}.propertyIsEnumerable,jo=Object.getOwnPropertyDescriptor,$c=jo&&!Uo.call({1:2},1);Fo.f=$c?function(e){var t=jo(this,e);return!!t&&t.enumerable}:Uo;var kc=Ge,Pc=ve,Ac=Fo,wc=cr,_c=li,Rc=qs,Ic=Oe,Nc=Ao,za=Object.getOwnPropertyDescriptor;Qs.f=kc?za:function(e,t){if(e=_c(e),t=Rc(t),Nc)try{return za(e,t)}catch(r){}if(Ic(e,t))return wc(!Pc(Ac.f,e,t),e[t])};var Cc=Ee,Dc=se,Oc=/#|\.prototype\./,di=function(i,e){var t=xc[Lc(i)];return t==Mc?!0:t==Bc?!1:Dc(e)?Cc(e):!!e},Lc=di.normalize=function(i){return String(i).replace(Oc,".").toLowerCase()},xc=di.data={},Bc=di.NATIVE="N",Mc=di.POLYFILL="P",Ho=di,Wa=Vo,Vc=pt,Fc=ar,Uc=Wa(Wa.bind),hr=function(i,e){return Vc(i),e===void 0?i:Fc?Uc(i,e):function(){return i.apply(e,arguments)}},ki=le,jc=Mo,Hc=Vo,Gc=se,Yc=Qs.f,qc=Ho,yt=Gs,zc=hr,Tt=ui,Qa=Oe,Wc=function(i){var e=function(t,r,s){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,s)}return jc(i,this,arguments)};return e.prototype=i.prototype,e},we=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?ki:s?ki[t]:(ki[t]||{}).prototype,l=r?yt:yt[t]||Tt(yt,t,{})[t],d=l.prototype,u,c,h,f,p,m,v,b,S;for(f in e)u=qc(r?f:t+(s?".":"#")+f,i.forced),c=!u&&o&&Qa(o,f),m=l[f],c&&(i.dontCallGetSet?(S=Yc(o,f),v=S&&S.value):v=o[f]),p=c&&v?v:e[f],!(c&&typeof m==typeof p)&&(i.bind&&c?b=zc(p,ki):i.wrap&&c?b=Wc(p):n&&Gc(p)?b=Hc(p):b=p,(i.sham||p&&p.sham||m&&m.sham)&&Tt(b,"sham",!0),Tt(l,f,b),n&&(h=t+"Prototype",Qa(yt,h)||Tt(yt,h,{}),Tt(yt[h],f,p),i.real&&d&&(u||!d[f])&&Tt(d,f,p)))},$s=Ge,Qc=Oe,Go=Function.prototype,Jc=$s&&Object.getOwnPropertyDescriptor,Js=Qc(Go,"name"),Kc=Js&&function(){}.name==="something",Xc=Js&&(!$s||$s&&Jc(Go,"name").configurable),Zc={EXISTS:Js,PROPER:Kc,CONFIGURABLE:Xc},Yo={},eh=Math.ceil,th=Math.floor,ih=Math.trunc||function(e){var t=+e;return(t>0?th:eh)(t)},rh=ih,Ks=function(i){var e=+i;return e!==e||e===0?0:rh(e)},sh=Ks,ah=Math.max,nh=Math.min,oh=function(i,e){var t=sh(i);return t<0?ah(t+e,0):nh(t,e)},lh=Ks,uh=Math.min,dh=function(i){return i>0?uh(lh(i),9007199254740991):0},ch=dh,Xs=function(i){return ch(i.length)},hh=li,fh=oh,ph=Xs,Ja=function(i){return function(e,t,r){var s=hh(e),n=ph(s),o=fh(r,n),l;if(i&&t!=t){for(;n>o;)if(l=s[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in s)&&s[o]===t)return i||o||0;return!i&&-1}},vh={includes:Ja(!0),indexOf:Ja(!1)},mh=$e,xr=Oe,bh=li,Sh=vh.indexOf,gh=Ws,Ka=mh([].push),yh=function(i,e){var t=bh(i),r=0,s=[],n;for(n in t)!xr(gh,n)&&xr(t,n)&&Ka(s,n);for(;e.length>r;)xr(t,n=e[r++])&&(~Sh(s,n)||Ka(s,n));return s},qo=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Th=yh,Eh=qo,$h=Object.keys||function(e){return Th(e,Eh)},kh=Ge,Ph=wo,Ah=ht,wh=Ye,_h=li,Rh=$h;Yo.f=kh&&!Ph?Object.defineProperties:function(e,t){wh(e);for(var r=_h(t),s=Rh(t),n=s.length,o=0,l;n>o;)Ah.f(e,l=s[o++],r[l]);return e};var Ih=ft,zo=Ih("document","documentElement"),Nh=Ye,Ch=Yo,Xa=qo,Dh=Ws,Oh=zo,Lh=Hs,xh=zs,Za=">",en="<",ks="prototype",Ps="script",Wo=xh("IE_PROTO"),Br=function(){},Qo=function(i){return en+Ps+Za+i+en+"/"+Ps+Za},tn=function(i){i.write(Qo("")),i.close();var e=i.parentWindow.Object;return i=null,e},Bh=function(){var i=Lh("iframe"),e="java"+Ps+":",t;return i.style.display="none",Oh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Qo("document.F=Object")),t.close(),t.F},Pi,Hi=function(){try{Pi=new ActiveXObject("htmlfile")}catch(e){}Hi=typeof document!="undefined"?document.domain&&Pi?tn(Pi):Bh():tn(Pi);for(var i=Xa.length;i--;)delete Hi[ks][Xa[i]];return Hi()};Dh[Wo]=!0;var Jo=Object.create||function(e,t){var r;return e!==null?(Br[ks]=Nh(e),r=new Br,Br[ks]=null,r[Wo]=e):r=Hi(),t===void 0?r:Ch.f(r,t)},Mh=Ee,Vh=!Mh(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Fh=Oe,Uh=se,jh=dr,Hh=zs,Gh=Vh,rn=Hh("IE_PROTO"),As=Object,Yh=As.prototype,Ko=Gh?As.getPrototypeOf:function(i){var e=jh(i);if(Fh(e,rn))return e[rn];var t=e.constructor;return Uh(t)&&e instanceof t?t.prototype:e instanceof As?Yh:null},qh=ui,Zs=function(i,e,t,r){return r&&r.enumerable?i[e]=t:qh(i,e,t),i},zh=Ee,Wh=se,Qh=He,Jh=Jo,sn=Ko,Kh=Zs,Xh=ue,ws=Xh("iterator"),Xo=!1,Ue,Mr,Vr;[].keys&&(Vr=[].keys(),"next"in Vr?(Mr=sn(sn(Vr)),Mr!==Object.prototype&&(Ue=Mr)):Xo=!0);var Zh=!Qh(Ue)||zh(function(){var i={};return Ue[ws].call(i)!==i});Zh?Ue={}:Ue=Jh(Ue);Wh(Ue[ws])||Kh(Ue,ws,function(){return this});var Zo={IteratorPrototype:Ue,BUGGY_SAFARI_ITERATORS:Xo},ef=ue,tf=ef("toStringTag"),el={};el[tf]="z";var ea=String(el)==="[object z]",rf=ea,sf=se,Gi=ni,af=ue,nf=af("toStringTag"),of=Object,lf=Gi(function(){return arguments}())=="Arguments",uf=function(i,e){try{return i[e]}catch(t){}},ci=rf?Gi:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=uf(e=of(i),nf))=="string"?t:lf?Gi(e):(r=Gi(e))=="Object"&&sf(e.callee)?"Arguments":r},df=ea,cf=ci,hf=df?{}.toString:function(){return"[object "+cf(this)+"]"},ff=ea,pf=ht.f,vf=ui,mf=Oe,bf=hf,Sf=ue,an=Sf("toStringTag"),ta=function(i,e,t,r){if(i){var s=t?i:i.prototype;mf(s,an)||pf(s,an,{configurable:!0,value:e}),r&&!ff&&vf(s,"toString",bf)}},gf=Zo.IteratorPrototype,yf=Jo,Tf=cr,Ef=ta,$f=Lt,kf=function(){return this},Pf=function(i,e,t,r){var s=e+" Iterator";return i.prototype=yf(gf,{next:Tf(+!r,t)}),Ef(i,s,!1,!0),$f[s]=kf,i},Af=we,wf=ve,tl=Zc,_f=Pf,Rf=Ko,If=ta,nn=Zs,Nf=ue,on=Lt,il=Zo,Cf=tl.PROPER;tl.CONFIGURABLE;il.IteratorPrototype;var Ai=il.BUGGY_SAFARI_ITERATORS,Fr=Nf("iterator"),ln="keys",wi="values",un="entries",Df=function(){return this},Of=function(i,e,t,r,s,n,o){_f(t,e,r);var l=function(S){if(S===s&&f)return f;if(!Ai&&S in c)return c[S];switch(S){case ln:return function(){return new t(this,S)};case wi:return function(){return new t(this,S)};case un:return function(){return new t(this,S)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[Fr]||c["@@iterator"]||s&&c[s],f=!Ai&&h||l(s),p=e=="Array"&&c.entries||h,m,v,b;if(p&&(m=Rf(p.call(new i)),m!==Object.prototype&&m.next&&(If(m,d,!0,!0),on[d]=Df)),Cf&&s==wi&&h&&h.name!==wi&&(u=!0,f=function(){return wf(h,this)}),s)if(v={values:l(wi),keys:n?f:l(ln),entries:l(un)},o)for(b in v)(Ai||u||!(b in c))&&nn(c,b,v[b]);else Af({target:e,proto:!0,forced:Ai||u},v);return o&&c[Fr]!==f&&nn(c,Fr,f,{name:s}),on[e]=f,v},Lf=function(i,e){return{value:i,done:e}},xf=li,ia=Gu,dn=Lt,rl=xo,Bf=ht.f,Mf=Of,_i=Lf,Vf=Do,Ff=Ge,sl="Array Iterator",Uf=rl.set,jf=rl.getterFor(sl);Mf(Array,"Array",function(i,e){Uf(this,{type:sl,target:xf(i),index:0,kind:e})},function(){var i=jf(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,_i(void 0,!0)):t=="keys"?_i(r,!1):t=="values"?_i(e[r],!1):_i([r,e[r]],!1)},"values");var cn=dn.Arguments=dn.Array;ia();ia();ia();if(!Vf&&Ff&&cn.name!=="values")try{Bf(cn,"name",{value:"values"})}catch(i){}var Hf=ue,Gf=Lt,Yf=Hf("iterator"),qf=Array.prototype,zf=function(i){return i!==void 0&&(Gf.Array===i||qf[Yf]===i)},Wf=ci,hn=ur,Qf=oi,Jf=Lt,Kf=ue,Xf=Kf("iterator"),al=function(i){if(!Qf(i))return hn(i,Xf)||hn(i,"@@iterator")||Jf[Wf(i)]},Zf=ve,ep=pt,tp=Ye,ip=lr,rp=al,sp=TypeError,ap=function(i,e){var t=arguments.length<2?rp(i):e;if(ep(t))return tp(Zf(t,i));throw sp(ip(i)+" is not iterable")},np=ve,fn=Ye,op=ur,lp=function(i,e,t){var r,s;fn(i);try{if(r=op(i,"return"),!r){if(e==="throw")throw t;return t}r=np(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return fn(r),t},up=hr,dp=ve,cp=Ye,hp=lr,fp=zf,pp=Xs,pn=nr,vp=ap,mp=al,vn=lp,bp=TypeError,Yi=function(i,e){this.stopped=i,this.result=e},mn=Yi.prototype,ra=function(i,e,t){var r=t&&t.that,s=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=up(e,r),u,c,h,f,p,m,v,b=function(g){return u&&vn(u,"normal",g),new Yi(!0,g)},S=function(g){return s?(cp(g),l?d(g[0],g[1],b):d(g[0],g[1])):l?d(g,b):d(g)};if(n)u=i.iterator;else if(o)u=i;else{if(c=mp(i),!c)throw bp(hp(i)+" is not iterable");if(fp(c)){for(h=0,f=pp(i);f>h;h++)if(p=S(i[h]),p&&pn(mn,p))return p;return new Yi(!1)}u=vp(i,c)}for(m=n?i.next:u.next;!(v=dp(m,u)).done;){try{p=S(v.value)}catch(g){vn(u,"throw",g)}if(typeof p=="object"&&p&&pn(mn,p))return p}return new Yi(!1)},Sp=qs,gp=ht,yp=cr,Tp=function(i,e,t){var r=Sp(e);r in i?gp.f(i,r,yp(0,t)):i[r]=t},Ep=we,$p=ra,kp=Tp;Ep({target:"Object",stat:!0},{fromEntries:function(e){var t={};return $p(e,function(r,s){kp(t,r,s)},{AS_ENTRIES:!0}),t}});var Pp=Gs,Ap=Pp.Object.fromEntries,wp={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},_p=wp,Rp=le,Ip=ci,Np=ui,bn=Lt,Cp=ue,Sn=Cp("toStringTag");for(var Ur in _p){var gn=Rp[Ur],jr=gn&&gn.prototype;jr&&Ip(jr)!==Sn&&Np(jr,Sn,Ur),bn[Ur]=bn.Array}var Dp=Ap,Op=Dp,Lp=Op,xp=Lp,hi=xp,Bp=ni,fr=typeof process!="undefined"&&Bp(process)=="process",Mp=ft,Vp=ht,Fp=ue,Up=Ge,yn=Fp("species"),jp=function(i){var e=Mp(i),t=Vp.f;Up&&e&&!e[yn]&&t(e,yn,{configurable:!0,get:function(){return this}})},Hp=nr,Gp=TypeError,Yp=function(i,e){if(Hp(e,i))return i;throw Gp("Incorrect invocation")},qp=$e,zp=se,_s=Ys,Wp=qp(Function.toString);zp(_s.inspectSource)||(_s.inspectSource=function(i){return Wp(i)});var nl=_s.inspectSource,Qp=$e,Jp=Ee,ol=se,Kp=ci,Xp=ft,Zp=nl,ll=function(){},ev=[],ul=Xp("Reflect","construct"),sa=/^\s*(?:class|function)\b/,tv=Qp(sa.exec),iv=!sa.exec(ll),Qt=function(e){if(!ol(e))return!1;try{return ul(ll,ev,e),!0}catch(t){return!1}},dl=function(e){if(!ol(e))return!1;switch(Kp(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return iv||!!tv(sa,Zp(e))}catch(t){return!0}};dl.sham=!0;var rv=!ul||Jp(function(){var i;return Qt(Qt.call)||!Qt(Object)||!Qt(function(){i=!0})||i})?dl:Qt,sv=rv,av=lr,nv=TypeError,ov=function(i){if(sv(i))return i;throw nv(av(i)+" is not a constructor")},Tn=Ye,lv=ov,uv=oi,dv=ue,cv=dv("species"),cl=function(i,e){var t=Tn(i).constructor,r;return t===void 0||uv(r=Tn(t)[cv])?e:lv(r)},hv=$e,fv=hv([].slice),pv=TypeError,vv=function(i,e){if(i<e)throw pv("Not enough arguments");return i},mv=or,hl=/(?:ipad|iphone|ipod).*applewebkit/i.test(mv),pe=le,bv=Mo,Sv=hr,En=se,gv=Oe,fl=Ee,$n=zo,yv=fv,kn=Hs,Tv=vv,Ev=hl,$v=fr,Rs=pe.setImmediate,Is=pe.clearImmediate,kv=pe.process,Hr=pe.Dispatch,Pv=pe.Function,Pn=pe.MessageChannel,Av=pe.String,Gr=0,Zt={},An="onreadystatechange",ai,ot,Yr,qr;fl(function(){ai=pe.location});var aa=function(i){if(gv(Zt,i)){var e=Zt[i];delete Zt[i],e()}},zr=function(i){return function(){aa(i)}},wn=function(i){aa(i.data)},_n=function(i){pe.postMessage(Av(i),ai.protocol+"//"+ai.host)};(!Rs||!Is)&&(Rs=function(e){Tv(arguments.length,1);var t=En(e)?e:Pv(e),r=yv(arguments,1);return Zt[++Gr]=function(){bv(t,void 0,r)},ot(Gr),Gr},Is=function(e){delete Zt[e]},$v?ot=function(i){kv.nextTick(zr(i))}:Hr&&Hr.now?ot=function(i){Hr.now(zr(i))}:Pn&&!Ev?(Yr=new Pn,qr=Yr.port2,Yr.port1.onmessage=wn,ot=Sv(qr.postMessage,qr)):pe.addEventListener&&En(pe.postMessage)&&!pe.importScripts&&ai&&ai.protocol!=="file:"&&!fl(_n)?(ot=_n,pe.addEventListener("message",wn,!1)):An in kn("script")?ot=function(i){$n.appendChild(kn("script"))[An]=function(){$n.removeChild(this),aa(i)}}:ot=function(i){setTimeout(zr(i),0)});var pl={set:Rs,clear:Is},vl=function(){this.head=null,this.tail=null};vl.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var ml=vl,wv=or,_v=/ipad|iphone|ipod/i.test(wv)&&typeof Pebble!="undefined",Rv=or,Iv=/web0s(?!.*chrome)/i.test(Rv),ct=le,Rn=hr,Nv=Qs.f,Wr=pl.set,Cv=ml,Dv=hl,Ov=_v,Lv=Iv,Qr=fr,In=ct.MutationObserver||ct.WebKitMutationObserver,Nn=ct.document,Cn=ct.process,Ri=ct.Promise,Dn=Nv(ct,"queueMicrotask"),Ns=Dn&&Dn.value,Et,Jr,Kr,Ii,On;if(!Ns){var Ni=new Cv,Ci=function(){var i,e;for(Qr&&(i=Cn.domain)&&i.exit();e=Ni.get();)try{e()}catch(t){throw Ni.head&&Et(),t}i&&i.enter()};!Dv&&!Qr&&!Lv&&In&&Nn?(Jr=!0,Kr=Nn.createTextNode(""),new In(Ci).observe(Kr,{characterData:!0}),Et=function(){Kr.data=Jr=!Jr}):!Ov&&Ri&&Ri.resolve?(Ii=Ri.resolve(void 0),Ii.constructor=Ri,On=Rn(Ii.then,Ii),Et=function(){On(Ci)}):Qr?Et=function(){Cn.nextTick(Ci)}:(Wr=Rn(Wr,ct),Et=function(){Wr(Ci)}),Ns=function(i){Ni.head||Et(),Ni.add(i)}}var xv=Ns,Bv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},na=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Mv=le,xt=Mv.Promise,bl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Vv=bl,Fv=fr,Uv=!Vv&&!Fv&&typeof window=="object"&&typeof document=="object",jv=le,ei=xt,Hv=se,Gv=Ho,Yv=nl,qv=ue,zv=Uv,Wv=bl,Xr=Ro,Ln=ei&&ei.prototype,Qv=qv("species"),Cs=!1,Sl=Hv(jv.PromiseRejectionEvent),Jv=Gv("Promise",function(){var i=Yv(ei),e=i!==String(ei);if(!e&&Xr===66||!(Ln.catch&&Ln.finally))return!0;if(!Xr||Xr<51||!/native code/.test(i)){var t=new ei(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[Qv]=r,Cs=t.then(function(){})instanceof r,!Cs)return!0}return!e&&(zv||Wv)&&!Sl}),fi={CONSTRUCTOR:Jv,REJECTION_EVENT:Sl,SUBCLASSING:Cs},Bt={},xn=pt,Kv=TypeError,Xv=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw Kv("Bad Promise constructor");e=r,t=s}),this.resolve=xn(e),this.reject=xn(t)};Bt.f=function(i){return new Xv(i)};var Zv=we,Xi=fr,Ze=le,pi=ve,em=Zs,tm=ta,im=jp,rm=pt,Ds=se,sm=He,am=Yp,nm=cl,gl=pl.set,oa=xv,om=Bv,lm=na,um=ml,yl=xo,Os=xt,la=fi,Tl=Bt,pr="Promise",El=la.CONSTRUCTOR,dm=la.REJECTION_EVENT;la.SUBCLASSING;var Zr=yl.getterFor(pr),cm=yl.set,hm=Os&&Os.prototype,At=Os,es=hm,$l=Ze.TypeError,Ls=Ze.document,ua=Ze.process,xs=Tl.f,fm=xs,pm=!!(Ls&&Ls.createEvent&&Ze.dispatchEvent),kl="unhandledrejection",vm="rejectionhandled",Bn=0,Pl=1,mm=2,da=1,Al=2,Di,Mn,bm,wl=function(i){var e;return sm(i)&&Ds(e=i.then)?e:!1},_l=function(i,e){var t=e.value,r=e.state==Pl,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{s?(r||(e.rejection===Al&&gm(e),e.rejection=da),s===!0?d=t:(l&&l.enter(),d=s(t),l&&(l.exit(),c=!0)),d===i.promise?o($l("Promise-chain cycle")):(u=wl(d))?pi(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},Rl=function(i,e){i.notified||(i.notified=!0,oa(function(){for(var t=i.reactions,r;r=t.get();)_l(r,i);i.notified=!1,e&&!i.rejection&&Sm(i)}))},Il=function(i,e,t){var r,s;pm?(r=Ls.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Ze.dispatchEvent(r)):r={promise:e,reason:t},!dm&&(s=Ze["on"+i])?s(r):i===kl&&om("Unhandled promise rejection",t)},Sm=function(i){pi(gl,Ze,function(){var e=i.facade,t=i.value,r=Vn(i),s;if(r&&(s=lm(function(){Xi?ua.emit("unhandledRejection",t,e):Il(kl,e,t)}),i.rejection=Xi||Vn(i)?Al:da,s.error))throw s.value})},Vn=function(i){return i.rejection!==da&&!i.parent},gm=function(i){pi(gl,Ze,function(){var e=i.facade;Xi?ua.emit("rejectionHandled",e):Il(vm,e,i.value)})},wt=function(i,e,t){return function(r){i(e,r,t)}},Rt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=mm,Rl(i,!0))},Bs=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw $l("Promise can't be resolved itself");var r=wl(e);r?oa(function(){var s={done:!1};try{pi(r,e,wt(Bs,s,i),wt(Rt,s,i))}catch(n){Rt(s,n,i)}}):(i.value=e,i.state=Pl,Rl(i,!1))}catch(s){Rt({done:!1},s,i)}}};El&&(At=function(e){am(this,es),rm(e),pi(Di,this);var t=Zr(this);try{e(wt(Bs,t),wt(Rt,t))}catch(r){Rt(t,r)}},es=At.prototype,Di=function(e){cm(this,{type:pr,done:!1,notified:!1,parent:!1,reactions:new um,rejection:!1,state:Bn,value:void 0})},Di.prototype=em(es,"then",function(e,t){var r=Zr(this),s=xs(nm(this,At));return r.parent=!0,s.ok=Ds(e)?e:!0,s.fail=Ds(t)&&t,s.domain=Xi?ua.domain:void 0,r.state==Bn?r.reactions.add(s):oa(function(){_l(s,r)}),s.promise}),Mn=function(){var i=new Di,e=Zr(i);this.promise=i,this.resolve=wt(Bs,e),this.reject=wt(Rt,e)},Tl.f=xs=function(i){return i===At||i===bm?new Mn(i):fm(i)});Zv({global:!0,constructor:!0,wrap:!0,forced:El},{Promise:At});tm(At,pr,!1,!0);im(pr);var ym=ue,Nl=ym("iterator"),Cl=!1;try{var Tm=0,Fn={next:function(){return{done:!!Tm++}},return:function(){Cl=!0}};Fn[Nl]=function(){return this},Array.from(Fn,function(){throw 2})}catch(i){}var Em=function(i,e){if(!e&&!Cl)return!1;var t=!1;try{var r={};r[Nl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},$m=xt,km=Em,Pm=fi.CONSTRUCTOR,Dl=Pm||!km(function(i){$m.all(i).then(void 0,function(){})}),Am=we,wm=ve,_m=pt,Rm=Bt,Im=na,Nm=ra,Cm=Dl;Am({target:"Promise",stat:!0,forced:Cm},{all:function(e){var t=this,r=Rm.f(t),s=r.resolve,n=r.reject,o=Im(function(){var l=_m(t.resolve),d=[],u=0,c=1;Nm(e,function(h){var f=u++,p=!1;c++,wm(l,t,h).then(function(m){p||(p=!0,d[f]=m,--c||s(d))},n)}),--c||s(d)});return o.error&&n(o.value),r.promise}});var Dm=we,Om=fi.CONSTRUCTOR,Un=xt;Un&&Un.prototype;Dm({target:"Promise",proto:!0,forced:Om,real:!0},{catch:function(i){return this.then(void 0,i)}});var Lm=we,xm=ve,Bm=pt,Mm=Bt,Vm=na,Fm=ra,Um=Dl;Lm({target:"Promise",stat:!0,forced:Um},{race:function(e){var t=this,r=Mm.f(t),s=r.reject,n=Vm(function(){var o=Bm(t.resolve);Fm(e,function(l){xm(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var jm=we,Hm=ve,Gm=Bt,Ym=fi.CONSTRUCTOR;jm({target:"Promise",stat:!0,forced:Ym},{reject:function(e){var t=Gm.f(this);return Hm(t.reject,void 0,e),t.promise}});var qm=Ye,zm=He,Wm=Bt,Ol=function(i,e){if(qm(i),zm(e)&&e.constructor===i)return e;var t=Wm.f(i),r=t.resolve;return r(e),t.promise},Qm=we,Jm=ft,Km=Do,Xm=xt,Zm=fi.CONSTRUCTOR,eb=Ol,tb=Jm("Promise"),ib=!Zm;Qm({target:"Promise",stat:!0,forced:Km},{resolve:function(e){return eb(ib&&this===tb?Xm:this,e)}});var rb=we,Ms=xt,sb=Ee,ab=ft,nb=se,ob=cl,jn=Ol,lb=Ms&&Ms.prototype,ub=!!Ms&&sb(function(){lb.finally.call({then:function(){}},function(){})});rb({target:"Promise",proto:!0,real:!0,forced:ub},{finally:function(i){var e=ob(this,ab("Promise")),t=nb(i);return this.then(t?function(r){return jn(e,i()).then(function(){return r})}:i,t?function(r){return jn(e,i()).then(function(){throw r})}:i)}});var db=ft,ca=db,cb=ca,hb=cb("Promise","finally"),fb=hb,pb=fb,vb=pb,mb=vb,vr=mb,It;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(It||(It={}));var Nt=(i,e=0,t=It.OFFSET_P)=>{switch(t){case It.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case It.PLAYBACK_SHIFT:{if(e===0)return i;const r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}default:a.assertNever(t)}return i},k=(i,e,t=!1)=>{const r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};exports.VideoQuality=void 0;(function(i){i.INVARIANT="Invariant quality",i.Q_144P="144p",i.Q_240P="240p",i.Q_360P="360p",i.Q_480P="480p",i.Q_720P="720p",i.Q_1080P="1080p",i.Q_1440P="1440p",i.Q_2160P="2160p",i.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const Ae={[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}},qi=(i,e)=>Ae[i].height>Ae[e].height,bb=(i,e)=>Ae[i].height>=Ae[e].height,ti=(i,e)=>Ae[i].height<Ae[e].height,Sb=(i,e)=>Ae[i].height<=Ae[e].height,gb=i=>i.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:ti(e,t)?1:-1)[0],yb=Object.keys(Ae).sort((i,e)=>ti(i,e)?-1:1),vt=({width:i,height:e})=>{const t=Math.min(i,e),r=Math.max(i,e);return yb.find(s=>{const n=Ae[s];return n.width>=r&&n.height>=t})},Tb=i=>Ae[i].height,Zi=i=>i===exports.VideoQuality.INVARIANT;class J{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,r=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:r,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,r=this.state;r===e||a.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:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const Eb=i=>{switch(i){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 a.assertNever(i)}};var L;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(L||(L={}));const $b=5,kb=5,Pb=500,Hn=7e3;class Ab{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new J(L.STOPPED),this.syncPlayback=()=>{const r=this.videoState.getState(),s=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: ${r}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){r!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===C.Requested&&r!==L.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(r){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PLAYING:{switch(r){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:a.assertNever(r)}break}case exports.PlaybackState.PAUSED:{switch(r){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:a.assertNever(r)}break}default:a.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(Eb(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 a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(a.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new a.Subject;e.add(s.pipe(a.debounce(Pb)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.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===C.Applying||Math.abs(l-n)>$b)&&s.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.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<kb&&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:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const r=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(r,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 r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:C.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}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,r;const s=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:s.volume,muted:(r=e.muted)!==null&&r!==void 0?r:s.muted};(n.volume!==s.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const r=this.params.source;let s,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=r[e];a.assertNonNullable(c);const h=gb(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),s=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=r[e];a.assertNonNullable(c),s=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=r[e];a.assertNonNullable(c),s=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=r[e];a.assertNonNullable(c),s=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=r[e];a.assertNonNullable(c),s=Nt(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:a.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 a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:s,n);l.contentUrl=s,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const r=this.params.desiredState.seekState.getState();return r.state===C.Applying||r.state===C.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),r=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(Hn).subscribe(()=>n(`timeout(${Hn})`)))});vr(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Gn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;const r=this.listeners[e];for(let s=0,n=r.length;s<n;s++)if(r[s].callback===t){r.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const r=this.listeners[e.type].slice();for(let s=0,n=r.length;s<n;s++){const o=r[s];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 Ll extends Gn{constructor(){super(),this.listeners||Gn.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 xl=class{constructor(){Object.defineProperty(this,"signal",{value:new Ll,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(s){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 r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(s){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(xl.prototype[Symbol.toStringTag]="AbortController",Ll.prototype[Symbol.toStringTag]="AbortSignal");function Bl(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function wb(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!Bl({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(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(p){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((p,m)=>{c.addEventListener("abort",()=>m(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const mr=Bl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ml=mr?wb({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ct=mr?Ml.fetch:window.fetch;mr?Ml.Request:window.Request;const ut=mr?xl:window.AbortController,Jt=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ii{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:r}=e.request,s=(t=this.dashJsRequestQueue.get(r))!==null&&t!==void 0?t:[];s.push(e),this.dashJsRequestQueue.set(r,s)}executeNextRequests(){return Q(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const r=this.activeRequests.get(e);if(r){t.length&&this.onBigRequestProgress(r);const s=t[0];if(!s||!s.request.range)continue;const[n,o]=Jt(s.request);if(n>=r.from&&o<=r.to)continue;this.activeRequests.delete(e)}if(t.length){const s=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,s)}}})}abort(e){var t;if(e){const{request:r}=e,s=((t=this.dashJsRequestQueue.get(r.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(r.url);s&&n&&n.abortController.abort()}else for(const{abortController:r}of this.activeRequests.values())r.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const r=t.map(Jt),s=r[0][0];let n=r[0][1];for(let f=1;f<r.length&&n<this.params.minDataSize;f++){const p=r[f][1];p-s<=2*this.params.minDataSize&&(n=Math.max(n,p))}s===0?n=Math.max(n,s+this.params.minInitSize):n=Math.max(n,s+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${s}-${n}`);const l=o.toString(),d=new ut,u=d.signal,c={url:e,from:s,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var p,m;throw(m=(p=this.params).onError)===null||m===void 0||m.call(p,{id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return Ct(l,{signal:u}).then(f=>{var p,m,v;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[b,S]=f.body.tee();(m=(p=this.params).onDownloadStream)===null||m===void 0||m.call(p,S);const g=b.getReader(),P=parseInt((v=f.headers.get("Content-Length"))!==null&&v!==void 0?v:"",10)||n-s+1;c.data=new ArrayBuffer(P);const E=new Uint8Array(c.data),T=({done:w,value:F})=>Q(this,void 0,void 0,function*(){w?this.onBigRequestProgress(c):F&&(E.set(F,c.loaded),c.loaded+=F.byteLength,this.onBigRequestProgress(c),yield g==null?void 0:g.read().then(T,ii.suppressStreamErrors).catch(h))});g==null||g.read().then(T,ii.suppressStreamErrors).catch(h)},ii.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:r,loaded:s,data:n,response:o}){var l,d,u,c,h,f,p,m;if(!this.activeRequests.has(e)||!n)return;const v=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const b of v){const{request:S}=b,[g,P]=Jt(S),E=g>=t&&P<=t+s,T=t>=g&&t+s<P,w=n.slice(g-t,Math.min(P-t+1,s));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=r-t),E){S.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(O=>O!==b)),(h=b.success)===null||h===void 0||h.call(b,w,"",e);const F=o?Array.from(o.headers.entries()).map(([O,I])=>`${O}: ${I}`).join(`\r
7
- `):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(S,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,F,[])}else T&&((m=b.progress)===null||m===void 0||m.call(b,{loaded:s,total:r-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:r},s){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:a.ErrorCategory.NETWORK,message:"Download error",thrown:s}),!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]=Jt(c.request);(h>=t&&h<r||f>t&&f<=r)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(s)))}if(this.activeRequests.delete(e),s)throw s}onBigRequestAbort({url:e,from:t,to:r}){var s,n;if(!this.activeRequests.has(e))return;const o=(s=this.dashJsRequestQueue.get(e))!==null&&s!==void 0?s:[];for(const l of o){const[d,u]=Jt(l.request);(d>=t&&d<r||u>t&&u<=r)&&((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 er{constructor(e,t,r){this.baseLoader=e,this.config=r,this.bigRequest=t,t.setMetrics(r.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(er.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;er.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const _b=(i,e)=>t=>({create:r=>{const s=i(t).create(r);return new er(s,e,r)}}),Rb=(i,e)=>{const t=new ii(e);return i.extend("SchemeLoaderFactory",function(){const{parent:r}=this,s=r.getLoader;return{getLoader:n=>{const o=s(n);return _b(o,t)}}},!0),()=>t.destroy()};var Ib=i=>{let e,t=!1,r=!1;i.on("playbackTimeUpdated",({timeToEnd:s})=>{r=s<=3,t&&r&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:s}=this,n=s.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&r&&(e==null||e())}}},!0)},Nb=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,r=new a.ValueSubject(void 0),s=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,m,v;const b=hi(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(P=>P.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const P=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=(p=E!=null?E:P*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const S=(m=b["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,g=(v={1:!0,0:!1}[b["x-reused"]])!==null&&v!==void 0?v:void 0;r.next(S),s.next(g)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,m=f.progress;f.onload=function(...v){return d(this),p(...v)},f.progress=function(...v){return u(this),m(...v)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:r}},Dt=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Cb=i=>i.extend("RequestModifier",()=>({modifyRequestURL:Dt}),!0),Db=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:r=>{if(r.request&&r.request.range){const[s,n]=r.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(r.request.url,location.href);o.searchParams.append("bytes",`${s}-${n}`),r.request.url=o.toString(),r.request.range=void 0}t(r)}}},!0)};const De=(i,e,t,{equal:r=(o,l)=>o===l,changed$:s,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(s),u=new a.Subscription;return s&&u.add(s.subscribe(c=>{const h=i.getState();r(c,h)&&i.setState(c)},n)),r(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),d&&i.setState(c.to)},n)),u},mt=(i,e,t)=>De(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),qe=(i,e,t,r)=>De(e,()=>({muted:i.muted,volume:i.volume}),s=>{a.isNonNullable(s)&&(i.muted=s.muted,i.volume=s.volume)},{equal:(s,n)=>s===n||(s==null?void 0:s.muted)===(n==null?void 0:n.muted)&&(s==null?void 0:s.volume)===(n==null?void 0:n.volume),changed$:t,onError:r}),et=(i,e,t,r)=>De(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),Ob=i=>["__",i.language,i.label].join("|"),Lb=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class Le{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(De(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(De(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:s})),this.subscription.add(De(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const r=this.current$.getValue();this.select(r)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),a.filterChanged((r,s)=>r.length===s.length&&r.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),a.map(r=>r&&this.htmlTextTrackToITextTrack(r).id),a.filterChanged()).subscribe(this.current$));const t=r=>{var s,n;return this.applyCueSettings((n=(s=r.target)===null||s===void 0?void 0:s.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)===null||s===void 0||s.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.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=r.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(r=>{var s;(s=r.track)===null||s===void 0||s.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const r of Array.from(e)){const s=r;a.isNonNullable(t.align)&&(s.align=t.align),a.isNonNullable(t.position)&&(s.position=t.position),a.isNonNullable(t.size)&&(s.size=t.size),a.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Le.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:r}=e,s=e.id!==""?e.id:Ob(e);return this.externalTracks.has(s)?{id:s,type:"external",language:t,label:r,url:this.externalTracks.get(s).url}:{id:s,type:"internal",language:t,label:r}}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(r=>r.id===t)).forEach(t=>this.detach(t))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))a.isNonNullable(e)&&Lb(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){a.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){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var ze=i=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i.appendChild(e),e};class ha{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 Vl=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const Vs=3;class xb{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,r=this._source.buffered.length;t<r;t++){let s=this._source.buffered.start(t);const n=this._source.buffered.end(t);s>e&&s-e<Vs&&(s=e),this._buffer.push({from:s,to:n,i:t})}return this._buffer.sort(function(t,r){return t.from-r.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const r=this.getNext(e);if(r&&r.from-e.to<(t||Vs))return r}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,r){this._buffer.forEach(({from:s,to:n})=>{const o=s>=e&&s<t,l=n>=e&&n<t;o&&l||(o?r(t,n):l?r(s,e):s<e&&n>t?(r(t,n),r(s,e)):r(s,n))})}destroy(){this._buffer=[]}}var Fl=(i,e,t=Vs)=>{let r=0,s=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(r=o,s=l,!t)return{from:r,to:s};for(let d=n-1;d>=0;d--)i.end(d)+t>=r&&(r=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=s&&(s=i.end(d))}}return{from:r,to:s}};const Bb=50,Mb=i=>i.webkitAudioDecodedByteCount!=="undefined"?!!i.webkitAudioDecodedByteCount:i.mozHasAudio!=="undefined"?i.mozHasAudio:i.audioTracks?!!i.audioTracks.length:!0,We=i=>{const e=m=>a.fromEvent(i,m).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(m=>a.fromEvent(i,m))).pipe(a.map(m=>m.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>Fl(i.buffered,i.currentTime))),n=Vl()?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),o=a.fromEvent(i,"playing").pipe(a.debounce(Bb),a.map(()=>Mb(i))),l=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),d=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),u=a.fromEvent(i,"error").pipe(a.filter(()=>Boolean(i.error||i.played.length)),a.map(()=>{var m;const v=i.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(m=i.error)!==null&&m!==void 0?m:void 0}})),c=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),h=new a.Subject,f=.3;let p;return c.subscribe(m=>{i.loop&&a.isNonNullable(p)&&a.isNonNullable(m)&&p>=i.duration-f&&m<=f&&h.next(p),p=m}),{playing$:n,pause$:e("pause").pipe(a.filter(()=>!i.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$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:l,isAudioAvailable$:o,playbackRateState$:d}},fa=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Vb=we,Fb=dr,Ub=Xs,jb=Ks;Vb({target:"Array",proto:!0},{at:function(e){var t=Fb(this),r=Ub(t),s=jb(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var Hb=ca,Gb=Hb("Array","at"),Yb=Gb,qb=Yb,zb=qb,Wb=zb,Me=Wb;let pa=!1,Ve={};const Qb=i=>{pa=i},Jb=()=>{Ve={}},Kb=i=>{i(Ve)},Oi=(i,e)=>{var t;pa&&(Ve.meta=(t=Ve.meta)!==null&&t!==void 0?t:{},Ve.meta[i]=e)};class Ce{constructor(e){this.name=e}next(e){var t,r;if(!pa)return;Ve.series=(t=Ve.series)!==null&&t!==void 0?t:{};const s=(r=Ve.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),Ve.series[this.name]=s}}const Xb=new Ce("best_bitrate"),Zb=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class eS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const vi=(i,{container:e,throughput:t,tuning:r,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,p;const m=r.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,v=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*r.containerSizeFactor,height:e.height*m*r.containerSizeFactor},b=v&&vt(v),S=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,g=i.filter(N=>!Zi(N.quality)).sort((N,_)=>qi(N.quality,_.quality)?-1:1),P=(h=Me(g,-1))===null||h===void 0?void 0:h.quality,E=(f=Me(g,0))===null||f===void 0?void 0:f.quality,T=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&ti(s.max,s.min)||a.isNonNullable(s.min)&&E&&qi(s.min,E)||a.isNonNullable(s.max)&&P&&ti(s.max,P),w=S*Zb(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),O=g.filter(N=>{const _=b?ti(N.quality,b):!0,G=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(N.bitrate)?t-n>=N.bitrate*w:!0,K=r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&d&&!Zi(d.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&qi(N.quality,d.quality),te=T||(a.isNullable(s.max)||Sb(N.quality,s.max))&&(a.isNullable(s.min)||bb(N.quality,s.min));return _&&G&&!K&&te})[0];O&&O.bitrate&&Xb.next(O.bitrate);const I=(p=O!=null?O:g[Math.ceil((g.length-1)/2)])!==null&&p!==void 0?p:i[0],U=I&&u&&u.history[I.id]&&a.now()-u.history[I.id]<=r.trackCooldown&&(!u.last||I.id!==u.last.id);if(I!=null&&I.id&&u&&!U&&u.recordSelection(I),U&&(u!=null&&u.last)){const N=u.last;return u==null||u.recordSwitch(N),N}return u==null||u.recordSwitch(I),I};var ce=i=>new URL(i).hostname;const tS=300,tr=(i,e=tS)=>new a.Observable(t=>{const{width:r,height:s}=i.getBoundingClientRect();if(t.next({width:r,height:s}),!window.ResizeObserver)return;const n=new ResizeObserver(Pu(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),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(i),()=>n.disconnect()}),Qe=i=>{try{i.pause(),i.playbackRate=0,i.removeAttribute("src"),i.load(),i.remove()}catch(e){console.error(e)}},iS=5e3,Kt={};var x;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(x||(x={}));const re=(i,e)=>new a.Observable(t=>{const r=s=>t.next(s);return i.on(e,r),()=>i.off(e,r)});class Yn{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(x.DOWNLOADING_LIB),this.textTracksManager=new Le,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new ha,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=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((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&t!==x.STOPPED&&r!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),r){case exports.PlaybackState.STOPPED:{switch(t){case x.STOPPED:break;case x.PLAYING:case x.PAUSED:case x.READY:this.stop();break;default:a.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:a.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:a.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:a.assertNever(t)}break}default:a.assertNever(r)}},this.video=ze(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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{var n;e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=s==null?void 0:s.toString)===null||n===void 0?void 0:n.call(s)}`,thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),iS);vr(import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Kt.MediaPlayer=s.MediaPlayer,Kt.Debug=s.Debug,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Kt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Kt.Debug,"dashjs not loaded"),this.player=Kt.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?fa(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=Rb(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&&Db(this.player),Ib(this.player),this.params.tuning.requestQuick&&Cb(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(x.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,r=v=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:v})},s=(v,b)=>this.subscription.add(v.subscribe(b,r));s(tr(this.video),this.elementSize$),s(re(this.player,"error").pipe(a.map(v=>{const b=typeof v.error=="object"?v.error.code:v.error,S=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${b}`,message:S}})),e.error$),s(re(this.player,"playbackError").pipe(a.map(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const n=re(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({newQuality:v})=>{var b;return(b=this.videoTracks.find(({bitrateInfo:S})=>S.qualityIndex===v))===null||b===void 0?void 0:b.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:v})=>v===x.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(De(t.videoTrack,()=>{var v,b;const S=this.player.getQualityFor("video");return(b=(v=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===S))===null||v===void 0?void 0:v.track)===null||b===void 0?void 0:b.id},v=>{var b;if(a.isNullable(v))return;const S=(b=this.videoTracks.find(({track:g})=>g.id===v))===null||b===void 0?void 0:b.bitrateInfo;S&&this.player.setQualityFor("video",S.qualityIndex)},{changed$:n.pipe(a.map(v=>v==null?void 0:v.id)),onError:r}))},r)),this.subscription.add(De(t.autoVideoTrackSwitching,()=>{var v,b,S;return(S=(b=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||b===void 0?void 0:b.autoSwitchBitrate)===null||S===void 0?void 0:S.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:r})),s(re(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({state:v})=>v==="bufferStalled")),e.isBuffering$),s(re(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:b}})=>{var S,g;const P=this.player.getDashMetrics(),E=P.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),T=(S=P.getLatestFragmentRequestHeaderValueByID(v,"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(ce(b))}),s(re(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:b,availableFrom:S}}})=>{this.isLive$.next(b),this.availableFrom$.next(S.getTime()),b||e.duration$.next(v),this.videoTracks=[];const g=this.player.getQualityFor("video");let P;for(const E of this.player.getBitrateInfoListFor("video")){const T=E.qualityIndex.toString(10),w=vt(E),F=E.bitrate/1e3,O={width:E.width,height:E.height},I=this.frameRatesByFrameHeight[E.height];if(w){const U={id:T,quality:w,bitrate:F,size:O,fps:I};this.videoTracks.push({track:U,bitrateInfo:E}),E.qualityIndex===g&&(P=U)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:E})=>E)),P&&e.currentVideoTrack$.next(P),this.videoState.setState(x.STREAM_INITIALIZED),this.videoState.startTransitionTo(x.READY)}),s(re(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const b=v.requestEndDate.getTime()-v.firstByteDate.getTime(),S=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(S,b)}),s(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),b=vi(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),S=this.videoTracks.find(({track:g})=>g===b);S!=null&&S.bitrateInfo&&this.player.setQualityFor("video",S==null?void 0:S.bitrateInfo.qualityIndex,!1)}),s(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:v})=>v),a.map(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const o=re(this.player,"playbackTimeUpdated").pipe(a.map(({time:v})=>v!=null?v:0));s(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:v,currentTime:b})=>this.params.output.liveTime$.next(v+b*1e3)),s(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),s(re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(re(this.player,"playbackEnded"),e.endedEvent$),s(re(this.player,"playbackProgress").pipe(a.map(()=>Fl(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(x.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),s(re(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())}),s(re(this.player,"playbackPaused"),()=>{this.videoState.setState(x.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),s(re(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===x.READY&&this.videoState.setState(x.READY)}),s(this.isLive$,e.isLive$),s(tr(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));s(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=Nb(this.player);s(c,this.params.output.httpConnectionType$),s(h,this.params.output.httpConnectionReused$),s(d,this.maxSeekBackTime$),s(u.pipe(a.once()),e.firstBytesEvent$),s(re(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(v=>v<60))}),({isLive:v,isShort:b})=>{const S=!v&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:S}}})}),s(o.pipe(a.filter(v=>v>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(re(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(re(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,r))},r)),this.subscription.add(mt(this.video,t.isLooped,r));const{volumeState$:f,looped$:p,playbackRateState$:m}=We(this.video);this.subscription.add(qe(this.video,t.volume,f,r)),this.subscription.add(f.subscribe(e.volume$,r)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(et(this.video,t.playbackRate,m,r))}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,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3);const s=Nt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,It.PLAYBACK_SHIFT);this.player.attachSource(s)}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(r){}Qe(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var mi=i=>{switch(i){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}},tt=i=>Q(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return i.muted=!1,console.warn(r),!1}}return!0});function oe(){return a.now()}function Ul(i){return oe()-i}function qn(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,s=o=>r.test(o);return{resolve:(o,l,d=!1)=>{s(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 rS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function zi(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",m=7e3,v=2e3,b=()=>{if(d)return;a.assertNonNullable(c);const _=Ul(c);let G;if(_<v){G=v-_,setTimeout(b,G);return}v*=2,v>m&&(v=m),o&&o.abort(),o=new s,w()};const S=_=>(n=_,N),g=_=>(h=_,N),P=()=>(p="json",N),E=()=>{if(!d){if(--u>=0){b(),r&&r();return}d=!0,h&&h(),t&&t()}},T=_=>(f=_,N),w=()=>{c=oe(),o=new s,o.open("get",i);let _=0,G,K=0;const te=()=>(a.assertNonNullable(c),Math.max(c,Math.max(G||0,K||0)));if(n&&o.addEventListener("progress",$=>{const D=oe();n.updateChunk&&$.loaded>_&&(n.updateChunk(te(),$.loaded-_),_=$.loaded,G=D)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const D=o.response.byteLength-_;D&&n.updateChunk&&n.updateChunk(te(),D)}h&&h(),o&&e(o.response)}else E()}),o.addEventListener("error",()=>{E()}),f){const $=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=oe(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),N},N={withBitrateReporting:S,withParallel:T,withJSONResponse:P,withRetryCount:_=>(u=_,N),withRetryInterval:(_,G)=>(a.isNonNullable(_)&&(v=_),a.isNonNullable(G)&&(m=G),N),withTimeout:_=>(l=_,N),withFinally:g,send:w,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return N}const sS=100,aS=2e3,nS=500;let oS=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,r){return{start:e,end:t,bytes:r}}_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-nS;if(t-e>aS){let r=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)r+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;r+=o;const d=n.bytes*o/l;s+=d,n.start=t,n.bytes-=d}}}if(s>0&&r>0){const n=s*8/(r/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(s)}/${Math.round(r)} 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,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>sS&&(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 lS{constructor(e,t,r,s,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=r,this.MAX_PARALLEL_REQUESTS=s,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 r=oe(),s=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=oe()-r,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=zi(t,n,()=>s("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=oe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=oe();if(Object.keys(this.activeRequests).length>=e)return!1;const r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!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,r,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=r,o._retryCB=s,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}`),r(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=r,n._retryCB=s,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 Li=1e4,xi=3,uS=300,dS=2e3,cS=6e4,hS=10,fS=1,pS=500;class vS{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 oS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=qn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],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=qn(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 r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-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 r;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(r=e.error)===null||r===void 0?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.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,r=t.buffered.length;let s;r!==0&&(s=t.buffered.start(r-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let r,s,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)?(!s||n.bitrate>s.bitrate)&&(s=n):(!r||r.bitrate>n.bitrate)&&(r=n));return s||r}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:r,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{rS(s,"progress",()=>{s.buffered.length?(s.currentTime=s.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 lS(xi,Li,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:r,playerCallback:s}=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=zi(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withTimeout(Li).withBitrateReporting(this.bitrateSwitcher).withRetryCount(xi).withFinally(()=>{d=null}).send()},p=(E,T,w)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=E=>{const T=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${T}=>${E}`),r.playbackRate=E)},v=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const w=oe()-1e4;let F=0;for(let I=0;I<this.bufferStates.length;I++){const U=this.bufferStates[I];E=Math.min(E,U.buf),U.ts<w&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${E} drop=${F} jitter=${this.sourceJitter}`);let O=E-fS;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?m(1.15):O>1?m(1.1):O>.3?m(1.05):m(1)}},S=E=>{let T;const w=()=>T&&T.start?T.start.length:0,F=$=>T.start[$]/1e3,O=$=>T.dur[$]/1e3,I=$=>T.fragIndex+$,U=($,D)=>({chunkIdx:I($),startTS:F($),dur:O($),discontinuity:D}),N=()=>{let $=0;if(T&&T.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=D;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let ie=T.dur.length-1;for(;ie>=0&&(ee-=T.dur[ie],!(ee<=0));--ie);$=Math.min(ie,T.dur.length-1-z),$=Math.max($,0)}return U($,!0)},_=$=>{const D=w();if(!(D<=0)){if(a.isNonNullable($)){for(let z=0;z<D;z++)if(F(z)>$)return U(z)}return N()}},G=$=>{const D=w(),z=$?$.chunkIdx+1:0,ee=z-T.fragIndex;if(!(D<=0)){if(!$||ee<0||ee-D>hS)return t(`Resync: offset=${ee} bChunks=${D} chunk=`+JSON.stringify($)),N();if(!(ee>=D))return U(z-T.fragIndex,!1)}},K=($,D,z)=>{u&&u.abort(),u=zi(this.urlResolver.resolve($,!0,this.lowLatency),D,z,()=>this._retryCallback()).withTimeout(Li).withRetryCount(xi).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,D)=>{K(E,z=>{if(!h())return;T=z;const ee=Boolean(T.lowLatency);ee!==this.lowLatency&&v(ee);let ie=0;for(let he=0;he<T.dur.length;++he)ie+=T.dur[he];ie>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/T.dur.length)),s({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:G}},g=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{const{videoElement:T,logger:w}=this.params;let F=S(e.jidxUrl),O,I,U,N,_=0,G,K,te;const $=()=>{G&&(clearTimeout(G),G=void 0);const j=Math.max(pS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=_+j,de=oe(),me=Math.min(1e4,ae-de);_=de;const it=()=>{u||h()&&F.seek(()=>{h()&&(_=oe(),D(),$())})};me>0?G=window.setTimeout(()=>{this.paused?$():it()},me):it()},D=()=>{let j;for(;j=F.nextChunk(N);)N=j,_e(j);const ae=F.nextChunk(U);if(ae){if(U&&ae.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?$():(g(),this._initPlayerWith(e));return}he(ae)}else $()},z=(j,ae)=>{if(!h()||!this.sourceBuffer)return;let de,me,it;const Re=Je=>{window.setTimeout(()=>{h()&&z(j,ae)},Je)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),Re(100);else{const Je=oe(),rt=T.currentTime;!this.paused&&T.buffered.length>1&&K===rt&&Je-te>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),K!==rt&&(K=rt,te=Je);const Vt=this._getBufferSizeSec();if(Vt>30)w(`Buffered ${Vt} seconds; delaying appendBuffer`),Re(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:Je,buf:Vt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(bt){if(bt.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),it=this.sourceBuffer.buffered.length,it!==0&&(de=this.sourceBuffer.buffered.start(0),me=rt,me-de>4&&this.sourceBuffer.remove(de,me-3)),Re(1e3);else throw bt}}},ee=()=>{I&&O&&(w([`Appending chunk, sz=${I.byteLength}:`,JSON.stringify(U)]),z(I,function(){I=null,D()}))},ie=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),he=j=>{h()&&p(ie(j),(ae,de)=>{if(h()){if(de/=1e3,I=ae,U=j,o=j.startTS,de){const me=Math.min(10,j.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}ee()}},()=>this._handleNetworkError())},_e=j=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(j),!1)))},Mt=j=>{h()&&(e.cachedHeader=j,z(j,()=>{O=!0,ee()}))};n=!0,F.seek(j=>{if(h()){if(_=oe(),!j){$();return}N=j,!a.isNullable(E)||j.startTS>E?he(j):(U=j,D())}},E),e.cachedHeader?Mt(e.cachedHeader):f(e.headerUrl,Mt,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:r}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),a.isNonNullable(s)&&(s+=.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,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,r=h=>{if(!this.autoQuality)return;let f,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),m=h/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; 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,p)=>{const m=oe();if(this.chunkRateEstimator.addInterval(f,m,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-f,speed:b}),!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&&Ul(o)<3e4)return;r(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=oe();h<l&&(o=f),l=h}}}_fetchManifest(e,t,r){this.manifestRequest=zi(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Li).withRetryCount(xi).withRetryInterval(uS,dS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;tt(t).then(r=>{r||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:r,videoElement:s}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&s.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}`),r({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))},cS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var B;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(B||(B={}));const mS=[B.PAUSED,B.PLAYING,B.READY],bS=[B.PAUSED,B.PLAYING,B.READY];class SS{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(B.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Le,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new ha,this._dashCb=s=>{var n,o,l,d;switch(s.name){case"buffering":{const u=s.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${s.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=s.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=mi(h.name))!==null&&o!==void 0?o:vt(h.video),m=h.bitrate/1e3,v=Object.assign({},h.video);if(!p)continue;const b={id:f,quality:p,bitrate:m,size:v};c.push({track:b,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)===B.MANIFEST_READY&&this.videoState.setState(B.MANIFEST_READY);break}case"qualitySwitch":{const u=s.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),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=s;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(s.shiftDuration),this.zeroTime$.next(s.zeroTime);break}}},this.syncPlayback=()=>{var s;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!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(B.STOPPED));return}if(!o){if(bS.includes(n)){const c=(s=this.params.desiredState.videoTrack.getTransition())===null||s===void 0?void 0:s.to;a.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===C.Requested&&mS.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_READY),this.dash.attachSource(Nt(this.params.source.url));return;case B.MANIFEST_READY:this.videoState.startTransitionTo(B.READY),this.prepare();break;case B.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(B.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(B.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(B.PAUSED)})}return;case B.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(B.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case B.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.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(B.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=ze(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(ce(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 r=We(this.video);this.subscription.add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())===null||s===void 0?void 0:s.to)===B.READY&&this.videoState.setState(B.READY)},t)).add(r.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED)},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(B.PLAYING)},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:s,position:n})=>this.params.output.liveTime$.next(s+n*1e3),t)).add(mt(this.video,this.params.desiredState.isLooped,t)).add(qe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(et(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:s}})=>{const n=s&&Tb(s);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(s=>{var n;switch(s.to){case B.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case B.MANIFEST_READY:case B.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 B.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case B.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(s.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}createLiveDashPlayer(){const e=new vS({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,r,s,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=(s=(r=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||r===void 0?void 0:r.to)!==null&&s!==void 0?s:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:(n=vi(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;a.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 r=(t=this.representations$.getValue().find(({track:s})=>s.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(r,`No such representation ${e}`),this.dash.switchByName(r.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,r=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(r),this.dash.reinit(Nt(this.params.source.url,r))}}var jl=i=>{var e,t;const r=i.get("X-Delivery-Type"),s=i.get("X-Reused"),n=r===null?exports.HttpConnectionType.HTTP1:(e=r)!==null&&e!==void 0?e:void 0,o=s===null?void 0:(t={1:!0,0:!1}[s])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},lt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){const s=i.start(r)*1e3,n=i.end(r)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const gS=i=>{const e=document.createElement("a");return e.href=i,e.origin},yS=i=>{const e=document.createElement("a");return e.href=i,e.host};class Hl{constructor(e,t=[],r,s,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=r,this._progressCb=s,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,r,s,n,o,l,d,u;if(a.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(r=this._errorCb)===null||r===void 0||r.call(this,`Http${(s=this._xhr)===null||s===void 0?void 0:s.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=hi(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 r;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(r=this._errorCb)===null||r===void 0||r.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let s;this._failoverIndex>=this._failoverHosts.length?(s=this._url,this._failoverIndex=0):(s=this._url.replace(yS(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",s,!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 ir{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(r){if(r.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let n=0;for(let o=0,l=s.length;o<l;o++)n+=s.end(o)-s.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",r),r}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,r,s,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=v=>{s(ir._str2ua(v.substr(d))),d=v.length};let m=e.baseURL+"&bytes="+t+"-"+r;this._params.requestQuic&&(m=Dt(m)),this._lastXhr=new Hl(m,e.failoverHosts,v=>{this._lastXhr=void 0,p(v);const b=Date.now()-u;this._params.onBandwidthChange({size:v.length,duration:b,speed:8*v.length/(b/1e3)}),this._onDashCallback("loading",{size:v.length,done:!0}),n==null||n()},v=>{if(v.length-d>l&&p(v),h===0){h=Date.now();return}f=v.length-c;const b=Date.now()-h;f>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:f,duration:b,speed:8*f/(b/1e3)}),f=0,c=v.length,h=Date.now()),this._onDashCallback("loading",{size:v.length,done:!1})},o,(v,b,S)=>this._params.onError(v,b,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(r){throw this._params.onError("SourceBuffer","Source Buffer update error",r),r}};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=ir._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 r=new Uint8Array(e.byteLength+t.byteLength);return r.set(e,0),r.set(t,e.byteLength),r}static _str2ua(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);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 TS{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)?)?$/,r=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},s=t.exec(e),n=(s==null?void 0:s[1])==="-"?-1:1,o={years:r(s==null?void 0:s[2],n),months:r(s==null?void 0:s[3],n),weeks:r(s==null?void 0:s[4],n),days:r(s==null?void 0:s[5],n),hours:r(s==null?void 0:s[6],n),minutes:r(s==null?void 0:s[7],n),seconds:r(s==null?void 0:s[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let r=e;this._config.REQUEST_QUIC&&(r=Dt(r)),new Hl(r,t,s=>{this.attachManifest(s,t,gS(r))},void 0,s=>{this._params.onResponseHeaders(s)},(s,n,o)=>this._params.onError(s,n,o))}attachManifest(e,t,r){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,p,m,v,b,S,g,P,E,T,w,F,O,I,U,N,_;const G=u.getElementsByTagName("SegmentBase")[0],K=G&&o(G,"indexRange").split("-"),te=G&&G.getElementsByTagName("Initialization")[0],$=te&&o(te,"range").split("-");if(!$||!K){const _e=u.parentElement;if((_e==null?void 0:_e.getAttribute("contentType"))==="text"){const Mt=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,j=(r?r+"/":"")+((m=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||m===void 0?void 0:m.data),ae=(v=_e.getAttribute("lang"))!==null&&v!==void 0?v:void 0;j&&d.push({id:Mt,url:j,language:ae})}return}const D=.1,z=Number((b=u.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),ee=(r?r+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ie;const he=(g=(S=u.attributes.getNamedItem("frameRate"))===null||S===void 0?void 0:S.value)!==null&&g!==void 0?g:void 0;ie=he?fa(he):void 0,l.push({width:Number((P=u.attributes.getNamedItem("width"))===null||P===void 0?void 0:P.value),height:Number((E=u.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:z,baseURL:ee,failoverHosts:t,indexFrom:Number(K[0]),indexTo:Number(K[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:(O=(F=u.attributes.getNamedItem("mimeType"))===null||F===void 0?void 0:F.value)!==null&&O!==void 0?O:void 0,fps:ie,bufferSize:D*z/8,bufferLength:D,name:(U=(I=u.attributes.getNamedItem("okQuality"))===null||I===void 0?void 0:I.value)!==null&&U!==void 0?U:void 0,id:(_=(N=u.attributes.getNamedItem("id"))===null||N===void 0?void 0:N.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 r=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let n=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,n);const o=new DataView(s.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 p=u+(o.getUint32(n,!1)&2147483647),m=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:m/l,fromOffset:u,toOffset:p-1}),u=p,d=m}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-r)},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 r=new t;let s,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 p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const c=this._appendVector[String(u.fromTime)];c!==s&&(s=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(p);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},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=r.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new ir({mediaSource:r,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),r.duration||(r.duration=this._duration),this._loopTimeout||l(),r.removeEventListener("sourceopen",d),r.removeEventListener("webkitsourceopen",d)};r.addEventListener("sourceopen",d,!1),r.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(r),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,r=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(r){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=s||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 r=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!r||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(s.toTime<r.to+n){const o=this._findRef(s.toTime);o&&o.toTime<r.to+n?(this._buffer.smartRemove(s.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(s.fromTime-n,s.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,s.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||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return;if(Array.isArray(r)&&r.length===0){this._params.onError("emptyrefs","Empty refs");return}let s;for(let n=0;n<r.length;n++){const o=r[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!s||o.fromTime<s.fromTime)&&(s=o)}if(!s){const n=r[r.length-1];if(e>n.toTime)return n}return s}_isLastRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return!1;const s=r[r.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const r=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>r&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var M;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(M||(M={}));const ES=[M.PAUSED,M.PLAYING];class $S{constructor(e){this.videoState=new J(M.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Le,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=t=>{var r,s,n;const o=[];for(const l of t){const d=(s=(r=l.name)!==null&&r!==void 0?r:l.id)!==null&&s!==void 0?s:l.height.toString(10),u=(n=l.name&&mi(l.name))!==null&&n!==void 0?n:vt(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const p={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:p,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(M.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var r;const s=(r=this.representations$.getValue().find(({representation:n})=>n===t))===null||r===void 0?void 0:r.track;s&&(this.params.output.currentVideoTrack$.next(s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(s.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.videoState.getTransition(),s=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(r)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(o)};`}),s===exports.PlaybackState.STOPPED){t!==M.STOPPED&&(this.videoState.startTransitionTo(M.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(M.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!r)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===C.Requested&&ES.includes(t)&&this.seek(o.position,o.forcePrecise),t){case M.STOPPED:this.videoState.startTransitionTo(M.MANIFEST_LOADED),this.prepare();return;case M.MANIFEST_LOADED:this.videoState.startTransitionTo(M.INITIAL_REPRESENTATION_SELECTED);return;case M.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(M.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case M.METADATA_LOADED:this.videoState.startTransitionTo(M.READY),this.dash.updateRefsForCurrentTime();return;case M.READY:s===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed());return;case M.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(M.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case M.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(t)}`})}),this.video=ze(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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new xb(this.video),this.dash=new TS({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,r,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:r,thrown:s,category:a.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,r=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},s=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=We(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,r));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(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===M.PLAYING||this.videoState.getState()===M.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(qe(this.video,t.volume,n.volumeState$,r)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,t.playbackRate,n.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),o(tr(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===M.READY&&this.videoState.setState(M.READY)},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},r)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(M.METADATA_LOADED)},r)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},r)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.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$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),v=this.elementSize$.getValue(),b=s();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let S;if(!b&&a.isNonNullable(p))S=p;else{const g=lt(this.video.buffered,this.video.currentTime*1e3),P=b?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(g/P,1);S=(d=vi(h.map(({track:T})=>T),{container:v,throughput:m,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 a.isNonNullable(S)?(u=h.find(({track:g})=>g.id===S))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,r)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===M.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(M.INITIAL_REPRESENTATION_SELECTED),r)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?l.height<=d.height:l===d)).subscribe(l=>{const d=lt(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!s())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(ce(l.baseURL)))},r)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=jl(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.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,r)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,r)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Qe(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 a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var ge;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(ge||(ge={}));var rr;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(rr||(rr={}));var ye;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(ye||(ye={}));var H;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(H||(H={}));var Ot;(function(i){i.MP4="mp4",i.WEBM="webm"})(Ot||(Ot={}));var Fs=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const kS=(i,e={})=>{const r=e.timeout||1,s=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-s-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},PS=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",zn=PS?kS:window.requestIdleCallback;var ts,is;let Gl=!1;try{Gl=Vl()&&parseInt((is=(ts=navigator.userAgent.match(/Version\/(\d+)/))===null||ts===void 0?void 0:ts[1])!==null&&is!==void 0?is:"",10)<16}catch(i){console.error(i)}class AS{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const r=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!r),this.currentTask=null}this.queue.length&&this.pull()}catch(r){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:r})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return Q(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(r=>{const s={operation:"append",data:e,signal:t,callback:r};this.queue.push(s),this.pull()})})}remove(e,t,r){return Q(this,void 0,void 0,function*(){return r&&r.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:r,callback:s};this.queue.unshift(n),this.pull()})})}abort(e){return Q(this,void 0,void 0,function*(){return new Promise(t=>{let r;Gl&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.buffer.abort()}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:r}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&r==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"&&r==="remove"||this.error$.next({id:`BufferTaskQueue:${r}`,category:a.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:a.assertNever(t)}}}var Wn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const Yl=new TextDecoder("ascii"),ql=i=>{let e=0,t=i.getUint32(e);e+=4;const r=new DataView(i.buffer,i.byteOffset+e,4),s=Yl.decode(r);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,i.byteLength)-e,o=new DataView(i.buffer,i.byteOffset+e,n);return{id:s,size:t,contents:o}},wS=i=>Yl.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",_S=(i,e,t)=>{const r=ql(i),s=[];let n=0;const o=()=>{const v=r.contents.getUint32(n);return n+=4,v};if((o()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");o();const u=o(),c=o(),h=o(),f=o()&4294967295;let p=c/u*1e3,m=(t?t.to+1:i.byteOffset+i.byteLength)+h;for(let v=0;v<f;v++){const b=o(),S=b>>>31,g=b<<1>>>1,P=o();if(o(),S!==0)throw new Error("Unsupported multilevel sidx");const E=P/u*1e3;s.push({status:H.NONE,time:{from:p,to:p+E},byte:{from:m,to:m+g-1}}),p+=E,m+=g}return s},RS=i=>{let e=0,t=!1,r=!1;for(;e<=i.byteLength&&!t;){const s=new DataView(i.buffer,i.byteOffset+e);try{const n=ql(s);if(r||(r=n.id==="mdat"),e+n.size<=i.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=i.byteLength&&r?new DataView(i.buffer,i.byteOffset,e):null},IS={validateData:wS,parseInit:()=>null,getIndexRange:()=>{},parseSegments:_S,parseFeedableSegmentChunk:RS};var y;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(y||(y={}));var A;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(A||(A={}));const Qn={[y.EBML]:{type:A.Master},[y.EBMLVersion]:{type:A.UnsignedInteger},[y.EBMLReadVersion]:{type:A.UnsignedInteger},[y.EBMLMaxIDLength]:{type:A.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:A.UnsignedInteger},[y.DocType]:{type:A.String},[y.DocTypeVersion]:{type:A.UnsignedInteger},[y.DocTypeReadVersion]:{type:A.UnsignedInteger},[y.Void]:{type:A.Binary},[y.Segment]:{type:A.Master},[y.SeekHead]:{type:A.Master},[y.Seek]:{type:A.Master},[y.SeekID]:{type:A.Binary},[y.SeekPosition]:{type:A.UnsignedInteger},[y.Info]:{type:A.Master},[y.TimestampScale]:{type:A.UnsignedInteger},[y.Duration]:{type:A.Float},[y.Tracks]:{type:A.Master},[y.Chapters]:{type:A.Master},[y.Cluster]:{type:A.Master},[y.Timestamp]:{type:A.UnsignedInteger},[y.SilentTracks]:{type:A.Master},[y.SilentTrackNumber]:{type:A.UnsignedInteger},[y.Position]:{type:A.UnsignedInteger},[y.PrevSize]:{type:A.UnsignedInteger},[y.SimpleBlock]:{type:A.Binary},[y.BlockGroup]:{type:A.Master},[y.EncryptedBlock]:{type:A.Binary},[y.Attachments]:{type:A.Master},[y.Tags]:{type:A.Master},[y.Cues]:{type:A.Master},[y.CuePoint]:{type:A.Master},[y.CueTime]:{type:A.UnsignedInteger},[y.CueTrackPositions]:{type:A.Master},[y.CueTrack]:{type:A.UnsignedInteger},[y.CueClusterPosition]:{type:A.UnsignedInteger},[y.CueRelativePosition]:{type:A.UnsignedInteger},[y.CueDuration]:{type:A.UnsignedInteger},[y.CueBlockNumber]:{type:A.UnsignedInteger},[y.CueCodecState]:{type:A.UnsignedInteger},[y.CueReference]:{type:A.Master},[y.CueRefTime]:{type:A.UnsignedInteger}},zl=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const r=sr(i,t),s=r in Qn,n=s?Qn[r].type:A.Binary,o=i.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(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,c=sr(d),h=u*Math.pow(2,(l-1)*8)+c,f=t+l;let p;return f+h>i.byteLength?p=new DataView(i.buffer,i.byteOffset+f):p=new DataView(i.buffer,i.byteOffset+f,h),{tag:s?r:"0x"+r.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},sr=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Fe=(i,e)=>{switch(e){case A.SignedInteger:return i.getInt8(0);case A.UnsignedInteger:return sr(i);case A.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case A.String:return new TextDecoder("ascii").decode(i);case A.UTF8:return new TextDecoder("utf-8").decode(i);case A.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case A.Master:return i;case A.Binary:return i;default:a.assertNever(e)}},bi=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=zl(r);if(!e(s))return;s.type===A.Master&&bi(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},NS=i=>{if(i.getUint32(0)!==y.EBML)return!1;let e,t,r;const s=zl(i);return bi(s.value,({tag:n,type:o,value:l})=>(n===y.EBMLReadVersion?e=Fe(l,o):n===y.DocType?t=Fe(l,o):n===y.DocTypeReadVersion&&(r=Fe(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},Wl=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],CS=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],DS=i=>{let e,t,r,s,n=!1,o=!1,l=!1,d,u;return bi(i,({tag:c,type:h,value:f,valueSize:p})=>{if(c===y.SeekID){const m=Fe(f,h);u=sr(m)}else c!==y.SeekPosition&&(u=void 0);return c===y.Segment?(e=f.byteOffset,t=f.byteOffset+p):c===y.Info?n=!0:c===y.SeekHead?o=!0:c===y.TimestampScale?r=Fe(f,h):c===y.Duration?s=Fe(f,h):c===y.SeekPosition&&u===y.Cues?d=Fe(f,h):n&&o&&Wl.includes(c)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(s,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(s/1e9*r*1e3),cuesSeekPosition:d}},OS=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},LS=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return bi(i,({tag:l,type:d,value:u})=>{switch(l){case y.Cues:t=!0;break;case y.CuePoint:o&&s(o)&&n.push(o),o={};break;case y.CueTime:o&&(o.time=Fe(u,d));break;case y.CueTrackPositions:break;case y.CueClusterPosition:o&&(o.position=Fe(u,d));break;default:t&&Wl.includes(l)&&(r=!0)}return!(t&&r)}),o&&s(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:H.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}}})},xS=i=>{let e=0,t=!1;try{bi(i,r=>r.tag===y.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):CS.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},BS={validateData:NS,parseInit:DS,getIndexRange:OS,parseSegments:LS,parseFeedableSegmentChunk:xS};class Jn{constructor(e,t,r,s,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new ut,this.destroyAbortController=new ut,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(u){return Pe(this,arguments,function*(){const c=this.representations.get(u);a.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 AS(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},m=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:m}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(m=>{if(!this.sourceBuffer)return;const v=Math.min(this.bufferLimit,Wn(this.sourceBuffer.buffered)*.8);this.bufferLimit=v,this.pruneBuffer(this.getCurrentPosition(),m)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(m=>this.error$.next(m))),yield yield R(this.loadInit(c,"high",!0));const h=this.initData.get(c.id),f=this.segments.get(c.id);if(a.assertNonNullable(h,"No init buffer for starting representation"),a.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return yield R(void 0);let p=0;for(const m of f)m.time.from-p>0&&this.gaps.push({representation:c.id,from:p,to:m.time.from}),p=m.time.to;a.isNonNullable(c.duration)&&c.duration-p>0&&this.gaps.push({representation:c.id,from:p,to:c.duration}),yield yield R(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(u){return Pe(this,arguments,function*(){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return yield R(void 0);this.switchingToRepresentationId=u;const c=this.representations.get(u);a.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(a.isNullable(h)?yield yield R(this.loadInit(c,"high",!1)):h instanceof Promise&&(yield yield R(h)),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return yield R(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield yield R(this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal));const f=this.getCurrentPosition();a.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=r,r){case Ot.MP4:this.containerParser=IS;break;case Ot.WEBM:this.containerParser=BS;break;default:a.assertNever(r)}this.initData=new Map(s.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(s.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 ut,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;const s=r.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=lt(this.sourceBuffer.buffered,e),h=s?s.time.to+100:-1/0;s&&c>=s.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&Wn(this.sourceBuffer.buffered)>=this.bufferLimit){const u=lt(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(r,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(l.includes(s))u="high";else{const c=Me(l,0);c&&c.time.from-s.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===H.FED&&!l.length&&lt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Me(r,-1);d&&d.status===H.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===d))}findSegmentStartTime(e){var t,r,s;const n=(r=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&r!==void 0?r: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(s=l==null?void 0:l.time.from)!==null&&s!==void 0?s: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,r){const s=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const v=f<=r&&p>=r,b=f>r||v||m===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&f<=r+S||p<=r+S;return(h===H.NONE||h===H.PARTIALLY_EJECTED&&b&&g&&this.sourceBuffer&&!Fs(this.sourceBuffer.buffered,r))&&b&&g});if(s===-1)return[];if(t!==ye.BYTE_RANGE)return e.slice(s,s+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=s;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===H.NONE||f.status===H.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,r="auto"){return Q(this,void 0,void 0,function*(){if(!e.length)return;let s,n,o=e;const{type:l}=t.segmentReference;switch(l){case ye.BYTE_RANGE:{s=t.segmentReference.url,n={from:Me(e,0).byte.from,to:Me(e,-1).byte.to};break}case ye.TEMPLATE:{const u=Me(e,0);s=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=H.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield a.abortable(d,function(){return Pe(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(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(s,{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:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:r}).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 r=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(r=lt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,r||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,r,s,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=H.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const m of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])m.status===H.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=H.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,p=u===ye.BYTE_RANGE,m=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=r&&f.byte.to<r+e.byteLength))continue;if(n.aborted){o();continue}const b=p?f.byte.from-r:0,S=p?f.byte.to-r:e.byteLength,g=b<s,P=S<=s;if(f.status===H.DOWNLOADING&&g&&P){f.status=H.DOWNLOADED,this.activeSegments.delete(h);const E=new DataView(e.buffer,e.byteOffset+b,m);this.sourceBufferTaskQueue.append(E,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(h.loadedBytes=Math.min(m,s-b),h.loadedBytes>h.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+b+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===m?E:this.containerParser.parseFeedableSegmentChunk(E);T!=null&&T.byteLength&&(f.status=H.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===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){e.status===H.PARTIALLY_FED||e.status===H.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=H.NONE),e.status=H.PARTIALLY_EJECTED):e.status=H.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[s,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const r=this.representations.get(e);r&&(this.initLoadIdleCallback=zn(()=>vr(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return Q(this,void 0,void 0,function*(){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!r&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Pe(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).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),r&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,r=!1){return Q(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let s=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;s+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;c.status===H.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){s=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)||s>t)break;c.status===H.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 p of f)if(p.status===H.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&r){s=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===H.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 r of t){let s={representation:e,from:r.time.from,to:r.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<=r.time.from||o>=r.time.to)){if(o<=r.time.from&&l>=r.time.to){s=void 0;break}l>r.time.from&&l<r.time.to&&(s.from=l),o<r.time.to&&o>r.time.from&&(s.to=o)}}s&&s.to-s.from>=1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=zn(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){const s=Math.round(this.sourceBuffer.buffered.start(r)*1e3),n=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:s,to:n})}const t=1;for(const r of this.segments.values())for(const s of r){const{status:n}=s;if(n!==H.FED&&n!==H.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),l=Math.ceil(s.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?s.status=H.PARTIALLY_EJECTED:s.status=H.NONE)}}}var _t;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(_t||(_t={}));class MS{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new ut,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return Pe(this,arguments,function*(){let n=s;this.requestQuic&&(n=Dt(n));const o=yield yield R(Ct(n,{signal:this.abortAllController.signal}).catch(Xt));return o?(this.onHeadersReceived(o.headers),yield R(o.text())):yield R(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?_t.HEADER:_t.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,m;return Pe(this,arguments,function*(){let v=s;const b=new Headers;if(o)switch(n){case _t.HEADER:{b.append("Range",`bytes=${o.from}-${o.to}`);break}case _t.PARAM:{const $=new URL(v,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),v=$.toString();break}default:a.assertNever(n)}this.requestQuic&&(v=Dt(v));let S=this.abortAllController.signal;if(u){const $=new ut;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.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=a.now(),P=yield yield R(Ct(v,{priority:d,headers:b,signal:S}).catch(Xt)),E=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-g),!P)return yield R(null);if(!P.ok||!P.body)return yield R(Promise.reject(new Error(`Fetch error ${P.status}: ${P.statusText}`)));this.onHeadersReceived(P.headers);const T=parseInt((f=P.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!T){const $=yield yield R(P.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed($.byteLength,a.now()-E),l==null||l(new DataView($),$.byteLength),yield R($)}if(!l&&!c)return yield R(P.arrayBuffer());const[w,F]=P.body.tee(),O=w.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(F));let I=0;const U=new ArrayBuffer(T),N=new Uint8Array(U),_=new DataView(U);let G=!1;const K=$=>{G=!0,Xt($)},te=a.abortable(S,function({done:$,value:D}){return Pe(this,arguments,function*(){if(I===0&&this.lastRequestFirstBytes$.next(a.now()-g),S.aborted)return yield R(void 0);$?l==null||l(_,I):D&&(N.set(D,I),I+=D.byteLength,l==null||l(_,I),yield yield R(O==null?void 0:O.read().then(te,K)))})}.bind(this));return yield yield R(O==null?void 0:O.read().then(te,K)),yield R(G?null:U)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){var l;return Pe(this,arguments,function*(){if(s.type!==ye.BYTE_RANGE)return yield R(null);const{from:d,to:u}=s.initRange;let c=d,h=u,f=!1,p,m;s.indexRange&&(p=s.indexRange.from,m=s.indexRange.to,f=u+1===p,f&&(c=Math.min(p,d),h=Math.max(m,u))),c=Math.min(c,0);const v=yield yield R(this.fetch(s.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!v)return yield R(null);const b=new DataView(v,d-c,u-c+1);if(!n.validateData(b))throw new Error("Invalid media file");const S=n.parseInit(b),g=(l=s.indexRange)!==null&&l!==void 0?l:n.getIndexRange(S);if(!g)throw new ReferenceError("No way to load representation index");let P;if(f)P=new DataView(v,g.from-c,g.to-g.from+1);else{const T=yield yield R(this.fetch(s.url,{range:g,priority:o,measureThroughput:!1}));if(!T)return yield R(null);P=new DataView(T)}const E=n.parseSegments(P,S,g);return yield R({dataView:new DataView(v),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return Pe(this,arguments,function*(){if(s.type!==ye.TEMPLATE)return yield R(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield R(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield R(null);const d=s.segments.map(u=>Object.assign(Object.assign({},u),{status:H.NONE,size:void 0}));return yield R({segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=jl(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){var s,n;return Q(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case ye.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case ye.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,r))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Xt=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var VS=He,FS=ni,US=ue,jS=US("match"),HS=function(i){var e;return VS(i)&&((e=i[jS])!==void 0?!!e:FS(i)=="RegExp")},GS=ci,YS=String,qS=function(i){if(GS(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return YS(i)},zS=Ye,WS=function(){var i=zS(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},QS=ve,JS=Oe,KS=nr,XS=WS,Kn=RegExp.prototype,ZS=function(i){var e=i.flags;return e===void 0&&!("flags"in Kn)&&!JS(i,"flags")&&KS(Kn,i)?QS(XS,i):e},va=$e,eg=dr,tg=Math.floor,rs=va("".charAt),ig=va("".replace),ss=va("".slice),rg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,sg=/\$([$&'`]|\d{1,2})/g,ag=function(i,e,t,r,s,n){var o=t+i.length,l=r.length,d=sg;return s!==void 0&&(s=eg(s),d=rg),ig(n,d,function(u,c){var h;switch(rs(c,0)){case"$":return"$";case"&":return i;case"`":return ss(e,0,t);case"'":return ss(e,o);case"<":h=s[ss(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=tg(f/10);return p===0?u:p<=l?r[p-1]===void 0?rs(c,1):r[p-1]+rs(c,1):u}h=r[f-1]}return h===void 0?"":h})},ng=we,og=ve,ma=$e,Xn=js,lg=se,ug=oi,dg=HS,$t=qS,cg=ur,hg=ZS,fg=ag,pg=ue,vg=pg("replace"),mg=TypeError,Ql=ma("".indexOf),bg=ma("".replace),Zn=ma("".slice),Sg=Math.max,eo=function(i,e,t){return t>i.length?-1:e===""?t:Ql(i,e,t)};ng({target:"String",proto:!0},{replaceAll:function(e,t){var r=Xn(this),s,n,o,l,d,u,c,h,f,p=0,m=0,v="";if(!ug(e)){if(s=dg(e),s&&(n=$t(Xn(hg(e))),!~Ql(n,"g")))throw mg("`.replaceAll` does not allow non-global regexes");if(o=cg(e,vg),o)return og(o,e,r,t);if(s)return bg($t(r),e,t)}for(l=$t(r),d=$t(e),u=lg(t),u||(t=$t(t)),c=d.length,h=Sg(1,c),p=eo(l,d,0);p!==-1;)f=u?$t(t(d,p,l)):fg(d,l,p,[],void 0,t),v+=Zn(l,m,p)+f,m=p+c,p=eo(l,d,p+h);return m<l.length&&(v+=Zn(l,m)),v}});var gg=ca,yg=gg("String","replaceAll"),Tg=yg,Eg=Tg,$g=Eg,kg=$g,to=kg;const io=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),s=(r==null?void 0:r[1])==="-"?-1:1,n={days:e(r==null?void 0:r[5],s),hours:e(r==null?void 0:r[6],s),minutes:e(r==null?void 0:r[7],s),seconds:e(r==null?void 0:r[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},as=(i,e)=>{let t=i;t=to(t,"$$","$");const r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(r)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=to(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Pg=(i,e)=>{var t,r,s,n,o,l,d,u,c,h,f,p,m,v,b,S,g,P,E,T,w,F,O,I,U,N,_,G,K,te,$,D,z,ee,ie,he,_e;const j=new DOMParser().parseFromString(i,"application/xml"),ae={video:[],audio:[],text:[]},de=j.children[0],me=de.getElementsByTagName("Period")[0],it=me.children;let Re;const Je=de.getAttribute("mediaPresentationDuration"),rt=me.getAttribute("duration");if(Je)Re=io(Je);else if(rt){const Ie=io(rt);a.isNonNullable(Ie)&&(Re=Ie)}let Vt=0;const bt=(r=(t=de.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&r!==void 0?r:[],tu=bt.includes(rr.WEBM_AS_IN_FFMPEG)||bt.includes(rr.WEBM_AS_IN_SPEC)?Ot.WEBM:Ot.MP4;for(const Ie of it){const Si=Ie.getAttribute("mimeType"),iu=Ie.getAttribute("codecs"),ba=(s=Ie.getAttribute("contentType"))!==null&&s!==void 0?s:Si==null?void 0:Si.split("/")[0],ru=(o=(n=Ie.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],su=Ie.querySelectorAll("Representation"),au=Ie.querySelector("SegmentTemplate");if(ba!=="text")for(const ne of su){const Ft=(l=ne.getAttribute("mimeType"))!==null&&l!==void 0?l:Si,Sa=(u=(d=ne.getAttribute("codecs"))!==null&&d!==void 0?d:iu)!==null&&u!==void 0?u:"",gi=(h=(c=ne.getAttribute("contentType"))!==null&&c!==void 0?c:Ft==null?void 0:Ft.split("/")[0])!==null&&h!==void 0?h:ba,nu=(p=(f=Ie.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&p!==void 0?p:[],ou=parseInt((m=ne.getAttribute("width"))!==null&&m!==void 0?m:"",10),ga=parseInt((v=ne.getAttribute("height"))!==null&&v!==void 0?v:"",10),ya=parseInt((b=ne.getAttribute("bandwidth"))!==null&&b!==void 0?b:"",10)/1e3,Ta=(S=ne.getAttribute("frameRate"))!==null&&S!==void 0?S:"",lu=(g=ne.getAttribute("quality"))!==null&&g!==void 0?g:void 0,uu=Ta?fa(Ta):void 0,du=(P=ne.getAttribute("id"))!==null&&P!==void 0?P:(Vt++).toString(10),cu=gi==="video"?`${ga}p`:gi==="audio"?`${ya}Kbps`:Sa,hu=`${du}@${cu}`,fu=(w=(T=(E=ne.querySelector("BaseURL"))===null||E===void 0?void 0:E.textContent)===null||T===void 0?void 0:T.trim())!==null&&w!==void 0?w:"",Ea=new URL(fu,e).toString(),pu=[...bt,...ru,...nu];let Sr;const vu=ne.querySelector("SegmentBase"),st=(F=ne.querySelector("SegmentTemplate"))!==null&&F!==void 0?F:au;if(vu){const Ut=(I=(O=ne.querySelector("SegmentBase Initialization"))===null||O===void 0?void 0:O.getAttribute("range"))!==null&&I!==void 0?I:"",[jt,yr]=Ut.split("-").map(at=>parseInt(at,10)),Ht={from:jt,to:yr},Gt=(U=ne.querySelector("SegmentBase"))===null||U===void 0?void 0:U.getAttribute("indexRange"),[Tr,yi]=Gt?Gt.split("-").map(at=>parseInt(at,10)):[],Yt=Gt?{from:Tr,to:yi}:void 0;Sr={type:ye.BYTE_RANGE,url:Ea,initRange:Ht,indexRange:Yt}}else if(st){const Ut={representationId:(N=ne.getAttribute("id"))!==null&&N!==void 0?N:void 0,bandwidth:(_=ne.getAttribute("bandwidth"))!==null&&_!==void 0?_:void 0},jt=parseInt((G=st.getAttribute("timescale"))!==null&&G!==void 0?G:"",10),yr=(K=st.getAttribute("initialization"))!==null&&K!==void 0?K:"",Ht=st.getAttribute("media"),Gt=($=parseInt((te=st.getAttribute("startNumber"))!==null&&te!==void 0?te:"",10))!==null&&$!==void 0?$:1,Tr=as(yr,Ut);if(!Ht)throw new ReferenceError("No media attribute in SegmentTemplate");const yi=(D=st.querySelectorAll("SegmentTimeline S"))!==null&&D!==void 0?D:[],Yt=[];if(yi.length){let at=Gt,nt=0;for(const qt of yi){const St=parseInt((z=qt.getAttribute("d"))!==null&&z!==void 0?z:"",10)*1e3,zt=parseInt((ee=qt.getAttribute("r"))!==null&&ee!==void 0?ee:"",10)||0,Wt=(he=parseInt((ie=qt.getAttribute("t"))!==null&&ie!==void 0?ie:"",10))!==null&&he!==void 0?he:void 0;for(let $a=0;$a<zt+1;$a++){const mu=as(Ht,Object.assign(Object.assign({},Ut),{segmentNumber:at.toString(10),segmentTime:Wt.toString(10)})),bu=Wt?Wt/jt:nt;nt+=St/jt;const Su=nt;at++,Yt.push({time:{from:bu,to:Su},url:mu})}}}else if(a.isNonNullable(Re)){const nt=parseInt((_e=st.getAttribute("duration"))!==null&&_e!==void 0?_e:"",10)/jt*1e3,qt=Math.ceil(Re/nt);let St=0;for(let zt=1;zt<qt;zt++){const Wt=as(Ht,Object.assign(Object.assign({},Ut),{segmentNumber:zt.toString(10),segmentTime:St.toString(10)}));Yt.push({time:{from:St,to:St+nt},url:Wt}),St+=nt}}Sr={type:ye.TEMPLATE,baseUrl:Ea,initUrl:Tr,segments:Yt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!gi||!Ft)continue;const gr={video:ge.VIDEO,audio:ge.AUDIO,text:ge.TEXT}[gi];gr&&ae[gr].push({id:hu,kind:gr,segmentReference:Sr,profiles:pu,duration:Re,bitrate:ya,mime:Ft,codecs:Sa,width:ou,height:ga,fps:uu,quality:lu})}}return{duration:Re,container:tu,representations:ae}},Ag=["timeupdate","progress","play","seeked","stalled","waiting"];var Se;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Se||(Se={}));let wg=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.state$=new J(Se.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new ut,this.initManifest=a.abortable(this.destroyController.signal,function(t,r){return Pe(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(Se.MANIFEST_READY);const s=yield yield R(this.fetcher.fetchManifest(r).catch(l=>this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l})));if(!s)return yield R(void 0);let n;try{n=Pg(s!=null?s:"",r)}catch(l){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return yield R(void 0);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=Object.assign(Object.assign({},n),{representations:hi(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))}),this.manifest.representations.video.length?this.state$.setState(Se.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,r){return Pe(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.state$.startTransitionTo(Se.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new Jn(ge.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new Jn(ge.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),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=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.subscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.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:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield yield R(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(r)?yield yield R(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield R(this.videoBufferManager.startWith(t)),this.state$.setState(Se.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;const s=this.element.currentTime*1e3;this.videoBufferManager.maintain(s),(t=this.audioBufferManager)===null||t===void 0||t.maintain(s),(this.videoBufferManager.gaps.length||!((r=this.audioBufferManager)===null||r===void 0)&&r.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new MS({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(Se.RUNNING),this.subscription.add(a.merge(...Ag.map(e=>a.fromEvent(this.element,e)),a.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:a.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(a.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(a.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Fs(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return Q(this,void 0,void 0,function*(){const r={[ge.VIDEO]:this.videoBufferManager,[ge.AUDIO]:this.audioBufferManager,[ge.TEXT]:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var r,s,n,o,l;a.assertNonNullable(this.element),a.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((r=this.videoBufferManager.findSegmentStartTime(e))!==null&&r!==void 0?r:e,(n=(s=this.audioBufferManager)===null||s===void 0?void 0:s.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Fs(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(Se.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 r of this.bufferManagers)for(const s of r.gaps)r.playingRepresentation$.getValue()===s.representation&&s.from<=e&&s.to>e&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?t.push(1/0):t.push(s.to));if(t.length){const r=Math.max(...t);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};var X;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));const _g=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?mi(n):void 0)!==null&&o!==void 0?o:vt({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},Rg=({id:i,bitrate:e})=>({id:i,bitrate:e}),Ig=(i,e,t)=>{var r;const s=e.indexOf(t);return(r=Me(i,Math.round(i.length*s/e.length)))!==null&&r!==void 0?r:Me(i,-1)};class Ng{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(X.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Le,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new eS,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===C.Requested&&(s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&t!==X.STOPPED&&r!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),r===exports.PlaybackState.STOPPED){t!==X.STOPPED&&(this.videoState.startTransitionTo(X.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(X.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(t){case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();return;case X.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case X.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case X.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}}},this.params=e,this.video=ze(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(ce(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new wg({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=We(this.video),s=u=>{e.error$.next({id:"DashVKProvider",category:a.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,c)=>this.subscription.add(u.subscribe(c,s));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.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(a.filter(a.isNonNullable),a.once(),a.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(mt(this.video,t.isLooped,s)),this.subscription.add(qe(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(et(this.video,t.playbackRate,r.playbackRateState$,s)),n(tr(this.video),this.elementSize$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===Se.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const h=this.player.getRepresentations();a.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((v,b)=>b.bitrate-v.bitrate),p=Array.from(h.video).sort((v,b)=>b.bitrate-v.bitrate);if(!this.params.tuning.isAudioDisabled)for(const v of f){const b=Rg(v);b&&this.audioTracks.push({track:b,representation:v})}for(const v of p){const b=_g(v);if(b){this.videoTracks.push({track:b,representation:v});const S=!this.params.tuning.isAudioDisabled&&Ig(f,p,v);S&&this.audioRepresentations.set(v.id,S)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const m=this.selectVideoRepresentation();a.assertNonNullable(m),this.player.initRepresentations(m.id,(c=this.audioRepresentations.get(m.id))===null||c===void 0?void 0:c.id)}else u===Se.REPRESENTATIOS_READY&&(this.videoState.setState(X.READY),this.player.initBuffer())},s));const o=u=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==Se.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(ge.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(ge.AUDIO,f.id).catch(o)}},s)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.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$,s)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.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(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){var e,t,r,s,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=lt(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(u&&!l&&(r=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&r!==void 0?r:0,c&&(n=(s=this.audioRepresentations.get(c.id))===null||s===void 0?void 0:s.bitrate)!==null&&n!==void 0?n:0),v=vi(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:m,forwardBufferHealth:p,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),b=l?v!=null?v:u:u!=null?u:v;return b&&((o=this.videoTracks.find(({track:S})=>S===b))===null||o===void 0?void 0:o.representation)}prepare(){return Q(this,void 0,void 0,function*(){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),Qe(this.video)}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const Cg=5e3,xe={};var V;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const Bi=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class Dg{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(V.INITIALIZING),this.textTracksManager=new Le,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==V.INITIALIZING)switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&this.seek(n.position),r){case exports.PlaybackState.STOPPED:switch(t){case V.STOPPED:break;case V.READY:case V.PLAYING:case V.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case V.STOPPED:this.prepare();break;case V.READY:case V.PLAYING:case V.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case V.PLAYING:break;case V.STOPPED:this.prepare();break;case V.READY:case V.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case V.PAUSED:break;case V.STOPPED:this.prepare();break;case V.READY:this.videoState.setState(V.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case V.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(r)}},this.video=ze(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(ce(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),Qe(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),Cg);vr(import("hls.js").then(s=>{e||(xe.Hls=s.default,xe.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(xe.Hls,"hls.js not loaded"),this.hls=new xe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(V.STOPPED)}subscribe(){a.assertNonNullable(xe.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},s=We(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,r));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),n(s.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(mt(this.video,e.isLooped,r)),this.subscription.add(qe(this.video,e.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,e.playbackRate,s.playbackRateState$,r)),this.subscription.add(Bi(this.hls,xe.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.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(s.playing$.subscribe(()=>{this.videoState.setState(V.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(V.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===V.READY&&this.videoState.setState(V.READY),this.videoState.getState()===V.PLAYING&&this.playIfAllowed()},r)),n(Bi(this.hls,xe.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const m=h.name||h.height.toString(10),{width:v,height:b}=h,S=(p=mi((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:vt({width:v,height:b});if(!S)return c;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,P={id:m.toString(),quality:S,bitrate:h.bitrate/1e3,size:{width:v,height:b},fps:g};return this.trackLevels.set(m,{track:P,level:h}),c.push(P),c},[]))),t.availableVideoTracks$),n(Bi(this.hls,xe.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>ce(u))),t.hostname$),this.subscription.add(De(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));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=Bi(this.hls,xe.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(De(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(a.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),p=this.hls.currentLevel,m=this.hls.levels[p];!m||h.bitrate>m.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(a.map(u=>u==null?void 0:u.id)),onError:r})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo(V.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return Q(this,void 0,void 0,function*(){this.videoState.startTransitionTo(V.PLAYING),(yield tt(this.video))||(this.videoState.setState(V.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(V.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(V.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const ro="X-Playback-Duration";var so=i=>Q(void 0,void 0,void 0,function*(){const e=yield Ct(i,{method:"HEAD"});return e.headers.has(ro)?parseInt(e.headers.get(ro),10):void 0});const Og=i=>{let e=null;if(i.QUALITY&&(e=mi(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=vt({width:t,height:r})}return e!=null?e:null},Jl=(i,e=i)=>Q(void 0,void 0,void 0,function*(){var t;const n=(yield(yield Ct(i)).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=hi(u[1].split(",").map(S=>S.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Og(c);let p;c.BANDWIDTH&&(p=parseInt(c.BANDWIDTH,10)/1e3||void 0),!p&&c["AVERAGE-BANDWIDTH"]&&(p=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let v;if(c.RESOLUTION){const[S,g]=c.RESOLUTION.split("x").map(P=>parseInt(P,10));S&&g&&(v={width:S,height:g})}const b=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:b,bandwidth:p,size:v,fps:m})}return o});var Y;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(Y||(Y={}));class Lg{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new J(Y.STOPPED),this.textTracksManager=new Le,this.manifests$=new a.ValueSubject([]),this.liveOffset=new ha,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{const s=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){s!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.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(Y.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(s===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(Y.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===C.Requested){this.videoState.startTransitionTo(Y.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(s){case Y.READY:n===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.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 Y.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.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 Y.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=ze(e.container),this.params.output.element$.next(this.video);const r={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([r]),Jl(Nt(this.params.source.url),this.params.source.url).then(s=>{this.manifests$.next([r,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),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(ce(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},s=We(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(qe(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(s.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&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ce(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===Y.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===C.Requested&&this.seek(l.position)},r)),this.subscription.add(s.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)},r)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),r)),this.subscription.add(this.manifests$.pipe(a.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$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=Nt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),so(t).then(r=>{var s;if(!a.isNullable(r))this.maxSeekBackTime$.next(r);else{const n=(s=this.params.source.maxSeekBackTime)!==null&&s!==void 0?s:this.maxSeekBackTime$.getValue();if(a.isNullable(n)||!isFinite(n))try{Ct(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();so(u).then(c=>{a.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}}var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(W||(W={}));class xg{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(W.STOPPED),this.textTracksManager=new Le,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s===exports.PlaybackState.STOPPED){r!==W.STOPPED&&(this.videoState.startTransitionTo(W.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(W.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(r===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(W.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===C.Requested&&this.seek(u.position),r){case W.READY:s===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case W.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=ze(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(ce(this.params.source.url)),Jl(this.params.source.url).then(r=>{this.manifests$.next([t,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},s=We(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(qe(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},r).add(s.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&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ce(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===W.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===C.Requested&&this.seek(l.position)},r))),this.subscription.add(this.manifests$.pipe(a.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$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var Z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Z||(Z={}));class Bg{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(Z.STOPPED),this.trackUrls={},this.textTracksManager=new Le,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==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 o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(t===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:d*1e3,forcePrecise:!0});return}switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&l.state===C.Requested&&this.seek(l.position),t){case Z.READY:r===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.video=ze(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,r],s)=>{const n=s.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:r}}),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,r=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},s=We(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(qe(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(this.video,t.playbackRate,s.playbackRateState$,r)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Z.READY&&this.videoState.setState(Z.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&a.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Qe(this.video)}prepare(){var e,t;const r=(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();a.assertNonNullable(r,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[r];a.assertNonNullable(s,`MpegProvider: No url for ${r}`),this.params.tuning.requestQuick&&(s=Dt(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(ce(s))}playIfAllowed(){tt(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}}const ao=["stun:videostun.mycdn.me:80"],Mg=1e3,Vg=3,ns=()=>null;class Fg{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=ns,this.externalStopCallback=ns,this.externalErrorCallback=ns,this.options=this.normalizeOptions(t);const r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.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}}handleUpdateMessage(e){return Q(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return Q(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:ao}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return Q(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return Q(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:a.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return Q(this,void 0,void 0,function*(){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()))}}createOffer(){return Q(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))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),Mg)}normalizeOptions(e={}){const t={stunServerList:ao,maxRetryNumber:Vg,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));class Ug{constructor(e){this.videoState=new J(q.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==q.STOPPED&&(this.videoState.startTransitionTo(q.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(q.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===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case q.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ze(e.container),this.liveStreamClient=new Fg(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),Qe(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const s=We(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,r));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===q.READY&&this.videoState.setState(q.READY)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED)},r)).add(s.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING)},r)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(qe(this.video,t.volume,s.volumeState$,r)).add(s.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case q.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case q.READY:break;case q.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case q.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},r)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}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(ce(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(q.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:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class no{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 jg=()=>{var i,e;const t=window.navigator;return t.userAgentData?((e=(i=t.userAgentData)===null||i===void 0?void 0:i.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},os,ls,us,ds,cs,hs,Mi,fs,Vi,ps,Fi,vs,Ui,ms,ji,bs;const Kl=jg(),Ke=document.createElement("video"),Be={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((ls=(os=window.SourceBuffer)===null||os===void 0?void 0:os.prototype)===null||ls===void 0?void 0:ls.appendBuffer)),hls:Boolean(((us=Ke.canPlayType)===null||us===void 0?void 0:us.call(Ke,"application/x-mpegurl"))||((ds=Ke.canPlayType)===null||ds===void 0?void 0:ds.call(Ke,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},be={mp4:Boolean((cs=Ke.canPlayType)===null||cs===void 0?void 0:cs.call(Ke,"video/mp4")),webm:Boolean((hs=Ke.canPlayType)===null||hs===void 0?void 0:hs.call(Ke,"video/webm")),cmaf:!0},Xe={h264:Boolean((fs=(Mi=window.MediaSource)===null||Mi===void 0?void 0:Mi.isTypeSupported)===null||fs===void 0?void 0:fs.call(Mi,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((ps=(Vi=window.MediaSource)===null||Vi===void 0?void 0:Vi.isTypeSupported)===null||ps===void 0?void 0:ps.call(Vi,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((vs=(Fi=window.MediaSource)===null||Fi===void 0?void 0:Fi.isTypeSupported)===null||vs===void 0?void 0:vs.call(Fi,'video/webm; codecs="vp9"')),aac:Boolean((ms=(Ui=window.MediaSource)===null||Ui===void 0?void 0:Ui.isTypeSupported)===null||ms===void 0?void 0:ms.call(Ui,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((bs=(ji=window.MediaSource)===null||ji===void 0?void 0:ji.isTypeSupported)===null||bs===void 0?void 0:bs.call(ji,'audio/webm; codecs="opus"'))},kt=(Xe.h264||Xe.h265)&&Xe.aac,br=Be.hls&&be.mp4,Hg=Boolean(window.WebSocket),Gg=()=>Object.keys(Xe).filter(i=>Xe[i]),Yg=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return Be.mse&&be.mp4&&kt;case exports.VideoFormat.DASH_SEP:return Be.mse&&be.mp4&&kt;case exports.VideoFormat.DASH_WEBM:return Be.mse&&be.webm&&Xe.vp9&&Xe.opus;case exports.VideoFormat.DASH_LIVE:return Be.mse&&be.mp4&&kt;case exports.VideoFormat.DASH_LIVE_CMAF:return Be.mse&&be.mp4&&kt&&be.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return Be.mse&&be.mp4&&kt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return br||e&&Be.mse&&be.mp4&&kt;case exports.VideoFormat.MPEG:return be.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Be.webrtc&&Hg&&Xe.h264&&(be.mp4||be.webm);default:return a.assertNever(t)}}),qg=()=>Kl?[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]:br?[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],zg=()=>Kl?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:br?[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],oo=i=>i?[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 Wg=i=>new a.Observable(e=>{const t=new a.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),s=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$,o=new a.Subject;let l=0,d="unknown";return t.add(r.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(l),d="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const lo={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Qg={cacheDuration:12e4},Jg={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Kg={maxPausedTime:3e4},uo={maxPausedTime:3e4};class Xg{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),element$:new a.ValueSubject(void 0)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Yg([...zg(),...qg()],this.params.tuning.useHlsJs).filter(o=>a.isNonNullable(e.sources[o])),{formatsToAvoid:r}=this.params.tuning,s=r.length?[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:t;this.screenFormatsIterator=new no(s);const n=[...oo(!0),...oo(!1)];this.chromecastFormatsIterator=new no(n.filter(o=>a.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(a.isNullable(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}r?this.current$.next({type:t,provider:r,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;a.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,r=this.params.desiredState.seekState.getState(),s=r.state!==C.None;this.params.desiredState.seekState.setState({state:C.Requested,position:s?r.position:t,forcePrecise:s?r.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 fe.SCREEN:return this.createScreenProvider(t);case fe.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:r,desiredState:s}=this.params,n=this.providerOutput,o={container:r,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new $S(Object.assign(Object.assign({},o),{source:l,config:Qg}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new Yn(Object.assign(Object.assign({},o),{source:l,format:e,config:uo})):new Ng(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Yn(Object.assign(Object.assign({},o),{source:l,format:e,config:uo}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),br||!this.params.tuning.useHlsJs?new xg(Object.assign(Object.assign({},o),{source:l})):new Dg(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Lg(Object.assign(Object.assign({},o),{source:l,config:Kg}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Bg(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new SS(Object.assign(Object.assign({},o),{source:l,config:Jg}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Ug({container:r,source:l,desiredState:s,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 a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:r,desiredState:s,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new Ab({connection:l,meta:n,container:r,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?fe.CHROMECAST:fe.SCREEN}chooseFormat(e){switch(e){case fe.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case fe.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case fe.SCREEN:return this.screenFormatsIterator.next();case fe.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case fe.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case fe.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const r=s=>{const n=new URL(s);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 Object.assign(Object.assign({},e),{url:r(e.url)})}return hi(Object.entries(e).map(([s,n])=>[s,r(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,r=0;return e.add(a.merge(this.providerOutput.error$,Wg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:lo.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(a.filter(({type:s})=>s!==void 0))}).pipe(a.map(s=>({id:`ProviderHangup:${s}`,category:a.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{if(this.current$.getValue().destination===fe.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=s.category===a.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<lo.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var Te;(function(i){i[i.LOCAL_STORAGE=0]="LOCAL_STORAGE",i[i.SESSION_STORAGE=1]="SESSION_STORAGE",i[i.RUNTIME=2]="RUNTIME"})(Te||(Te={}));const Xl=new Map;let dt=Te.RUNTIME;const Ss=`vk-videoplayer-dummy-key-${Math.random()}`,Zg=()=>{try{localStorage.setItem(Ss,"test"),localStorage.removeItem(Ss),dt=Te.LOCAL_STORAGE}catch(i){if(i instanceof DOMException||i instanceof TypeError)try{sessionStorage.getItem(Ss),dt=Te.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)dt=Te.RUNTIME;else throw e}else throw i}};Zg();const ey=i=>{var e,t;switch(dt){case Te.LOCAL_STORAGE:return(e=localStorage.getItem(i))!==null&&e!==void 0?e:void 0;case Te.SESSION_STORAGE:return(t=sessionStorage.getItem(i))!==null&&t!==void 0?t:void 0;case Te.RUNTIME:return Xl.get(i);default:a.assertNever(dt)}},co=(i,e)=>{switch(dt){case Te.LOCAL_STORAGE:try{localStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Te.SESSION_STORAGE:try{sessionStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Te.RUNTIME:return void Xl.set(i,e);default:a.assertNever(dt)}},Us=(i,e,t)=>t*e+(1-t)*i,Zl=(i,e)=>i.reduce((t,r)=>t+r,0)/e,ty=(i,e,t,r)=>{let s=0,n=t;const o=Zl(i,e),l=e<r?e:r;for(let d=0;d<l;d++)i[n]>o?s++:s--,n=(i.length+n-1)%i.length;return Math.abs(s)===l};class eu{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 a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const r=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ce(`raw_${r}`),this.smoothedSeries$=new Ce(`smoothed_${r}`),this.reportedSeries$=new Ce(`reported_${r}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;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)&&(a.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 iy extends eu{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Us(this.slow,e,this.params.emaAlphaSlow),this.fast=Us(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class ry extends eu{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Zl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Us(this.emaSmoothed,e,this.params.emaAlpha);const r=ty(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}}class ho{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new iy({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ry({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}}const sy=5e3,fo="one_video_throughput",po="one_video_rtt",je=window.navigator.connection,vo=()=>{const i=je==null?void 0:je.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},mo=()=>{const i=je==null?void 0:je.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},bo=(i,e,t)=>{const r=t*8,s=r/i;return r/(s+e)};class ri{constructor(e){var t,r;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const s=ri.load(fo)||(e.useBrowserEstimation?vo():void 0)||sy,n=(r=(t=ri.load(po))!==null&&t!==void 0?t:e.useBrowserEstimation?mo():void 0)!==null&&r!==void 0?r:0;if(this.throughput$=new a.ValueSubject(s),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(bo(s,n,e.rttPenaltyRequestSize)),this.throughput=ho.getSmoothedValue(s,-1,e),this.rtt=ho.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=vo();d&&this.throughput.next(d);const u=mo();a.isNonNullable(u)&&this.rtt.next(u)};je&&"onchange"in je&&this.subscription.add(a.fromEvent(je,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{co(fo,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{co(po,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(a.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a.map(({throughput:o,rtt:l})=>bo(o,l,e.rttPenaltyRequestSize)),a.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,r=a.now();const s=new a.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,r=a.now()}));break;case 1:case 0:s.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,r=a.now()}));break}s.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-r;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let r=0;const s=a.now();let n=0,o=a.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=({done:u,value:c})=>Q(this,void 0,void 0,function*(){u?(this.addRawSpeed(r,a.now()-s,1),this.concurrentDownloads.delete(e)):c&&(r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&a.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,a.now()-o,this.concurrentDownloads.size),n=0,o=a.now()),yield t==null?void 0:t.read().then(d,l))});this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,r=1){if(ri.sanityCheck(e,t)){const s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||e<10*1024||t<=20)}static load(e){var t;const r=ey(e);if(a.isNonNullable(r))return(t=parseInt(r,10))!==null&&t!==void 0?t:void 0}}const So={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}},ay=i=>{const e={};for(const t of Object.keys(So)){const r=So[t],s=i[t];Array.isArray(r)&&Array.isArray(s)?e[t]=s:typeof r=="object"&&typeof s=="object"?e[t]=Object.assign(Object.assign({},r),s):e[t]=s!=null?s:r}return e};var ny=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var r;return t.state===C.None?void 0:((r=t.position)!==null&&r!==void 0?r:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===C.None))),oy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const go=({playbackState:i,seekState:e,playbackAbort$:t,looped$:r,position$:s})=>new a.Observable(n=>{let o;const l=i.transitionEnded$.pipe(a.filter(p=>(p.from===exports.PlaybackState.PAUSED||p.from===exports.PlaybackState.STOPPED)&&p.to===exports.PlaybackState.PLAYING)),d=i.stateChangeEnded$.pipe(a.filter(p=>p.from===exports.PlaybackState.PLAYING&&p.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(a.filter(({to:p})=>{var m,v;return p.state===C.Requested&&((v=(m=i.getTransition())===null||m===void 0?void 0:m.from)!==null&&v!==void 0?v:i.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(a.filter(({from:p,to:m})=>{var v,b;return p.state===C.Applying&&m.state===C.None&&((b=(v=i.getTransition())===null||v===void 0?void 0:v.from)!==null&&b!==void 0?b:i.getState())===exports.PlaybackState.PLAYING})),h=a.merge(l,c).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable)),f=a.merge(a.merge(d,u,t),r).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable));return new a.Subscription().add(h.subscribe(p=>{o=p})).add(f.subscribe(p=>{if(a.isNullable(o)||o===p)return;const m={from:o,to:p};o=void 0,n.next(m)}))});class ly{constructor(e={}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new J(exports.PlaybackState.STOPPED),seekState:new J({state:C.None}),volume:new J({volume:1,muted:!1}),videoTrack:new J(void 0),autoVideoTrackSwitching:new J(!0),autoVideoTrackLimits:new J({}),isLooped:new J(!1),playbackRate:new J(1),externalTextTracks:new J([]),currentTextTrack:new J(void 0),textTrackCuesSettings:new J({})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0)},this.events={inited$:new a.Subject,started$:new a.Subject,willPause$:new a.Subject,willResume$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:Kb},this.initLogs(),this.tuning=ay(e),this.chromecastInitializer=new Ru({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ri(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,s)=>{const n=Reflect.get(t,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,p)=>{const m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,r,s;return this.config=e,this.domContainer=oy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Xg({sources:e.sources,meta:(r=e.meta)!==null&&r!==void 0?r:{},failoverHosts:(s=e.failoverHosts)!==null&&s!==void 0?s:[],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:C.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){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const r=t.find(s=>s.quality===e);return r&&this.desiredState.videoTrack.startTransitionTo(r.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const r=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return r&&(this.desiredState.playbackRate.setState(e),r.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(r=>r.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(){a.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),r=t.state===C.None?void 0:t.position;return a.isNonNullable(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((r,{width:s})=>r||s||0,0),height:e.reduce((r,{height:s})=>r||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(()=>!this.isPlaybackStarted),a.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===C.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},d),{state:C.Applying})):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===C.Applying&&(this.desiredState.seekState.setState({state:C.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(d=>d.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(d=>d.map(({quality:u})=>u).sort((u,c)=>Zi(u)?1:Zi(c)?-1:qi(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(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.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(a.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(a.map(d=>d.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(d=>d.volume),a.filterChanged()).subscribe(this.info.volume$)).add(ny({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.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(a.map(d=>({id:"NoProviders",category:a.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(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.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 a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const r=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:d})=>d===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>r.next(!1)));let s=0;const n=a.merge(e.providerOutput.isBuffering$,t,r).pipe(a.map(()=>{const d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||r.getValue();return d&&!u}),a.filterChanged());this.subscription.add(n.subscribe(d=>{d?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))}));const o=new a.Subscription;this.subscription.add(o);const l=a.merge(a.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(a.filter(d=>Boolean(d==null?void 0:d.provider))));e.providerOutput.isLive$.pipe(a.filterChanged()).subscribe(d=>{switch(a.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new a.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>u.next(c&&Math.floor(c/1e3)))),o.add(go({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:l,looped$:this.events.looped$,position$:u}).pipe(a.map(({from:c,to:h})=>({start:c,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(go({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:l,position$:this.providerContainer.providerOutput.position$}).pipe(a.map(({from:u,to:c})=>({start:u,end:c}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(a.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(a.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 a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((r,s)=>r.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:r})=>r===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=vi(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(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.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;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),Jb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Qb(r)),this.providerContainer.current$.subscribe(({type:r})=>Oi("provider",r)),t.duration$.subscribe(r=>Oi("duration",r)),t.availableVideoTracks$.pipe(a.filter(r=>!!r.length),a.once()).subscribe(r=>Oi("tracks",r)),this.events.fatalError$.subscribe(new Ce("fatalError")),this.events.managedError$.subscribe(new Ce("managedError")),t.position$.subscribe(new Ce("position")),t.currentVideoTrack$.pipe(a.map(r=>r==null?void 0:r.quality)).subscribe(new Ce("quality")),this.info.currentBuffer$.subscribe(new Ce("buffer")),t.isBuffering$.subscribe(new Ce("isBuffering"))].forEach(r=>this.subscription.add(r)),Oi("codecs",Gg())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},r=()=>Q(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:a.ErrorCategory.DOM,message:String(s)})})});this.subscription.add(a.merge(a.fromEvent(document,"visibilitychange"),a.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const s=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=Boolean(e)&&!(e!=null&&e.released);s&&n?o||r():t()})).add(this.events.willDestruct$.subscribe(t))}}const uy=`${wu}@${Au}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});exports.Player=ly;exports.SDK_VERSION=uy;
6
+ "use strict";var gu=Object.create;var ka=Object.defineProperty;var yu=Object.getOwnPropertyDescriptor;var Eu=Object.getOwnPropertyNames;var Tu=Object.getPrototypeOf,$u=Object.prototype.hasOwnProperty;var ku=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Eu(e))!$u.call(i,s)&&s!==t&&ka(i,s,{get:()=>e[s],enumerable:!(r=yu(e,s))||r.enumerable});return i};var Pa=(i,e,t)=>(t=i!=null?gu(Tu(i)):{},ku(e||!i||!i.__esModule?ka(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),Pu=require("lodash/debounce.js");const Au="2.0.84",wu="es2015.cjs.js";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var fe;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(fe||(fe={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var C;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(C||(C={}));function Q(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(c){try{u(r.next(c))}catch(h){o(h)}}function d(c){try{u(r.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):s(c.value).then(l,d)}u((r=r.apply(i,e||[])).next())})}function R(i){return this instanceof R?(this.v=i,this):new R(i)}function Pe(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(m,v){n.push([f,p,m,v])>1||l(f,p)})})}function l(f,p){try{d(r[f](p))}catch(m){h(n[0][3],m)}}function d(f){f.value instanceof R?Promise.resolve(f.value.v).then(u,c):h(n[0][2],f)}function u(f){l("next",f)}function c(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}var _u=i=>new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});class Ru{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const r="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${r}`}),e.isDisabled||!r)return;const s=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||_u("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.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 r,s,n;(n=(s=(r=cast.framework.CastContext.getInstance())===null||r===void 0?void 0:r.getCurrentSession())===null||s===void 0?void 0:s.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.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),r=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{var n,o;switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=r.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 a.assertNever(s.sessionState)}})).add(a.merge(a.fromEvent(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),a.map(s=>s.castState)),a.observableFrom([r.getCastState()])).pipe(a.filterChanged(),a.map(Iu),a.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{var n;const o=s===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=r.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.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(s===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){var e;let t,r,s;try{t=cast.framework.CastContext.getInstance(),r=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:r,autoJoinPolicy:s}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Iu=i=>{switch(i){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 a.assertNever(i)}};var Aa=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Te=function(i){try{return!!i()}catch(e){return!0}},Nu=Te,ar=!Nu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),yo=ar,Eo=Function.prototype,gs=Eo.call,Cu=yo&&Eo.bind.bind(gs,gs),$e=yo?Cu:function(i){return function(){return gs.apply(i,arguments)}},To=$e,Du=To({}.toString),Ou=To("".slice),ni=function(i){return Ou(Du(i),8,-1)},Lu=$e,xu=Te,Bu=ni,Tr=Object,Mu=Lu("".split),Vu=xu(function(){return!Tr("z").propertyIsEnumerable(0)})?function(i){return Bu(i)=="String"?Mu(i,""):Tr(i)}:Tr,oi=function(i){return i==null},Fu=oi,Uu=TypeError,js=function(i){if(Fu(i))throw Uu("Can't call method on "+i);return i},ju=Vu,Hu=js,li=function(i){return ju(Hu(i))},Gu=function(){},Lt={},Ei=function(i){return i&&i.Math==Math&&i},le=Ei(typeof globalThis=="object"&&globalThis)||Ei(typeof window=="object"&&window)||Ei(typeof self=="object"&&self)||Ei(typeof Aa=="object"&&Aa)||function(){return this}()||Function("return this")(),ys=typeof document=="object"&&document.all,Yu=typeof ys=="undefined"&&ys!==void 0,$o={all:ys,IS_HTMLDDA:Yu},ko=$o,qu=ko.all,se=ko.IS_HTMLDDA?function(i){return typeof i=="function"||i===qu}:function(i){return typeof i=="function"},zu=le,Wu=se,wa=zu.WeakMap,Qu=Wu(wa)&&/native code/.test(String(wa)),_a=se,Po=$o,Ju=Po.all,He=Po.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:_a(i)||i===Ju}:function(i){return typeof i=="object"?i!==null:_a(i)},Ku=Te,Ge=!Ku(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ht={},Xu=le,Ra=He,Es=Xu.document,Zu=Ra(Es)&&Ra(Es.createElement),Hs=function(i){return Zu?Es.createElement(i):{}},ed=Ge,td=Te,id=Hs,Ao=!ed&&!td(function(){return Object.defineProperty(id("div"),"a",{get:function(){return 7}}).a!=7}),rd=Ge,sd=Te,wo=rd&&sd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),ad=He,nd=String,od=TypeError,Ye=function(i){if(ad(i))return i;throw od(nd(i)+" is not an object")},ld=ar,Ti=Function.prototype.call,ve=ld?Ti.bind(Ti):function(){return Ti.apply(Ti,arguments)},Gs={},$r=Gs,kr=le,ud=se,Ia=function(i){return ud(i)?i:void 0},ft=function(i,e){return arguments.length<2?Ia($r[i])||Ia(kr[i]):$r[i]&&$r[i][e]||kr[i]&&kr[i][e]},dd=$e,nr=dd({}.isPrototypeOf),or=typeof navigator!="undefined"&&String(navigator.userAgent)||"",_o=le,Pr=or,Na=_o.process,Ca=_o.Deno,Da=Na&&Na.versions||Ca&&Ca.version,Oa=Da&&Da.v8,ke,Wi;Oa&&(ke=Oa.split("."),Wi=ke[0]>0&&ke[0]<4?1:+(ke[0]+ke[1]));!Wi&&Pr&&(ke=Pr.match(/Edge\/(\d+)/),(!ke||ke[1]>=74)&&(ke=Pr.match(/Chrome\/(\d+)/),ke&&(Wi=+ke[1])));var Ro=Wi,La=Ro,cd=Te,Io=!!Object.getOwnPropertySymbols&&!cd(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&La&&La<41}),hd=Io,No=hd&&!Symbol.sham&&typeof Symbol.iterator=="symbol",fd=ft,pd=se,vd=nr,md=No,bd=Object,Co=md?function(i){return typeof i=="symbol"}:function(i){var e=fd("Symbol");return pd(e)&&vd(e.prototype,bd(i))},Sd=String,lr=function(i){try{return Sd(i)}catch(e){return"Object"}},gd=se,yd=lr,Ed=TypeError,pt=function(i){if(gd(i))return i;throw Ed(yd(i)+" is not a function")},Td=pt,$d=oi,ur=function(i,e){var t=i[e];return $d(t)?void 0:Td(t)},Ar=ve,wr=se,_r=He,kd=TypeError,Pd=function(i,e){var t,r;if(e==="string"&&wr(t=i.toString)&&!_r(r=Ar(t,i))||wr(t=i.valueOf)&&!_r(r=Ar(t,i))||e!=="string"&&wr(t=i.toString)&&!_r(r=Ar(t,i)))return r;throw kd("Can't convert object to primitive value")},Qi={},Ad={get exports(){return Qi},set exports(i){Qi=i}},Do=!0,xa=le,wd=Object.defineProperty,_d=function(i,e){try{wd(xa,i,{value:e,configurable:!0,writable:!0})}catch(t){xa[i]=e}return e},Rd=le,Id=_d,Ba="__core-js_shared__",Nd=Rd[Ba]||Id(Ba,{}),Ys=Nd,Ma=Ys;(Ad.exports=function(i,e){return Ma[i]||(Ma[i]=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 Cd=js,Dd=Object,dr=function(i){return Dd(Cd(i))},Od=$e,Ld=dr,xd=Od({}.hasOwnProperty),Oe=Object.hasOwn||function(e,t){return xd(Ld(e),t)},Bd=$e,Md=0,Vd=Math.random(),Fd=Bd(1 .toString),Oo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Fd(++Md+Vd,36)},Ud=le,jd=Qi,Va=Oe,Hd=Oo,Gd=Io,Yd=No,Pt=Ud.Symbol,Rr=jd("wks"),qd=Yd?Pt.for||Pt:Pt&&Pt.withoutSetter||Hd,ue=function(i){return Va(Rr,i)||(Rr[i]=Gd&&Va(Pt,i)?Pt[i]:qd("Symbol."+i)),Rr[i]},zd=ve,Fa=He,Ua=Co,Wd=ur,Qd=Pd,Jd=ue,Kd=TypeError,Xd=Jd("toPrimitive"),Zd=function(i,e){if(!Fa(i)||Ua(i))return i;var t=Wd(i,Xd),r;if(t){if(e===void 0&&(e="default"),r=zd(t,i,e),!Fa(r)||Ua(r))return r;throw Kd("Can't convert object to primitive value")}return e===void 0&&(e="number"),Qd(i,e)},ec=Zd,tc=Co,qs=function(i){var e=ec(i,"string");return tc(e)?e:e+""},ic=Ge,rc=Ao,sc=wo,$i=Ye,ja=qs,ac=TypeError,Ir=Object.defineProperty,nc=Object.getOwnPropertyDescriptor,Nr="enumerable",Cr="configurable",Dr="writable";ht.f=ic?sc?function(e,t,r){if($i(e),t=ja(t),$i(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Dr in r&&!r[Dr]){var s=nc(e,t);s&&s[Dr]&&(e[t]=r.value,r={configurable:Cr in r?r[Cr]:s[Cr],enumerable:Nr in r?r[Nr]:s[Nr],writable:!1})}return Ir(e,t,r)}:Ir:function(e,t,r){if($i(e),t=ja(t),$i(r),rc)try{return Ir(e,t,r)}catch(s){}if("get"in r||"set"in r)throw ac("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var cr=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},oc=Ge,lc=ht,uc=cr,ui=oc?function(i,e,t){return lc.f(i,e,uc(1,t))}:function(i,e,t){return i[e]=t,i},dc=Qi,cc=Oo,Ha=dc("keys"),zs=function(i){return Ha[i]||(Ha[i]=cc(i))},Ws={},hc=Qu,Lo=le,fc=He,pc=ui,Or=Oe,Lr=Ys,vc=zs,mc=Ws,Ga="Object already initialized",Ts=Lo.TypeError,bc=Lo.WeakMap,Ji,si,Ki,Sc=function(i){return Ki(i)?si(i):Ji(i,{})},gc=function(i){return function(e){var t;if(!fc(e)||(t=si(e)).type!==i)throw Ts("Incompatible receiver, "+i+" required");return t}};if(hc||Lr.state){var Ne=Lr.state||(Lr.state=new bc);Ne.get=Ne.get,Ne.has=Ne.has,Ne.set=Ne.set,Ji=function(i,e){if(Ne.has(i))throw Ts(Ga);return e.facade=i,Ne.set(i,e),e},si=function(i){return Ne.get(i)||{}},Ki=function(i){return Ne.has(i)}}else{var gt=vc("state");mc[gt]=!0,Ji=function(i,e){if(Or(i,gt))throw Ts(Ga);return e.facade=i,pc(i,gt,e),e},si=function(i){return Or(i,gt)?i[gt]:{}},Ki=function(i){return Or(i,gt)}}var xo={set:Ji,get:si,has:Ki,enforce:Sc,getterFor:gc},yc=ar,Bo=Function.prototype,Ya=Bo.apply,qa=Bo.call,Mo=typeof Reflect=="object"&&Reflect.apply||(yc?qa.bind(Ya):function(){return qa.apply(Ya,arguments)}),Ec=ni,Tc=$e,Vo=function(i){if(Ec(i)==="Function")return Tc(i)},Qs={},Fo={},Uo={}.propertyIsEnumerable,jo=Object.getOwnPropertyDescriptor,$c=jo&&!Uo.call({1:2},1);Fo.f=$c?function(e){var t=jo(this,e);return!!t&&t.enumerable}:Uo;var kc=Ge,Pc=ve,Ac=Fo,wc=cr,_c=li,Rc=qs,Ic=Oe,Nc=Ao,za=Object.getOwnPropertyDescriptor;Qs.f=kc?za:function(e,t){if(e=_c(e),t=Rc(t),Nc)try{return za(e,t)}catch(r){}if(Ic(e,t))return wc(!Pc(Ac.f,e,t),e[t])};var Cc=Te,Dc=se,Oc=/#|\.prototype\./,di=function(i,e){var t=xc[Lc(i)];return t==Mc?!0:t==Bc?!1:Dc(e)?Cc(e):!!e},Lc=di.normalize=function(i){return String(i).replace(Oc,".").toLowerCase()},xc=di.data={},Bc=di.NATIVE="N",Mc=di.POLYFILL="P",Ho=di,Wa=Vo,Vc=pt,Fc=ar,Uc=Wa(Wa.bind),hr=function(i,e){return Vc(i),e===void 0?i:Fc?Uc(i,e):function(){return i.apply(e,arguments)}},ki=le,jc=Mo,Hc=Vo,Gc=se,Yc=Qs.f,qc=Ho,yt=Gs,zc=hr,Et=ui,Qa=Oe,Wc=function(i){var e=function(t,r,s){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,s)}return jc(i,this,arguments)};return e.prototype=i.prototype,e},we=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?ki:s?ki[t]:(ki[t]||{}).prototype,l=r?yt:yt[t]||Et(yt,t,{})[t],d=l.prototype,u,c,h,f,p,m,v,b,S;for(f in e)u=qc(r?f:t+(s?".":"#")+f,i.forced),c=!u&&o&&Qa(o,f),m=l[f],c&&(i.dontCallGetSet?(S=Yc(o,f),v=S&&S.value):v=o[f]),p=c&&v?v:e[f],!(c&&typeof m==typeof p)&&(i.bind&&c?b=zc(p,ki):i.wrap&&c?b=Wc(p):n&&Gc(p)?b=Hc(p):b=p,(i.sham||p&&p.sham||m&&m.sham)&&Et(b,"sham",!0),Et(l,f,b),n&&(h=t+"Prototype",Qa(yt,h)||Et(yt,h,{}),Et(yt[h],f,p),i.real&&d&&(u||!d[f])&&Et(d,f,p)))},$s=Ge,Qc=Oe,Go=Function.prototype,Jc=$s&&Object.getOwnPropertyDescriptor,Js=Qc(Go,"name"),Kc=Js&&function(){}.name==="something",Xc=Js&&(!$s||$s&&Jc(Go,"name").configurable),Zc={EXISTS:Js,PROPER:Kc,CONFIGURABLE:Xc},Yo={},eh=Math.ceil,th=Math.floor,ih=Math.trunc||function(e){var t=+e;return(t>0?th:eh)(t)},rh=ih,Ks=function(i){var e=+i;return e!==e||e===0?0:rh(e)},sh=Ks,ah=Math.max,nh=Math.min,oh=function(i,e){var t=sh(i);return t<0?ah(t+e,0):nh(t,e)},lh=Ks,uh=Math.min,dh=function(i){return i>0?uh(lh(i),9007199254740991):0},ch=dh,Xs=function(i){return ch(i.length)},hh=li,fh=oh,ph=Xs,Ja=function(i){return function(e,t,r){var s=hh(e),n=ph(s),o=fh(r,n),l;if(i&&t!=t){for(;n>o;)if(l=s[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in s)&&s[o]===t)return i||o||0;return!i&&-1}},vh={includes:Ja(!0),indexOf:Ja(!1)},mh=$e,xr=Oe,bh=li,Sh=vh.indexOf,gh=Ws,Ka=mh([].push),yh=function(i,e){var t=bh(i),r=0,s=[],n;for(n in t)!xr(gh,n)&&xr(t,n)&&Ka(s,n);for(;e.length>r;)xr(t,n=e[r++])&&(~Sh(s,n)||Ka(s,n));return s},qo=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Eh=yh,Th=qo,$h=Object.keys||function(e){return Eh(e,Th)},kh=Ge,Ph=wo,Ah=ht,wh=Ye,_h=li,Rh=$h;Yo.f=kh&&!Ph?Object.defineProperties:function(e,t){wh(e);for(var r=_h(t),s=Rh(t),n=s.length,o=0,l;n>o;)Ah.f(e,l=s[o++],r[l]);return e};var Ih=ft,zo=Ih("document","documentElement"),Nh=Ye,Ch=Yo,Xa=qo,Dh=Ws,Oh=zo,Lh=Hs,xh=zs,Za=">",en="<",ks="prototype",Ps="script",Wo=xh("IE_PROTO"),Br=function(){},Qo=function(i){return en+Ps+Za+i+en+"/"+Ps+Za},tn=function(i){i.write(Qo("")),i.close();var e=i.parentWindow.Object;return i=null,e},Bh=function(){var i=Lh("iframe"),e="java"+Ps+":",t;return i.style.display="none",Oh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Qo("document.F=Object")),t.close(),t.F},Pi,Hi=function(){try{Pi=new ActiveXObject("htmlfile")}catch(e){}Hi=typeof document!="undefined"?document.domain&&Pi?tn(Pi):Bh():tn(Pi);for(var i=Xa.length;i--;)delete Hi[ks][Xa[i]];return Hi()};Dh[Wo]=!0;var Jo=Object.create||function(e,t){var r;return e!==null?(Br[ks]=Nh(e),r=new Br,Br[ks]=null,r[Wo]=e):r=Hi(),t===void 0?r:Ch.f(r,t)},Mh=Te,Vh=!Mh(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Fh=Oe,Uh=se,jh=dr,Hh=zs,Gh=Vh,rn=Hh("IE_PROTO"),As=Object,Yh=As.prototype,Ko=Gh?As.getPrototypeOf:function(i){var e=jh(i);if(Fh(e,rn))return e[rn];var t=e.constructor;return Uh(t)&&e instanceof t?t.prototype:e instanceof As?Yh:null},qh=ui,Zs=function(i,e,t,r){return r&&r.enumerable?i[e]=t:qh(i,e,t),i},zh=Te,Wh=se,Qh=He,Jh=Jo,sn=Ko,Kh=Zs,Xh=ue,ws=Xh("iterator"),Xo=!1,Ue,Mr,Vr;[].keys&&(Vr=[].keys(),"next"in Vr?(Mr=sn(sn(Vr)),Mr!==Object.prototype&&(Ue=Mr)):Xo=!0);var Zh=!Qh(Ue)||zh(function(){var i={};return Ue[ws].call(i)!==i});Zh?Ue={}:Ue=Jh(Ue);Wh(Ue[ws])||Kh(Ue,ws,function(){return this});var Zo={IteratorPrototype:Ue,BUGGY_SAFARI_ITERATORS:Xo},ef=ue,tf=ef("toStringTag"),el={};el[tf]="z";var ea=String(el)==="[object z]",rf=ea,sf=se,Gi=ni,af=ue,nf=af("toStringTag"),of=Object,lf=Gi(function(){return arguments}())=="Arguments",uf=function(i,e){try{return i[e]}catch(t){}},ci=rf?Gi:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=uf(e=of(i),nf))=="string"?t:lf?Gi(e):(r=Gi(e))=="Object"&&sf(e.callee)?"Arguments":r},df=ea,cf=ci,hf=df?{}.toString:function(){return"[object "+cf(this)+"]"},ff=ea,pf=ht.f,vf=ui,mf=Oe,bf=hf,Sf=ue,an=Sf("toStringTag"),ta=function(i,e,t,r){if(i){var s=t?i:i.prototype;mf(s,an)||pf(s,an,{configurable:!0,value:e}),r&&!ff&&vf(s,"toString",bf)}},gf=Zo.IteratorPrototype,yf=Jo,Ef=cr,Tf=ta,$f=Lt,kf=function(){return this},Pf=function(i,e,t,r){var s=e+" Iterator";return i.prototype=yf(gf,{next:Ef(+!r,t)}),Tf(i,s,!1,!0),$f[s]=kf,i},Af=we,wf=ve,tl=Zc,_f=Pf,Rf=Ko,If=ta,nn=Zs,Nf=ue,on=Lt,il=Zo,Cf=tl.PROPER;tl.CONFIGURABLE;il.IteratorPrototype;var Ai=il.BUGGY_SAFARI_ITERATORS,Fr=Nf("iterator"),ln="keys",wi="values",un="entries",Df=function(){return this},Of=function(i,e,t,r,s,n,o){_f(t,e,r);var l=function(S){if(S===s&&f)return f;if(!Ai&&S in c)return c[S];switch(S){case ln:return function(){return new t(this,S)};case wi:return function(){return new t(this,S)};case un:return function(){return new t(this,S)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[Fr]||c["@@iterator"]||s&&c[s],f=!Ai&&h||l(s),p=e=="Array"&&c.entries||h,m,v,b;if(p&&(m=Rf(p.call(new i)),m!==Object.prototype&&m.next&&(If(m,d,!0,!0),on[d]=Df)),Cf&&s==wi&&h&&h.name!==wi&&(u=!0,f=function(){return wf(h,this)}),s)if(v={values:l(wi),keys:n?f:l(ln),entries:l(un)},o)for(b in v)(Ai||u||!(b in c))&&nn(c,b,v[b]);else Af({target:e,proto:!0,forced:Ai||u},v);return o&&c[Fr]!==f&&nn(c,Fr,f,{name:s}),on[e]=f,v},Lf=function(i,e){return{value:i,done:e}},xf=li,ia=Gu,dn=Lt,rl=xo,Bf=ht.f,Mf=Of,_i=Lf,Vf=Do,Ff=Ge,sl="Array Iterator",Uf=rl.set,jf=rl.getterFor(sl);Mf(Array,"Array",function(i,e){Uf(this,{type:sl,target:xf(i),index:0,kind:e})},function(){var i=jf(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,_i(void 0,!0)):t=="keys"?_i(r,!1):t=="values"?_i(e[r],!1):_i([r,e[r]],!1)},"values");var cn=dn.Arguments=dn.Array;ia();ia();ia();if(!Vf&&Ff&&cn.name!=="values")try{Bf(cn,"name",{value:"values"})}catch(i){}var Hf=ue,Gf=Lt,Yf=Hf("iterator"),qf=Array.prototype,zf=function(i){return i!==void 0&&(Gf.Array===i||qf[Yf]===i)},Wf=ci,hn=ur,Qf=oi,Jf=Lt,Kf=ue,Xf=Kf("iterator"),al=function(i){if(!Qf(i))return hn(i,Xf)||hn(i,"@@iterator")||Jf[Wf(i)]},Zf=ve,ep=pt,tp=Ye,ip=lr,rp=al,sp=TypeError,ap=function(i,e){var t=arguments.length<2?rp(i):e;if(ep(t))return tp(Zf(t,i));throw sp(ip(i)+" is not iterable")},np=ve,fn=Ye,op=ur,lp=function(i,e,t){var r,s;fn(i);try{if(r=op(i,"return"),!r){if(e==="throw")throw t;return t}r=np(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return fn(r),t},up=hr,dp=ve,cp=Ye,hp=lr,fp=zf,pp=Xs,pn=nr,vp=ap,mp=al,vn=lp,bp=TypeError,Yi=function(i,e){this.stopped=i,this.result=e},mn=Yi.prototype,ra=function(i,e,t){var r=t&&t.that,s=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=up(e,r),u,c,h,f,p,m,v,b=function(g){return u&&vn(u,"normal",g),new Yi(!0,g)},S=function(g){return s?(cp(g),l?d(g[0],g[1],b):d(g[0],g[1])):l?d(g,b):d(g)};if(n)u=i.iterator;else if(o)u=i;else{if(c=mp(i),!c)throw bp(hp(i)+" is not iterable");if(fp(c)){for(h=0,f=pp(i);f>h;h++)if(p=S(i[h]),p&&pn(mn,p))return p;return new Yi(!1)}u=vp(i,c)}for(m=n?i.next:u.next;!(v=dp(m,u)).done;){try{p=S(v.value)}catch(g){vn(u,"throw",g)}if(typeof p=="object"&&p&&pn(mn,p))return p}return new Yi(!1)},Sp=qs,gp=ht,yp=cr,Ep=function(i,e,t){var r=Sp(e);r in i?gp.f(i,r,yp(0,t)):i[r]=t},Tp=we,$p=ra,kp=Ep;Tp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return $p(e,function(r,s){kp(t,r,s)},{AS_ENTRIES:!0}),t}});var Pp=Gs,Ap=Pp.Object.fromEntries,wp={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},_p=wp,Rp=le,Ip=ci,Np=ui,bn=Lt,Cp=ue,Sn=Cp("toStringTag");for(var Ur in _p){var gn=Rp[Ur],jr=gn&&gn.prototype;jr&&Ip(jr)!==Sn&&Np(jr,Sn,Ur),bn[Ur]=bn.Array}var Dp=Ap,Op=Dp,Lp=Op,xp=Lp,hi=xp,Bp=ni,fr=typeof process!="undefined"&&Bp(process)=="process",Mp=ft,Vp=ht,Fp=ue,Up=Ge,yn=Fp("species"),jp=function(i){var e=Mp(i),t=Vp.f;Up&&e&&!e[yn]&&t(e,yn,{configurable:!0,get:function(){return this}})},Hp=nr,Gp=TypeError,Yp=function(i,e){if(Hp(e,i))return i;throw Gp("Incorrect invocation")},qp=$e,zp=se,_s=Ys,Wp=qp(Function.toString);zp(_s.inspectSource)||(_s.inspectSource=function(i){return Wp(i)});var nl=_s.inspectSource,Qp=$e,Jp=Te,ol=se,Kp=ci,Xp=ft,Zp=nl,ll=function(){},ev=[],ul=Xp("Reflect","construct"),sa=/^\s*(?:class|function)\b/,tv=Qp(sa.exec),iv=!sa.exec(ll),Qt=function(e){if(!ol(e))return!1;try{return ul(ll,ev,e),!0}catch(t){return!1}},dl=function(e){if(!ol(e))return!1;switch(Kp(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return iv||!!tv(sa,Zp(e))}catch(t){return!0}};dl.sham=!0;var rv=!ul||Jp(function(){var i;return Qt(Qt.call)||!Qt(Object)||!Qt(function(){i=!0})||i})?dl:Qt,sv=rv,av=lr,nv=TypeError,ov=function(i){if(sv(i))return i;throw nv(av(i)+" is not a constructor")},En=Ye,lv=ov,uv=oi,dv=ue,cv=dv("species"),cl=function(i,e){var t=En(i).constructor,r;return t===void 0||uv(r=En(t)[cv])?e:lv(r)},hv=$e,fv=hv([].slice),pv=TypeError,vv=function(i,e){if(i<e)throw pv("Not enough arguments");return i},mv=or,hl=/(?:ipad|iphone|ipod).*applewebkit/i.test(mv),pe=le,bv=Mo,Sv=hr,Tn=se,gv=Oe,fl=Te,$n=zo,yv=fv,kn=Hs,Ev=vv,Tv=hl,$v=fr,Rs=pe.setImmediate,Is=pe.clearImmediate,kv=pe.process,Hr=pe.Dispatch,Pv=pe.Function,Pn=pe.MessageChannel,Av=pe.String,Gr=0,Zt={},An="onreadystatechange",ai,ot,Yr,qr;fl(function(){ai=pe.location});var aa=function(i){if(gv(Zt,i)){var e=Zt[i];delete Zt[i],e()}},zr=function(i){return function(){aa(i)}},wn=function(i){aa(i.data)},_n=function(i){pe.postMessage(Av(i),ai.protocol+"//"+ai.host)};(!Rs||!Is)&&(Rs=function(e){Ev(arguments.length,1);var t=Tn(e)?e:Pv(e),r=yv(arguments,1);return Zt[++Gr]=function(){bv(t,void 0,r)},ot(Gr),Gr},Is=function(e){delete Zt[e]},$v?ot=function(i){kv.nextTick(zr(i))}:Hr&&Hr.now?ot=function(i){Hr.now(zr(i))}:Pn&&!Tv?(Yr=new Pn,qr=Yr.port2,Yr.port1.onmessage=wn,ot=Sv(qr.postMessage,qr)):pe.addEventListener&&Tn(pe.postMessage)&&!pe.importScripts&&ai&&ai.protocol!=="file:"&&!fl(_n)?(ot=_n,pe.addEventListener("message",wn,!1)):An in kn("script")?ot=function(i){$n.appendChild(kn("script"))[An]=function(){$n.removeChild(this),aa(i)}}:ot=function(i){setTimeout(zr(i),0)});var pl={set:Rs,clear:Is},vl=function(){this.head=null,this.tail=null};vl.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var ml=vl,wv=or,_v=/ipad|iphone|ipod/i.test(wv)&&typeof Pebble!="undefined",Rv=or,Iv=/web0s(?!.*chrome)/i.test(Rv),ct=le,Rn=hr,Nv=Qs.f,Wr=pl.set,Cv=ml,Dv=hl,Ov=_v,Lv=Iv,Qr=fr,In=ct.MutationObserver||ct.WebKitMutationObserver,Nn=ct.document,Cn=ct.process,Ri=ct.Promise,Dn=Nv(ct,"queueMicrotask"),Ns=Dn&&Dn.value,Tt,Jr,Kr,Ii,On;if(!Ns){var Ni=new Cv,Ci=function(){var i,e;for(Qr&&(i=Cn.domain)&&i.exit();e=Ni.get();)try{e()}catch(t){throw Ni.head&&Tt(),t}i&&i.enter()};!Dv&&!Qr&&!Lv&&In&&Nn?(Jr=!0,Kr=Nn.createTextNode(""),new In(Ci).observe(Kr,{characterData:!0}),Tt=function(){Kr.data=Jr=!Jr}):!Ov&&Ri&&Ri.resolve?(Ii=Ri.resolve(void 0),Ii.constructor=Ri,On=Rn(Ii.then,Ii),Tt=function(){On(Ci)}):Qr?Tt=function(){Cn.nextTick(Ci)}:(Wr=Rn(Wr,ct),Tt=function(){Wr(Ci)}),Ns=function(i){Ni.head||Tt(),Ni.add(i)}}var xv=Ns,Bv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},na=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Mv=le,xt=Mv.Promise,bl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Vv=bl,Fv=fr,Uv=!Vv&&!Fv&&typeof window=="object"&&typeof document=="object",jv=le,ei=xt,Hv=se,Gv=Ho,Yv=nl,qv=ue,zv=Uv,Wv=bl,Xr=Ro,Ln=ei&&ei.prototype,Qv=qv("species"),Cs=!1,Sl=Hv(jv.PromiseRejectionEvent),Jv=Gv("Promise",function(){var i=Yv(ei),e=i!==String(ei);if(!e&&Xr===66||!(Ln.catch&&Ln.finally))return!0;if(!Xr||Xr<51||!/native code/.test(i)){var t=new ei(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[Qv]=r,Cs=t.then(function(){})instanceof r,!Cs)return!0}return!e&&(zv||Wv)&&!Sl}),fi={CONSTRUCTOR:Jv,REJECTION_EVENT:Sl,SUBCLASSING:Cs},Bt={},xn=pt,Kv=TypeError,Xv=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw Kv("Bad Promise constructor");e=r,t=s}),this.resolve=xn(e),this.reject=xn(t)};Bt.f=function(i){return new Xv(i)};var Zv=we,Xi=fr,Ze=le,pi=ve,em=Zs,tm=ta,im=jp,rm=pt,Ds=se,sm=He,am=Yp,nm=cl,gl=pl.set,oa=xv,om=Bv,lm=na,um=ml,yl=xo,Os=xt,la=fi,El=Bt,pr="Promise",Tl=la.CONSTRUCTOR,dm=la.REJECTION_EVENT;la.SUBCLASSING;var Zr=yl.getterFor(pr),cm=yl.set,hm=Os&&Os.prototype,At=Os,es=hm,$l=Ze.TypeError,Ls=Ze.document,ua=Ze.process,xs=El.f,fm=xs,pm=!!(Ls&&Ls.createEvent&&Ze.dispatchEvent),kl="unhandledrejection",vm="rejectionhandled",Bn=0,Pl=1,mm=2,da=1,Al=2,Di,Mn,bm,wl=function(i){var e;return sm(i)&&Ds(e=i.then)?e:!1},_l=function(i,e){var t=e.value,r=e.state==Pl,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{s?(r||(e.rejection===Al&&gm(e),e.rejection=da),s===!0?d=t:(l&&l.enter(),d=s(t),l&&(l.exit(),c=!0)),d===i.promise?o($l("Promise-chain cycle")):(u=wl(d))?pi(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},Rl=function(i,e){i.notified||(i.notified=!0,oa(function(){for(var t=i.reactions,r;r=t.get();)_l(r,i);i.notified=!1,e&&!i.rejection&&Sm(i)}))},Il=function(i,e,t){var r,s;pm?(r=Ls.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Ze.dispatchEvent(r)):r={promise:e,reason:t},!dm&&(s=Ze["on"+i])?s(r):i===kl&&om("Unhandled promise rejection",t)},Sm=function(i){pi(gl,Ze,function(){var e=i.facade,t=i.value,r=Vn(i),s;if(r&&(s=lm(function(){Xi?ua.emit("unhandledRejection",t,e):Il(kl,e,t)}),i.rejection=Xi||Vn(i)?Al:da,s.error))throw s.value})},Vn=function(i){return i.rejection!==da&&!i.parent},gm=function(i){pi(gl,Ze,function(){var e=i.facade;Xi?ua.emit("rejectionHandled",e):Il(vm,e,i.value)})},wt=function(i,e,t){return function(r){i(e,r,t)}},Rt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=mm,Rl(i,!0))},Bs=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw $l("Promise can't be resolved itself");var r=wl(e);r?oa(function(){var s={done:!1};try{pi(r,e,wt(Bs,s,i),wt(Rt,s,i))}catch(n){Rt(s,n,i)}}):(i.value=e,i.state=Pl,Rl(i,!1))}catch(s){Rt({done:!1},s,i)}}};Tl&&(At=function(e){am(this,es),rm(e),pi(Di,this);var t=Zr(this);try{e(wt(Bs,t),wt(Rt,t))}catch(r){Rt(t,r)}},es=At.prototype,Di=function(e){cm(this,{type:pr,done:!1,notified:!1,parent:!1,reactions:new um,rejection:!1,state:Bn,value:void 0})},Di.prototype=em(es,"then",function(e,t){var r=Zr(this),s=xs(nm(this,At));return r.parent=!0,s.ok=Ds(e)?e:!0,s.fail=Ds(t)&&t,s.domain=Xi?ua.domain:void 0,r.state==Bn?r.reactions.add(s):oa(function(){_l(s,r)}),s.promise}),Mn=function(){var i=new Di,e=Zr(i);this.promise=i,this.resolve=wt(Bs,e),this.reject=wt(Rt,e)},El.f=xs=function(i){return i===At||i===bm?new Mn(i):fm(i)});Zv({global:!0,constructor:!0,wrap:!0,forced:Tl},{Promise:At});tm(At,pr,!1,!0);im(pr);var ym=ue,Nl=ym("iterator"),Cl=!1;try{var Em=0,Fn={next:function(){return{done:!!Em++}},return:function(){Cl=!0}};Fn[Nl]=function(){return this},Array.from(Fn,function(){throw 2})}catch(i){}var Tm=function(i,e){if(!e&&!Cl)return!1;var t=!1;try{var r={};r[Nl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},$m=xt,km=Tm,Pm=fi.CONSTRUCTOR,Dl=Pm||!km(function(i){$m.all(i).then(void 0,function(){})}),Am=we,wm=ve,_m=pt,Rm=Bt,Im=na,Nm=ra,Cm=Dl;Am({target:"Promise",stat:!0,forced:Cm},{all:function(e){var t=this,r=Rm.f(t),s=r.resolve,n=r.reject,o=Im(function(){var l=_m(t.resolve),d=[],u=0,c=1;Nm(e,function(h){var f=u++,p=!1;c++,wm(l,t,h).then(function(m){p||(p=!0,d[f]=m,--c||s(d))},n)}),--c||s(d)});return o.error&&n(o.value),r.promise}});var Dm=we,Om=fi.CONSTRUCTOR,Un=xt;Un&&Un.prototype;Dm({target:"Promise",proto:!0,forced:Om,real:!0},{catch:function(i){return this.then(void 0,i)}});var Lm=we,xm=ve,Bm=pt,Mm=Bt,Vm=na,Fm=ra,Um=Dl;Lm({target:"Promise",stat:!0,forced:Um},{race:function(e){var t=this,r=Mm.f(t),s=r.reject,n=Vm(function(){var o=Bm(t.resolve);Fm(e,function(l){xm(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var jm=we,Hm=ve,Gm=Bt,Ym=fi.CONSTRUCTOR;jm({target:"Promise",stat:!0,forced:Ym},{reject:function(e){var t=Gm.f(this);return Hm(t.reject,void 0,e),t.promise}});var qm=Ye,zm=He,Wm=Bt,Ol=function(i,e){if(qm(i),zm(e)&&e.constructor===i)return e;var t=Wm.f(i),r=t.resolve;return r(e),t.promise},Qm=we,Jm=ft,Km=Do,Xm=xt,Zm=fi.CONSTRUCTOR,eb=Ol,tb=Jm("Promise"),ib=!Zm;Qm({target:"Promise",stat:!0,forced:Km},{resolve:function(e){return eb(ib&&this===tb?Xm:this,e)}});var rb=we,Ms=xt,sb=Te,ab=ft,nb=se,ob=cl,jn=Ol,lb=Ms&&Ms.prototype,ub=!!Ms&&sb(function(){lb.finally.call({then:function(){}},function(){})});rb({target:"Promise",proto:!0,real:!0,forced:ub},{finally:function(i){var e=ob(this,ab("Promise")),t=nb(i);return this.then(t?function(r){return jn(e,i()).then(function(){return r})}:i,t?function(r){return jn(e,i()).then(function(){throw r})}:i)}});var db=ft,ca=db,cb=ca,hb=cb("Promise","finally"),fb=hb,pb=fb,vb=pb,mb=vb,vr=mb,It;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(It||(It={}));var Nt=(i,e=0,t=It.OFFSET_P)=>{switch(t){case It.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case It.PLAYBACK_SHIFT:{if(e===0)return i;const r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}default:a.assertNever(t)}return i},k=(i,e,t=!1)=>{const r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};exports.VideoQuality=void 0;(function(i){i.INVARIANT="Invariant quality",i.Q_144P="144p",i.Q_240P="240p",i.Q_360P="360p",i.Q_480P="480p",i.Q_720P="720p",i.Q_1080P="1080p",i.Q_1440P="1440p",i.Q_2160P="2160p",i.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const Ae={[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}},qi=(i,e)=>Ae[i].height>Ae[e].height,bb=(i,e)=>Ae[i].height>=Ae[e].height,ti=(i,e)=>Ae[i].height<Ae[e].height,Sb=(i,e)=>Ae[i].height<=Ae[e].height,gb=i=>i.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:ti(e,t)?1:-1)[0],yb=Object.keys(Ae).sort((i,e)=>ti(i,e)?-1:1),vt=({width:i,height:e})=>{const t=Math.min(i,e),r=Math.max(i,e);return yb.find(s=>{const n=Ae[s];return n.width>=r&&n.height>=t})},Eb=i=>Ae[i].height,Zi=i=>i===exports.VideoQuality.INVARIANT;class J{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,r=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:r,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,r=this.state;r===e||a.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:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const Tb=i=>{switch(i){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 a.assertNever(i)}};var L;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(L||(L={}));const $b=5,kb=5,Pb=500,Hn=7e3;class Ab{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new J(L.STOPPED),this.syncPlayback=()=>{const r=this.videoState.getState(),s=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: ${r}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){r!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===C.Requested&&r!==L.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(r){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PLAYING:{switch(r){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:a.assertNever(r)}break}case exports.PlaybackState.PAUSED:{switch(r){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:a.assertNever(r)}break}default:a.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(Tb(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 a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(a.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new a.Subject;e.add(s.pipe(a.debounce(Pb)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.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===C.Applying||Math.abs(l-n)>$b)&&s.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.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<kb&&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:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const r=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(r,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 r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:C.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}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,r;const s=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:s.volume,muted:(r=e.muted)!==null&&r!==void 0?r:s.muted};(n.volume!==s.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const r=this.params.source;let s,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=r[e];a.assertNonNullable(c);const h=gb(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),s=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=r[e];a.assertNonNullable(c),s=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=r[e];a.assertNonNullable(c),s=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=r[e];a.assertNonNullable(c),s=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=r[e];a.assertNonNullable(c),s=Nt(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:a.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 a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:s,n);l.contentUrl=s,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const r=this.params.desiredState.seekState.getState();return r.state===C.Applying||r.state===C.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),r=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(Hn).subscribe(()=>n(`timeout(${Hn})`)))});vr(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Gn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;const r=this.listeners[e];for(let s=0,n=r.length;s<n;s++)if(r[s].callback===t){r.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const r=this.listeners[e.type].slice();for(let s=0,n=r.length;s<n;s++){const o=r[s];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 Ll extends Gn{constructor(){super(),this.listeners||Gn.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 xl=class{constructor(){Object.defineProperty(this,"signal",{value:new Ll,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(s){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 r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(s){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(xl.prototype[Symbol.toStringTag]="AbortController",Ll.prototype[Symbol.toStringTag]="AbortSignal");function Bl(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function wb(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!Bl({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(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(p){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((p,m)=>{c.addEventListener("abort",()=>m(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const mr=Bl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ml=mr?wb({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ct=mr?Ml.fetch:window.fetch;mr?Ml.Request:window.Request;const ut=mr?xl:window.AbortController,Jt=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ii{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:r}=e.request,s=(t=this.dashJsRequestQueue.get(r))!==null&&t!==void 0?t:[];s.push(e),this.dashJsRequestQueue.set(r,s)}executeNextRequests(){return Q(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const r=this.activeRequests.get(e);if(r){t.length&&this.onBigRequestProgress(r);const s=t[0];if(!s||!s.request.range)continue;const[n,o]=Jt(s.request);if(n>=r.from&&o<=r.to)continue;this.activeRequests.delete(e)}if(t.length){const s=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,s)}}})}abort(e){var t;if(e){const{request:r}=e,s=((t=this.dashJsRequestQueue.get(r.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(r.url);s&&n&&n.abortController.abort()}else for(const{abortController:r}of this.activeRequests.values())r.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const r=t.map(Jt),s=r[0][0];let n=r[0][1];for(let f=1;f<r.length&&n<this.params.minDataSize;f++){const p=r[f][1];p-s<=2*this.params.minDataSize&&(n=Math.max(n,p))}s===0?n=Math.max(n,s+this.params.minInitSize):n=Math.max(n,s+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${s}-${n}`);const l=o.toString(),d=new ut,u=d.signal,c={url:e,from:s,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var p,m;throw(m=(p=this.params).onError)===null||m===void 0||m.call(p,{id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return Ct(l,{signal:u}).then(f=>{var p,m,v;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[b,S]=f.body.tee();(m=(p=this.params).onDownloadStream)===null||m===void 0||m.call(p,S);const g=b.getReader(),P=parseInt((v=f.headers.get("Content-Length"))!==null&&v!==void 0?v:"",10)||n-s+1;c.data=new ArrayBuffer(P);const T=new Uint8Array(c.data),E=({done:w,value:F})=>Q(this,void 0,void 0,function*(){w?this.onBigRequestProgress(c):F&&(T.set(F,c.loaded),c.loaded+=F.byteLength,this.onBigRequestProgress(c),yield g==null?void 0:g.read().then(E,ii.suppressStreamErrors).catch(h))});g==null||g.read().then(E,ii.suppressStreamErrors).catch(h)},ii.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:r,loaded:s,data:n,response:o}){var l,d,u,c,h,f,p,m;if(!this.activeRequests.has(e)||!n)return;const v=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const b of v){const{request:S}=b,[g,P]=Jt(S),T=g>=t&&P<=t+s,E=t>=g&&t+s<P,w=n.slice(g-t,Math.min(P-t+1,s));if((T||E)&&(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=r-t),T){S.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(O=>O!==b)),(h=b.success)===null||h===void 0||h.call(b,w,"",e);const F=o?Array.from(o.headers.entries()).map(([O,I])=>`${O}: ${I}`).join(`\r
7
+ `):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(S,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,F,[])}else E&&((m=b.progress)===null||m===void 0||m.call(b,{loaded:s,total:r-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:r},s){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:a.ErrorCategory.NETWORK,message:"Download error",thrown:s}),!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]=Jt(c.request);(h>=t&&h<r||f>t&&f<=r)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(s)))}if(this.activeRequests.delete(e),s)throw s}onBigRequestAbort({url:e,from:t,to:r}){var s,n;if(!this.activeRequests.has(e))return;const o=(s=this.dashJsRequestQueue.get(e))!==null&&s!==void 0?s:[];for(const l of o){const[d,u]=Jt(l.request);(d>=t&&d<r||u>t&&u<=r)&&((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 er{constructor(e,t,r){this.baseLoader=e,this.config=r,this.bigRequest=t,t.setMetrics(r.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(er.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;er.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const _b=(i,e)=>t=>({create:r=>{const s=i(t).create(r);return new er(s,e,r)}}),Rb=(i,e)=>{const t=new ii(e);return i.extend("SchemeLoaderFactory",function(){const{parent:r}=this,s=r.getLoader;return{getLoader:n=>{const o=s(n);return _b(o,t)}}},!0),()=>t.destroy()};var Ib=i=>{let e,t=!1,r=!1;i.on("playbackTimeUpdated",({timeToEnd:s})=>{r=s<=3,t&&r&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:s}=this,n=s.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&r&&(e==null||e())}}},!0)},Nb=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,r=new a.ValueSubject(void 0),s=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,m,v;const b=hi(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(P=>P.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const P=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),T=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),E=(p=T!=null?T:P*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const S=(m=b["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,g=(v={1:!0,0:!1}[b["x-reused"]])!==null&&v!==void 0?v:void 0;r.next(S),s.next(g)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,m=f.progress;f.onload=function(...v){return d(this),p(...v)},f.progress=function(...v){return u(this),m(...v)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:r}},Dt=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Cb=i=>i.extend("RequestModifier",()=>({modifyRequestURL:Dt}),!0),Db=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:r=>{if(r.request&&r.request.range){const[s,n]=r.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(r.request.url,location.href);o.searchParams.append("bytes",`${s}-${n}`),r.request.url=o.toString(),r.request.range=void 0}t(r)}}},!0)};const De=(i,e,t,{equal:r=(o,l)=>o===l,changed$:s,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(s),u=new a.Subscription;return s&&u.add(s.subscribe(c=>{const h=i.getState();r(c,h)&&i.setState(c)},n)),r(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),d&&i.setState(c.to)},n)),u},mt=(i,e,t)=>De(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),qe=(i,e,t,r)=>De(e,()=>({muted:i.muted,volume:i.volume}),s=>{a.isNonNullable(s)&&(i.muted=s.muted,i.volume=s.volume)},{equal:(s,n)=>s===n||(s==null?void 0:s.muted)===(n==null?void 0:n.muted)&&(s==null?void 0:s.volume)===(n==null?void 0:n.volume),changed$:t,onError:r}),et=(i,e,t,r)=>De(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),Ob=i=>["__",i.language,i.label].join("|"),Lb=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class Le{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(De(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(De(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:s})),this.subscription.add(De(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const r=this.current$.getValue();this.select(r)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),a.filterChanged((r,s)=>r.length===s.length&&r.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),a.map(r=>r&&this.htmlTextTrackToITextTrack(r).id),a.filterChanged()).subscribe(this.current$));const t=r=>{var s,n;return this.applyCueSettings((n=(s=r.target)===null||s===void 0?void 0:s.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)===null||s===void 0||s.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.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=r.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(r=>{var s;(s=r.track)===null||s===void 0||s.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const r of Array.from(e)){const s=r;a.isNonNullable(t.align)&&(s.align=t.align),a.isNonNullable(t.position)&&(s.position=t.position),a.isNonNullable(t.size)&&(s.size=t.size),a.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Le.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:r}=e,s=e.id!==""?e.id:Ob(e);return this.externalTracks.has(s)?{id:s,type:"external",language:t,label:r,url:this.externalTracks.get(s).url}:{id:s,type:"internal",language:t,label:r}}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(r=>r.id===t)).forEach(t=>this.detach(t))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))a.isNonNullable(e)&&Lb(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){a.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){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var ze=i=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i.appendChild(e),e};class ha{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 Vl=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const Vs=3;class xb{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,r=this._source.buffered.length;t<r;t++){let s=this._source.buffered.start(t);const n=this._source.buffered.end(t);s>e&&s-e<Vs&&(s=e),this._buffer.push({from:s,to:n,i:t})}return this._buffer.sort(function(t,r){return t.from-r.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const r=this.getNext(e);if(r&&r.from-e.to<(t||Vs))return r}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,r){this._buffer.forEach(({from:s,to:n})=>{const o=s>=e&&s<t,l=n>=e&&n<t;o&&l||(o?r(t,n):l?r(s,e):s<e&&n>t?(r(t,n),r(s,e)):r(s,n))})}destroy(){this._buffer=[]}}var Fl=(i,e,t=Vs)=>{let r=0,s=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(r=o,s=l,!t)return{from:r,to:s};for(let d=n-1;d>=0;d--)i.end(d)+t>=r&&(r=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=s&&(s=i.end(d))}}return{from:r,to:s}};const Bb=50,Mb=i=>i.webkitAudioDecodedByteCount!=="undefined"?!!i.webkitAudioDecodedByteCount:i.mozHasAudio!=="undefined"?i.mozHasAudio:i.audioTracks?!!i.audioTracks.length:!0,We=i=>{const e=m=>a.fromEvent(i,m).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(m=>a.fromEvent(i,m))).pipe(a.map(m=>m.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>Fl(i.buffered,i.currentTime))),n=Vl()?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),o=a.fromEvent(i,"playing").pipe(a.debounce(Bb),a.map(()=>Mb(i))),l=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),d=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),u=a.fromEvent(i,"error").pipe(a.filter(()=>Boolean(i.error||i.played.length)),a.map(()=>{var m;const v=i.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(m=i.error)!==null&&m!==void 0?m:void 0}})),c=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),h=new a.Subject,f=.3;let p;return c.subscribe(m=>{i.loop&&a.isNonNullable(p)&&a.isNonNullable(m)&&p>=i.duration-f&&m<=f&&h.next(p),p=m}),{playing$:n,pause$:e("pause").pipe(a.filter(()=>!i.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$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:l,isAudioAvailable$:o,playbackRateState$:d}},fa=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Vb=we,Fb=dr,Ub=Xs,jb=Ks;Vb({target:"Array",proto:!0},{at:function(e){var t=Fb(this),r=Ub(t),s=jb(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var Hb=ca,Gb=Hb("Array","at"),Yb=Gb,qb=Yb,zb=qb,Wb=zb,Me=Wb;let pa=!1,Ve={};const Qb=i=>{pa=i},Jb=()=>{Ve={}},Kb=i=>{i(Ve)},Oi=(i,e)=>{var t;pa&&(Ve.meta=(t=Ve.meta)!==null&&t!==void 0?t:{},Ve.meta[i]=e)};class Ce{constructor(e){this.name=e}next(e){var t,r;if(!pa)return;Ve.series=(t=Ve.series)!==null&&t!==void 0?t:{};const s=(r=Ve.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),Ve.series[this.name]=s}}const Xb=new Ce("best_bitrate"),Zb=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class eS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const vi=(i,{container:e,throughput:t,tuning:r,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,p;const m=r.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,v=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*r.containerSizeFactor,height:e.height*m*r.containerSizeFactor},b=v&&vt(v),S=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,g=i.filter(N=>!Zi(N.quality)).sort((N,_)=>qi(N.quality,_.quality)?-1:1),P=(h=Me(g,-1))===null||h===void 0?void 0:h.quality,T=(f=Me(g,0))===null||f===void 0?void 0:f.quality,E=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&ti(s.max,s.min)||a.isNonNullable(s.min)&&T&&qi(s.min,T)||a.isNonNullable(s.max)&&P&&ti(s.max,P),w=S*Zb(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),O=g.filter(N=>{const _=b?ti(N.quality,b):!0,G=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(N.bitrate)?t-n>=N.bitrate*w:!0,K=r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&d&&!Zi(d.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&qi(N.quality,d.quality),te=E||(a.isNullable(s.max)||Sb(N.quality,s.max))&&(a.isNullable(s.min)||bb(N.quality,s.min));return _&&G&&!K&&te})[0];O&&O.bitrate&&Xb.next(O.bitrate);const I=(p=O!=null?O:g[Math.ceil((g.length-1)/2)])!==null&&p!==void 0?p:i[0],U=I&&u&&u.history[I.id]&&a.now()-u.history[I.id]<=r.trackCooldown&&(!u.last||I.id!==u.last.id);if(I!=null&&I.id&&u&&!U&&u.recordSelection(I),U&&(u!=null&&u.last)){const N=u.last;return u==null||u.recordSwitch(N),N}return u==null||u.recordSwitch(I),I};var ce=i=>new URL(i).hostname;const tS=300,tr=(i,e=tS)=>new a.Observable(t=>{const{width:r,height:s}=i.getBoundingClientRect();if(t.next({width:r,height:s}),!window.ResizeObserver)return;const n=new ResizeObserver(Pu(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),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(i),()=>n.disconnect()}),Qe=i=>{try{i.pause(),i.playbackRate=0,i.removeAttribute("src"),i.load(),i.remove()}catch(e){console.error(e)}},iS=5e3,Kt={};var x;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(x||(x={}));const re=(i,e)=>new a.Observable(t=>{const r=s=>t.next(s);return i.on(e,r),()=>i.off(e,r)});class Yn{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(x.DOWNLOADING_LIB),this.textTracksManager=new Le,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new ha,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=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((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&t!==x.STOPPED&&r!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),r){case exports.PlaybackState.STOPPED:{switch(t){case x.STOPPED:break;case x.PLAYING:case x.PAUSED:case x.READY:this.stop();break;default:a.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:a.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:a.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:a.assertNever(t)}break}default:a.assertNever(r)}},this.video=ze(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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{var n;e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=s==null?void 0:s.toString)===null||n===void 0?void 0:n.call(s)}`,thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),iS);vr(import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Kt.MediaPlayer=s.MediaPlayer,Kt.Debug=s.Debug,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Kt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Kt.Debug,"dashjs not loaded"),this.player=Kt.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?fa(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=Rb(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&&Db(this.player),Ib(this.player),this.params.tuning.requestQuick&&Cb(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(x.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,r=v=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:v})},s=(v,b)=>this.subscription.add(v.subscribe(b,r));s(tr(this.video),this.elementSize$),s(re(this.player,"error").pipe(a.map(v=>{const b=typeof v.error=="object"?v.error.code:v.error,S=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${b}`,message:S}})),e.error$),s(re(this.player,"playbackError").pipe(a.map(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const n=re(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({newQuality:v})=>{var b;return(b=this.videoTracks.find(({bitrateInfo:S})=>S.qualityIndex===v))===null||b===void 0?void 0:b.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:v})=>v===x.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(De(t.videoTrack,()=>{var v,b;const S=this.player.getQualityFor("video");return(b=(v=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===S))===null||v===void 0?void 0:v.track)===null||b===void 0?void 0:b.id},v=>{var b;if(a.isNullable(v))return;const S=(b=this.videoTracks.find(({track:g})=>g.id===v))===null||b===void 0?void 0:b.bitrateInfo;S&&this.player.setQualityFor("video",S.qualityIndex)},{changed$:n.pipe(a.map(v=>v==null?void 0:v.id)),onError:r}))},r)),this.subscription.add(De(t.autoVideoTrackSwitching,()=>{var v,b,S;return(S=(b=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||b===void 0?void 0:b.autoSwitchBitrate)===null||S===void 0?void 0:S.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:r})),s(re(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({state:v})=>v==="bufferStalled")),e.isBuffering$),s(re(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:b}})=>{var S,g;const P=this.player.getDashMetrics(),T=P.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),E=(S=P.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&S!==void 0?S:exports.HttpConnectionType.HTTP1,w=(g={1:!0,0:!1}[T])!==null&&g!==void 0?g:void 0;this.params.output.httpConnectionType$.next(E),this.params.output.httpConnectionReused$.next(w),e.hostname$.next(ce(b))}),s(re(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:b,availableFrom:S}}})=>{this.isLive$.next(b),this.availableFrom$.next(S.getTime()),b||e.duration$.next(v),this.videoTracks=[];const g=this.player.getQualityFor("video");let P;for(const T of this.player.getBitrateInfoListFor("video")){const E=T.qualityIndex.toString(10),w=vt(T),F=T.bitrate/1e3,O={width:T.width,height:T.height},I=this.frameRatesByFrameHeight[T.height];if(w){const U={id:E,quality:w,bitrate:F,size:O,fps:I};this.videoTracks.push({track:U,bitrateInfo:T}),T.qualityIndex===g&&(P=U)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:T})=>T)),P&&e.currentVideoTrack$.next(P),this.videoState.setState(x.STREAM_INITIALIZED),this.videoState.startTransitionTo(x.READY)}),s(re(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const b=v.requestEndDate.getTime()-v.firstByteDate.getTime(),S=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(S,b)}),s(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),b=vi(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),S=this.videoTracks.find(({track:g})=>g===b);S!=null&&S.bitrateInfo&&this.player.setQualityFor("video",S==null?void 0:S.bitrateInfo.qualityIndex,!1)}),s(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:v})=>v),a.map(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const o=re(this.player,"playbackTimeUpdated").pipe(a.map(({time:v})=>v!=null?v:0));s(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:v,currentTime:b})=>this.params.output.liveTime$.next(v+b*1e3)),s(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),s(re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(re(this.player,"playbackEnded"),e.endedEvent$),s(re(this.player,"playbackProgress").pipe(a.map(()=>Fl(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(x.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),s(re(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())}),s(re(this.player,"playbackPaused"),()=>{this.videoState.setState(x.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),s(re(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===x.READY&&this.videoState.setState(x.READY)}),s(this.isLive$,e.isLive$),s(tr(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));s(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=Nb(this.player);s(c,this.params.output.httpConnectionType$),s(h,this.params.output.httpConnectionReused$),s(d,this.maxSeekBackTime$),s(u.pipe(a.once()),e.firstBytesEvent$),s(re(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(v=>v<60))}),({isLive:v,isShort:b})=>{const S=!v&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:S}}})}),s(o.pipe(a.filter(v=>v>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(re(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(re(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,r))},r)),this.subscription.add(mt(this.video,t.isLooped,r));const{volumeState$:f,looped$:p,playbackRateState$:m}=We(this.video);this.subscription.add(qe(this.video,t.volume,f,r)),this.subscription.add(f.subscribe(e.volume$,r)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(et(this.video,t.playbackRate,m,r))}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,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3);const s=Nt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,It.PLAYBACK_SHIFT);this.player.attachSource(s)}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(r){}Qe(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var mi=i=>{switch(i){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}},tt=i=>Q(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return i.muted=!1,console.warn(r),!1}}return!0});function oe(){return a.now()}function Ul(i){return oe()-i}function qn(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,s=o=>r.test(o);return{resolve:(o,l,d=!1)=>{s(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 rS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function zi(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",m=7e3,v=2e3,b=()=>{if(d)return;a.assertNonNullable(c);const _=Ul(c);let G;if(_<v){G=v-_,setTimeout(b,G);return}v*=2,v>m&&(v=m),o&&o.abort(),o=new s,w()};const S=_=>(n=_,N),g=_=>(h=_,N),P=()=>(p="json",N),T=()=>{if(!d){if(--u>=0){b(),r&&r();return}d=!0,h&&h(),t&&t()}},E=_=>(f=_,N),w=()=>{c=oe(),o=new s,o.open("get",i);let _=0,G,K=0;const te=()=>(a.assertNonNullable(c),Math.max(c,Math.max(G||0,K||0)));if(n&&o.addEventListener("progress",$=>{const D=oe();n.updateChunk&&$.loaded>_&&(n.updateChunk(te(),$.loaded-_),_=$.loaded,G=D)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const D=o.response.byteLength-_;D&&n.updateChunk&&n.updateChunk(te(),D)}h&&h(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),f){const $=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=oe(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),N},N={withBitrateReporting:S,withParallel:E,withJSONResponse:P,withRetryCount:_=>(u=_,N),withRetryInterval:(_,G)=>(a.isNonNullable(_)&&(v=_),a.isNonNullable(G)&&(m=G),N),withTimeout:_=>(l=_,N),withFinally:g,send:w,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return N}const sS=100,aS=2e3,nS=500;let oS=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,r){return{start:e,end:t,bytes:r}}_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-nS;if(t-e>aS){let r=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)r+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;r+=o;const d=n.bytes*o/l;s+=d,n.start=t,n.bytes-=d}}}if(s>0&&r>0){const n=s*8/(r/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(s)}/${Math.round(r)} 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,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>sS&&(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 lS{constructor(e,t,r,s,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=r,this.MAX_PARALLEL_REQUESTS=s,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 r=oe(),s=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=oe()-r,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=zi(t,n,()=>s("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=oe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=oe();if(Object.keys(this.activeRequests).length>=e)return!1;const r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!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,r,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=r,o._retryCB=s,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}`),r(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=r,n._retryCB=s,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 Li=1e4,xi=3,uS=300,dS=2e3,cS=6e4,hS=10,fS=1,pS=500;class vS{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 oS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=qn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],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=qn(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 r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-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 r;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(r=e.error)===null||r===void 0?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.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,r=t.buffered.length;let s;r!==0&&(s=t.buffered.start(r-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let r,s,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)?(!s||n.bitrate>s.bitrate)&&(s=n):(!r||r.bitrate>n.bitrate)&&(r=n));return s||r}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:r,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{rS(s,"progress",()=>{s.buffered.length?(s.currentTime=s.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 lS(xi,Li,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:r,playerCallback:s}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const T=n&&(!c||c===this.rep);return T||t("Not running!"),T},f=(T,E,w)=>{d&&d.abort(),d=zi(this.urlResolver.resolve(T,!1),E,w,()=>this._retryCallback()).withTimeout(Li).withBitrateReporting(this.bitrateSwitcher).withRetryCount(xi).withFinally(()=>{d=null}).send()},p=(T,E,w)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),E,w,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=T=>{const E=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${E}=>${T}`),r.playbackRate=T)},v=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const w=oe()-1e4;let F=0;for(let I=0;I<this.bufferStates.length;I++){const U=this.bufferStates[I];T=Math.min(T,U.buf),U.ts<w&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${T} drop=${F} jitter=${this.sourceJitter}`);let O=T-fS;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?m(1.15):O>1?m(1.1):O>.3?m(1.05):m(1)}},S=T=>{let E;const w=()=>E&&E.start?E.start.length:0,F=$=>E.start[$]/1e3,O=$=>E.dur[$]/1e3,I=$=>E.fragIndex+$,U=($,D)=>({chunkIdx:I($),startTS:F($),dur:O($),discontinuity:D}),N=()=>{let $=0;if(E&&E.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=D;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let ie=E.dur.length-1;for(;ie>=0&&(ee-=E.dur[ie],!(ee<=0));--ie);$=Math.min(ie,E.dur.length-1-z),$=Math.max($,0)}return U($,!0)},_=$=>{const D=w();if(!(D<=0)){if(a.isNonNullable($)){for(let z=0;z<D;z++)if(F(z)>$)return U(z)}return N()}},G=$=>{const D=w(),z=$?$.chunkIdx+1:0,ee=z-E.fragIndex;if(!(D<=0)){if(!$||ee<0||ee-D>hS)return t(`Resync: offset=${ee} bChunks=${D} chunk=`+JSON.stringify($)),N();if(!(ee>=D))return U(z-E.fragIndex,!1)}},K=($,D,z)=>{u&&u.abort(),u=zi(this.urlResolver.resolve($,!0,this.lowLatency),D,z,()=>this._retryCallback()).withTimeout(Li).withRetryCount(xi).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,D)=>{K(T,z=>{if(!h())return;E=z;const ee=Boolean(E.lowLatency);ee!==this.lowLatency&&v(ee);let ie=0;for(let he=0;he<E.dur.length;++he)ie+=E.dur[he];ie>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/E.dur.length)),s({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,$(_(D))},()=>this._handleNetworkError())},nextChunk:G}},g=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{const{videoElement:E,logger:w}=this.params;let F=S(e.jidxUrl),O,I,U,N,_=0,G,K,te;const $=()=>{G&&(clearTimeout(G),G=void 0);const j=Math.max(pS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=_+j,de=oe(),me=Math.min(1e4,ae-de);_=de;const it=()=>{u||h()&&F.seek(()=>{h()&&(_=oe(),D(),$())})};me>0?G=window.setTimeout(()=>{this.paused?$():it()},me):it()},D=()=>{let j;for(;j=F.nextChunk(N);)N=j,_e(j);const ae=F.nextChunk(U);if(ae){if(U&&ae.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?$():(g(),this._initPlayerWith(e));return}he(ae)}else $()},z=(j,ae)=>{if(!h()||!this.sourceBuffer)return;let de,me,it;const Re=Je=>{window.setTimeout(()=>{h()&&z(j,ae)},Je)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),Re(100);else{const Je=oe(),rt=E.currentTime;!this.paused&&E.buffered.length>1&&K===rt&&Je-te>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),K!==rt&&(K=rt,te=Je);const Vt=this._getBufferSizeSec();if(Vt>30)w(`Buffered ${Vt} seconds; delaying appendBuffer`),Re(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:Je,buf:Vt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(bt){if(bt.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),it=this.sourceBuffer.buffered.length,it!==0&&(de=this.sourceBuffer.buffered.start(0),me=rt,me-de>4&&this.sourceBuffer.remove(de,me-3)),Re(1e3);else throw bt}}},ee=()=>{I&&O&&(w([`Appending chunk, sz=${I.byteLength}:`,JSON.stringify(U)]),z(I,function(){I=null,D()}))},ie=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),he=j=>{h()&&p(ie(j),(ae,de)=>{if(h()){if(de/=1e3,I=ae,U=j,o=j.startTS,de){const me=Math.min(10,j.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}ee()}},()=>this._handleNetworkError())},_e=j=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(j),!1)))},Mt=j=>{h()&&(e.cachedHeader=j,z(j,()=>{O=!0,ee()}))};n=!0,F.seek(j=>{if(h()){if(_=oe(),!j){$();return}N=j,!a.isNullable(T)||j.startTS>T?he(j):(U=j,D())}},T),e.cachedHeader?Mt(e.cachedHeader):f(e.headerUrl,Mt,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:r}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),a.isNonNullable(s)&&(s+=.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,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,r=h=>{if(!this.autoQuality)return;let f,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),m=h/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; 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,p)=>{const m=oe();if(this.chunkRateEstimator.addInterval(f,m,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-f,speed:b}),!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&&Ul(o)<3e4)return;r(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=oe();h<l&&(o=f),l=h}}}_fetchManifest(e,t,r){this.manifestRequest=zi(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Li).withRetryCount(xi).withRetryInterval(uS,dS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;tt(t).then(r=>{r||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:r,videoElement:s}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&s.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}`),r({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))},cS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var B;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(B||(B={}));const mS=[B.PAUSED,B.PLAYING,B.READY],bS=[B.PAUSED,B.PLAYING,B.READY];class SS{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(B.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Le,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new ha,this._dashCb=s=>{var n,o,l,d;switch(s.name){case"buffering":{const u=s.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${s.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=s.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=mi(h.name))!==null&&o!==void 0?o:vt(h.video),m=h.bitrate/1e3,v=Object.assign({},h.video);if(!p)continue;const b={id:f,quality:p,bitrate:m,size:v};c.push({track:b,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)===B.MANIFEST_READY&&this.videoState.setState(B.MANIFEST_READY);break}case"qualitySwitch":{const u=s.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),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=s;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(s.shiftDuration),this.zeroTime$.next(s.zeroTime);break}}},this.syncPlayback=()=>{var s;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!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(B.STOPPED));return}if(!o){if(bS.includes(n)){const c=(s=this.params.desiredState.videoTrack.getTransition())===null||s===void 0?void 0:s.to;a.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===C.Requested&&mS.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_READY),this.dash.attachSource(Nt(this.params.source.url));return;case B.MANIFEST_READY:this.videoState.startTransitionTo(B.READY),this.prepare();break;case B.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(B.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(B.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(B.PAUSED)})}return;case B.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(B.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case B.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.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(B.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=ze(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(ce(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 r=We(this.video);this.subscription.add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())===null||s===void 0?void 0:s.to)===B.READY&&this.videoState.setState(B.READY)},t)).add(r.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED)},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(B.PLAYING)},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:s,position:n})=>this.params.output.liveTime$.next(s+n*1e3),t)).add(mt(this.video,this.params.desiredState.isLooped,t)).add(qe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(et(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:s}})=>{const n=s&&Eb(s);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(s=>{var n;switch(s.to){case B.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case B.MANIFEST_READY:case B.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 B.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case B.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(s.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}createLiveDashPlayer(){const e=new vS({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,r,s,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=(s=(r=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||r===void 0?void 0:r.to)!==null&&s!==void 0?s:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:(n=vi(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;a.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 r=(t=this.representations$.getValue().find(({track:s})=>s.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(r,`No such representation ${e}`),this.dash.switchByName(r.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,r=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(r),this.dash.reinit(Nt(this.params.source.url,r))}}var jl=i=>{var e,t;const r=i.get("X-Delivery-Type"),s=i.get("X-Reused"),n=r===null?exports.HttpConnectionType.HTTP1:(e=r)!==null&&e!==void 0?e:void 0,o=s===null?void 0:(t={1:!0,0:!1}[s])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},lt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){const s=i.start(r)*1e3,n=i.end(r)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const gS=i=>{const e=document.createElement("a");return e.href=i,e.origin},yS=i=>{const e=document.createElement("a");return e.href=i,e.host};class Hl{constructor(e,t=[],r,s,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=r,this._progressCb=s,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,r,s,n,o,l,d,u;if(a.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(r=this._errorCb)===null||r===void 0||r.call(this,`Http${(s=this._xhr)===null||s===void 0?void 0:s.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=hi(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 r;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(r=this._errorCb)===null||r===void 0||r.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let s;this._failoverIndex>=this._failoverHosts.length?(s=this._url,this._failoverIndex=0):(s=this._url.replace(yS(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",s,!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 ir{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(r){if(r.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let n=0;for(let o=0,l=s.length;o<l;o++)n+=s.end(o)-s.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",r),r}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,r,s,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=v=>{s(ir._str2ua(v.substr(d))),d=v.length};let m=e.baseURL+"&bytes="+t+"-"+r;this._params.requestQuic&&(m=Dt(m)),this._lastXhr=new Hl(m,e.failoverHosts,v=>{this._lastXhr=void 0,p(v);const b=Date.now()-u;this._params.onBandwidthChange({size:v.length,duration:b,speed:8*v.length/(b/1e3)}),this._onDashCallback("loading",{size:v.length,done:!0}),n==null||n()},v=>{if(v.length-d>l&&p(v),h===0){h=Date.now();return}f=v.length-c;const b=Date.now()-h;f>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:f,duration:b,speed:8*f/(b/1e3)}),f=0,c=v.length,h=Date.now()),this._onDashCallback("loading",{size:v.length,done:!1})},o,(v,b,S)=>this._params.onError(v,b,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(r){throw this._params.onError("SourceBuffer","Source Buffer update error",r),r}};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=ir._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 r=new Uint8Array(e.byteLength+t.byteLength);return r.set(e,0),r.set(t,e.byteLength),r}static _str2ua(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);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 ES{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)?)?$/,r=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},s=t.exec(e),n=(s==null?void 0:s[1])==="-"?-1:1,o={years:r(s==null?void 0:s[2],n),months:r(s==null?void 0:s[3],n),weeks:r(s==null?void 0:s[4],n),days:r(s==null?void 0:s[5],n),hours:r(s==null?void 0:s[6],n),minutes:r(s==null?void 0:s[7],n),seconds:r(s==null?void 0:s[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let r=e;this._config.REQUEST_QUIC&&(r=Dt(r)),new Hl(r,t,s=>{this.attachManifest(s,t,gS(r))},void 0,s=>{this._params.onResponseHeaders(s)},(s,n,o)=>this._params.onError(s,n,o))}attachManifest(e,t,r){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,p,m,v,b,S,g,P,T,E,w,F,O,I,U,N,_;const G=u.getElementsByTagName("SegmentBase")[0],K=G&&o(G,"indexRange").split("-"),te=G&&G.getElementsByTagName("Initialization")[0],$=te&&o(te,"range").split("-");if(!$||!K){const _e=u.parentElement;if((_e==null?void 0:_e.getAttribute("contentType"))==="text"){const Mt=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,j=(r?r+"/":"")+((m=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||m===void 0?void 0:m.data),ae=(v=_e.getAttribute("lang"))!==null&&v!==void 0?v:void 0;j&&d.push({id:Mt,url:j,language:ae})}return}const D=.1,z=Number((b=u.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),ee=(r?r+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ie;const he=(g=(S=u.attributes.getNamedItem("frameRate"))===null||S===void 0?void 0:S.value)!==null&&g!==void 0?g:void 0;ie=he?fa(he):void 0,l.push({width:Number((P=u.attributes.getNamedItem("width"))===null||P===void 0?void 0:P.value),height:Number((T=u.attributes.getNamedItem("height"))===null||T===void 0?void 0:T.value),bandwidth:z,baseURL:ee,failoverHosts:t,indexFrom:Number(K[0]),indexTo:Number(K[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(w=(E=u.attributes.getNamedItem("codecs"))===null||E===void 0?void 0:E.value)!==null&&w!==void 0?w:void 0,mimeType:(O=(F=u.attributes.getNamedItem("mimeType"))===null||F===void 0?void 0:F.value)!==null&&O!==void 0?O:void 0,fps:ie,bufferSize:D*z/8,bufferLength:D,name:(U=(I=u.attributes.getNamedItem("okQuality"))===null||I===void 0?void 0:I.value)!==null&&U!==void 0?U:void 0,id:(_=(N=u.attributes.getNamedItem("id"))===null||N===void 0?void 0:N.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 r=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let n=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,n);const o=new DataView(s.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 p=u+(o.getUint32(n,!1)&2147483647),m=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:m/l,fromOffset:u,toOffset:p-1}),u=p,d=m}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-r)},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 r=new t;let s,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 p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const c=this._appendVector[String(u.fromTime)];c!==s&&(s=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(p);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},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=r.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new ir({mediaSource:r,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),r.duration||(r.duration=this._duration),this._loopTimeout||l(),r.removeEventListener("sourceopen",d),r.removeEventListener("webkitsourceopen",d)};r.addEventListener("sourceopen",d,!1),r.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(r),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,r=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(r){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=s||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 r=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!r||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(s.toTime<r.to+n){const o=this._findRef(s.toTime);o&&o.toTime<r.to+n?(this._buffer.smartRemove(s.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(s.fromTime-n,s.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,s.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||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return;if(Array.isArray(r)&&r.length===0){this._params.onError("emptyrefs","Empty refs");return}let s;for(let n=0;n<r.length;n++){const o=r[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!s||o.fromTime<s.fromTime)&&(s=o)}if(!s){const n=r[r.length-1];if(e>n.toTime)return n}return s}_isLastRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return!1;const s=r[r.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const r=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>r&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var M;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(M||(M={}));const TS=[M.PAUSED,M.PLAYING];class $S{constructor(e){this.videoState=new J(M.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Le,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=t=>{var r,s,n;const o=[];for(const l of t){const d=(s=(r=l.name)!==null&&r!==void 0?r:l.id)!==null&&s!==void 0?s:l.height.toString(10),u=(n=l.name&&mi(l.name))!==null&&n!==void 0?n:vt(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const p={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:p,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(M.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var r;const s=(r=this.representations$.getValue().find(({representation:n})=>n===t))===null||r===void 0?void 0:r.track;s&&(this.params.output.currentVideoTrack$.next(s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(s.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.videoState.getTransition(),s=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(r)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(o)};`}),s===exports.PlaybackState.STOPPED){t!==M.STOPPED&&(this.videoState.startTransitionTo(M.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(M.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!r)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===C.Requested&&TS.includes(t)&&this.seek(o.position,o.forcePrecise),t){case M.STOPPED:this.videoState.startTransitionTo(M.MANIFEST_LOADED),this.prepare();return;case M.MANIFEST_LOADED:this.videoState.startTransitionTo(M.INITIAL_REPRESENTATION_SELECTED);return;case M.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(M.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case M.METADATA_LOADED:this.videoState.startTransitionTo(M.READY),this.dash.updateRefsForCurrentTime();return;case M.READY:s===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed());return;case M.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(M.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case M.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(t)}`})}),this.video=ze(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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new xb(this.video),this.dash=new ES({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,r,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:r,thrown:s,category:a.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,r=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},s=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=We(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,r));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(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===M.PLAYING||this.videoState.getState()===M.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(qe(this.video,t.volume,n.volumeState$,r)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,t.playbackRate,n.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),o(tr(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===M.READY&&this.videoState.setState(M.READY)},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},r)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(M.METADATA_LOADED)},r)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},r)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.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$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),v=this.elementSize$.getValue(),b=s();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let S;if(!b&&a.isNonNullable(p))S=p;else{const g=lt(this.video.buffered,this.video.currentTime*1e3),P=b?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,T=Math.min(g/P,1);S=(d=vi(h.map(({track:E})=>E),{container:v,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:T,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:E})=>E===c))===null||l===void 0?void 0:l.track}))===null||d===void 0?void 0:d.id}return a.isNonNullable(S)?(u=h.find(({track:g})=>g.id===S))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,r)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===M.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(M.INITIAL_REPRESENTATION_SELECTED),r)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?l.height<=d.height:l===d)).subscribe(l=>{const d=lt(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!s())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(ce(l.baseURL)))},r)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=jl(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.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,r)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,r)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Qe(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 a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var ge;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(ge||(ge={}));var rr;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(rr||(rr={}));var ye;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(ye||(ye={}));var H;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(H||(H={}));var Ot;(function(i){i.MP4="mp4",i.WEBM="webm"})(Ot||(Ot={}));var Fs=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const kS=(i,e={})=>{const r=e.timeout||1,s=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-s-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},PS=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",zn=PS?kS:window.requestIdleCallback;var ts,is;let Gl=!1;try{Gl=Vl()&&parseInt((is=(ts=navigator.userAgent.match(/Version\/(\d+)/))===null||ts===void 0?void 0:ts[1])!==null&&is!==void 0?is:"",10)<16}catch(i){console.error(i)}class AS{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const r=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!r),this.currentTask=null}this.queue.length&&this.pull()}catch(r){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:r})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return Q(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(r=>{const s={operation:"append",data:e,signal:t,callback:r};this.queue.push(s),this.pull()})})}remove(e,t,r){return Q(this,void 0,void 0,function*(){return r&&r.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:r,callback:s};this.queue.unshift(n),this.pull()})})}abort(e){return Q(this,void 0,void 0,function*(){return new Promise(t=>{let r;Gl&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);r&&(this.queue=[r]),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:r}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&r==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"&&r==="remove"||this.error$.next({id:`BufferTaskQueue:${r}`,category:a.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:a.assertNever(t)}}}var Wn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const Yl=new TextDecoder("ascii"),ql=i=>{let e=0,t=i.getUint32(e);e+=4;const r=new DataView(i.buffer,i.byteOffset+e,4),s=Yl.decode(r);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,i.byteLength)-e,o=new DataView(i.buffer,i.byteOffset+e,n);return{id:s,size:t,contents:o}},wS=i=>Yl.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",_S=(i,e,t)=>{const r=ql(i),s=[];let n=0;const o=()=>{const v=r.contents.getUint32(n);return n+=4,v};if((o()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");o();const u=o(),c=o(),h=o(),f=o()&4294967295;let p=c/u*1e3,m=(t?t.to+1:i.byteOffset+i.byteLength)+h;for(let v=0;v<f;v++){const b=o(),S=b>>>31,g=b<<1>>>1,P=o();if(o(),S!==0)throw new Error("Unsupported multilevel sidx");const T=P/u*1e3;s.push({status:H.NONE,time:{from:p,to:p+T},byte:{from:m,to:m+g-1}}),p+=T,m+=g}return s},RS=i=>{let e=0,t=!1,r=!1;for(;e<=i.byteLength&&!t;){const s=new DataView(i.buffer,i.byteOffset+e);try{const n=ql(s);if(r||(r=n.id==="mdat"),e+n.size<=i.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=i.byteLength&&r?new DataView(i.buffer,i.byteOffset,e):null},IS={validateData:wS,parseInit:()=>null,getIndexRange:()=>{},parseSegments:_S,parseFeedableSegmentChunk:RS};var y;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(y||(y={}));var A;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(A||(A={}));const Qn={[y.EBML]:{type:A.Master},[y.EBMLVersion]:{type:A.UnsignedInteger},[y.EBMLReadVersion]:{type:A.UnsignedInteger},[y.EBMLMaxIDLength]:{type:A.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:A.UnsignedInteger},[y.DocType]:{type:A.String},[y.DocTypeVersion]:{type:A.UnsignedInteger},[y.DocTypeReadVersion]:{type:A.UnsignedInteger},[y.Void]:{type:A.Binary},[y.Segment]:{type:A.Master},[y.SeekHead]:{type:A.Master},[y.Seek]:{type:A.Master},[y.SeekID]:{type:A.Binary},[y.SeekPosition]:{type:A.UnsignedInteger},[y.Info]:{type:A.Master},[y.TimestampScale]:{type:A.UnsignedInteger},[y.Duration]:{type:A.Float},[y.Tracks]:{type:A.Master},[y.Chapters]:{type:A.Master},[y.Cluster]:{type:A.Master},[y.Timestamp]:{type:A.UnsignedInteger},[y.SilentTracks]:{type:A.Master},[y.SilentTrackNumber]:{type:A.UnsignedInteger},[y.Position]:{type:A.UnsignedInteger},[y.PrevSize]:{type:A.UnsignedInteger},[y.SimpleBlock]:{type:A.Binary},[y.BlockGroup]:{type:A.Master},[y.EncryptedBlock]:{type:A.Binary},[y.Attachments]:{type:A.Master},[y.Tags]:{type:A.Master},[y.Cues]:{type:A.Master},[y.CuePoint]:{type:A.Master},[y.CueTime]:{type:A.UnsignedInteger},[y.CueTrackPositions]:{type:A.Master},[y.CueTrack]:{type:A.UnsignedInteger},[y.CueClusterPosition]:{type:A.UnsignedInteger},[y.CueRelativePosition]:{type:A.UnsignedInteger},[y.CueDuration]:{type:A.UnsignedInteger},[y.CueBlockNumber]:{type:A.UnsignedInteger},[y.CueCodecState]:{type:A.UnsignedInteger},[y.CueReference]:{type:A.Master},[y.CueRefTime]:{type:A.UnsignedInteger}},zl=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const r=sr(i,t),s=r in Qn,n=s?Qn[r].type:A.Binary,o=i.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(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,c=sr(d),h=u*Math.pow(2,(l-1)*8)+c,f=t+l;let p;return f+h>i.byteLength?p=new DataView(i.buffer,i.byteOffset+f):p=new DataView(i.buffer,i.byteOffset+f,h),{tag:s?r:"0x"+r.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},sr=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Fe=(i,e)=>{switch(e){case A.SignedInteger:return i.getInt8(0);case A.UnsignedInteger:return sr(i);case A.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case A.String:return new TextDecoder("ascii").decode(i);case A.UTF8:return new TextDecoder("utf-8").decode(i);case A.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case A.Master:return i;case A.Binary:return i;default:a.assertNever(e)}},bi=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=zl(r);if(!e(s))return;s.type===A.Master&&bi(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},NS=i=>{if(i.getUint32(0)!==y.EBML)return!1;let e,t,r;const s=zl(i);return bi(s.value,({tag:n,type:o,value:l})=>(n===y.EBMLReadVersion?e=Fe(l,o):n===y.DocType?t=Fe(l,o):n===y.DocTypeReadVersion&&(r=Fe(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},Wl=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],CS=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],DS=i=>{let e,t,r,s,n=!1,o=!1,l=!1,d,u;return bi(i,({tag:c,type:h,value:f,valueSize:p})=>{if(c===y.SeekID){const m=Fe(f,h);u=sr(m)}else c!==y.SeekPosition&&(u=void 0);return c===y.Segment?(e=f.byteOffset,t=f.byteOffset+p):c===y.Info?n=!0:c===y.SeekHead?o=!0:c===y.TimestampScale?r=Fe(f,h):c===y.Duration?s=Fe(f,h):c===y.SeekPosition&&u===y.Cues?d=Fe(f,h):n&&o&&Wl.includes(c)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(s,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(s/1e9*r*1e3),cuesSeekPosition:d}},OS=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},LS=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return bi(i,({tag:l,type:d,value:u})=>{switch(l){case y.Cues:t=!0;break;case y.CuePoint:o&&s(o)&&n.push(o),o={};break;case y.CueTime:o&&(o.time=Fe(u,d));break;case y.CueTrackPositions:break;case y.CueClusterPosition:o&&(o.position=Fe(u,d));break;default:t&&Wl.includes(l)&&(r=!0)}return!(t&&r)}),o&&s(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:H.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}}})},xS=i=>{let e=0,t=!1;try{bi(i,r=>r.tag===y.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):CS.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},BS={validateData:NS,parseInit:DS,getIndexRange:OS,parseSegments:LS,parseFeedableSegmentChunk:xS};class Jn{constructor(e,t,r,s,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new ut,this.destroyAbortController=new ut,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(u){return Pe(this,arguments,function*(){const c=this.representations.get(u);a.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 AS(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},m=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:m}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(m=>{if(!this.sourceBuffer)return;const v=Math.min(this.bufferLimit,Wn(this.sourceBuffer.buffered)*.8);this.bufferLimit=v,this.pruneBuffer(this.getCurrentPosition(),m)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(m=>this.error$.next(m))),yield yield R(this.loadInit(c,"high",!0));const h=this.initData.get(c.id),f=this.segments.get(c.id);if(a.assertNonNullable(h,"No init buffer for starting representation"),a.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return yield R(void 0);let p=0;for(const m of f)m.time.from-p>0&&this.gaps.push({representation:c.id,from:p,to:m.time.from}),p=m.time.to;a.isNonNullable(c.duration)&&c.duration-p>0&&this.gaps.push({representation:c.id,from:p,to:c.duration}),yield yield R(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(u){return Pe(this,arguments,function*(){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return yield R(void 0);this.switchingToRepresentationId=u;const c=this.representations.get(u);a.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(a.isNullable(h)?yield yield R(this.loadInit(c,"high",!1)):h instanceof Promise&&(yield yield R(h)),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return yield R(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield yield R(this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal));const f=this.getCurrentPosition();a.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=r,r){case Ot.MP4:this.containerParser=IS;break;case Ot.WEBM:this.containerParser=BS;break;default:a.assertNever(r)}this.initData=new Map(s.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(s.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 ut,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;const s=r.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=lt(this.sourceBuffer.buffered,e),h=s?s.time.to+100:-1/0;s&&c>=s.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&Wn(this.sourceBuffer.buffered)>=this.bufferLimit){const u=lt(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(r,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(l.includes(s))u="high";else{const c=Me(l,0);c&&c.time.from-s.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===H.FED&&!l.length&&lt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Me(r,-1);d&&d.status===H.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===d))}findSegmentStartTime(e){var t,r,s;const n=(r=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&r!==void 0?r: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(s=l==null?void 0:l.time.from)!==null&&s!==void 0?s: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,r){const s=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const v=f<=r&&p>=r,b=f>r||v||m===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&f<=r+S||p<=r+S;return(h===H.NONE||h===H.PARTIALLY_EJECTED&&b&&g&&this.sourceBuffer&&!Fs(this.sourceBuffer.buffered,r))&&b&&g});if(s===-1)return[];if(t!==ye.BYTE_RANGE)return e.slice(s,s+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=s;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===H.NONE||f.status===H.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,r="auto"){return Q(this,void 0,void 0,function*(){if(!e.length)return;let s,n,o=e;const{type:l}=t.segmentReference;switch(l){case ye.BYTE_RANGE:{s=t.segmentReference.url,n={from:Me(e,0).byte.from,to:Me(e,-1).byte.to};break}case ye.TEMPLATE:{const u=Me(e,0);s=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=H.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield a.abortable(d,function(){return Pe(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(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(s,{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:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:r}).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 r=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(r=lt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,r||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,r,s,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=H.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const m of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])m.status===H.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=H.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,p=u===ye.BYTE_RANGE,m=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=r&&f.byte.to<r+e.byteLength))continue;if(n.aborted){o();continue}const b=p?f.byte.from-r:0,S=p?f.byte.to-r:e.byteLength,g=b<s,P=S<=s;if(f.status===H.DOWNLOADING&&g&&P){f.status=H.DOWNLOADED,this.activeSegments.delete(h);const T=new DataView(e.buffer,e.byteOffset+b,m);this.sourceBufferTaskQueue.append(T,n).then(E=>E&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(h.loadedBytes=Math.min(m,s-b),h.loadedBytes>h.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+b+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===m?T:this.containerParser.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(f.status=H.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then(w=>{if(n.aborted)o();else if(w)h.fedBytes+=E.byteLength,h.fedBytes===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){e.status===H.PARTIALLY_FED||e.status===H.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=H.NONE),e.status=H.PARTIALLY_EJECTED):e.status=H.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[s,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const r=this.representations.get(e);r&&(this.initLoadIdleCallback=zn(()=>vr(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return Q(this,void 0,void 0,function*(){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!r&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Pe(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).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),r&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,r=!1){return Q(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let s=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;s+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;c.status===H.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){s=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)||s>t)break;c.status===H.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 p of f)if(p.status===H.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&r){s=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===H.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 r of t){let s={representation:e,from:r.time.from,to:r.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<=r.time.from||o>=r.time.to)){if(o<=r.time.from&&l>=r.time.to){s=void 0;break}l>r.time.from&&l<r.time.to&&(s.from=l),o<r.time.to&&o>r.time.from&&(s.to=o)}}s&&s.to-s.from>=1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=zn(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){const s=Math.round(this.sourceBuffer.buffered.start(r)*1e3),n=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:s,to:n})}const t=1;for(const r of this.segments.values())for(const s of r){const{status:n}=s;if(n!==H.FED&&n!==H.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),l=Math.ceil(s.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?s.status=H.PARTIALLY_EJECTED:s.status=H.NONE)}}}var _t;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(_t||(_t={}));class MS{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new ut,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return Pe(this,arguments,function*(){let n=s;this.requestQuic&&(n=Dt(n));const o=yield yield R(Ct(n,{signal:this.abortAllController.signal}).catch(Xt));return o?(this.onHeadersReceived(o.headers),yield R(o.text())):yield R(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?_t.HEADER:_t.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,m;return Pe(this,arguments,function*(){let v=s;const b=new Headers;if(o)switch(n){case _t.HEADER:{b.append("Range",`bytes=${o.from}-${o.to}`);break}case _t.PARAM:{const $=new URL(v,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),v=$.toString();break}default:a.assertNever(n)}this.requestQuic&&(v=Dt(v));let S=this.abortAllController.signal;if(u){const $=new ut;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.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=a.now(),P=yield yield R(Ct(v,{priority:d,headers:b,signal:S}).catch(Xt)),T=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(T-g),!P)return yield R(null);if(!P.ok||!P.body)return yield R(Promise.reject(new Error(`Fetch error ${P.status}: ${P.statusText}`)));this.onHeadersReceived(P.headers);const E=parseInt((f=P.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!E){const $=yield yield R(P.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed($.byteLength,a.now()-T),l==null||l(new DataView($),$.byteLength),yield R($)}if(!l&&!c)return yield R(P.arrayBuffer());const[w,F]=P.body.tee(),O=w.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(F));let I=0;const U=new ArrayBuffer(E),N=new Uint8Array(U),_=new DataView(U);let G=!1;const K=$=>{G=!0,Xt($)},te=a.abortable(S,function({done:$,value:D}){return Pe(this,arguments,function*(){if(I===0&&this.lastRequestFirstBytes$.next(a.now()-g),S.aborted)return yield R(void 0);$?l==null||l(_,I):D&&(N.set(D,I),I+=D.byteLength,l==null||l(_,I),yield yield R(O==null?void 0:O.read().then(te,K)))})}.bind(this));return yield yield R(O==null?void 0:O.read().then(te,K)),yield R(G?null:U)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){var l;return Pe(this,arguments,function*(){if(s.type!==ye.BYTE_RANGE)return yield R(null);const{from:d,to:u}=s.initRange;let c=d,h=u,f=!1,p,m;s.indexRange&&(p=s.indexRange.from,m=s.indexRange.to,f=u+1===p,f&&(c=Math.min(p,d),h=Math.max(m,u))),c=Math.min(c,0);const v=yield yield R(this.fetch(s.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!v)return yield R(null);const b=new DataView(v,d-c,u-c+1);if(!n.validateData(b))throw new Error("Invalid media file");const S=n.parseInit(b),g=(l=s.indexRange)!==null&&l!==void 0?l:n.getIndexRange(S);if(!g)throw new ReferenceError("No way to load representation index");let P;if(f)P=new DataView(v,g.from-c,g.to-g.from+1);else{const E=yield yield R(this.fetch(s.url,{range:g,priority:o,measureThroughput:!1}));if(!E)return yield R(null);P=new DataView(E)}const T=n.parseSegments(P,S,g);return yield R({dataView:new DataView(v),segments:T})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return Pe(this,arguments,function*(){if(s.type!==ye.TEMPLATE)return yield R(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield R(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield R(null);const d=s.segments.map(u=>Object.assign(Object.assign({},u),{status:H.NONE,size:void 0}));return yield R({segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=jl(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){var s,n;return Q(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case ye.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case ye.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,r))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Xt=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var VS=He,FS=ni,US=ue,jS=US("match"),HS=function(i){var e;return VS(i)&&((e=i[jS])!==void 0?!!e:FS(i)=="RegExp")},GS=ci,YS=String,qS=function(i){if(GS(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return YS(i)},zS=Ye,WS=function(){var i=zS(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},QS=ve,JS=Oe,KS=nr,XS=WS,Kn=RegExp.prototype,ZS=function(i){var e=i.flags;return e===void 0&&!("flags"in Kn)&&!JS(i,"flags")&&KS(Kn,i)?QS(XS,i):e},va=$e,eg=dr,tg=Math.floor,rs=va("".charAt),ig=va("".replace),ss=va("".slice),rg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,sg=/\$([$&'`]|\d{1,2})/g,ag=function(i,e,t,r,s,n){var o=t+i.length,l=r.length,d=sg;return s!==void 0&&(s=eg(s),d=rg),ig(n,d,function(u,c){var h;switch(rs(c,0)){case"$":return"$";case"&":return i;case"`":return ss(e,0,t);case"'":return ss(e,o);case"<":h=s[ss(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=tg(f/10);return p===0?u:p<=l?r[p-1]===void 0?rs(c,1):r[p-1]+rs(c,1):u}h=r[f-1]}return h===void 0?"":h})},ng=we,og=ve,ma=$e,Xn=js,lg=se,ug=oi,dg=HS,$t=qS,cg=ur,hg=ZS,fg=ag,pg=ue,vg=pg("replace"),mg=TypeError,Ql=ma("".indexOf),bg=ma("".replace),Zn=ma("".slice),Sg=Math.max,eo=function(i,e,t){return t>i.length?-1:e===""?t:Ql(i,e,t)};ng({target:"String",proto:!0},{replaceAll:function(e,t){var r=Xn(this),s,n,o,l,d,u,c,h,f,p=0,m=0,v="";if(!ug(e)){if(s=dg(e),s&&(n=$t(Xn(hg(e))),!~Ql(n,"g")))throw mg("`.replaceAll` does not allow non-global regexes");if(o=cg(e,vg),o)return og(o,e,r,t);if(s)return bg($t(r),e,t)}for(l=$t(r),d=$t(e),u=lg(t),u||(t=$t(t)),c=d.length,h=Sg(1,c),p=eo(l,d,0);p!==-1;)f=u?$t(t(d,p,l)):fg(d,l,p,[],void 0,t),v+=Zn(l,m,p)+f,m=p+c,p=eo(l,d,p+h);return m<l.length&&(v+=Zn(l,m)),v}});var gg=ca,yg=gg("String","replaceAll"),Eg=yg,Tg=Eg,$g=Tg,kg=$g,to=kg;const io=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),s=(r==null?void 0:r[1])==="-"?-1:1,n={days:e(r==null?void 0:r[5],s),hours:e(r==null?void 0:r[6],s),minutes:e(r==null?void 0:r[7],s),seconds:e(r==null?void 0:r[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},as=(i,e)=>{let t=i;t=to(t,"$$","$");const r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(r)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=to(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Pg=(i,e)=>{var t,r,s,n,o,l,d,u,c,h,f,p,m,v,b,S,g,P,T,E,w,F,O,I,U,N,_,G,K,te,$,D,z,ee,ie,he,_e;const j=new DOMParser().parseFromString(i,"application/xml"),ae={video:[],audio:[],text:[]},de=j.children[0],me=de.getElementsByTagName("Period")[0],it=me.children;let Re;const Je=de.getAttribute("mediaPresentationDuration"),rt=me.getAttribute("duration");if(Je)Re=io(Je);else if(rt){const Ie=io(rt);a.isNonNullable(Ie)&&(Re=Ie)}let Vt=0;const bt=(r=(t=de.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&r!==void 0?r:[],tu=bt.includes(rr.WEBM_AS_IN_FFMPEG)||bt.includes(rr.WEBM_AS_IN_SPEC)?Ot.WEBM:Ot.MP4;for(const Ie of it){const Si=Ie.getAttribute("mimeType"),iu=Ie.getAttribute("codecs"),ba=(s=Ie.getAttribute("contentType"))!==null&&s!==void 0?s:Si==null?void 0:Si.split("/")[0],ru=(o=(n=Ie.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],su=Ie.querySelectorAll("Representation"),au=Ie.querySelector("SegmentTemplate");if(ba!=="text")for(const ne of su){const Ft=(l=ne.getAttribute("mimeType"))!==null&&l!==void 0?l:Si,Sa=(u=(d=ne.getAttribute("codecs"))!==null&&d!==void 0?d:iu)!==null&&u!==void 0?u:"",gi=(h=(c=ne.getAttribute("contentType"))!==null&&c!==void 0?c:Ft==null?void 0:Ft.split("/")[0])!==null&&h!==void 0?h:ba,nu=(p=(f=Ie.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&p!==void 0?p:[],ou=parseInt((m=ne.getAttribute("width"))!==null&&m!==void 0?m:"",10),ga=parseInt((v=ne.getAttribute("height"))!==null&&v!==void 0?v:"",10),ya=parseInt((b=ne.getAttribute("bandwidth"))!==null&&b!==void 0?b:"",10)/1e3,Ea=(S=ne.getAttribute("frameRate"))!==null&&S!==void 0?S:"",lu=(g=ne.getAttribute("quality"))!==null&&g!==void 0?g:void 0,uu=Ea?fa(Ea):void 0,du=(P=ne.getAttribute("id"))!==null&&P!==void 0?P:(Vt++).toString(10),cu=gi==="video"?`${ga}p`:gi==="audio"?`${ya}Kbps`:Sa,hu=`${du}@${cu}`,fu=(w=(E=(T=ne.querySelector("BaseURL"))===null||T===void 0?void 0:T.textContent)===null||E===void 0?void 0:E.trim())!==null&&w!==void 0?w:"",Ta=new URL(fu,e).toString(),pu=[...bt,...ru,...nu];let Sr;const vu=ne.querySelector("SegmentBase"),st=(F=ne.querySelector("SegmentTemplate"))!==null&&F!==void 0?F:au;if(vu){const Ut=(I=(O=ne.querySelector("SegmentBase Initialization"))===null||O===void 0?void 0:O.getAttribute("range"))!==null&&I!==void 0?I:"",[jt,yr]=Ut.split("-").map(at=>parseInt(at,10)),Ht={from:jt,to:yr},Gt=(U=ne.querySelector("SegmentBase"))===null||U===void 0?void 0:U.getAttribute("indexRange"),[Er,yi]=Gt?Gt.split("-").map(at=>parseInt(at,10)):[],Yt=Gt?{from:Er,to:yi}:void 0;Sr={type:ye.BYTE_RANGE,url:Ta,initRange:Ht,indexRange:Yt}}else if(st){const Ut={representationId:(N=ne.getAttribute("id"))!==null&&N!==void 0?N:void 0,bandwidth:(_=ne.getAttribute("bandwidth"))!==null&&_!==void 0?_:void 0},jt=parseInt((G=st.getAttribute("timescale"))!==null&&G!==void 0?G:"",10),yr=(K=st.getAttribute("initialization"))!==null&&K!==void 0?K:"",Ht=st.getAttribute("media"),Gt=($=parseInt((te=st.getAttribute("startNumber"))!==null&&te!==void 0?te:"",10))!==null&&$!==void 0?$:1,Er=as(yr,Ut);if(!Ht)throw new ReferenceError("No media attribute in SegmentTemplate");const yi=(D=st.querySelectorAll("SegmentTimeline S"))!==null&&D!==void 0?D:[],Yt=[];if(yi.length){let at=Gt,nt=0;for(const qt of yi){const St=parseInt((z=qt.getAttribute("d"))!==null&&z!==void 0?z:"",10)*1e3,zt=parseInt((ee=qt.getAttribute("r"))!==null&&ee!==void 0?ee:"",10)||0,Wt=(he=parseInt((ie=qt.getAttribute("t"))!==null&&ie!==void 0?ie:"",10))!==null&&he!==void 0?he:void 0;for(let $a=0;$a<zt+1;$a++){const mu=as(Ht,Object.assign(Object.assign({},Ut),{segmentNumber:at.toString(10),segmentTime:Wt.toString(10)})),bu=Wt?Wt/jt:nt;nt+=St/jt;const Su=nt;at++,Yt.push({time:{from:bu,to:Su},url:mu})}}}else if(a.isNonNullable(Re)){const nt=parseInt((_e=st.getAttribute("duration"))!==null&&_e!==void 0?_e:"",10)/jt*1e3,qt=Math.ceil(Re/nt);let St=0;for(let zt=1;zt<qt;zt++){const Wt=as(Ht,Object.assign(Object.assign({},Ut),{segmentNumber:zt.toString(10),segmentTime:St.toString(10)}));Yt.push({time:{from:St,to:St+nt},url:Wt}),St+=nt}}Sr={type:ye.TEMPLATE,baseUrl:Ta,initUrl:Er,segments:Yt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!gi||!Ft)continue;const gr={video:ge.VIDEO,audio:ge.AUDIO,text:ge.TEXT}[gi];gr&&ae[gr].push({id:hu,kind:gr,segmentReference:Sr,profiles:pu,duration:Re,bitrate:ya,mime:Ft,codecs:Sa,width:ou,height:ga,fps:uu,quality:lu})}}return{duration:Re,container:tu,representations:ae}},Ag=["timeupdate","progress","play","seeked","stalled","waiting"];var Se;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Se||(Se={}));let wg=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.state$=new J(Se.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new ut,this.initManifest=a.abortable(this.destroyController.signal,function(t,r){return Pe(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(Se.MANIFEST_READY);const s=yield yield R(this.fetcher.fetchManifest(r).catch(l=>this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l})));if(!s)return yield R(void 0);let n;try{n=Pg(s!=null?s:"",r)}catch(l){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return yield R(void 0);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=Object.assign(Object.assign({},n),{representations:hi(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))}),this.manifest.representations.video.length?this.state$.setState(Se.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,r){return Pe(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.state$.startTransitionTo(Se.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new Jn(ge.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new Jn(ge.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),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=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.subscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.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:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield yield R(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(r)?yield yield R(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield R(this.videoBufferManager.startWith(t)),this.state$.setState(Se.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;const s=this.element.currentTime*1e3;this.videoBufferManager.maintain(s),(t=this.audioBufferManager)===null||t===void 0||t.maintain(s),(this.videoBufferManager.gaps.length||!((r=this.audioBufferManager)===null||r===void 0)&&r.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new MS({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(Se.RUNNING),this.subscription.add(a.merge(...Ag.map(e=>a.fromEvent(this.element,e)),a.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:a.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(a.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(a.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Fs(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return Q(this,void 0,void 0,function*(){const r={[ge.VIDEO]:this.videoBufferManager,[ge.AUDIO]:this.audioBufferManager,[ge.TEXT]:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var r,s,n,o,l;a.assertNonNullable(this.element),a.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((r=this.videoBufferManager.findSegmentStartTime(e))!==null&&r!==void 0?r:e,(n=(s=this.audioBufferManager)===null||s===void 0?void 0:s.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Fs(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(Se.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 r of this.bufferManagers)for(const s of r.gaps)r.playingRepresentation$.getValue()===s.representation&&s.from<=e&&s.to>e&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?t.push(1/0):t.push(s.to));if(t.length){const r=Math.max(...t);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};var X;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));const _g=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?mi(n):void 0)!==null&&o!==void 0?o:vt({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},Rg=({id:i,bitrate:e})=>({id:i,bitrate:e}),Ig=(i,e,t)=>{var r;const s=e.indexOf(t);return(r=Me(i,Math.round(i.length*s/e.length)))!==null&&r!==void 0?r:Me(i,-1)};class Ng{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(X.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Le,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new eS,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===C.Requested&&(s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&t!==X.STOPPED&&r!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),r===exports.PlaybackState.STOPPED){t!==X.STOPPED&&(this.videoState.startTransitionTo(X.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(X.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(t){case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();return;case X.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case X.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case X.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}}},this.params=e,this.video=ze(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(ce(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new wg({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=We(this.video),s=u=>{e.error$.next({id:"DashVKProvider",category:a.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,c)=>this.subscription.add(u.subscribe(c,s));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.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(a.filter(a.isNonNullable),a.once(),a.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(mt(this.video,t.isLooped,s)),this.subscription.add(qe(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(et(this.video,t.playbackRate,r.playbackRateState$,s)),n(tr(this.video),this.elementSize$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===Se.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const h=this.player.getRepresentations();a.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((v,b)=>b.bitrate-v.bitrate),p=Array.from(h.video).sort((v,b)=>b.bitrate-v.bitrate);if(!this.params.tuning.isAudioDisabled)for(const v of f){const b=Rg(v);b&&this.audioTracks.push({track:b,representation:v})}for(const v of p){const b=_g(v);if(b){this.videoTracks.push({track:b,representation:v});const S=!this.params.tuning.isAudioDisabled&&Ig(f,p,v);S&&this.audioRepresentations.set(v.id,S)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const m=this.selectVideoRepresentation();a.assertNonNullable(m),this.player.initRepresentations(m.id,(c=this.audioRepresentations.get(m.id))===null||c===void 0?void 0:c.id)}else u===Se.REPRESENTATIOS_READY&&(this.videoState.setState(X.READY),this.player.initBuffer())},s));const o=u=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==Se.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(ge.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(ge.AUDIO,f.id).catch(o)}},s)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.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$,s)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.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(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){var e,t,r,s,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=lt(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(u&&!l&&(r=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&r!==void 0?r:0,c&&(n=(s=this.audioRepresentations.get(c.id))===null||s===void 0?void 0:s.bitrate)!==null&&n!==void 0?n:0),v=vi(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:m,forwardBufferHealth:p,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),b=l?v!=null?v:u:u!=null?u:v;return b&&((o=this.videoTracks.find(({track:S})=>S===b))===null||o===void 0?void 0:o.representation)}prepare(){return Q(this,void 0,void 0,function*(){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),Qe(this.video)}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const Cg=5e3,xe={};var V;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const Bi=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class Dg{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(V.INITIALIZING),this.textTracksManager=new Le,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==V.INITIALIZING)switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&this.seek(n.position),r){case exports.PlaybackState.STOPPED:switch(t){case V.STOPPED:break;case V.READY:case V.PLAYING:case V.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case V.STOPPED:this.prepare();break;case V.READY:case V.PLAYING:case V.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case V.PLAYING:break;case V.STOPPED:this.prepare();break;case V.READY:case V.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case V.PAUSED:break;case V.STOPPED:this.prepare();break;case V.READY:this.videoState.setState(V.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case V.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(r)}},this.video=ze(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(ce(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),Qe(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),Cg);vr(import("hls.js").then(s=>{e||(xe.Hls=s.default,xe.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(xe.Hls,"hls.js not loaded"),this.hls=new xe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(V.STOPPED)}subscribe(){a.assertNonNullable(xe.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},s=We(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,r));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),n(s.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(mt(this.video,e.isLooped,r)),this.subscription.add(qe(this.video,e.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,e.playbackRate,s.playbackRateState$,r)),this.subscription.add(Bi(this.hls,xe.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.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(s.playing$.subscribe(()=>{this.videoState.setState(V.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(V.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===V.READY&&this.videoState.setState(V.READY),this.videoState.getState()===V.PLAYING&&this.playIfAllowed()},r)),n(Bi(this.hls,xe.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const m=h.name||h.height.toString(10),{width:v,height:b}=h,S=(p=mi((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:vt({width:v,height:b});if(!S)return c;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,P={id:m.toString(),quality:S,bitrate:h.bitrate/1e3,size:{width:v,height:b},fps:g};return this.trackLevels.set(m,{track:P,level:h}),c.push(P),c},[]))),t.availableVideoTracks$),n(Bi(this.hls,xe.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>ce(u))),t.hostname$),this.subscription.add(De(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));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=Bi(this.hls,xe.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(De(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(a.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),p=this.hls.currentLevel,m=this.hls.levels[p];!m||h.bitrate>m.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(a.map(u=>u==null?void 0:u.id)),onError:r})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo(V.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return Q(this,void 0,void 0,function*(){this.videoState.startTransitionTo(V.PLAYING),(yield tt(this.video))||(this.videoState.setState(V.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(V.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(V.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const ro="X-Playback-Duration";var so=i=>Q(void 0,void 0,void 0,function*(){const e=yield Ct(i,{method:"HEAD"});return e.headers.has(ro)?parseInt(e.headers.get(ro),10):void 0});const Og=i=>{let e=null;if(i.QUALITY&&(e=mi(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=vt({width:t,height:r})}return e!=null?e:null},Jl=(i,e=i)=>Q(void 0,void 0,void 0,function*(){var t;const n=(yield(yield Ct(i)).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=hi(u[1].split(",").map(S=>S.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Og(c);let p;c.BANDWIDTH&&(p=parseInt(c.BANDWIDTH,10)/1e3||void 0),!p&&c["AVERAGE-BANDWIDTH"]&&(p=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let v;if(c.RESOLUTION){const[S,g]=c.RESOLUTION.split("x").map(P=>parseInt(P,10));S&&g&&(v={width:S,height:g})}const b=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:b,bandwidth:p,size:v,fps:m})}return o});var Y;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(Y||(Y={}));class Lg{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new J(Y.STOPPED),this.textTracksManager=new Le,this.manifests$=new a.ValueSubject([]),this.liveOffset=new ha,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{const s=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){s!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.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(Y.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(s===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(Y.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===C.Requested){this.videoState.startTransitionTo(Y.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(s){case Y.READY:n===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.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 Y.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.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 Y.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=ze(e.container),this.params.output.element$.next(this.video);const r={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([r]),Jl(Nt(this.params.source.url),this.params.source.url).then(s=>{this.manifests$.next([r,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),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(ce(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},s=We(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(qe(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(s.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&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ce(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===Y.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===C.Requested&&this.seek(l.position)},r)),this.subscription.add(s.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)},r)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),r)),this.subscription.add(this.manifests$.pipe(a.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$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=Nt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),so(t).then(r=>{var s;if(!a.isNullable(r))this.maxSeekBackTime$.next(r);else{const n=(s=this.params.source.maxSeekBackTime)!==null&&s!==void 0?s:this.maxSeekBackTime$.getValue();if(a.isNullable(n)||!isFinite(n))try{Ct(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();so(u).then(c=>{a.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}}var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(W||(W={}));class xg{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(W.STOPPED),this.textTracksManager=new Le,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s===exports.PlaybackState.STOPPED){r!==W.STOPPED&&(this.videoState.startTransitionTo(W.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(W.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(r===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(W.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===C.Requested&&this.seek(u.position),r){case W.READY:s===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case W.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=ze(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(ce(this.params.source.url)),Jl(this.params.source.url).then(r=>{this.manifests$.next([t,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},s=We(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(qe(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},r).add(s.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&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ce(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===W.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===C.Requested&&this.seek(l.position)},r))),this.subscription.add(this.manifests$.pipe(a.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$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var Z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Z||(Z={}));class Bg{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(Z.STOPPED),this.trackUrls={},this.textTracksManager=new Le,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==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 o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(t===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:d*1e3,forcePrecise:!0});return}switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&l.state===C.Requested&&this.seek(l.position),t){case Z.READY:r===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.video=ze(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,r],s)=>{const n=s.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:r}}),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,r=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},s=We(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(qe(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(this.video,t.playbackRate,s.playbackRateState$,r)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Z.READY&&this.videoState.setState(Z.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&a.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Qe(this.video)}prepare(){var e,t;const r=(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();a.assertNonNullable(r,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[r];a.assertNonNullable(s,`MpegProvider: No url for ${r}`),this.params.tuning.requestQuick&&(s=Dt(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(ce(s))}playIfAllowed(){tt(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}}const ao=["stun:videostun.mycdn.me:80"],Mg=1e3,Vg=3,ns=()=>null;class Fg{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=ns,this.externalStopCallback=ns,this.externalErrorCallback=ns,this.options=this.normalizeOptions(t);const r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.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}}handleUpdateMessage(e){return Q(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return Q(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:ao}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return Q(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return Q(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:a.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return Q(this,void 0,void 0,function*(){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()))}}createOffer(){return Q(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))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),Mg)}normalizeOptions(e={}){const t={stunServerList:ao,maxRetryNumber:Vg,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));class Ug{constructor(e){this.videoState=new J(q.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==q.STOPPED&&(this.videoState.startTransitionTo(q.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(q.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===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case q.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ze(e.container),this.liveStreamClient=new Fg(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),Qe(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const s=We(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,r));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===q.READY&&this.videoState.setState(q.READY)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED)},r)).add(s.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING)},r)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(qe(this.video,t.volume,s.volumeState$,r)).add(s.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case q.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case q.READY:break;case q.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case q.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},r)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}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(ce(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(q.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:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class no{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 jg=()=>{var i,e;const t=window.navigator;return t.userAgentData?((e=(i=t.userAgentData)===null||i===void 0?void 0:i.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},os,ls,us,ds,cs,hs,Mi,fs,Vi,ps,Fi,vs,Ui,ms,ji,bs;const Kl=jg(),Ke=document.createElement("video"),Be={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((ls=(os=window.SourceBuffer)===null||os===void 0?void 0:os.prototype)===null||ls===void 0?void 0:ls.appendBuffer)),hls:Boolean(((us=Ke.canPlayType)===null||us===void 0?void 0:us.call(Ke,"application/x-mpegurl"))||((ds=Ke.canPlayType)===null||ds===void 0?void 0:ds.call(Ke,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},be={mp4:Boolean((cs=Ke.canPlayType)===null||cs===void 0?void 0:cs.call(Ke,"video/mp4")),webm:Boolean((hs=Ke.canPlayType)===null||hs===void 0?void 0:hs.call(Ke,"video/webm")),cmaf:!0},Xe={h264:Boolean((fs=(Mi=window.MediaSource)===null||Mi===void 0?void 0:Mi.isTypeSupported)===null||fs===void 0?void 0:fs.call(Mi,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((ps=(Vi=window.MediaSource)===null||Vi===void 0?void 0:Vi.isTypeSupported)===null||ps===void 0?void 0:ps.call(Vi,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((vs=(Fi=window.MediaSource)===null||Fi===void 0?void 0:Fi.isTypeSupported)===null||vs===void 0?void 0:vs.call(Fi,'video/webm; codecs="vp9"')),aac:Boolean((ms=(Ui=window.MediaSource)===null||Ui===void 0?void 0:Ui.isTypeSupported)===null||ms===void 0?void 0:ms.call(Ui,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((bs=(ji=window.MediaSource)===null||ji===void 0?void 0:ji.isTypeSupported)===null||bs===void 0?void 0:bs.call(ji,'audio/webm; codecs="opus"'))},kt=(Xe.h264||Xe.h265)&&Xe.aac,br=Be.hls&&be.mp4,Hg=Boolean(window.WebSocket),Gg=()=>Object.keys(Xe).filter(i=>Xe[i]),Yg=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return Be.mse&&be.mp4&&kt;case exports.VideoFormat.DASH_SEP:return Be.mse&&be.mp4&&kt;case exports.VideoFormat.DASH_WEBM:return Be.mse&&be.webm&&Xe.vp9&&Xe.opus;case exports.VideoFormat.DASH_LIVE:return Be.mse&&be.mp4&&kt;case exports.VideoFormat.DASH_LIVE_CMAF:return Be.mse&&be.mp4&&kt&&be.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return Be.mse&&be.mp4&&kt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return br||e&&Be.mse&&be.mp4&&kt;case exports.VideoFormat.MPEG:return be.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Be.webrtc&&Hg&&Xe.h264&&(be.mp4||be.webm);default:return a.assertNever(t)}}),qg=()=>Kl?[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]:br?[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],zg=()=>Kl?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:br?[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],oo=i=>i?[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 Wg=i=>new a.Observable(e=>{const t=new a.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),s=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$,o=new a.Subject;let l=0,d="unknown";return t.add(r.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(l),d="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const lo={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Qg={cacheDuration:12e4},Jg={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Kg={maxPausedTime:3e4},uo={maxPausedTime:3e4};class Xg{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),element$:new a.ValueSubject(void 0)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Yg([...zg(),...qg()],this.params.tuning.useHlsJs).filter(o=>a.isNonNullable(e.sources[o])),{formatsToAvoid:r}=this.params.tuning,s=r.length?[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:t;this.screenFormatsIterator=new no(s);const n=[...oo(!0),...oo(!1)];this.chromecastFormatsIterator=new no(n.filter(o=>a.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(a.isNullable(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}r?this.current$.next({type:t,provider:r,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;a.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,r=this.params.desiredState.seekState.getState(),s=r.state!==C.None;this.params.desiredState.seekState.setState({state:C.Requested,position:s?r.position:t,forcePrecise:s?r.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 fe.SCREEN:return this.createScreenProvider(t);case fe.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:r,desiredState:s}=this.params,n=this.providerOutput,o={container:r,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new $S(Object.assign(Object.assign({},o),{source:l,config:Qg}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new Yn(Object.assign(Object.assign({},o),{source:l,format:e,config:uo})):new Ng(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Yn(Object.assign(Object.assign({},o),{source:l,format:e,config:uo}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),br||!this.params.tuning.useHlsJs?new xg(Object.assign(Object.assign({},o),{source:l})):new Dg(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Lg(Object.assign(Object.assign({},o),{source:l,config:Kg}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Bg(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new SS(Object.assign(Object.assign({},o),{source:l,config:Jg}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Ug({container:r,source:l,desiredState:s,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 a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:r,desiredState:s,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new Ab({connection:l,meta:n,container:r,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?fe.CHROMECAST:fe.SCREEN}chooseFormat(e){switch(e){case fe.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case fe.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case fe.SCREEN:return this.screenFormatsIterator.next();case fe.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case fe.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case fe.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const r=s=>{const n=new URL(s);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 Object.assign(Object.assign({},e),{url:r(e.url)})}return hi(Object.entries(e).map(([s,n])=>[s,r(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,r=0;return e.add(a.merge(this.providerOutput.error$,Wg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:lo.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(a.filter(({type:s})=>s!==void 0))}).pipe(a.map(s=>({id:`ProviderHangup:${s}`,category:a.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{if(this.current$.getValue().destination===fe.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=s.category===a.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<lo.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var Ee;(function(i){i[i.LOCAL_STORAGE=0]="LOCAL_STORAGE",i[i.SESSION_STORAGE=1]="SESSION_STORAGE",i[i.RUNTIME=2]="RUNTIME"})(Ee||(Ee={}));const Xl=new Map;let dt=Ee.RUNTIME;const Ss=`vk-videoplayer-dummy-key-${Math.random()}`,Zg=()=>{try{localStorage.setItem(Ss,"test"),localStorage.removeItem(Ss),dt=Ee.LOCAL_STORAGE}catch(i){if(i instanceof DOMException||i instanceof TypeError)try{sessionStorage.getItem(Ss),dt=Ee.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)dt=Ee.RUNTIME;else throw e}else throw i}};Zg();const ey=i=>{var e,t;switch(dt){case Ee.LOCAL_STORAGE:return(e=localStorage.getItem(i))!==null&&e!==void 0?e:void 0;case Ee.SESSION_STORAGE:return(t=sessionStorage.getItem(i))!==null&&t!==void 0?t:void 0;case Ee.RUNTIME:return Xl.get(i);default:a.assertNever(dt)}},co=(i,e)=>{switch(dt){case Ee.LOCAL_STORAGE:try{localStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Ee.SESSION_STORAGE:try{sessionStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Ee.RUNTIME:return void Xl.set(i,e);default:a.assertNever(dt)}},Us=(i,e,t)=>t*e+(1-t)*i,Zl=(i,e)=>i.reduce((t,r)=>t+r,0)/e,ty=(i,e,t,r)=>{let s=0,n=t;const o=Zl(i,e),l=e<r?e:r;for(let d=0;d<l;d++)i[n]>o?s++:s--,n=(i.length+n-1)%i.length;return Math.abs(s)===l};class eu{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 a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const r=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ce(`raw_${r}`),this.smoothedSeries$=new Ce(`smoothed_${r}`),this.reportedSeries$=new Ce(`reported_${r}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;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)&&(a.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 iy extends eu{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Us(this.slow,e,this.params.emaAlphaSlow),this.fast=Us(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class ry extends eu{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Zl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Us(this.emaSmoothed,e,this.params.emaAlpha);const r=ty(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}}class ho{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new iy({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ry({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}}const sy=5e3,fo="one_video_throughput",po="one_video_rtt",je=window.navigator.connection,vo=()=>{const i=je==null?void 0:je.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},mo=()=>{const i=je==null?void 0:je.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},bo=(i,e,t)=>{const r=t*8,s=r/i;return r/(s+e)};class ri{constructor(e){var t,r;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const s=ri.load(fo)||(e.useBrowserEstimation?vo():void 0)||sy,n=(r=(t=ri.load(po))!==null&&t!==void 0?t:e.useBrowserEstimation?mo():void 0)!==null&&r!==void 0?r:0;if(this.throughput$=new a.ValueSubject(s),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(bo(s,n,e.rttPenaltyRequestSize)),this.throughput=ho.getSmoothedValue(s,-1,e),this.rtt=ho.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=vo();d&&this.throughput.next(d);const u=mo();a.isNonNullable(u)&&this.rtt.next(u)};je&&"onchange"in je&&this.subscription.add(a.fromEvent(je,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{co(fo,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{co(po,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(a.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a.map(({throughput:o,rtt:l})=>bo(o,l,e.rttPenaltyRequestSize)),a.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,r=a.now();const s=new a.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,r=a.now()}));break;case 1:case 0:s.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,r=a.now()}));break}s.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-r;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let r=0;const s=a.now();let n=0,o=a.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=({done:u,value:c})=>Q(this,void 0,void 0,function*(){u?(this.addRawSpeed(r,a.now()-s,1),this.concurrentDownloads.delete(e)):c&&(r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&a.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,a.now()-o,this.concurrentDownloads.size),n=0,o=a.now()),yield t==null?void 0:t.read().then(d,l))});this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,r=1){if(ri.sanityCheck(e,t)){const s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||e<10*1024||t<=20)}static load(e){var t;const r=ey(e);if(a.isNonNullable(r))return(t=parseInt(r,10))!==null&&t!==void 0?t:void 0}}const So={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}},ay=i=>{const e={};for(const t of Object.keys(So)){const r=So[t],s=i[t];Array.isArray(r)&&Array.isArray(s)?e[t]=s:typeof r=="object"&&typeof s=="object"?e[t]=Object.assign(Object.assign({},r),s):e[t]=s!=null?s:r}return e};var ny=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var r;return t.state===C.None?void 0:((r=t.position)!==null&&r!==void 0?r:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===C.None))),oy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const go=({playbackState:i,seekState:e,playbackAbort$:t,looped$:r,position$:s})=>new a.Observable(n=>{let o;const l=i.transitionEnded$.pipe(a.filter(p=>(p.from===exports.PlaybackState.PAUSED||p.from===exports.PlaybackState.STOPPED)&&p.to===exports.PlaybackState.PLAYING)),d=i.stateChangeEnded$.pipe(a.filter(p=>p.from===exports.PlaybackState.PLAYING&&p.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(a.filter(({to:p})=>{var m,v;return p.state===C.Requested&&((v=(m=i.getTransition())===null||m===void 0?void 0:m.from)!==null&&v!==void 0?v:i.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(a.filter(({from:p,to:m})=>{var v,b;return p.state===C.Applying&&m.state===C.None&&((b=(v=i.getTransition())===null||v===void 0?void 0:v.from)!==null&&b!==void 0?b:i.getState())===exports.PlaybackState.PLAYING})),h=a.merge(l,c).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable)),f=a.merge(a.merge(d,u,t),r).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable));return new a.Subscription().add(h.subscribe(p=>{o=p})).add(f.subscribe(p=>{if(a.isNullable(o)||o===p)return;const m={from:o,to:p};o=void 0,n.next(m)}))});class ly{constructor(e={}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new J(exports.PlaybackState.STOPPED),seekState:new J({state:C.None}),volume:new J({volume:1,muted:!1}),videoTrack:new J(void 0),autoVideoTrackSwitching:new J(!0),autoVideoTrackLimits:new J({}),isLooped:new J(!1),playbackRate:new J(1),externalTextTracks:new J([]),currentTextTrack:new J(void 0),textTrackCuesSettings:new J({})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0)},this.events={inited$:new a.Subject,started$:new a.Subject,willPause$:new a.Subject,willResume$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:Kb},this.initLogs(),this.tuning=ay(e),this.chromecastInitializer=new Ru({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ri(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,s)=>{const n=Reflect.get(t,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,p)=>{const m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,r,s;return this.config=e,this.domContainer=oy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Xg({sources:e.sources,meta:(r=e.meta)!==null&&r!==void 0?r:{},failoverHosts:(s=e.failoverHosts)!==null&&s!==void 0?s:[],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:C.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){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const r=t.find(s=>s.quality===e);return r&&this.desiredState.videoTrack.startTransitionTo(r.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const r=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return r&&(this.desiredState.playbackRate.setState(e),r.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(r=>r.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(){a.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),r=t.state===C.None?void 0:t.position;return a.isNonNullable(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((r,{width:s})=>r||s||0,0),height:e.reduce((r,{height:s})=>r||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(()=>!this.isPlaybackStarted),a.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===C.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},d),{state:C.Applying})):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===C.Applying&&(this.desiredState.seekState.setState({state:C.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(d=>d.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(d=>d.map(({quality:u})=>u).sort((u,c)=>Zi(u)?1:Zi(c)?-1:qi(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(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.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(a.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(a.map(d=>d.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(d=>d.volume),a.filterChanged()).subscribe(this.info.volume$)).add(ny({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.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(a.map(d=>({id:"NoProviders",category:a.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(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.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 a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const r=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:d})=>d===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>r.next(!1)));let s=0;const n=a.merge(e.providerOutput.isBuffering$,t,r).pipe(a.map(()=>{const d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||r.getValue();return d&&!u}),a.filterChanged());this.subscription.add(n.subscribe(d=>{d?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))}));const o=new a.Subscription;this.subscription.add(o);const l=a.merge(a.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(a.filter(d=>Boolean(d==null?void 0:d.provider))));e.providerOutput.isLive$.pipe(a.filterChanged()).subscribe(d=>{switch(a.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new a.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>u.next(c&&Math.floor(c/1e3)))),o.add(go({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:l,looped$:this.events.looped$,position$:u}).pipe(a.map(({from:c,to:h})=>({start:c,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(go({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:l,position$:this.providerContainer.providerOutput.position$}).pipe(a.map(({from:u,to:c})=>({start:u,end:c}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(a.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(a.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 a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((r,s)=>r.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:r})=>r===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=vi(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(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.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;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),Jb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Qb(r)),this.providerContainer.current$.subscribe(({type:r})=>Oi("provider",r)),t.duration$.subscribe(r=>Oi("duration",r)),t.availableVideoTracks$.pipe(a.filter(r=>!!r.length),a.once()).subscribe(r=>Oi("tracks",r)),this.events.fatalError$.subscribe(new Ce("fatalError")),this.events.managedError$.subscribe(new Ce("managedError")),t.position$.subscribe(new Ce("position")),t.currentVideoTrack$.pipe(a.map(r=>r==null?void 0:r.quality)).subscribe(new Ce("quality")),this.info.currentBuffer$.subscribe(new Ce("buffer")),t.isBuffering$.subscribe(new Ce("isBuffering"))].forEach(r=>this.subscription.add(r)),Oi("codecs",Gg())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},r=()=>Q(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:a.ErrorCategory.DOM,message:String(s)})})});this.subscription.add(a.merge(a.fromEvent(document,"visibilitychange"),a.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const s=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=Boolean(e)&&!(e!=null&&e.released);s&&n?o||r():t()})).add(this.events.willDestruct$.subscribe(t))}}const uy=`${wu}@${Au}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});exports.Player=ly;exports.SDK_VERSION=uy;