@vkontakte/videoplayer-core 2.0.78-dev.196c6f0.0 → 2.0.78
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 +3 -3
- package/es2015.esm.js +5 -5
- package/es2018.cjs.js +3 -3
- package/es2018.esm.js +3 -3
- package/esnext.cjs.js +3 -3
- package/esnext.esm.js +3 -3
- package/package.json +2 -2
package/es2018.cjs.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.78
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.78
|
|
3
|
+
* Thu, 02 Feb 2023 10:14:35 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-78/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var qn=Object.create;var tr=Object.defineProperty;var Yn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Qn=Object.getPrototypeOf,Wn=Object.prototype.hasOwnProperty;var Jn=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of zn(e))!Wn.call(s,r)&&r!==t&&tr(s,r,{get:()=>e[r],enumerable:!(i=Yn(e,r))||i.enumerable});return s};var ir=(s,e,t)=>(t=s!=null?qn(Qn(s)):{},Jn(e||!s||!s.__esModule?tr(t,"default",{value:s,enumerable:!0}):t,s));var a=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),Kn=require("lodash/debounce.js");const Xn="2.0.78-dev.196c6f0.0",Zn="@vkontakte/videoplayer-core";exports.PlaybackState=void 0;(function(s){s.STOPPED="stopped",s.PLAYING="playing",s.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var le;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(le||(le={}));exports.ChromecastState=void 0;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var D;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(D||(D={}));var eo=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class to{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 i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);r?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||eo("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 i,r,n;(n=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.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),i=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=i.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(r.sessionState)}})).add(a.merge(a.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),a.map(r=>r.castState)),a.observableFrom([i.getCastState()])).pipe(a.filterChanged(),a.map(io),a.tap(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var n;const o=r===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=i.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(r===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const io=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(s)}};var sr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},De=function(s){try{return!!s()}catch(e){return!0}},so=De,wi=!so(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Ta=wi,Ea=Function.prototype,bs=Ea.call,ro=Ta&&Ea.bind.bind(bs,bs),Xe=Ta?ro:function(s){return function(){return bs.apply(s,arguments)}},$a=Xe,ao=$a({}.toString),no=$a("".slice),_s=function(s){return no(ao(s),8,-1)},oo=Xe,lo=De,uo=_s,Li=Object,co=oo("".split),ho=lo(function(){return!Li("z").propertyIsEnumerable(0)})?function(s){return uo(s)=="String"?co(s,""):Li(s)}:Li,As=function(s){return s==null},fo=As,po=TypeError,ka=function(s){if(fo(s))throw po("Can't call method on "+s);return s},mo=ho,So=ka,Mt=function(s){return mo(So(s))},bo=function(){},mt={},Qt=function(s){return s&&s.Math==Math&&s},ke=Qt(typeof globalThis=="object"&&globalThis)||Qt(typeof window=="object"&&window)||Qt(typeof self=="object"&&self)||Qt(typeof sr=="object"&&sr)||function(){return this}()||Function("return this")(),vs=typeof document=="object"&&document.all,vo=typeof vs=="undefined"&&vs!==void 0,Pa={all:vs,IS_HTMLDDA:vo},wa=Pa,go=wa.all,Se=wa.IS_HTMLDDA?function(s){return typeof s=="function"||s===go}:function(s){return typeof s=="function"},yo=ke,To=Se,rr=yo.WeakMap,Eo=To(rr)&&/native code/.test(String(rr)),ar=Se,_a=Pa,$o=_a.all,St=_a.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:ar(s)||s===$o}:function(s){return typeof s=="object"?s!==null:ar(s)},ko=De,Ue=!ko(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),bt={},Po=ke,nr=St,gs=Po.document,wo=nr(gs)&&nr(gs.createElement),Aa=function(s){return wo?gs.createElement(s):{}},_o=Ue,Ao=De,Ro=Aa,Ra=!_o&&!Ao(function(){return Object.defineProperty(Ro("div"),"a",{get:function(){return 7}}).a!=7}),Io=Ue,No=De,Ia=Io&&No(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Do=St,Co=String,Lo=TypeError,vt=function(s){if(Do(s))return s;throw Lo(Co(s)+" is not an object")},xo=wi,Wt=Function.prototype.call,Ze=xo?Wt.bind(Wt):function(){return Wt.apply(Wt,arguments)},Rs={},xi=Rs,Oi=ke,Oo=Se,or=function(s){return Oo(s)?s:void 0},Is=function(s,e){return arguments.length<2?or(xi[s])||or(Oi[s]):xi[s]&&xi[s][e]||Oi[s]&&Oi[s][e]},Bo=Xe,Na=Bo({}.isPrototypeOf),Mo=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Da=ke,Bi=Mo,lr=Da.process,ur=Da.Deno,dr=lr&&lr.versions||ur&&ur.version,cr=dr&&dr.v8,pe,Si;cr&&(pe=cr.split("."),Si=pe[0]>0&&pe[0]<4?1:+(pe[0]+pe[1]));!Si&&Bi&&(pe=Bi.match(/Edge\/(\d+)/),(!pe||pe[1]>=74)&&(pe=Bi.match(/Chrome\/(\d+)/),pe&&(Si=+pe[1])));var Vo=Si,hr=Vo,Fo=De,Ca=!!Object.getOwnPropertySymbols&&!Fo(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&hr&&hr<41}),Uo=Ca,La=Uo&&!Symbol.sham&&typeof Symbol.iterator=="symbol",jo=Is,Ho=Se,Go=Na,qo=La,Yo=Object,xa=qo?function(s){return typeof s=="symbol"}:function(s){var e=jo("Symbol");return Ho(e)&&Go(e.prototype,Yo(s))},zo=String,Ns=function(s){try{return zo(s)}catch(e){return"Object"}},Qo=Se,Wo=Ns,Jo=TypeError,Ds=function(s){if(Qo(s))return s;throw Jo(Wo(s)+" is not a function")},Ko=Ds,Xo=As,Cs=function(s,e){var t=s[e];return Xo(t)?void 0:Ko(t)},Mi=Ze,Vi=Se,Fi=St,Zo=TypeError,el=function(s,e){var t,i;if(e==="string"&&Vi(t=s.toString)&&!Fi(i=Mi(t,s))||Vi(t=s.valueOf)&&!Fi(i=Mi(t,s))||e!=="string"&&Vi(t=s.toString)&&!Fi(i=Mi(t,s)))return i;throw Zo("Can't convert object to primitive value")},bi={},tl={get exports(){return bi},set exports(s){bi=s}},il=!0,fr=ke,sl=Object.defineProperty,rl=function(s,e){try{sl(fr,s,{value:e,configurable:!0,writable:!0})}catch(t){fr[s]=e}return e},al=ke,nl=rl,pr="__core-js_shared__",ol=al[pr]||nl(pr,{}),Oa=ol,mr=Oa;(tl.exports=function(s,e){return mr[s]||(mr[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var ll=ka,ul=Object,Ls=function(s){return ul(ll(s))},dl=Xe,cl=Ls,hl=dl({}.hasOwnProperty),je=Object.hasOwn||function(e,t){return hl(cl(e),t)},fl=Xe,pl=0,ml=Math.random(),Sl=fl(1 .toString),Ba=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Sl(++pl+ml,36)},bl=ke,vl=bi,Sr=je,gl=Ba,yl=Ca,Tl=La,ot=bl.Symbol,Ui=vl("wks"),El=Tl?ot.for||ot:ot&&ot.withoutSetter||gl,Ce=function(s){return Sr(Ui,s)||(Ui[s]=yl&&Sr(ot,s)?ot[s]:El("Symbol."+s)),Ui[s]},$l=Ze,br=St,vr=xa,kl=Cs,Pl=el,wl=Ce,_l=TypeError,Al=wl("toPrimitive"),Rl=function(s,e){if(!br(s)||vr(s))return s;var t=kl(s,Al),i;if(t){if(e===void 0&&(e="default"),i=$l(t,s,e),!br(i)||vr(i))return i;throw _l("Can't convert object to primitive value")}return e===void 0&&(e="number"),Pl(s,e)},Il=Rl,Nl=xa,xs=function(s){var e=Il(s,"string");return Nl(e)?e:e+""},Dl=Ue,Cl=Ra,Ll=Ia,Jt=vt,gr=xs,xl=TypeError,ji=Object.defineProperty,Ol=Object.getOwnPropertyDescriptor,Hi="enumerable",Gi="configurable",qi="writable";bt.f=Dl?Ll?function(e,t,i){if(Jt(e),t=gr(t),Jt(i),typeof e=="function"&&t==="prototype"&&"value"in i&&qi in i&&!i[qi]){var r=Ol(e,t);r&&r[qi]&&(e[t]=i.value,i={configurable:Gi in i?i[Gi]:r[Gi],enumerable:Hi in i?i[Hi]:r[Hi],writable:!1})}return ji(e,t,i)}:ji:function(e,t,i){if(Jt(e),t=gr(t),Jt(i),Cl)try{return ji(e,t,i)}catch(r){}if("get"in i||"set"in i)throw xl("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var _i=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Bl=Ue,Ml=bt,Vl=_i,Vt=Bl?function(s,e,t){return Ml.f(s,e,Vl(1,t))}:function(s,e,t){return s[e]=t,s},Fl=bi,Ul=Ba,yr=Fl("keys"),Os=function(s){return yr[s]||(yr[s]=Ul(s))},Bs={},jl=Eo,Ma=ke,Hl=St,Gl=Vt,Yi=je,zi=Oa,ql=Os,Yl=Bs,Tr="Object already initialized",ys=Ma.TypeError,zl=Ma.WeakMap,vi,Bt,gi,Ql=function(s){return gi(s)?Bt(s):vi(s,{})},Wl=function(s){return function(e){var t;if(!Hl(e)||(t=Bt(e)).type!==s)throw ys("Incompatible receiver, "+s+" required");return t}};if(jl||zi.state){var ye=zi.state||(zi.state=new zl);ye.get=ye.get,ye.has=ye.has,ye.set=ye.set,vi=function(s,e){if(ye.has(s))throw ys(Tr);return e.facade=s,ye.set(s,e),e},Bt=function(s){return ye.get(s)||{}},gi=function(s){return ye.has(s)}}else{var rt=ql("state");Yl[rt]=!0,vi=function(s,e){if(Yi(s,rt))throw ys(Tr);return e.facade=s,Gl(s,rt,e),e},Bt=function(s){return Yi(s,rt)?s[rt]:{}},gi=function(s){return Yi(s,rt)}}var Jl={set:vi,get:Bt,has:gi,enforce:Ql,getterFor:Wl},Kl=wi,Va=Function.prototype,Er=Va.apply,$r=Va.call,Xl=typeof Reflect=="object"&&Reflect.apply||(Kl?$r.bind(Er):function(){return $r.apply(Er,arguments)}),Zl=_s,eu=Xe,Fa=function(s){if(Zl(s)==="Function")return eu(s)},Ua={},ja={},Ha={}.propertyIsEnumerable,Ga=Object.getOwnPropertyDescriptor,tu=Ga&&!Ha.call({1:2},1);ja.f=tu?function(e){var t=Ga(this,e);return!!t&&t.enumerable}:Ha;var iu=Ue,su=Ze,ru=ja,au=_i,nu=Mt,ou=xs,lu=je,uu=Ra,kr=Object.getOwnPropertyDescriptor;Ua.f=iu?kr:function(e,t){if(e=nu(e),t=ou(t),uu)try{return kr(e,t)}catch(i){}if(lu(e,t))return au(!su(ru.f,e,t),e[t])};var du=De,cu=Se,hu=/#|\.prototype\./,Ft=function(s,e){var t=pu[fu(s)];return t==Su?!0:t==mu?!1:cu(e)?du(e):!!e},fu=Ft.normalize=function(s){return String(s).replace(hu,".").toLowerCase()},pu=Ft.data={},mu=Ft.NATIVE="N",Su=Ft.POLYFILL="P",bu=Ft,Pr=Fa,vu=Ds,gu=wi,yu=Pr(Pr.bind),qa=function(s,e){return vu(s),e===void 0?s:gu?yu(s,e):function(){return s.apply(e,arguments)}},Kt=ke,Tu=Xl,Eu=Fa,$u=Se,ku=Ua.f,Pu=bu,at=Rs,wu=qa,nt=Vt,wr=je,_u=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Tu(s,this,arguments)};return e.prototype=s.prototype,e},Ms=function(s,e){var t=s.target,i=s.global,r=s.stat,n=s.proto,o=i?Kt:r?Kt[t]:(Kt[t]||{}).prototype,l=i?at:at[t]||nt(at,t,{})[t],d=l.prototype,u,c,h,f,p,S,m,b,v;for(f in e)u=Pu(i?f:t+(r?".":"#")+f,s.forced),c=!u&&o&&wr(o,f),S=l[f],c&&(s.dontCallGetSet?(v=ku(o,f),m=v&&v.value):m=o[f]),p=c&&m?m:e[f],!(c&&typeof S==typeof p)&&(s.bind&&c?b=wu(p,Kt):s.wrap&&c?b=_u(p):n&&$u(p)?b=Eu(p):b=p,(s.sham||p&&p.sham||S&&S.sham)&&nt(b,"sham",!0),nt(l,f,b),n&&(h=t+"Prototype",wr(at,h)||nt(at,h,{}),nt(at[h],f,p),s.real&&d&&(u||!d[f])&&nt(d,f,p)))},Ts=Ue,Au=je,Ya=Function.prototype,Ru=Ts&&Object.getOwnPropertyDescriptor,Vs=Au(Ya,"name"),Iu=Vs&&function(){}.name==="something",Nu=Vs&&(!Ts||Ts&&Ru(Ya,"name").configurable),Du={EXISTS:Vs,PROPER:Iu,CONFIGURABLE:Nu},za={},Cu=Math.ceil,Lu=Math.floor,xu=Math.trunc||function(e){var t=+e;return(t>0?Lu:Cu)(t)},Ou=xu,Fs=function(s){var e=+s;return e!==e||e===0?0:Ou(e)},Bu=Fs,Mu=Math.max,Vu=Math.min,Fu=function(s,e){var t=Bu(s);return t<0?Mu(t+e,0):Vu(t,e)},Uu=Fs,ju=Math.min,Hu=function(s){return s>0?ju(Uu(s),9007199254740991):0},Gu=Hu,Us=function(s){return Gu(s.length)},qu=Mt,Yu=Fu,zu=Us,_r=function(s){return function(e,t,i){var r=qu(e),n=zu(r),o=Yu(i,n),l;if(s&&t!=t){for(;n>o;)if(l=r[o++],l!=l)return!0}else for(;n>o;o++)if((s||o in r)&&r[o]===t)return s||o||0;return!s&&-1}},Qu={includes:_r(!0),indexOf:_r(!1)},Wu=Xe,Qi=je,Ju=Mt,Ku=Qu.indexOf,Xu=Bs,Ar=Wu([].push),Zu=function(s,e){var t=Ju(s),i=0,r=[],n;for(n in t)!Qi(Xu,n)&&Qi(t,n)&&Ar(r,n);for(;e.length>i;)Qi(t,n=e[i++])&&(~Ku(r,n)||Ar(r,n));return r},Qa=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ed=Zu,td=Qa,id=Object.keys||function(e){return ed(e,td)},sd=Ue,rd=Ia,ad=bt,nd=vt,od=Mt,ld=id;za.f=sd&&!rd?Object.defineProperties:function(e,t){nd(e);for(var i=od(t),r=ld(t),n=r.length,o=0,l;n>o;)ad.f(e,l=r[o++],i[l]);return e};var ud=Is,dd=ud("document","documentElement"),cd=vt,hd=za,Rr=Qa,fd=Bs,pd=dd,md=Aa,Sd=Os,Ir=">",Nr="<",Es="prototype",$s="script",Wa=Sd("IE_PROTO"),Wi=function(){},Ja=function(s){return Nr+$s+Ir+s+Nr+"/"+$s+Ir},Dr=function(s){s.write(Ja("")),s.close();var e=s.parentWindow.Object;return s=null,e},bd=function(){var s=md("iframe"),e="java"+$s+":",t;return s.style.display="none",pd.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Ja("document.F=Object")),t.close(),t.F},Xt,ci=function(){try{Xt=new ActiveXObject("htmlfile")}catch(e){}ci=typeof document!="undefined"?document.domain&&Xt?Dr(Xt):bd():Dr(Xt);for(var s=Rr.length;s--;)delete ci[Es][Rr[s]];return ci()};fd[Wa]=!0;var Ka=Object.create||function(e,t){var i;return e!==null?(Wi[Es]=cd(e),i=new Wi,Wi[Es]=null,i[Wa]=e):i=ci(),t===void 0?i:hd.f(i,t)},vd=De,gd=!vd(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),yd=je,Td=Se,Ed=Ls,$d=Os,kd=gd,Cr=$d("IE_PROTO"),ks=Object,Pd=ks.prototype,Xa=kd?ks.getPrototypeOf:function(s){var e=Ed(s);if(yd(e,Cr))return e[Cr];var t=e.constructor;return Td(t)&&e instanceof t?t.prototype:e instanceof ks?Pd:null},wd=Vt,Za=function(s,e,t,i){return i&&i.enumerable?s[e]=t:wd(s,e,t),s},_d=De,Ad=Se,Rd=St,Id=Ka,Lr=Xa,Nd=Za,Dd=Ce,Ps=Dd("iterator"),en=!1,Ie,Ji,Ki;[].keys&&(Ki=[].keys(),"next"in Ki?(Ji=Lr(Lr(Ki)),Ji!==Object.prototype&&(Ie=Ji)):en=!0);var Cd=!Rd(Ie)||_d(function(){var s={};return Ie[Ps].call(s)!==s});Cd?Ie={}:Ie=Id(Ie);Ad(Ie[Ps])||Nd(Ie,Ps,function(){return this});var tn={IteratorPrototype:Ie,BUGGY_SAFARI_ITERATORS:en},Ld=Ce,xd=Ld("toStringTag"),sn={};sn[xd]="z";var js=String(sn)==="[object z]",Od=js,Bd=Se,hi=_s,Md=Ce,Vd=Md("toStringTag"),Fd=Object,Ud=hi(function(){return arguments}())=="Arguments",jd=function(s,e){try{return s[e]}catch(t){}},Hs=Od?hi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=jd(e=Fd(s),Vd))=="string"?t:Ud?hi(e):(i=hi(e))=="Object"&&Bd(e.callee)?"Arguments":i},Hd=js,Gd=Hs,qd=Hd?{}.toString:function(){return"[object "+Gd(this)+"]"},Yd=js,zd=bt.f,Qd=Vt,Wd=je,Jd=qd,Kd=Ce,xr=Kd("toStringTag"),rn=function(s,e,t,i){if(s){var r=t?s:s.prototype;Wd(r,xr)||zd(r,xr,{configurable:!0,value:e}),i&&!Yd&&Qd(r,"toString",Jd)}},Xd=tn.IteratorPrototype,Zd=Ka,ec=_i,tc=rn,ic=mt,sc=function(){return this},rc=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Zd(Xd,{next:ec(+!i,t)}),tc(s,r,!1,!0),ic[r]=sc,s},ac=Ms,nc=Ze,an=Du,oc=rc,lc=Xa,uc=rn,Or=Za,dc=Ce,Br=mt,nn=tn,cc=an.PROPER;an.CONFIGURABLE;nn.IteratorPrototype;var Zt=nn.BUGGY_SAFARI_ITERATORS,Xi=dc("iterator"),Mr="keys",ei="values",Vr="entries",hc=function(){return this},fc=function(s,e,t,i,r,n,o){oc(t,e,i);var l=function(v){if(v===r&&f)return f;if(!Zt&&v in c)return c[v];switch(v){case Mr:return function(){return new t(this,v)};case ei:return function(){return new t(this,v)};case Vr:return function(){return new t(this,v)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[Xi]||c["@@iterator"]||r&&c[r],f=!Zt&&h||l(r),p=e=="Array"&&c.entries||h,S,m,b;if(p&&(S=lc(p.call(new s)),S!==Object.prototype&&S.next&&(uc(S,d,!0,!0),Br[d]=hc)),cc&&r==ei&&h&&h.name!==ei&&(u=!0,f=function(){return nc(h,this)}),r)if(m={values:l(ei),keys:n?f:l(Mr),entries:l(Vr)},o)for(b in m)(Zt||u||!(b in c))&&Or(c,b,m[b]);else ac({target:e,proto:!0,forced:Zt||u},m);return o&&c[Xi]!==f&&Or(c,Xi,f,{name:r}),Br[e]=f,m},pc=function(s,e){return{value:s,done:e}},mc=Mt,Gs=bo,Fr=mt,on=Jl,Sc=bt.f,bc=fc,ti=pc,vc=il,gc=Ue,ln="Array Iterator",yc=on.set,Tc=on.getterFor(ln);bc(Array,"Array",function(s,e){yc(this,{type:ln,target:mc(s),index:0,kind:e})},function(){var s=Tc(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,ti(void 0,!0)):t=="keys"?ti(i,!1):t=="values"?ti(e[i],!1):ti([i,e[i]],!1)},"values");var Ur=Fr.Arguments=Fr.Array;Gs();Gs();Gs();if(!vc&&gc&&Ur.name!=="values")try{Sc(Ur,"name",{value:"values"})}catch(s){}var Ec=Ce,$c=mt,kc=Ec("iterator"),Pc=Array.prototype,wc=function(s){return s!==void 0&&($c.Array===s||Pc[kc]===s)},_c=Hs,jr=Cs,Ac=As,Rc=mt,Ic=Ce,Nc=Ic("iterator"),un=function(s){if(!Ac(s))return jr(s,Nc)||jr(s,"@@iterator")||Rc[_c(s)]},Dc=Ze,Cc=Ds,Lc=vt,xc=Ns,Oc=un,Bc=TypeError,Mc=function(s,e){var t=arguments.length<2?Oc(s):e;if(Cc(t))return Lc(Dc(t,s));throw Bc(xc(s)+" is not iterable")},Vc=Ze,Hr=vt,Fc=Cs,Uc=function(s,e,t){var i,r;Hr(s);try{if(i=Fc(s,"return"),!i){if(e==="throw")throw t;return t}i=Vc(i,s)}catch(n){r=!0,i=n}if(e==="throw")throw t;if(r)throw i;return Hr(i),t},jc=qa,Hc=Ze,Gc=vt,qc=Ns,Yc=wc,zc=Us,Gr=Na,Qc=Mc,Wc=un,qr=Uc,Jc=TypeError,fi=function(s,e){this.stopped=s,this.result=e},Yr=fi.prototype,Kc=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=jc(e,i),u,c,h,f,p,S,m,b=function(g){return u&&qr(u,"normal",g),new fi(!0,g)},v=function(g){return r?(Gc(g),l?d(g[0],g[1],b):d(g[0],g[1])):l?d(g,b):d(g)};if(n)u=s.iterator;else if(o)u=s;else{if(c=Wc(s),!c)throw Jc(qc(s)+" is not iterable");if(Yc(c)){for(h=0,f=zc(s);f>h;h++)if(p=v(s[h]),p&&Gr(Yr,p))return p;return new fi(!1)}u=Qc(s,c)}for(S=n?s.next:u.next;!(m=Hc(S,u)).done;){try{p=v(m.value)}catch(g){qr(u,"throw",g)}if(typeof p=="object"&&p&&Gr(Yr,p))return p}return new fi(!1)},Xc=xs,Zc=bt,eh=_i,th=function(s,e,t){var i=Xc(e);i in s?Zc.f(s,i,eh(0,t)):s[i]=t},ih=Ms,sh=Kc,rh=th;ih({target:"Object",stat:!0},{fromEntries:function(e){var t={};return sh(e,function(i,r){rh(t,i,r)},{AS_ENTRIES:!0}),t}});var ah=Rs,nh=ah.Object.fromEntries,oh={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},lh=oh,uh=ke,dh=Hs,ch=Vt,zr=mt,hh=Ce,Qr=hh("toStringTag");for(var Zi in lh){var Wr=uh[Zi],es=Wr&&Wr.prototype;es&&dh(es)!==Qr&&ch(es,Qr,Zi),zr[Zi]=zr.Array}var fh=nh,ph=fh,mh=ph,Sh=mh,Ut=Sh,ut;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(ut||(ut={}));var ct=(s,e=0,t=ut.OFFSET_P)=>{switch(t){case ut.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ut.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:a.assertNever(t)}return s},k=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};exports.VideoQuality=void 0;(function(s){s.INVARIANT="Invariant quality",s.Q_144P="144p",s.Q_240P="240p",s.Q_360P="360p",s.Q_480P="480p",s.Q_720P="720p",s.Q_1080P="1080p",s.Q_1440P="1440p",s.Q_2160P="2160p",s.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const me={[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}},pi=(s,e)=>me[s].height>me[e].height,bh=(s,e)=>me[s].height>=me[e].height,Lt=(s,e)=>me[s].height<me[e].height,vh=(s,e)=>me[s].height<=me[e].height,gh=s=>s.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:Lt(e,t)?1:-1)[0],yh=Object.keys(me).sort((s,e)=>Lt(s,e)?-1:1),et=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return yh.find(r=>{const n=me[r];return n.width>=i&&n.height>=t})},Th=s=>me[s].height,yi=s=>s===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,i=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||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:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const Eh=s=>{switch(s){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(s)}};var F;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(F||(F={}));const $h=5,kh=5,Ph=500,Jr=7e3;class wh{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new J(F.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){i!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.stop());return}if(!r){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===D.Requested&&i!==F.STOPPED){this.seek(l.position);return}switch(n){case exports.PlaybackState.PLAYING:{switch(i){case F.PLAYING:break;case F.PAUSED:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.READY:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:a.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case F.PLAYING:this.videoState.startTransitionTo(F.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case F.PAUSED:break;case F.READY:this.videoState.startTransitionTo(F.PAUSED),this.videoState.setState(F.PAUSED);break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:a.assertNever(i)}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(Eh(e.format)),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(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(a.map(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,n)=>this.subscription.add(r.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new a.Subject;e.add(r.pipe(a.debounce(Ph)).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===D.Applying||Math.abs(l-n)>$h)&&r.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),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:n}=this.params.connection,o=r.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<kh&&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),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(F.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:D.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===F.PAUSED||e===F.PLAYING)&&(this.videoState.setState(F.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)===F.PLAYING||e===F.PAUSED)&&(this.videoState.setState(F.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const e=this.videoState.getTransition();(e==null?void 0:e.to)===F.READY&&this.videoState.setState(F.READY)}handleRemoteStop(){this.videoState.getState()!==F.STOPPED&&this.videoState.setState(F.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(n.volume!==r.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=i[e];a.assertNonNullable(c);const h=gh(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),r=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=i[e];a.assertNonNullable(c),r=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const c=i[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const c=i[e];a.assertNonNullable(c),r=ct(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:r,n);l.contentUrl=r,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 i=this.params.desiredState.seekState.getState();return i.state===D.Applying||i.state===D.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(Jr).subscribe(()=>n(`timeout(${Jr})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===D.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Kr{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,n=i.length;r<n;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,n=i.length;r<n;r++){const o=i[r];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 dn extends Kr{constructor(){super(),this.listeners||Kr.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 cn=class{constructor(){Object.defineProperty(this,"signal",{value:new dn,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(cn.prototype[Symbol.toStringTag]="AbortController",dn.prototype[Symbol.toStringTag]="AbortSignal");function hn(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function _h(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!hn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||r)&&(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,S)=>{c.addEventListener("abort",()=>S(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Ai=hn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),fn=Ai?_h({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ht=Ai?fn.fetch:window.fetch;Ai?fn.Request:window.Request;const Je=Ai?cn:window.AbortController,It=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class xt{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,r=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(i,r)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const r=t[0];if(!r||!r.request.range)continue;const[n,o]=It(r.request);if(n>=i.from&&o<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const r=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,r)}}}abort(e){var t;if(e){const{request:i}=e,r=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(i.url);r&&n&&n.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(It),r=i[0][0];let n=i[0][1];for(let f=1;f<i.length&&n<this.params.minDataSize;f++){const p=i[f][1];p-r<=2*this.params.minDataSize&&(n=Math.max(n,p))}r===0?n=Math.max(n,r+this.params.minInitSize):n=Math.max(n,r+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${r}-${n}`);const l=o.toString(),d=new Je,u=d.signal,c={url:e,from:r,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var p,S;throw(S=(p=this.params).onError)===null||S===void 0||S.call(p,{id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return ht(l,{signal:u}).then(f=>{var p,S,m;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[b,v]=f.body.tee();(S=(p=this.params).onDownloadStream)===null||S===void 0||S.call(p,v);const g=b.getReader(),P=parseInt((m=f.headers.get("Content-Length"))!==null&&m!==void 0?m:"",10)||n-r+1;c.data=new ArrayBuffer(P);const T=new Uint8Array(c.data),E=async({done:_,value:x})=>{_?this.onBigRequestProgress(c):x&&(T.set(x,c.loaded),c.loaded+=x.byteLength,this.onBigRequestProgress(c),await(g==null?void 0:g.read().then(E,xt.suppressStreamErrors).catch(h)))};g==null||g.read().then(E,xt.suppressStreamErrors).catch(h)},xt.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:i,loaded:r,data:n,response:o}){var l,d,u,c,h,f,p,S;if(!this.activeRequests.has(e)||!n)return;const m=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const b of m){const{request:v}=b,[g,P]=It(v),T=g>=t&&P<=t+r,E=t>=g&&t+r<P,_=n.slice(g-t,Math.min(P-t+1,r));if((T||E)&&(v.requestStartDate=(d=v.requestStartDate)!==null&&d!==void 0?d:new Date,v.firstByteDate=(u=v.firstByteDate)!==null&&u!==void 0?u:new Date,v.bytesLoaded=_.byteLength,v.bytesTotal=i-t),T){v.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(N=>N!==b)),(h=b.success)===null||h===void 0||h.call(b,_,"",e);const x=o?Array.from(o.headers.entries()).map(([N,R])=>`${N}: ${R}`).join(`\r
|
|
6
|
+
"use strict";var qn=Object.create;var tr=Object.defineProperty;var Yn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Qn=Object.getPrototypeOf,Wn=Object.prototype.hasOwnProperty;var Jn=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of zn(e))!Wn.call(s,r)&&r!==t&&tr(s,r,{get:()=>e[r],enumerable:!(i=Yn(e,r))||i.enumerable});return s};var ir=(s,e,t)=>(t=s!=null?qn(Qn(s)):{},Jn(e||!s||!s.__esModule?tr(t,"default",{value:s,enumerable:!0}):t,s));var a=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),Kn=require("lodash/debounce.js");const Xn="2.0.78",Zn="@vkontakte/videoplayer-core";exports.PlaybackState=void 0;(function(s){s.STOPPED="stopped",s.PLAYING="playing",s.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var le;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(le||(le={}));exports.ChromecastState=void 0;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var D;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(D||(D={}));var eo=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class to{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 i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);r?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||eo("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 i,r,n;(n=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.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),i=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=i.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(r.sessionState)}})).add(a.merge(a.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),a.map(r=>r.castState)),a.observableFrom([i.getCastState()])).pipe(a.filterChanged(),a.map(io),a.tap(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var n;const o=r===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=i.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(r===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const io=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(s)}};var sr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},De=function(s){try{return!!s()}catch(e){return!0}},so=De,wi=!so(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Ta=wi,Ea=Function.prototype,bs=Ea.call,ro=Ta&&Ea.bind.bind(bs,bs),Xe=Ta?ro:function(s){return function(){return bs.apply(s,arguments)}},$a=Xe,ao=$a({}.toString),no=$a("".slice),_s=function(s){return no(ao(s),8,-1)},oo=Xe,lo=De,uo=_s,Li=Object,co=oo("".split),ho=lo(function(){return!Li("z").propertyIsEnumerable(0)})?function(s){return uo(s)=="String"?co(s,""):Li(s)}:Li,As=function(s){return s==null},fo=As,po=TypeError,ka=function(s){if(fo(s))throw po("Can't call method on "+s);return s},mo=ho,So=ka,Mt=function(s){return mo(So(s))},bo=function(){},mt={},Qt=function(s){return s&&s.Math==Math&&s},ke=Qt(typeof globalThis=="object"&&globalThis)||Qt(typeof window=="object"&&window)||Qt(typeof self=="object"&&self)||Qt(typeof sr=="object"&&sr)||function(){return this}()||Function("return this")(),vs=typeof document=="object"&&document.all,vo=typeof vs=="undefined"&&vs!==void 0,Pa={all:vs,IS_HTMLDDA:vo},wa=Pa,go=wa.all,Se=wa.IS_HTMLDDA?function(s){return typeof s=="function"||s===go}:function(s){return typeof s=="function"},yo=ke,To=Se,rr=yo.WeakMap,Eo=To(rr)&&/native code/.test(String(rr)),ar=Se,_a=Pa,$o=_a.all,St=_a.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:ar(s)||s===$o}:function(s){return typeof s=="object"?s!==null:ar(s)},ko=De,Ue=!ko(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),bt={},Po=ke,nr=St,gs=Po.document,wo=nr(gs)&&nr(gs.createElement),Aa=function(s){return wo?gs.createElement(s):{}},_o=Ue,Ao=De,Ro=Aa,Ra=!_o&&!Ao(function(){return Object.defineProperty(Ro("div"),"a",{get:function(){return 7}}).a!=7}),Io=Ue,No=De,Ia=Io&&No(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Do=St,Co=String,Lo=TypeError,vt=function(s){if(Do(s))return s;throw Lo(Co(s)+" is not an object")},xo=wi,Wt=Function.prototype.call,Ze=xo?Wt.bind(Wt):function(){return Wt.apply(Wt,arguments)},Rs={},xi=Rs,Oi=ke,Oo=Se,or=function(s){return Oo(s)?s:void 0},Is=function(s,e){return arguments.length<2?or(xi[s])||or(Oi[s]):xi[s]&&xi[s][e]||Oi[s]&&Oi[s][e]},Bo=Xe,Na=Bo({}.isPrototypeOf),Mo=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Da=ke,Bi=Mo,lr=Da.process,ur=Da.Deno,dr=lr&&lr.versions||ur&&ur.version,cr=dr&&dr.v8,pe,Si;cr&&(pe=cr.split("."),Si=pe[0]>0&&pe[0]<4?1:+(pe[0]+pe[1]));!Si&&Bi&&(pe=Bi.match(/Edge\/(\d+)/),(!pe||pe[1]>=74)&&(pe=Bi.match(/Chrome\/(\d+)/),pe&&(Si=+pe[1])));var Vo=Si,hr=Vo,Fo=De,Ca=!!Object.getOwnPropertySymbols&&!Fo(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&hr&&hr<41}),Uo=Ca,La=Uo&&!Symbol.sham&&typeof Symbol.iterator=="symbol",jo=Is,Ho=Se,Go=Na,qo=La,Yo=Object,xa=qo?function(s){return typeof s=="symbol"}:function(s){var e=jo("Symbol");return Ho(e)&&Go(e.prototype,Yo(s))},zo=String,Ns=function(s){try{return zo(s)}catch(e){return"Object"}},Qo=Se,Wo=Ns,Jo=TypeError,Ds=function(s){if(Qo(s))return s;throw Jo(Wo(s)+" is not a function")},Ko=Ds,Xo=As,Cs=function(s,e){var t=s[e];return Xo(t)?void 0:Ko(t)},Mi=Ze,Vi=Se,Fi=St,Zo=TypeError,el=function(s,e){var t,i;if(e==="string"&&Vi(t=s.toString)&&!Fi(i=Mi(t,s))||Vi(t=s.valueOf)&&!Fi(i=Mi(t,s))||e!=="string"&&Vi(t=s.toString)&&!Fi(i=Mi(t,s)))return i;throw Zo("Can't convert object to primitive value")},bi={},tl={get exports(){return bi},set exports(s){bi=s}},il=!0,fr=ke,sl=Object.defineProperty,rl=function(s,e){try{sl(fr,s,{value:e,configurable:!0,writable:!0})}catch(t){fr[s]=e}return e},al=ke,nl=rl,pr="__core-js_shared__",ol=al[pr]||nl(pr,{}),Oa=ol,mr=Oa;(tl.exports=function(s,e){return mr[s]||(mr[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var ll=ka,ul=Object,Ls=function(s){return ul(ll(s))},dl=Xe,cl=Ls,hl=dl({}.hasOwnProperty),je=Object.hasOwn||function(e,t){return hl(cl(e),t)},fl=Xe,pl=0,ml=Math.random(),Sl=fl(1 .toString),Ba=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Sl(++pl+ml,36)},bl=ke,vl=bi,Sr=je,gl=Ba,yl=Ca,Tl=La,ot=bl.Symbol,Ui=vl("wks"),El=Tl?ot.for||ot:ot&&ot.withoutSetter||gl,Ce=function(s){return Sr(Ui,s)||(Ui[s]=yl&&Sr(ot,s)?ot[s]:El("Symbol."+s)),Ui[s]},$l=Ze,br=St,vr=xa,kl=Cs,Pl=el,wl=Ce,_l=TypeError,Al=wl("toPrimitive"),Rl=function(s,e){if(!br(s)||vr(s))return s;var t=kl(s,Al),i;if(t){if(e===void 0&&(e="default"),i=$l(t,s,e),!br(i)||vr(i))return i;throw _l("Can't convert object to primitive value")}return e===void 0&&(e="number"),Pl(s,e)},Il=Rl,Nl=xa,xs=function(s){var e=Il(s,"string");return Nl(e)?e:e+""},Dl=Ue,Cl=Ra,Ll=Ia,Jt=vt,gr=xs,xl=TypeError,ji=Object.defineProperty,Ol=Object.getOwnPropertyDescriptor,Hi="enumerable",Gi="configurable",qi="writable";bt.f=Dl?Ll?function(e,t,i){if(Jt(e),t=gr(t),Jt(i),typeof e=="function"&&t==="prototype"&&"value"in i&&qi in i&&!i[qi]){var r=Ol(e,t);r&&r[qi]&&(e[t]=i.value,i={configurable:Gi in i?i[Gi]:r[Gi],enumerable:Hi in i?i[Hi]:r[Hi],writable:!1})}return ji(e,t,i)}:ji:function(e,t,i){if(Jt(e),t=gr(t),Jt(i),Cl)try{return ji(e,t,i)}catch(r){}if("get"in i||"set"in i)throw xl("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var _i=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Bl=Ue,Ml=bt,Vl=_i,Vt=Bl?function(s,e,t){return Ml.f(s,e,Vl(1,t))}:function(s,e,t){return s[e]=t,s},Fl=bi,Ul=Ba,yr=Fl("keys"),Os=function(s){return yr[s]||(yr[s]=Ul(s))},Bs={},jl=Eo,Ma=ke,Hl=St,Gl=Vt,Yi=je,zi=Oa,ql=Os,Yl=Bs,Tr="Object already initialized",ys=Ma.TypeError,zl=Ma.WeakMap,vi,Bt,gi,Ql=function(s){return gi(s)?Bt(s):vi(s,{})},Wl=function(s){return function(e){var t;if(!Hl(e)||(t=Bt(e)).type!==s)throw ys("Incompatible receiver, "+s+" required");return t}};if(jl||zi.state){var ye=zi.state||(zi.state=new zl);ye.get=ye.get,ye.has=ye.has,ye.set=ye.set,vi=function(s,e){if(ye.has(s))throw ys(Tr);return e.facade=s,ye.set(s,e),e},Bt=function(s){return ye.get(s)||{}},gi=function(s){return ye.has(s)}}else{var rt=ql("state");Yl[rt]=!0,vi=function(s,e){if(Yi(s,rt))throw ys(Tr);return e.facade=s,Gl(s,rt,e),e},Bt=function(s){return Yi(s,rt)?s[rt]:{}},gi=function(s){return Yi(s,rt)}}var Jl={set:vi,get:Bt,has:gi,enforce:Ql,getterFor:Wl},Kl=wi,Va=Function.prototype,Er=Va.apply,$r=Va.call,Xl=typeof Reflect=="object"&&Reflect.apply||(Kl?$r.bind(Er):function(){return $r.apply(Er,arguments)}),Zl=_s,eu=Xe,Fa=function(s){if(Zl(s)==="Function")return eu(s)},Ua={},ja={},Ha={}.propertyIsEnumerable,Ga=Object.getOwnPropertyDescriptor,tu=Ga&&!Ha.call({1:2},1);ja.f=tu?function(e){var t=Ga(this,e);return!!t&&t.enumerable}:Ha;var iu=Ue,su=Ze,ru=ja,au=_i,nu=Mt,ou=xs,lu=je,uu=Ra,kr=Object.getOwnPropertyDescriptor;Ua.f=iu?kr:function(e,t){if(e=nu(e),t=ou(t),uu)try{return kr(e,t)}catch(i){}if(lu(e,t))return au(!su(ru.f,e,t),e[t])};var du=De,cu=Se,hu=/#|\.prototype\./,Ft=function(s,e){var t=pu[fu(s)];return t==Su?!0:t==mu?!1:cu(e)?du(e):!!e},fu=Ft.normalize=function(s){return String(s).replace(hu,".").toLowerCase()},pu=Ft.data={},mu=Ft.NATIVE="N",Su=Ft.POLYFILL="P",bu=Ft,Pr=Fa,vu=Ds,gu=wi,yu=Pr(Pr.bind),qa=function(s,e){return vu(s),e===void 0?s:gu?yu(s,e):function(){return s.apply(e,arguments)}},Kt=ke,Tu=Xl,Eu=Fa,$u=Se,ku=Ua.f,Pu=bu,at=Rs,wu=qa,nt=Vt,wr=je,_u=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Tu(s,this,arguments)};return e.prototype=s.prototype,e},Ms=function(s,e){var t=s.target,i=s.global,r=s.stat,n=s.proto,o=i?Kt:r?Kt[t]:(Kt[t]||{}).prototype,l=i?at:at[t]||nt(at,t,{})[t],d=l.prototype,u,c,h,f,p,S,m,b,v;for(f in e)u=Pu(i?f:t+(r?".":"#")+f,s.forced),c=!u&&o&&wr(o,f),S=l[f],c&&(s.dontCallGetSet?(v=ku(o,f),m=v&&v.value):m=o[f]),p=c&&m?m:e[f],!(c&&typeof S==typeof p)&&(s.bind&&c?b=wu(p,Kt):s.wrap&&c?b=_u(p):n&&$u(p)?b=Eu(p):b=p,(s.sham||p&&p.sham||S&&S.sham)&&nt(b,"sham",!0),nt(l,f,b),n&&(h=t+"Prototype",wr(at,h)||nt(at,h,{}),nt(at[h],f,p),s.real&&d&&(u||!d[f])&&nt(d,f,p)))},Ts=Ue,Au=je,Ya=Function.prototype,Ru=Ts&&Object.getOwnPropertyDescriptor,Vs=Au(Ya,"name"),Iu=Vs&&function(){}.name==="something",Nu=Vs&&(!Ts||Ts&&Ru(Ya,"name").configurable),Du={EXISTS:Vs,PROPER:Iu,CONFIGURABLE:Nu},za={},Cu=Math.ceil,Lu=Math.floor,xu=Math.trunc||function(e){var t=+e;return(t>0?Lu:Cu)(t)},Ou=xu,Fs=function(s){var e=+s;return e!==e||e===0?0:Ou(e)},Bu=Fs,Mu=Math.max,Vu=Math.min,Fu=function(s,e){var t=Bu(s);return t<0?Mu(t+e,0):Vu(t,e)},Uu=Fs,ju=Math.min,Hu=function(s){return s>0?ju(Uu(s),9007199254740991):0},Gu=Hu,Us=function(s){return Gu(s.length)},qu=Mt,Yu=Fu,zu=Us,_r=function(s){return function(e,t,i){var r=qu(e),n=zu(r),o=Yu(i,n),l;if(s&&t!=t){for(;n>o;)if(l=r[o++],l!=l)return!0}else for(;n>o;o++)if((s||o in r)&&r[o]===t)return s||o||0;return!s&&-1}},Qu={includes:_r(!0),indexOf:_r(!1)},Wu=Xe,Qi=je,Ju=Mt,Ku=Qu.indexOf,Xu=Bs,Ar=Wu([].push),Zu=function(s,e){var t=Ju(s),i=0,r=[],n;for(n in t)!Qi(Xu,n)&&Qi(t,n)&&Ar(r,n);for(;e.length>i;)Qi(t,n=e[i++])&&(~Ku(r,n)||Ar(r,n));return r},Qa=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ed=Zu,td=Qa,id=Object.keys||function(e){return ed(e,td)},sd=Ue,rd=Ia,ad=bt,nd=vt,od=Mt,ld=id;za.f=sd&&!rd?Object.defineProperties:function(e,t){nd(e);for(var i=od(t),r=ld(t),n=r.length,o=0,l;n>o;)ad.f(e,l=r[o++],i[l]);return e};var ud=Is,dd=ud("document","documentElement"),cd=vt,hd=za,Rr=Qa,fd=Bs,pd=dd,md=Aa,Sd=Os,Ir=">",Nr="<",Es="prototype",$s="script",Wa=Sd("IE_PROTO"),Wi=function(){},Ja=function(s){return Nr+$s+Ir+s+Nr+"/"+$s+Ir},Dr=function(s){s.write(Ja("")),s.close();var e=s.parentWindow.Object;return s=null,e},bd=function(){var s=md("iframe"),e="java"+$s+":",t;return s.style.display="none",pd.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Ja("document.F=Object")),t.close(),t.F},Xt,ci=function(){try{Xt=new ActiveXObject("htmlfile")}catch(e){}ci=typeof document!="undefined"?document.domain&&Xt?Dr(Xt):bd():Dr(Xt);for(var s=Rr.length;s--;)delete ci[Es][Rr[s]];return ci()};fd[Wa]=!0;var Ka=Object.create||function(e,t){var i;return e!==null?(Wi[Es]=cd(e),i=new Wi,Wi[Es]=null,i[Wa]=e):i=ci(),t===void 0?i:hd.f(i,t)},vd=De,gd=!vd(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),yd=je,Td=Se,Ed=Ls,$d=Os,kd=gd,Cr=$d("IE_PROTO"),ks=Object,Pd=ks.prototype,Xa=kd?ks.getPrototypeOf:function(s){var e=Ed(s);if(yd(e,Cr))return e[Cr];var t=e.constructor;return Td(t)&&e instanceof t?t.prototype:e instanceof ks?Pd:null},wd=Vt,Za=function(s,e,t,i){return i&&i.enumerable?s[e]=t:wd(s,e,t),s},_d=De,Ad=Se,Rd=St,Id=Ka,Lr=Xa,Nd=Za,Dd=Ce,Ps=Dd("iterator"),en=!1,Ie,Ji,Ki;[].keys&&(Ki=[].keys(),"next"in Ki?(Ji=Lr(Lr(Ki)),Ji!==Object.prototype&&(Ie=Ji)):en=!0);var Cd=!Rd(Ie)||_d(function(){var s={};return Ie[Ps].call(s)!==s});Cd?Ie={}:Ie=Id(Ie);Ad(Ie[Ps])||Nd(Ie,Ps,function(){return this});var tn={IteratorPrototype:Ie,BUGGY_SAFARI_ITERATORS:en},Ld=Ce,xd=Ld("toStringTag"),sn={};sn[xd]="z";var js=String(sn)==="[object z]",Od=js,Bd=Se,hi=_s,Md=Ce,Vd=Md("toStringTag"),Fd=Object,Ud=hi(function(){return arguments}())=="Arguments",jd=function(s,e){try{return s[e]}catch(t){}},Hs=Od?hi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=jd(e=Fd(s),Vd))=="string"?t:Ud?hi(e):(i=hi(e))=="Object"&&Bd(e.callee)?"Arguments":i},Hd=js,Gd=Hs,qd=Hd?{}.toString:function(){return"[object "+Gd(this)+"]"},Yd=js,zd=bt.f,Qd=Vt,Wd=je,Jd=qd,Kd=Ce,xr=Kd("toStringTag"),rn=function(s,e,t,i){if(s){var r=t?s:s.prototype;Wd(r,xr)||zd(r,xr,{configurable:!0,value:e}),i&&!Yd&&Qd(r,"toString",Jd)}},Xd=tn.IteratorPrototype,Zd=Ka,ec=_i,tc=rn,ic=mt,sc=function(){return this},rc=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Zd(Xd,{next:ec(+!i,t)}),tc(s,r,!1,!0),ic[r]=sc,s},ac=Ms,nc=Ze,an=Du,oc=rc,lc=Xa,uc=rn,Or=Za,dc=Ce,Br=mt,nn=tn,cc=an.PROPER;an.CONFIGURABLE;nn.IteratorPrototype;var Zt=nn.BUGGY_SAFARI_ITERATORS,Xi=dc("iterator"),Mr="keys",ei="values",Vr="entries",hc=function(){return this},fc=function(s,e,t,i,r,n,o){oc(t,e,i);var l=function(v){if(v===r&&f)return f;if(!Zt&&v in c)return c[v];switch(v){case Mr:return function(){return new t(this,v)};case ei:return function(){return new t(this,v)};case Vr:return function(){return new t(this,v)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[Xi]||c["@@iterator"]||r&&c[r],f=!Zt&&h||l(r),p=e=="Array"&&c.entries||h,S,m,b;if(p&&(S=lc(p.call(new s)),S!==Object.prototype&&S.next&&(uc(S,d,!0,!0),Br[d]=hc)),cc&&r==ei&&h&&h.name!==ei&&(u=!0,f=function(){return nc(h,this)}),r)if(m={values:l(ei),keys:n?f:l(Mr),entries:l(Vr)},o)for(b in m)(Zt||u||!(b in c))&&Or(c,b,m[b]);else ac({target:e,proto:!0,forced:Zt||u},m);return o&&c[Xi]!==f&&Or(c,Xi,f,{name:r}),Br[e]=f,m},pc=function(s,e){return{value:s,done:e}},mc=Mt,Gs=bo,Fr=mt,on=Jl,Sc=bt.f,bc=fc,ti=pc,vc=il,gc=Ue,ln="Array Iterator",yc=on.set,Tc=on.getterFor(ln);bc(Array,"Array",function(s,e){yc(this,{type:ln,target:mc(s),index:0,kind:e})},function(){var s=Tc(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,ti(void 0,!0)):t=="keys"?ti(i,!1):t=="values"?ti(e[i],!1):ti([i,e[i]],!1)},"values");var Ur=Fr.Arguments=Fr.Array;Gs();Gs();Gs();if(!vc&&gc&&Ur.name!=="values")try{Sc(Ur,"name",{value:"values"})}catch(s){}var Ec=Ce,$c=mt,kc=Ec("iterator"),Pc=Array.prototype,wc=function(s){return s!==void 0&&($c.Array===s||Pc[kc]===s)},_c=Hs,jr=Cs,Ac=As,Rc=mt,Ic=Ce,Nc=Ic("iterator"),un=function(s){if(!Ac(s))return jr(s,Nc)||jr(s,"@@iterator")||Rc[_c(s)]},Dc=Ze,Cc=Ds,Lc=vt,xc=Ns,Oc=un,Bc=TypeError,Mc=function(s,e){var t=arguments.length<2?Oc(s):e;if(Cc(t))return Lc(Dc(t,s));throw Bc(xc(s)+" is not iterable")},Vc=Ze,Hr=vt,Fc=Cs,Uc=function(s,e,t){var i,r;Hr(s);try{if(i=Fc(s,"return"),!i){if(e==="throw")throw t;return t}i=Vc(i,s)}catch(n){r=!0,i=n}if(e==="throw")throw t;if(r)throw i;return Hr(i),t},jc=qa,Hc=Ze,Gc=vt,qc=Ns,Yc=wc,zc=Us,Gr=Na,Qc=Mc,Wc=un,qr=Uc,Jc=TypeError,fi=function(s,e){this.stopped=s,this.result=e},Yr=fi.prototype,Kc=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=jc(e,i),u,c,h,f,p,S,m,b=function(g){return u&&qr(u,"normal",g),new fi(!0,g)},v=function(g){return r?(Gc(g),l?d(g[0],g[1],b):d(g[0],g[1])):l?d(g,b):d(g)};if(n)u=s.iterator;else if(o)u=s;else{if(c=Wc(s),!c)throw Jc(qc(s)+" is not iterable");if(Yc(c)){for(h=0,f=zc(s);f>h;h++)if(p=v(s[h]),p&&Gr(Yr,p))return p;return new fi(!1)}u=Qc(s,c)}for(S=n?s.next:u.next;!(m=Hc(S,u)).done;){try{p=v(m.value)}catch(g){qr(u,"throw",g)}if(typeof p=="object"&&p&&Gr(Yr,p))return p}return new fi(!1)},Xc=xs,Zc=bt,eh=_i,th=function(s,e,t){var i=Xc(e);i in s?Zc.f(s,i,eh(0,t)):s[i]=t},ih=Ms,sh=Kc,rh=th;ih({target:"Object",stat:!0},{fromEntries:function(e){var t={};return sh(e,function(i,r){rh(t,i,r)},{AS_ENTRIES:!0}),t}});var ah=Rs,nh=ah.Object.fromEntries,oh={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},lh=oh,uh=ke,dh=Hs,ch=Vt,zr=mt,hh=Ce,Qr=hh("toStringTag");for(var Zi in lh){var Wr=uh[Zi],es=Wr&&Wr.prototype;es&&dh(es)!==Qr&&ch(es,Qr,Zi),zr[Zi]=zr.Array}var fh=nh,ph=fh,mh=ph,Sh=mh,Ut=Sh,ut;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(ut||(ut={}));var ct=(s,e=0,t=ut.OFFSET_P)=>{switch(t){case ut.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ut.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:a.assertNever(t)}return s},k=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};exports.VideoQuality=void 0;(function(s){s.INVARIANT="Invariant quality",s.Q_144P="144p",s.Q_240P="240p",s.Q_360P="360p",s.Q_480P="480p",s.Q_720P="720p",s.Q_1080P="1080p",s.Q_1440P="1440p",s.Q_2160P="2160p",s.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const me={[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}},pi=(s,e)=>me[s].height>me[e].height,bh=(s,e)=>me[s].height>=me[e].height,Lt=(s,e)=>me[s].height<me[e].height,vh=(s,e)=>me[s].height<=me[e].height,gh=s=>s.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:Lt(e,t)?1:-1)[0],yh=Object.keys(me).sort((s,e)=>Lt(s,e)?-1:1),et=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return yh.find(r=>{const n=me[r];return n.width>=i&&n.height>=t})},Th=s=>me[s].height,yi=s=>s===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,i=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||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:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const Eh=s=>{switch(s){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(s)}};var F;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(F||(F={}));const $h=5,kh=5,Ph=500,Jr=7e3;class wh{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new J(F.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){i!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.stop());return}if(!r){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===D.Requested&&i!==F.STOPPED){this.seek(l.position);return}switch(n){case exports.PlaybackState.PLAYING:{switch(i){case F.PLAYING:break;case F.PAUSED:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.READY:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:a.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case F.PLAYING:this.videoState.startTransitionTo(F.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case F.PAUSED:break;case F.READY:this.videoState.startTransitionTo(F.PAUSED),this.videoState.setState(F.PAUSED);break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:a.assertNever(i)}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(Eh(e.format)),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(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(a.map(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,n)=>this.subscription.add(r.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new a.Subject;e.add(r.pipe(a.debounce(Ph)).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===D.Applying||Math.abs(l-n)>$h)&&r.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),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:n}=this.params.connection,o=r.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<kh&&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),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(F.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:D.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===F.PAUSED||e===F.PLAYING)&&(this.videoState.setState(F.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)===F.PLAYING||e===F.PAUSED)&&(this.videoState.setState(F.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const e=this.videoState.getTransition();(e==null?void 0:e.to)===F.READY&&this.videoState.setState(F.READY)}handleRemoteStop(){this.videoState.getState()!==F.STOPPED&&this.videoState.setState(F.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(n.volume!==r.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=i[e];a.assertNonNullable(c);const h=gh(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),r=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=i[e];a.assertNonNullable(c),r=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const c=i[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const c=i[e];a.assertNonNullable(c),r=ct(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:r,n);l.contentUrl=r,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 i=this.params.desiredState.seekState.getState();return i.state===D.Applying||i.state===D.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(Jr).subscribe(()=>n(`timeout(${Jr})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===D.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Kr{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,n=i.length;r<n;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,n=i.length;r<n;r++){const o=i[r];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 dn extends Kr{constructor(){super(),this.listeners||Kr.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 cn=class{constructor(){Object.defineProperty(this,"signal",{value:new dn,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(cn.prototype[Symbol.toStringTag]="AbortController",dn.prototype[Symbol.toStringTag]="AbortSignal");function hn(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function _h(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!hn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||r)&&(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,S)=>{c.addEventListener("abort",()=>S(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Ai=hn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),fn=Ai?_h({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ht=Ai?fn.fetch:window.fetch;Ai?fn.Request:window.Request;const Je=Ai?cn:window.AbortController,It=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class xt{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,r=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(i,r)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const r=t[0];if(!r||!r.request.range)continue;const[n,o]=It(r.request);if(n>=i.from&&o<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const r=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,r)}}}abort(e){var t;if(e){const{request:i}=e,r=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(i.url);r&&n&&n.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(It),r=i[0][0];let n=i[0][1];for(let f=1;f<i.length&&n<this.params.minDataSize;f++){const p=i[f][1];p-r<=2*this.params.minDataSize&&(n=Math.max(n,p))}r===0?n=Math.max(n,r+this.params.minInitSize):n=Math.max(n,r+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${r}-${n}`);const l=o.toString(),d=new Je,u=d.signal,c={url:e,from:r,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var p,S;throw(S=(p=this.params).onError)===null||S===void 0||S.call(p,{id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return ht(l,{signal:u}).then(f=>{var p,S,m;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[b,v]=f.body.tee();(S=(p=this.params).onDownloadStream)===null||S===void 0||S.call(p,v);const g=b.getReader(),P=parseInt((m=f.headers.get("Content-Length"))!==null&&m!==void 0?m:"",10)||n-r+1;c.data=new ArrayBuffer(P);const T=new Uint8Array(c.data),E=async({done:_,value:x})=>{_?this.onBigRequestProgress(c):x&&(T.set(x,c.loaded),c.loaded+=x.byteLength,this.onBigRequestProgress(c),await(g==null?void 0:g.read().then(E,xt.suppressStreamErrors).catch(h)))};g==null||g.read().then(E,xt.suppressStreamErrors).catch(h)},xt.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:i,loaded:r,data:n,response:o}){var l,d,u,c,h,f,p,S;if(!this.activeRequests.has(e)||!n)return;const m=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const b of m){const{request:v}=b,[g,P]=It(v),T=g>=t&&P<=t+r,E=t>=g&&t+r<P,_=n.slice(g-t,Math.min(P-t+1,r));if((T||E)&&(v.requestStartDate=(d=v.requestStartDate)!==null&&d!==void 0?d:new Date,v.firstByteDate=(u=v.firstByteDate)!==null&&u!==void 0?u:new Date,v.bytesLoaded=_.byteLength,v.bytesTotal=i-t),T){v.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(N=>N!==b)),(h=b.success)===null||h===void 0||h.call(b,_,"",e);const x=o?Array.from(o.headers.entries()).map(([N,R])=>`${N}: ${R}`).join(`\r
|
|
7
7
|
`):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(v,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,x,[])}else E&&((S=b.progress)===null||S===void 0||S.call(b,{loaded:r,total:i-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:i},r){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:r}),!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]=It(c.request);(h>=t&&h<i||f>t&&f<=i)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(r)))}if(this.activeRequests.delete(e),r)throw r}onBigRequestAbort({url:e,from:t,to:i}){var r,n;if(!this.activeRequests.has(e))return;const o=(r=this.dashJsRequestQueue.get(e))!==null&&r!==void 0?r:[];for(const l of o){const[d,u]=It(l.request);(d>=t&&d<i||u>t&&u<=i)&&((n=l==null?void 0:l.abort)===null||n===void 0||n.call(l,l.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Ti{constructor(e,t,i){this.baseLoader=e,this.config=i,this.bigRequest=t,t.setMetrics(i.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Ti.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;Ti.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Ah=(s,e)=>t=>({create:i=>{const r=s(t).create(i);return new Ti(r,e,i)}}),Rh=(s,e)=>{const t=new xt(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,r=i.getLoader;return{getLoader:n=>{const o=r(n);return Ah(o,t)}}},!0),()=>t.destroy()};var Ih=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,n=r.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&(e==null||e())}}},!0)},Nh=s=>{const e=new a.ValueSubject(1/0),t=new a.Subject,i=new a.ValueSubject(void 0),r=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,S,m;const b=Ut(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 v=(S=b["x-delivery-type"])!==null&&S!==void 0?S:exports.HttpConnectionType.HTTP1,g=(m={1:!0,0:!1}[b["x-reused"]])!==null&&m!==void 0?m:void 0;i.next(v),r.next(g)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return s.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,S=f.progress;f.onload=function(...m){return d(this),p(...m)},f.progress=function(...m){return u(this),S(...m)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},ft=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Dh=s=>s.extend("RequestModifier",()=>({modifyRequestURL:ft}),!0),Ch=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,n]=i.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${r}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const $e=(s,e,t,{equal:i=(o,l)=>o===l,changed$:r,onError:n}={})=>{const o=s.getState(),l=e(),d=a.isNullable(r),u=new a.Subscription;return r&&u.add(r.subscribe(c=>{const h=s.getState();i(c,h)&&s.setState(c)},n)),i(l,o)||(t(o),d&&s.setState(o)),u.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),d&&s.setState(c.to)},n)),u},tt=(s,e,t)=>$e(e,()=>s.loop,i=>{a.isNonNullable(i)&&(s.loop=i)},{onError:t}),Le=(s,e,t,i)=>$e(e,()=>({muted:s.muted,volume:s.volume}),r=>{a.isNonNullable(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,n)=>r===n||(r==null?void 0:r.muted)===(n==null?void 0:n.muted)&&(r==null?void 0:r.volume)===(n==null?void 0:n.volume),changed$:t,onError:i}),He=(s,e,t,i)=>$e(e,()=>s.playbackRate,r=>{a.isNonNullable(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Lh=s=>["__",s.language,s.label].join("|"),xh=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Pe{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,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add($e(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:r})),this.subscription.add($e(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:r})),this.subscription.add($e(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 i=this.current$.getValue();this.select(i)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),a.filterChanged((i,r)=>i.length===r.length&&i.every(({id:n},o)=>n===r[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),a.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),a.filterChanged()).subscribe(this.current$));const t=i=>{var r,n;return this.applyCueSettings((n=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(i=>{var r,n;(r=i.track)===null||r===void 0||r.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=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;a.isNonNullable(t.align)&&(r.align=t.align),a.isNonNullable(t.position)&&(r.position=t.position),a.isNonNullable(t.size)&&(r.size=t.size),a.isNonNullable(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Pe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,r=e.id!==""?e.id:Lh(e);return this.externalTracks.has(r)?{id:r,type:"external",language:t,label:i,url:this.externalTracks.get(r).url}:{id:r,type:"internal",language:t,label:i}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(i=>i.id===t)).forEach(t=>this.detach(t))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))a.isNonNullable(e)&&xh(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){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"),i=>i.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var xe=s=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),s.appendChild(e),e};class qs{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 pn=()=>{const{userAgent:s}=window.navigator;return!/chrome/i.test(s)&&/webkit|safari|khtml/i.test(s)};const ws=3;class Oh{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const n=this._source.buffered.end(t);r>e&&r-e<ws&&(r=e),this._buffer.push({from:r,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||ws))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:n})=>{const o=r>=e&&r<t,l=n>=e&&n<t;o&&l||(o?i(t,n):l?i(r,e):r<e&&n>t?(i(t,n),i(r,e)):i(r,n))})}destroy(){this._buffer=[]}}var mn=(s,e,t=ws)=>{let i=0,r=0;for(let n=0;n<s.length;n++){const o=s.start(n),l=s.end(n);if(o<=e&&e<=l){if(i=o,r=l,!t)return{from:i,to:r};for(let d=n-1;d>=0;d--)s.end(d)+t>=i&&(i=s.start(d));for(let d=n+1;d<s.length;d++)s.start(d)-t<=r&&(r=s.end(d))}}return{from:i,to:r}};const Oe=s=>{const e=p=>a.fromEvent(s,p).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=a.merge(...t.map(p=>a.fromEvent(s,p))).pipe(a.map(p=>p.type==="ended"?s.readyState<2:s.readyState<3),a.filterChanged()),r=a.merge(a.fromEvent(s,"progress"),a.fromEvent(s,"timeupdate")).pipe(a.map(()=>mn(s.buffered,s.currentTime))),n=pn()?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),o=a.fromEvent(s,"volumechange").pipe(a.map(()=>({muted:s.muted,volume:s.volume}))),l=a.fromEvent(s,"ratechange").pipe(a.map(()=>s.playbackRate)),d=a.fromEvent(s,"error").pipe(a.filter(()=>Boolean(s.error||s.played.length)),a.map(()=>{var p;const S=s.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(p=s.error)!==null&&p!==void 0?p:void 0}})),u=a.fromEvent(s,"timeupdate").pipe(a.map(()=>s.currentTime)),c=new a.Subject,h=.3;let f;return u.subscribe(p=>{s.loop&&a.isNonNullable(f)&&a.isNonNullable(p)&&f>=s.duration-h&&p<=h&&c.next(f),f=p}),{playing$:n,pause$:e("pause").pipe(a.filter(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:a.fromEvent(s,"durationchange").pipe(a.map(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:l}},Ys=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Bh=Ms,Mh=Ls,Vh=Us,Fh=Fs;Bh({target:"Array",proto:!0},{at:function(e){var t=Mh(this),i=Vh(t),r=Fh(e),n=r>=0?r:i+r;return n<0||n>=i?void 0:t[n]}});var Uh=Is,jh=Uh,Hh=jh,Gh=Hh("Array","at"),qh=Gh,Yh=qh,zh=Yh,Qh=zh,_e=Qh;let zs=!1,Ae={};const Wh=s=>{zs=s},Jh=()=>{Ae={}},Kh=s=>{s(Ae)},ii=(s,e)=>{var t;zs&&(Ae.meta=(t=Ae.meta)!==null&&t!==void 0?t:{},Ae.meta[s]=e)};class Ee{constructor(e){this.name=e}next(e){var t,i;if(!zs)return;Ae.series=(t=Ae.series)!==null&&t!==void 0?t:{};const r=(i=Ae.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Ae.series[this.name]=r}}const Xh=new Ee("best_bitrate"),Zh=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class ef{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const jt=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,p;const S=i.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,m=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*i.containerSizeFactor,height:e.height*S*i.containerSizeFactor},b=m&&et(m),v=i.considerPlaybackRate&&a.isNonNullable(l)?l:1,g=s.filter(I=>!yi(I.quality)).sort((I,A)=>pi(I.quality,A.quality)?-1:1),P=(h=_e(g,-1))===null||h===void 0?void 0:h.quality,T=(f=_e(g,0))===null||f===void 0?void 0:f.quality,E=a.isNullable(r)||a.isNonNullable(r.min)&&a.isNonNullable(r.max)&&Lt(r.max,r.min)||a.isNonNullable(r.min)&&T&&pi(r.min,T)||a.isNonNullable(r.max)&&P&&Lt(r.max,P),_=v*Zh(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),N=g.filter(I=>{const A=b?Lt(I.quality,b):!0,O=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(I.bitrate)?t-n>=I.bitrate*_:!0,V=i.lazyQualitySwitch&&a.isNonNullable(i.minBufferToSwitchUp)&&d&&!yi(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&pi(I.quality,d.quality),q=E||(a.isNullable(r.max)||vh(I.quality,r.max))&&(a.isNullable(r.min)||bh(I.quality,r.min));return A&&O&&!V&&q})[0];N&&N.bitrate&&Xh.next(N.bitrate);const R=(p=N!=null?N:g[Math.ceil((g.length-1)/2)])!==null&&p!==void 0?p:s[0],M=R&&u&&u.history[R.id]&&a.now()-u.history[R.id]<=i.trackCooldown&&(!u.last||R.id!==u.last.id);if(R!=null&&R.id&&u&&!M&&u.recordSelection(R),M&&(u!=null&&u.last)){const I=u.last;return u==null||u.recordSwitch(I),I}return u==null||u.recordSwitch(R),R};var ne=s=>new URL(s).hostname;const tf=300,Ei=(s,e=tf)=>new a.Observable(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(Kn(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(s),()=>n.disconnect()}),sf=5e3,Nt={};var U;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(U||(U={}));const te=(s,e)=>new a.Observable(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class rf{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(U.DOWNLOADING_LIB),this.textTracksManager=new Pe,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 qs,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===U.DOWNLOADING_LIB||t===U.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===D.Requested&&t!==U.STOPPED&&i!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),i){case exports.PlaybackState.STOPPED:{switch(t){case U.STOPPED:break;case U.PLAYING:case U.PAUSED:case U.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case U.PLAYING:break;case U.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 U.READY:this.play();break;case U.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case U.PLAYING:this.pause(),this.liveOffset.pause();break;case U.PAUSED:break;case U.READY:this.videoState.setState(U.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case U.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(i)}},this.video=xe(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var n;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=r==null?void 0:r.toString)===null||n===void 0?void 0:n.call(r)}`,thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),sf);import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(Nt.MediaPlayer=r.MediaPlayer,Nt.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){a.assertNonNullable(Nt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Nt.Debug,"dashjs not loaded"),this.player=Nt.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?Ys(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=Rh(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&&Ch(this.player),Ih(this.player),this.params.tuning.requestQuick&&Dh(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(U.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},r=(m,b)=>this.subscription.add(m.subscribe(b,i));r(Ei(this.video),this.elementSize$),r(te(this.player,"error").pipe(a.map(m=>{const b=typeof m.error=="object"?m.error.code:m.error,v=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${b}`,message:v}})),e.error$),r(te(this.player,"playbackError").pipe(a.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=te(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({newQuality:m})=>{var b;return(b=this.videoTracks.find(({bitrateInfo:v})=>v.qualityIndex===m))===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:m})=>m===U.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add($e(t.videoTrack,()=>{var m,b;const v=this.player.getQualityFor("video");return(b=(m=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===v))===null||m===void 0?void 0:m.track)===null||b===void 0?void 0:b.id},m=>{var b;if(a.isNullable(m))return;const v=(b=this.videoTracks.find(({track:g})=>g.id===m))===null||b===void 0?void 0:b.bitrateInfo;v&&this.player.setQualityFor("video",v.qualityIndex)},{changed$:n.pipe(a.map(m=>m==null?void 0:m.id)),onError:i}))},i)),this.subscription.add($e(t.autoVideoTrackSwitching,()=>{var m,b,v;return(v=(b=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||b===void 0?void 0:b.autoSwitchBitrate)===null||v===void 0?void 0:v.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),r(te(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),r(te(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:b}})=>{var v,g;const P=this.player.getDashMetrics(),T=P.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),E=(v=P.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&v!==void 0?v:exports.HttpConnectionType.HTTP1,_=(g={1:!0,0:!1}[T])!==null&&g!==void 0?g:void 0;this.params.output.httpConnectionType$.next(E),this.params.output.httpConnectionReused$.next(_),e.hostname$.next(ne(b))}),r(te(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:b,availableFrom:v}}})=>{this.isLive$.next(b),this.availableFrom$.next(v.getTime()),b||e.duration$.next(m),this.videoTracks=[];const g=this.player.getQualityFor("video");let P;for(const T of this.player.getBitrateInfoListFor("video")){const E=T.qualityIndex.toString(10),_=et(T),x=T.bitrate/1e3,N={width:T.width,height:T.height},R=this.frameRatesByFrameHeight[T.height];if(_){const M={id:E,quality:_,bitrate:x,size:N,fps:R};this.videoTracks.push({track:M,bitrateInfo:T}),T.qualityIndex===g&&(P=M)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:T})=>T)),P&&e.currentVideoTrack$.next(P),this.videoState.setState(U.STREAM_INITIALIZED),this.videoState.startTransitionTo(U.READY)}),r(te(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const b=m.requestEndDate.getTime()-m.firstByteDate.getTime(),v=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(v,b)}),r(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),b=jt(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),v=this.videoTracks.find(({track:g})=>g===b);v!=null&&v.bitrateInfo&&this.player.setQualityFor("video",v==null?void 0:v.bitrateInfo.qualityIndex,!1)}),r(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:m})=>m),a.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=te(this.player,"playbackTimeUpdated").pipe(a.map(({time:m})=>m!=null?m:0));r(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:b})=>this.params.output.liveTime$.next(m+b*1e3)),r(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),r(te(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(te(this.player,"playbackEnded"),e.endedEvent$),r(te(this.player,"playbackProgress").pipe(a.map(()=>mn(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(te(this.player,"playbackPlaying"),()=>{this.videoState.setState(U.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),r(te(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(U.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(te(this.player,"playbackPaused"),()=>{this.videoState.setState(U.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),r(te(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===U.READY&&this.videoState.setState(U.READY)}),r(this.isLive$,e.isLive$),r(Ei(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));r(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=Nh(this.player);r(c,this.params.output.httpConnectionType$),r(h,this.params.output.httpConnectionReused$),r(d,this.maxSeekBackTime$),r(u.pipe(a.once()),e.firstBytesEvent$),r(te(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(m=>m<60))}),({isLive:m,isShort:b})=>{const v=!m&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:v}}})}),r(o.pipe(a.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(te(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(te(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),this.subscription.add(tt(this.video,t.isLooped,i));const{volumeState$:f,looped$:p,playbackRateState$:S}=Oe(this.video);this.subscription.add(Le(this.video,t.volume,f,i)),this.subscription.add(f.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(He(this.video,t.playbackRate,S,i))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(U.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(U.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const r=ct(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ut.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(U.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(U.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(i){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Ht=s=>{switch(s){case"mobile":return exports.VideoQuality.Q_144P;case"lowest":return exports.VideoQuality.Q_240P;case"low":return exports.VideoQuality.Q_360P;case"sd":case"medium":return exports.VideoQuality.Q_480P;case"hd":case"high":return exports.VideoQuality.Q_720P;case"fullhd":case"full":return exports.VideoQuality.Q_1080P;case"quadhd":case"quad":return exports.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return exports.VideoQuality.Q_2160P}},Ge=async s=>{const e=s.muted;try{await s.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return s.muted=!1,console.warn(i),!1}}return!0};function re(){return a.now()}function Sn(s){return re()-s}function Xr(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=o=>i.test(o);return{resolve:(o,l,d=!1)=>{r(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 af(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function mi(s,e,t,i){const r=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",S=7e3,m=2e3,b=()=>{if(d)return;a.assertNonNullable(c);const A=Sn(c);let O;if(A<m){O=m-A,setTimeout(b,O);return}m*=2,m>S&&(m=S),o&&o.abort(),o=new r,_()};const v=A=>(n=A,I),g=A=>(h=A,I),P=()=>(p="json",I),T=()=>{if(!d){if(--u>=0){b(),i&&i();return}d=!0,h&&h(),t&&t()}},E=A=>(f=A,I),_=()=>{c=re(),o=new r,o.open("get",s);let A=0,O,V=0;const q=()=>(a.assertNonNullable(c),Math.max(c,Math.max(O||0,V||0)));if(n&&o.addEventListener("progress",$=>{const C=re();n.updateChunk&&$.loaded>A&&(n.updateChunk(q(),$.loaded-A),A=$.loaded,O=C)}),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 C=o.response.byteLength-A;C&&n.updateChunk&&n.updateChunk(q(),C)}h&&h(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),f){const $=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(V=re(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),I},I={withBitrateReporting:v,withParallel:E,withJSONResponse:P,withRetryCount:A=>(u=A,I),withRetryInterval:(A,O)=>(a.isNonNullable(A)&&(m=A),a.isNonNullable(O)&&(S=O),I),withTimeout:A=>(l=A,I),withFinally:g,send:_,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return I}const nf=100,of=2e3,lf=500;let uf=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-lf;if(t-e>of){let i=0,r=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,r+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;i+=o;const d=n.bytes*o/l;r+=d,n.start=t,n.bytes-=d}}}if(r>0&&i>0){const n=r*8/(i/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>nf&&(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 df{constructor(e,t,i,r,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const i=re(),r=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=re()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=mi(t,n,()=>r("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=re()}_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=re();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,o._retryCB=r,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=i,n._retryCB=r,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 si=1e4,ri=3,cf=300,hf=2e3,ff=6e4,pf=10,mf=1,Sf=500;class bf{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 uf(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Xr(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Xr(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,r,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)?(!r||n.bitrate>r.bitrate)&&(r=n):(!i||i.bitrate>n.bitrate)&&(i=n));return r||i}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:i,videoElement:r,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{af(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 df(ri,si,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:r}=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,_)=>{d&&d.abort(),d=mi(this.urlResolver.resolve(T,!1),E,_,()=>this._retryCallback()).withTimeout(si).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ri).withFinally(()=>{d=null}).send()},p=(T,E,_)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),E,_,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},S=T=>{const E=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${E}=>${T}`),i.playbackRate=T)},m=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),b()},b=()=>{if(!this.lowLatency)S(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){S(1);return}const _=re()-6e4;let x=0;for(let R=0;R<this.bufferStates.length;R++){const M=this.bufferStates[R];T=Math.min(T,M.buf),M.ts<_&&x++}this.bufferStates.splice(0,x),t(`update playback rate; minBuffer=${T} drop=${x} jitter=${this.sourceJitter}`);let N=T-mf;this.sourceJitter>=0?N-=this.sourceJitter/2:this.sourceJitter-=1,N>3?S(1.15):N>1?S(1.1):N>.3?S(1.01):S(1)}},v=T=>{let E;const _=()=>E&&E.start?E.start.length:0,x=$=>E.start[$]/1e3,N=$=>E.dur[$]/1e3,R=$=>E.fragIndex+$,M=($,C)=>({chunkIdx:R($),startTS:x($),dur:N($),discontinuity:C}),I=()=>{let $=0;if(E&&E.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=C;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let ee=E.dur.length-1;for(;ee>=0&&(Z-=E.dur[ee],!(Z<=0));--ee);$=Math.min(ee,E.dur.length-1-Q),$=Math.max($,0)}return M($,!0)},A=$=>{const C=_();if(!(C<=0)){if(a.isNonNullable($)){for(let Q=0;Q<C;Q++)if(x(Q)>$)return M(Q)}return I()}},O=$=>{const C=_(),Q=$?$.chunkIdx+1:0,Z=Q-E.fragIndex;if(!(C<=0)){if(!$||Z<0||Z-C>pf)return t(`Resync: offset=${Z} bChunks=${C} chunk=`+JSON.stringify($)),I();if(!(Z>=C))return M(Q-E.fragIndex,!1)}},V=($,C,Q)=>{u&&u.abort(),u=mi(this.urlResolver.resolve($,!0,this.lowLatency),C,Q,()=>this._retryCallback()).withTimeout(si).withRetryCount(ri).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,C)=>{V(T,Q=>{if(!h())return;E=Q;const Z=Boolean(E.lowLatency);Z!==this.lowLatency&&m(Z);let ee=0;for(let oe=0;oe<E.dur.length;++oe)ee+=E.dur[oe];ee>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ee/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,$(A(C))},()=>this._handleNetworkError())},nextChunk:O}},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:_}=this.params;let x=v(e.jidxUrl),N,R,M,I,A=0,O,V,q;const $=()=>{O&&(clearTimeout(O),O=void 0);const j=Math.max(Sf,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=A+j,ae=re(),ue=Math.min(1e4,ie-ae);A=ae;const qe=()=>{u||h()&&x.seek(()=>{h()&&(A=re(),C(),$())})};ue>0?O=window.setTimeout(()=>{this.paused?$():qe()},ue):qe()},C=()=>{let j;for(;j=x.nextChunk(I);)I=j,be(j);const ie=x.nextChunk(M);if(ie){if(M&&ie.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?$():(g(),this._initPlayerWith(e));return}oe(ie)}else $()},Q=(j,ie)=>{if(!h()||!this.sourceBuffer)return;let ae,ue,qe;const ve=Be=>{window.setTimeout(()=>{h()&&Q(j,ie)},Be)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),ve(100);else{const Be=re(),Ye=E.currentTime;!this.paused&&E.buffered.length>1&&V===Ye&&Be-q>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),V!==Ye&&(V=Ye,q=Be);const yt=this._getBufferSizeSec();if(yt>30)_(`Buffered ${yt} seconds; delaying appendBuffer`),ve(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:Be,buf:yt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch(it){if(it.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),qe=this.sourceBuffer.buffered.length,qe!==0&&(ae=this.sourceBuffer.buffered.start(0),ue=Ye,ue-ae>4&&this.sourceBuffer.remove(ae,ue-3)),ve(1e3);else throw it}}},Z=()=>{R&&N&&(_([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(M)]),Q(R,function(){R=null,C()}))},ee=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),oe=j=>{h()&&p(ee(j),(ie,ae)=>{if(h()){if(ae/=1e3,R=ie,M=j,o=j.startTS,ae){const ue=Math.min(10,j.dur/ae);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ue:ue}Z()}},()=>this._handleNetworkError())},be=j=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(j),!1)))},gt=j=>{h()&&(e.cachedHeader=j,Q(j,()=>{N=!0,Z()}))};n=!0,x.seek(j=>{if(h()){if(A=re(),!j){$();return}I=j,!a.isNullable(T)||j.startTS>T?oe(j):(M=j,C())}},T),e.cachedHeader?gt(e.cachedHeader):f(e.headerUrl,gt,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),a.isNonNullable(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=h=>{if(!this.autoQuality)return;let f,p,S;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),S=h/this.bitrate,p>10&&S>.8||p>15&&S>.5||p>20&&S>.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 S=re();if(this.chunkRateEstimator.addInterval(f,S,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:S-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&&Sn(o)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=re();h<l&&(o=f),l=h}}}_fetchManifest(e,t,i){this.manifestRequest=mi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(si).withRetryCount(ri).withRetryInterval(cf,hf).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Ge(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:r}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&r.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ff))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var L;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(L||(L={}));const vf=[L.PAUSED,L.PLAYING,L.READY],gf=[L.PAUSED,L.PLAYING,L.READY];class yf{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(L.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Pe,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new qs,this._dashCb=r=>{var n,o,l,d;switch(r.name){case"buffering":{const u=r.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=r.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=Ht(h.name))!==null&&o!==void 0?o:et(h.video),S=h.bitrate/1e3,m={...h.video};if(!p)continue;const b={id:f,quality:p,bitrate:S,size:m};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)===L.MANIFEST_READY&&this.videoState.setState(L.MANIFEST_READY);break}case"qualitySwitch":{const u=r.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}=r;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{var r;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!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(L.STOPPED));return}if(!o){if(gf.includes(n)){const c=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.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===D.Requested&&vf.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case L.STOPPED:this.videoState.startTransitionTo(L.MANIFEST_READY),this.dash.attachSource(ct(this.params.source.url));return;case L.MANIFEST_READY:this.videoState.startTransitionTo(L.READY),this.prepare();break;case L.READY:l===exports.PlaybackState.PAUSED?this.videoState.setState(L.PAUSED):l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(L.PLAYING),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(L.PAUSED)}));return;case L.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(L.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case L.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(L.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(L.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=r=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(r)}`})}),this.video=xe(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=Oe(this.video);this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===L.READY&&this.videoState.setState(L.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(L.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===D.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(L.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:n})=>this.params.output.liveTime$.next(r+n*1e3),t)).add(tt(this.video,this.params.desiredState.isLooped,t)).add(Le(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(He(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const n=r&&Th(r);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case L.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case L.MANIFEST_READY:case L.READY:break;case L.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case L.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(r.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.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new bf({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},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,i,r,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=(r=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:(n=jt(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 i=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(i,`No such representation ${e}`),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.dash.reinit(ct(this.params.source.url,i))}}var bn=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),n=i===null?exports.HttpConnectionType.HTTP1:(e=i)!==null&&e!==void 0?e:void 0,o=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},dt=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const r=s.start(i)*1e3,n=s.end(i)*1e3;r<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Tf=s=>{const e=document.createElement("a");return e.href=s,e.origin},Ef=s=>{const e=document.createElement("a");return e.href=s,e.host};class vn{constructor(e,t=[],i,r,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=r,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,i,r,n,o,l,d,u;if(a.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.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=Ut(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(Ef(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!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 $i{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let n=0;for(let o=0,l=r.length;o<l;o++)n+=r.end(o)-r.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,r,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=m=>{r($i._str2ua(m.substr(d))),d=m.length};let S=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(S=ft(S)),this._lastXhr=new vn(S,e.failoverHosts,m=>{this._lastXhr=void 0,p(m);const b=Date.now()-u;this._params.onBandwidthChange({size:m.length,duration:b,speed:8*m.length/(b/1e3)}),this._onDashCallback("loading",{size:m.length,done:!0}),n==null||n()},m=>{if(m.length-d>l&&p(m),h===0){h=Date.now();return}f=m.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=m.length,h=Date.now()),this._onDashCallback("loading",{size:m.length,done:!1})},o,(m,b,v)=>this._params.onError(m,b,v))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=$i._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class $f{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},r=t.exec(e),n=(r==null?void 0:r[1])==="-"?-1:1,o={years:i(r==null?void 0:r[2],n),months:i(r==null?void 0:r[3],n),weeks:i(r==null?void 0:r[4],n),days:i(r==null?void 0:r[5],n),hours:i(r==null?void 0:r[6],n),minutes:i(r==null?void 0:r[7],n),seconds:i(r==null?void 0:r[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=ft(i)),new vn(i,t,r=>{this.attachManifest(r,t,Tf(i))},void 0,r=>{this._params.onResponseHeaders(r)},(r,n,o)=>this._params.onError(r,n,o))}attachManifest(e,t,i){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,S,m,b,v,g,P,T,E,_,x,N,R,M,I,A;const O=u.getElementsByTagName("SegmentBase")[0],V=O&&o(O,"indexRange").split("-"),q=O&&O.getElementsByTagName("Initialization")[0],$=q&&o(q,"range").split("-");if(!$||!V){const be=u.parentElement;if((be==null?void 0:be.getAttribute("contentType"))==="text"){const gt=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,j=(i?i+"/":"")+((S=(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||S===void 0?void 0:S.data),ie=(m=be.getAttribute("lang"))!==null&&m!==void 0?m:void 0;j&&d.push({id:gt,url:j,language:ie})}return}const C=.1,Q=Number((b=u.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),Z=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ee;const oe=(g=(v=u.attributes.getNamedItem("frameRate"))===null||v===void 0?void 0:v.value)!==null&&g!==void 0?g:void 0;ee=oe?Ys(oe):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:Q,baseURL:Z,failoverHosts:t,indexFrom:Number(V[0]),indexTo:Number(V[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(_=(E=u.attributes.getNamedItem("codecs"))===null||E===void 0?void 0:E.value)!==null&&_!==void 0?_:void 0,mimeType:(N=(x=u.attributes.getNamedItem("mimeType"))===null||x===void 0?void 0:x.value)!==null&&N!==void 0?N:void 0,fps:ee,bufferSize:C*Q/8,bufferLength:C,name:(M=(R=u.attributes.getNamedItem("okQuality"))===null||R===void 0?void 0:R.value)!==null&&M!==void 0?M:void 0,id:(A=(I=u.attributes.getNamedItem("id"))===null||I===void 0?void 0:I.value)!==null&&A!==void 0?A:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let n=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,n);const o=new DataView(r.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),S=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:S/l,fromOffset:u,toOffset:p-1}),u=p,d=S}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let r,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!==r&&(r=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 S=this._buffer.getNextWithGap(p);S&&(this._video.currentTime=S.from)}catch(S){throw this._params.onError("GapSyncError",`Seek Error ${String(S)}`,S),S}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new $i({mediaSource:i,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||l(),i.removeEventListener("sourceopen",d),i.removeEventListener("webkitsourceopen",d)};i.addEventListener("sourceopen",d,!1),i.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(i){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!i||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(r.toTime<i.to+n){const o=this._findRef(r.toTime);o&&o.toTime<i.to+n?(this._buffer.smartRemove(r.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(r.fromTime-n,r.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,r.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 i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let n=0;n<i.length;n++){const o=i[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!r||o.fromTime<r.fromTime)&&(r=o)}if(!r){const n=i[i.length-1];if(e>n.toTime)return n}return r}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const r=i[i.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>i&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var B;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(B||(B={}));const kf=[B.PAUSED,B.PLAYING];class Pf{constructor(e){this.videoState=new J(B.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Pe,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 i,r,n;const o=[];for(const l of t){const d=(r=(i=l.name)!==null&&i!==void 0?i:l.id)!==null&&r!==void 0?r:l.height.toString(10),u=(n=l.name&&Ht(l.name))!==null&&n!==void 0?n:et(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(B.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const r=(i=this.representations$.getValue().find(({representation:n})=>n===t))===null||i===void 0?void 0:i.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.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(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(o)};`}),r===exports.PlaybackState.STOPPED){t!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(B.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!i)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===D.Requested&&kf.includes(t)&&this.seek(o.position,o.forcePrecise),t){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_LOADED),this.prepare();return;case B.MANIFEST_LOADED:this.videoState.startTransitionTo(B.INITIAL_REPRESENTATION_SELECTED);return;case B.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(B.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case B.METADATA_LOADED:this.videoState.startTransitionTo(B.READY),this.dash.updateRefsForCurrentTime();return;case B.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed());return;case B.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(B.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case B.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return 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:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=xe(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.source.type==="url"&&this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Oh(this.video),this.dash=new $f({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:r,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,i=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},r=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=Oe(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,i));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==D.Applying)&&(this.videoState.getState()===B.PLAYING||this.videoState.getState()===B.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(Le(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(He(this.video,t.playbackRate,n.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),o(Ei(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===B.READY&&this.videoState.setState(B.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(B.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(B.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},i)).add(this.dashLiteEvents.error$.pipe(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(),S=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),m=this.elementSize$.getValue(),b=r();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let v;if(!b&&a.isNonNullable(p))v=p;else{const g=dt(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);v=(d=jt(h.map(({track:E})=>E),{container:m,throughput:S,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(v)?(u=h.find(({track:g})=>g.id===v))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,i)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===B.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(B.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?l.height<=d.height:l===d)).subscribe(l=>{const d=dt(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!r())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(ne(l.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=bn(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,i)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}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(){Ge(this.video).then(e=>{e||(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var ce;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(ce||(ce={}));var ki;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ki||(ki={}));var he;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(he||(he={}));var H;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(H||(H={}));var pt;(function(s){s.MP4="mp4",s.WEBM="webm"})(pt||(pt={}));var Zr=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const wf=(s,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},_f=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ea=_f?wf:window.requestIdleCallback;var ts,is;let gn=!1;try{gn=pn()&&parseInt((is=(ts=navigator.userAgent.match(/Version\/(\d+)/))===null||ts===void 0?void 0:ts[1])!==null&&is!==void 0?is:"",10)<16}catch(s){console.error(s)}class Af{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 i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;gn&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"&&i==="remove"||this.error$.next({id:`BufferTaskQueue:${i}`,category: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 ta=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};const yn=new TextDecoder("ascii"),Tn=s=>{let e=0,t=s.getUint32(e);e+=4;const i=new DataView(s.buffer,s.byteOffset+e,4),r=yn.decode(i);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,s.byteLength)-e,o=new DataView(s.buffer,s.byteOffset+e,n);return{id:r,size:t,contents:o}},Rf=s=>yn.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",If=s=>{const e=Tn(s),t=[];let i=0;const r=()=>{const p=e.contents.getUint32(i);return i+=4,p};if((r()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");r();const l=r(),d=r(),u=r(),c=r()&4294967295;let h=d/l*1e3,f=s.byteOffset+s.byteLength+u;for(let p=0;p<c;p++){const S=r(),m=S>>>31,b=S<<1>>>1,v=r();if(r(),m!==0)throw new Error("Unsupported multilevel sidx");const g=v/l*1e3;t.push({status:H.NONE,time:{from:h,to:h+g},byte:{from:f,to:f+b-1}}),h+=g,f+=b}return t},Nf=s=>{let e=0,t=!1,i=!1;for(;e<=s.byteLength&&!t;){const r=new DataView(s.buffer,s.byteOffset+e);try{const n=Tn(r);if(i||(i=n.id==="mdat"),e+n.size<=s.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=s.byteLength&&i?new DataView(s.buffer,s.byteOffset,e):null},Df={validateData:Rf,parseInit:()=>null,getIndexRange:()=>{},parseSegments:If,parseFeedableSegmentChunk:Nf};var y;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(y||(y={}));var w;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(w||(w={}));const ia={[y.EBML]:{type:w.Master},[y.EBMLVersion]:{type:w.UnsignedInteger},[y.EBMLReadVersion]:{type:w.UnsignedInteger},[y.EBMLMaxIDLength]:{type:w.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:w.UnsignedInteger},[y.DocType]:{type:w.String},[y.DocTypeVersion]:{type:w.UnsignedInteger},[y.DocTypeReadVersion]:{type:w.UnsignedInteger},[y.Void]:{type:w.Binary},[y.Segment]:{type:w.Master},[y.SeekHead]:{type:w.Master},[y.Seek]:{type:w.Master},[y.SeekID]:{type:w.Binary},[y.SeekPosition]:{type:w.UnsignedInteger},[y.Info]:{type:w.Master},[y.TimestampScale]:{type:w.UnsignedInteger},[y.Duration]:{type:w.Float},[y.Tracks]:{type:w.Master},[y.Chapters]:{type:w.Master},[y.Cluster]:{type:w.Master},[y.Timestamp]:{type:w.UnsignedInteger},[y.SilentTracks]:{type:w.Master},[y.SilentTrackNumber]:{type:w.UnsignedInteger},[y.Position]:{type:w.UnsignedInteger},[y.PrevSize]:{type:w.UnsignedInteger},[y.SimpleBlock]:{type:w.Binary},[y.BlockGroup]:{type:w.Master},[y.EncryptedBlock]:{type:w.Binary},[y.Attachments]:{type:w.Master},[y.Tags]:{type:w.Master},[y.Cues]:{type:w.Master},[y.CuePoint]:{type:w.Master},[y.CueTime]:{type:w.UnsignedInteger},[y.CueTrackPositions]:{type:w.Master},[y.CueTrack]:{type:w.UnsignedInteger},[y.CueClusterPosition]:{type:w.UnsignedInteger},[y.CueRelativePosition]:{type:w.UnsignedInteger},[y.CueDuration]:{type:w.UnsignedInteger},[y.CueBlockNumber]:{type:w.UnsignedInteger},[y.CueCodecState]:{type:w.UnsignedInteger},[y.CueReference]:{type:w.Master},[y.CueRefTime]:{type:w.UnsignedInteger}},En=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Pi(s,t),r=i in ia,n=r?ia[i].type:w.Binary,o=s.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(s.buffer,s.byteOffset+t+1,l-1),u=((o&255>>l)<<(l-1)*8)+Pi(d),c=t+l;let h;return c+u>s.byteLength?h=new DataView(s.buffer,s.byteOffset+c):h=new DataView(s.buffer,s.byteOffset+c,u),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:c,tagSize:c+u,value:h,valueSize:u}},Pi=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint16(0)<<8|s.getUint8(2);case 4:return s.getUint32(0);case 5:return s.getUint32(0)<<8|s.getUint8(4);case 6:return s.getUint32(0)<<16|s.getUint16(4);case 7:return s.getUint32(0)<<32|s.getUint16(4)<<8|s.getUint8(6);case 8:return s.getUint32(0)<<32|s.getUint32(4)}return 0},Re=(s,e)=>{switch(e){case w.SignedInteger:return s.getInt8(0);case w.UnsignedInteger:return Pi(s);case w.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case w.String:return new TextDecoder("ascii").decode(s);case w.UTF8:return new TextDecoder("utf-8").decode(s);case w.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case w.Master:return s;case w.Binary:return s;default:a.assertNever(e)}},Gt=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=En(i);if(!e(r))return;r.type===w.Master&&Gt(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Cf=s=>{if(s.getUint32(0)!==y.EBML)return!1;let e,t,i;const r=En(s);return Gt(r.value,({tag:n,type:o,value:l})=>(n===y.EBMLReadVersion?e=Re(l,o):n===y.DocType?t=Re(l,o):n===y.DocTypeReadVersion&&(i=Re(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},$n=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],Lf=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],xf=s=>{let e,t,i,r,n=!1,o=!1,l=!1,d,u;return Gt(s,({tag:c,type:h,value:f,valueSize:p})=>{if(c===y.SeekID){const S=Re(f,h);u=Pi(S)}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?i=Re(f,h):c===y.Duration?r=Re(f,h):c===y.SeekPosition&&u===y.Cues?d=Re(f,h):n&&o&&$n.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(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:d}},Of=s=>{if(a.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Bf=(s,e)=>{let t=!1,i=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return Gt(s,({tag:l,type:d,value:u})=>{switch(l){case y.Cues:t=!0;break;case y.CuePoint:o&&r(o)&&n.push(o),o={};break;case y.CueTime:o&&(o.time=Re(u,d));break;case y.CueTrackPositions:break;case y.CueClusterPosition:o&&(o.position=Re(u,d));break;default:t&&$n.includes(l)&&(i=!0)}return!(t&&i)}),o&&r(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}}})},Mf=s=>{let e=0,t=!1;try{Gt(s,i=>i.tag===y.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Lf.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Vf={validateData:Cf,parseInit:xf,getIndexRange:Of,parseSegments:Bf,parseFeedableSegmentChunk:Mf};class sa{constructor(e,t,i,r,{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 Je,this.destroyAbortController=new Je,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=a.abortable(this.destroyAbortController.signal,async function*(u){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 Af(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>this.checkEjectedSegments(),S=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:S}))),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(S=>{if(!this.sourceBuffer)return;const m=Math.min(this.bufferLimit,ta(this.sourceBuffer.buffered));this.bufferLimit=m,this.pruneBuffer(S)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(S=>this.error$.next(S))),yield 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;let p=0;for(const S of f)S.time.from-p>0&&this.gaps.push({representation:c.id,from:p,to:S.time.from}),p=S.time.to;a.isNonNullable(c.duration)&&c.duration-p>0&&this.gaps.push({representation:c.id,from:p,to:c.duration}),yield this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,async function*(u){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return;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 this.loadInit(c,"high",!1):h instanceof Promise&&(yield h),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal);const f=this.getCurrentPosition();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=i,i){case pt.MP4:this.containerParser=Df;break;case pt.WEBM:this.containerParser=Vf;break;default:a.assertNever(i)}this.initData=new Map(r.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(r.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 Je,this.abortBuffer()}maintain(e){if(a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=dt(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&c>=r.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&ta(this.sourceBuffer.buffered)>=this.bufferLimit*.8&&(this.pruneBuffer(1/0),r&&r.status!==H.NONE))return;let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(i,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=_e(l,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.allInitsLoaded&&r&&r.status===H.FED&&!l.length&&dt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=_e(i,-1);d&&d.status===H.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}findSegmentStartTime(e){var t,i,r;const n=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}destroy(){var e;this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&this.mediaSource.readyState==="open"&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const r=e.findIndex(({status:d,time:{from:u,to:c}})=>d===H.NONE&&(u>i||u<=i&&c>=i)&&c<=i+this.forwardBufferTarget);if(r===-1)return[];if(t!==he.BYTE_RANGE)return e.slice(r,r+1);const n=e;let o=0;const l=[];for(let d=r;d<n.length&&o<=this.tuning.dash.segmentRequestSize;d++){const u=n[d];if(o+=u.byte.to+1-u.byte.from,u.status===H.NONE||u.status===H.PARTIALLY_EJECTED)l.push(u);else break}return l}async loadSegments(e,t,i="auto"){if(!e.length)return;let r,n,o=e;const{type:l}=t.segmentReference;switch(l){case he.BYTE_RANGE:{r=t.segmentReference.url,n={from:_e(e,0).byte.from,to:_e(e,-1).byte.to};break}case he.TEMPLATE:{const u=_e(e,0);r=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&&(await a.abortable(d,async function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(r,{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:i}).then(()=>this.failedDownloads=0,u=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)})}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(i=dt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,r,n){if(!this.activeSegments.size)return;const o=h=>{this.abortSegment(h.segment)},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 S of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])S.status===H.FED&&S.time.from===h.segment.time.from&&S.time.to===h.segment.time.to&&(S.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===he.BYTE_RANGE,S=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=i&&f.byte.to<i+e.byteLength))continue;if(n.aborted){o(h);continue}const b=p?f.byte.from-i:0,v=p?f.byte.to-i:e.byteLength,g=b<r,P=v<=r;if(f.status===H.DOWNLOADING&&g&&P){f.status=H.DOWNLOADED,this.activeSegments.delete(h);const T=new DataView(e.buffer,e.byteOffset+b,S);this.sourceBufferTaskQueue.append(T,n).then(E=>E&&!n.aborted?l(h):o(h))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(h.loadedBytes=Math.min(S,r-b),h.loadedBytes>h.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+b+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===S?T:this.containerParser.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(f.status=H.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then(_=>{if(n.aborted)o(h);else if(_)h.fedBytes+=E.byteLength,h.fedBytes===S&&l(h);else{if(h.feedingBytes<S)return;o(h)}}))}}}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[r,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=ea(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,async function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(l=>{if(!l)return;const{dataView:d,segments:u}=l,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o}async pruneBuffer(e){const t=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(t)||this.sourceBuffer.updating)return!1;const i=this.segments.get(this.playingRepresentationId);if(!i)return!1;let r=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;r+=h};for(const u of i){if(u.time.to>=t||r>=e)break;u.status===H.FED&&d(u)}if(l=isFinite(n)&&isFinite(o),!l){r=0,n=1/0,o=-1/0;for(const u of i){if(u.time.from<t+this.forwardBufferTarget||r>e)break;u.status===H.FED&&d(u)}}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 i)if(f.status===H.NONE&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.time.to)>=Math.round(h)){n=c,o=h;break}}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&l>=i.time.to){r=void 0;break}l>i.time.from&&l<i.time.to&&(r.from=l),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>=1&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ea(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:n})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:n}=r;if(n!==H.FED&&n!==H.PARTIALLY_EJECTED)continue;const o=Math.floor(r.time.from),l=Math.ceil(r.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.some(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u?r.status=H.PARTIALLY_EJECTED:r.status=H.NONE)}}}var lt;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(lt||(lt={}));class Ff{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!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 Je,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,async function*(r){let n=r;this.requestQuic&&(n=ft(n));const o=yield ht(n,{signal:this.abortAllController.signal}).catch(Dt);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,async function*(r,{rangeMethod:n=this.compatibilityMode?lt.HEADER:lt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,S;let m=r;const b=new Headers;if(o)switch(n){case lt.HEADER:{b.append("Range",`${o.from}-${o.to}`);break}case lt.PARAM:{const $=new URL(m,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),m=$.toString();break}default:a.assertNever(n)}this.requestQuic&&(m=ft(m));let v=this.abortAllController.signal;if(u){const $=new Je;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{$.abort()}catch(C){Dt(C)}})),this.abortAllController.signal.aborted||u.aborted)try{$.abort()}catch(C){Dt(C)}v=$.signal}const g=a.now(),P=yield ht(m,{priority:d,headers:b,signal:v}).catch(Dt),T=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(T-g),!P)return null;if(!P.ok||!P.body)return 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 P.arrayBuffer();return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed($.byteLength,a.now()-T),l==null||l(new DataView($),$.byteLength),$}if(!l&&!c)return P.arrayBuffer();const[_,x]=P.body.tee(),N=_.getReader();c&&((S=this.throughputEstimator)===null||S===void 0||S.trackStream(x));let R=0;const M=new ArrayBuffer(E),I=new Uint8Array(M),A=new DataView(M);let O=!1;const V=$=>{O=!0,Dt($)},q=a.abortable(v,async function*({done:$,value:C}){R===0&&this.lastRequestFirstBytes$.next(a.now()-g),!v.aborted&&($?l==null||l(A,R):C&&(I.set(C,R),R+=C.byteLength,l==null||l(A,R),yield N==null?void 0:N.read().then(q,V)))}.bind(this));return yield N==null?void 0:N.read().then(q,V),O?null:M}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,async function*(r,n,o){if(r.type!==he.BYTE_RANGE)return null;const{from:l,to:d}=r.initRange;let u=l,c=d,h=!1,f,p;r.indexRange&&(f=r.indexRange.from,p=r.indexRange.to,h=d+1===f,h&&(u=Math.min(f,l),c=Math.max(p,d))),u=Math.min(u,0);const S=yield this.fetch(r.url,{range:{from:u,to:c},priority:o,measureThroughput:!1});if(!S)return null;const m=new DataView(S,l-u,d-u+1);if(!n.validateData(m))throw new Error("Invalid media file");const b=n.parseInit(m);let v;if(h&&f!==void 0&&p!==void 0)v=new DataView(S,f-u,p-f+1);else{const P=n.getIndexRange(b);if(P){const T=yield this.fetch(r.url,{range:P,priority:o,measureThroughput:!1});if(!T)return null;v=new DataView(T)}}if(!v)throw new ReferenceError("No way to load representation index");const g=n.parseSegments(v,b);return{dataView:new DataView(S),segments:g}}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,async function*(r,n){if(r.type!==he.TEMPLATE)return null;const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{segments:r.segments.map(u=>({...u,status:H.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=bn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,n;const{type:o}=e;switch(o){case he.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case he.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:a.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Dt=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s},ra=s=>{if(!s.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},ss=(s,e)=>{let t=s;t=t.replaceAll("$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(i)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Uf=(s,e)=>{var t,i,r,n,o,l,d,u,c,h,f,p,S,m,b,v,g,P,T,E,_,x,N,R,M,I,A,O,V,q,$,C,Q,Z,ee,oe,be;const j=new DOMParser().parseFromString(s,"application/xml"),ie={video:[],audio:[],text:[]},ae=j.children[0],ue=ae.getElementsByTagName("Period")[0],qe=ue.children;let ve;const Be=ae.getAttribute("mediaPresentationDuration"),Ye=ue.getAttribute("duration");if(Be)ve=ra(Be);else if(Ye){const ge=ra(Ye);a.isNonNullable(ge)&&(ve=ge)}let yt=0;const it=(i=(t=ae.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],_n=it.includes(ki.WEBM_AS_IN_FFMPEG)||it.includes(ki.WEBM_AS_IN_SPEC)?pt.WEBM:pt.MP4;for(const ge of qe){const qt=ge.getAttribute("mimeType"),An=ge.getAttribute("codecs"),Qs=(r=ge.getAttribute("contentType"))!==null&&r!==void 0?r:qt==null?void 0:qt.split("/")[0],Rn=(o=(n=ge.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],In=ge.querySelectorAll("Representation"),Nn=ge.querySelector("SegmentTemplate");if(Qs!=="text")for(const se of In){const Tt=(l=se.getAttribute("mimeType"))!==null&&l!==void 0?l:qt,Ws=(u=(d=se.getAttribute("codecs"))!==null&&d!==void 0?d:An)!==null&&u!==void 0?u:"",Yt=(h=(c=se.getAttribute("contentType"))!==null&&c!==void 0?c:Tt==null?void 0:Tt.split("/")[0])!==null&&h!==void 0?h:Qs,Dn=(p=(f=ge.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&p!==void 0?p:[],Cn=parseInt((S=se.getAttribute("width"))!==null&&S!==void 0?S:"",10),Js=parseInt((m=se.getAttribute("height"))!==null&&m!==void 0?m:"",10),Ks=parseInt((b=se.getAttribute("bandwidth"))!==null&&b!==void 0?b:"",10)/1e3,Xs=(v=se.getAttribute("frameRate"))!==null&&v!==void 0?v:"",Ln=(g=se.getAttribute("quality"))!==null&&g!==void 0?g:void 0,xn=Xs?Ys(Xs):void 0,On=(P=se.getAttribute("id"))!==null&&P!==void 0?P:(yt++).toString(10),Bn=Yt==="video"?`${Js}p`:Yt==="audio"?`${Ks}Kbps`:Ws,Mn=`${On}@${Bn}`,Vn=(_=(E=(T=se.querySelector("BaseURL"))===null||T===void 0?void 0:T.textContent)===null||E===void 0?void 0:E.trim())!==null&&_!==void 0?_:"",Zs=new URL(Vn,e).toString(),Fn=[...it,...Rn,...Dn];let Ii;const Un=se.querySelector("SegmentBase"),ze=(x=se.querySelector("SegmentTemplate"))!==null&&x!==void 0?x:Nn;if(Un){const Et=(R=(N=se.querySelector("SegmentBase Initialization"))===null||N===void 0?void 0:N.getAttribute("range"))!==null&&R!==void 0?R:"",[$t,Di]=Et.split("-").map(Qe=>parseInt(Qe,10)),kt={from:$t,to:Di},Pt=(M=se.querySelector("SegmentBase"))===null||M===void 0?void 0:M.getAttribute("indexRange"),[Ci,zt]=Pt?Pt.split("-").map(Qe=>parseInt(Qe,10)):[],wt=Pt?{from:Ci,to:zt}:void 0;Ii={type:he.BYTE_RANGE,url:Zs,initRange:kt,indexRange:wt}}else if(ze){const Et={representationId:(I=se.getAttribute("id"))!==null&&I!==void 0?I:void 0,bandwidth:(A=se.getAttribute("bandwidth"))!==null&&A!==void 0?A:void 0},$t=parseInt((O=ze.getAttribute("timescale"))!==null&&O!==void 0?O:"",10),Di=(V=ze.getAttribute("initialization"))!==null&&V!==void 0?V:"",kt=ze.getAttribute("media"),Pt=($=parseInt((q=ze.getAttribute("startNumber"))!==null&&q!==void 0?q:"",10))!==null&&$!==void 0?$:1,Ci=ss(Di,Et);if(!kt)throw new ReferenceError("No media attribute in SegmentTemplate");const zt=(C=ze.querySelectorAll("SegmentTimeline S"))!==null&&C!==void 0?C:[],wt=[];if(zt.length){let Qe=Pt,We=0;for(const _t of zt){const st=parseInt((Q=_t.getAttribute("d"))!==null&&Q!==void 0?Q:"",10)*1e3,At=parseInt((Z=_t.getAttribute("r"))!==null&&Z!==void 0?Z:"",10)||0,Rt=(oe=parseInt((ee=_t.getAttribute("t"))!==null&&ee!==void 0?ee:"",10))!==null&&oe!==void 0?oe:void 0;for(let er=0;er<At+1;er++){const jn=ss(kt,{...Et,segmentNumber:Qe.toString(10),segmentTime:Rt.toString(10)}),Hn=Rt?Rt/$t:We;We+=st/$t;const Gn=We;Qe++,wt.push({time:{from:Hn,to:Gn},url:jn})}}}else if(a.isNonNullable(ve)){const We=parseInt((be=ze.getAttribute("duration"))!==null&&be!==void 0?be:"",10)/$t*1e3,_t=Math.ceil(ve/We);let st=0;for(let At=1;At<_t;At++){const Rt=ss(kt,{...Et,segmentNumber:At.toString(10),segmentTime:st.toString(10)});wt.push({time:{from:st,to:st+We},url:Rt}),st+=We}}Ii={type:he.TEMPLATE,baseUrl:Zs,initUrl:Ci,segments:wt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Yt||!Tt)continue;const Ni={video:ce.VIDEO,audio:ce.AUDIO,text:ce.TEXT}[Yt];Ni&&ie[Ni].push({id:Mn,kind:Ni,segmentReference:Ii,profiles:Fn,duration:ve,bitrate:Ks,mime:Tt,codecs:Ws,width:Cn,height:Js,fps:xn,quality:Ln})}}return{duration:ve,container:_n,representations:ie}},jf=["timeupdate","progress","play","seeked","stalled"];var de;(function(s){s.NONE="none",s.MANIFEST_LOADED="manifest_loaded",s.REPRESENTATION_SELECTED="representation_selected"})(de||(de={}));let Hf=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.state$=new J(de.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 Je,this.initManifest=a.abortable(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(de.MANIFEST_LOADED);const r=yield this.fetcher.fetchManifest(i).catch(l=>this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l}));if(!r)return null;let n;try{n=Uf(r!=null?r:"",i)}catch(l){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return null;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}"`)))};return this.manifest={...n,representations:Ut(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))},this.manifest.representations.video.length?this.state$.setState(de.MANIFEST_LOADED):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"}),this.manifest}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,async function*(t,i){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.state$.startTransitionTo(de.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new sa(ce.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(i)&&(this.audioBufferManager=new sa(ce.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),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 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(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(de.REPRESENTATION_SELECTED),a.assertNonNullable(this.element),this.subscription.add(a.merge(...jf.map(l=>a.fromEvent(this.element,l)),a.fromEvent(window,"online")).subscribe(this.tick,l=>{this.error$.next({id:"DashVKPlayer",category:a.ErrorCategory.WTF,message:"Internal logic error",thrown:l})})),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&&Zr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.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 Ff({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}async switchRepresentation(e,t){const i={[ce.VIDEO]:this.videoBufferManager,[ce.AUDIO]:this.audioBufferManager,[ce.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,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((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Zr(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(de.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const i of this.bufferManagers)for(const r of i.gaps)i.playingRepresentation$.getValue()===r.representation&&r.from<=e&&r.to>e&&(this.element.duration*1e3-r.to<this.tuning.endGapTolerance?t.push(1/0):t.push(r.to));if(t.length){const i=Math.max(...t);i===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=i/1e3}}};var K;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));const Gf=({id:s,width:e,height:t,bitrate:i,fps:r,quality:n})=>{var o;const l=(o=n?Ht(n):void 0)!==null&&o!==void 0?o:et({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:r}},qf=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=_e(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:_e(s,-1)};class Yf{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(K.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Pe,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new ef,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===D.Requested&&(r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&t!==K.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),i===exports.PlaybackState.STOPPED){t!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.player.stop(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(K.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(t===K.STOPPED){this.videoState.startTransitionTo(K.READY),this.prepare();return}switch(t){case K.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(K.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case K.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}}},this.params=e,this.video=xe(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Hf({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=Oe(this.video),r=d=>{e.error$.next({id:"DashVKProvider",category:a.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:d})},n=(d,u)=>this.subscription.add(d.subscribe(u,r));n(i.timeUpdate$,e.position$),n(i.durationChange$,e.duration$),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(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(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(Le(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(He(this.video,t.playbackRate,i.playbackRateState$,r)),n(Ei(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(a.filter(({to:d})=>d===de.REPRESENTATION_SELECTED)).subscribe(()=>{this.videoState.setState(K.READY)}));const o=d=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:d});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(()=>{var d,u,c,h,f,p,S,m;const b=this.player.state$.getState(),v=this.player.state$.getTransition();if(b===de.NONE||!this.videoTracks.length)return;const g=b===de.MANIFEST_LOADED&&!v,P=b===de.REPRESENTATION_SELECTED&&!v,T=t.autoVideoTrackSwitching.getState(),E=t.videoTrack.getState(),_=(d=this.videoTracks.find(({track:{id:V}})=>V===E))===null||d===void 0?void 0:d.track,x=e.currentVideoTrack$.getValue(),N=dt(this.video.buffered,this.video.currentTime*1e3),R=T?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,M=Math.min(N/Math.min(R,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),I=Math.max(_&&!T&&(c=(u=this.audioRepresentations.get(_.id))===null||u===void 0?void 0:u.bitrate)!==null&&c!==void 0?c:0,x&&(f=(h=this.audioRepresentations.get(x.id))===null||h===void 0?void 0:h.bitrate)!==null&&f!==void 0?f:0),A=jt(this.videoTracks.map(({track:V})=>V),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:M,current:x,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),O=T?A!=null?A:_:_!=null?_:A;if(t.autoVideoTrackSwitching.getTransition()&&(t.autoVideoTrackSwitching.setState(T),this.player.setBufferTarget(R)),g){const V=O&&((p=this.videoTracks.find(({track:q})=>q===O))===null||p===void 0?void 0:p.representation);a.assertNonNullable(V),this.player.initRepresentations(V.id,(S=this.audioRepresentations.get(V.id))===null||S===void 0?void 0:S.id)}else if(P){const V=O&&((m=this.videoTracks.find(({track:q})=>q===O))===null||m===void 0?void 0:m.representation);if(V){const q=this.audioRepresentations.get(V.id);this.player.switchRepresentation(ce.VIDEO,V.id).catch(o),q&&this.player.switchRepresentation(ce.AUDIO,q.id).catch(o)}}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(d=>{var u;return d&&((u=this.videoTracks.find(({representation:{id:c}})=>c===d))===null||u===void 0?void 0:u.track)})).subscribe(e.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,t,e);const l=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}async prepare(){const e=await this.player.initManifest(this.video,this.params.source.url);if(!e)return;this.videoTracks=[];const t=Array.from(e.representations.audio).sort((r,n)=>n.bitrate-r.bitrate),i=Array.from(e.representations.video).sort((r,n)=>n.bitrate-r.bitrate);for(const r of i){const n=Gf(r);if(n){this.videoTracks.push({track:n,representation:r});const o=qf(t,i,r);o&&this.audioRepresentations.set(r.id,o)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:r})=>r))}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const zf=5e3,we={};var G;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(G||(G={}));const ai=(s,e)=>new a.Observable(t=>{const i=(r,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class Qf{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(G.INITIALIZING),this.textTracksManager=new Pe,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==G.INITIALIZING)switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===D.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case G.STOPPED:break;case G.READY:case G.PLAYING:case G.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case G.PLAYING:break;case G.STOPPED:this.prepare();break;case G.READY:case G.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case G.PAUSED:break;case G.STOPPED:this.prepare();break;case G.READY:this.videoState.setState(G.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case G.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(i)}},this.video=xe(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(ne(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),zf);import("hls.js").then(r=>{e||(we.Hls=r.default,we.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){a.assertNonNullable(we.Hls,"hls.js not loaded"),this.hls=new we.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(G.STOPPED)}subscribe(){a.assertNonNullable(we.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},r=Oe(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,i));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadStart$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),this.subscription.add(tt(this.video,e.isLooped,i)),this.subscription.add(Le(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(He(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(ai(this.hls,we.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(r.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===G.READY&&this.videoState.setState(G.READY),this.videoState.getState()===G.PLAYING&&this.playIfAllowed()},i)),n(ai(this.hls,we.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const S=h.name||h.height.toString(10),{width:m,height:b}=h,v=(p=Ht((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:et({width:m,height:b});if(!v)return c;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,P={id:S.toString(),quality:v,bitrate:h.bitrate/1e3,size:{width:m,height:b},fps:g};return this.trackLevels.set(S,{track:P,level:h}),c.push(P),c},[]))),t.availableVideoTracks$),n(ai(this.hls,we.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>ne(u))),t.hostname$),this.subscription.add($e(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=ai(this.hls,we.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add($e(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,S=this.hls.levels[p];!S||h.bitrate>S.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:i})),n(r.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,i))}prepare(){this.videoState.startTransitionTo(G.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(G.PLAYING),await Ge(this.video)||(this.videoState.setState(G.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(G.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.setAttribute("src",""),this.video.load(),this.videoState.setState(G.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const aa="X-Playback-Duration";var na=async s=>{const e=await ht(s,{method:"HEAD"});return e.headers.has(aa)?parseInt(e.headers.get(aa),10):void 0};const Wf=s=>{let e=null;if(s.QUALITY&&(e=Ht(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=et({width:t,height:i})}return e!=null?e:null},kn=async(s,e=s)=>{var t;const n=(await(await ht(s)).text()).split(`
|
|
8
8
|
`),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=Ut(u[1].split(",").map(v=>v.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Wf(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 S=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let m;if(c.RESOLUTION){const[v,g]=c.RESOLUTION.split("x").map(P=>parseInt(P,10));v&&g&&(m={width:v,height:g})}const b=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:b,bandwidth:p,size:m,fps:S})}return o};var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(Y||(Y={}));class Jf{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new J(Y.STOPPED),this.textTracksManager=new Pe,this.manifests$=new a.ValueSubject([]),this.liveOffset=new qs,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{const r=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){r!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.setAttribute("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(r===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===D.None&&this.params.desiredState.seekState.setState({state:D.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===D.Requested){this.videoState.startTransitionTo(Y.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case Y.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(r)}},this.params=e,this.video=xe(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),kn(ct(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([i,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ne(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:i,videoTrack:r}=this.params.desiredState,n=i.getState(),o=r.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&r.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},r=Oe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(r.ended$,e.endedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(He(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.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()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.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(ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===Y.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===D.Requested&&this.seek(l.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},i)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),i)),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$,i));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,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=ct(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),na(t).then(i=>{var r;if(!a.isNullable(i))this.maxSeekBackTime$.next(i);else{const n=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(a.isNullable(n)||!isFinite(n))try{ht(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();na(u).then(c=>{a.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){Ge(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,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var W;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(W||(W={}));class Kf{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(W.STOPPED),this.textTracksManager=new Pe,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r===exports.PlaybackState.STOPPED){i!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.setAttribute("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(i===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===D.None&&this.params.desiredState.seekState.setState({state:D.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===D.Requested&&this.seek(u.position),i){case W.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:r===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:r===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(i)}},this.params=e,this.video=xe(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.hostname$.next(ne(this.params.source.url)),kn(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,n=i.getState(),o=r.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&r.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},r=Oe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));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.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(He(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.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()},i).add(r.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(ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===W.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===D.Requested&&this.seek(l.position)},i))),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$,i));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,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Ge(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 X;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(X||(X={}));class Xf{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(X.STOPPED),this.trackUrls={},this.textTracksManager=new Pe,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.video.setAttribute("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}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(t===X.STOPPED){this.videoState.startTransitionTo(X.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===D.None&&this.params.desiredState.seekState.setState({state:D.Requested,position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&l.state===D.Requested&&this.seek(l.position),t){case X.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed());return;case X.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case X.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.video=xe(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,i],r)=>{const n=r.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.isLive$.next(!1),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},r=Oe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));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.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(He(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===X.READY&&this.videoState.setState(X.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()===X.PLAYING&&this.playIfAllowed()},i)),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,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,t;const i=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState();a.assertNonNullable(i,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[i];a.assertNonNullable(r,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(r=ft(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(ne(r))}playIfAllowed(){Ge(this.video).then(e=>{e||(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const oa=["stun:videostun.mycdn.me:80"],Zf=1e3,ep=3,rs=()=>null;class tp{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=rs,this.externalStopCallback=rs,this.externalErrorCallback=rs,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:oa}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:a.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Zf)}normalizeOptions(e={}){const t={stunServerList:oa,maxRetryNumber:ep,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var z;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(z||(z={}));class ip{constructor(e){this.videoState=new J(z.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==z.STOPPED&&(this.videoState.startTransitionTo(z.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(z.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===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case z.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):(r==null?void 0:r.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=xe(e.container),this.liveStreamClient=new tp(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.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,i=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 r=Oe(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,i));n(r.timeUpdate$,e.liveTime$),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$),this.subscription.add(r.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===z.READY&&this.videoState.setState(z.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Le(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case z.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case z.READY:break;case z.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case z.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},i)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(z.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(){Ge(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class la{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 sp=()=>{var s,e;const t=window.navigator;return t.userAgentData?((e=(s=t.userAgentData)===null||s===void 0?void 0:s.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},as,ns,os,ls,us,ds,ni,cs,oi,hs,li,fs,ui,ps,di,ms;const Pn=sp(),Ve=document.createElement("video"),Me={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((ns=(as=window.SourceBuffer)===null||as===void 0?void 0:as.prototype)===null||ns===void 0?void 0:ns.appendBuffer)),hls:Boolean(((os=Ve.canPlayType)===null||os===void 0?void 0:os.call(Ve,"application/x-mpegurl"))||((ls=Ve.canPlayType)===null||ls===void 0?void 0:ls.call(Ve,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Te={mp4:Boolean((us=Ve.canPlayType)===null||us===void 0?void 0:us.call(Ve,"video/mp4")),webm:Boolean((ds=Ve.canPlayType)===null||ds===void 0?void 0:ds.call(Ve,"video/webm"))},Fe={h264:Boolean((cs=(ni=window.MediaSource)===null||ni===void 0?void 0:ni.isTypeSupported)===null||cs===void 0?void 0:cs.call(ni,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((hs=(oi=window.MediaSource)===null||oi===void 0?void 0:oi.isTypeSupported)===null||hs===void 0?void 0:hs.call(oi,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((fs=(li=window.MediaSource)===null||li===void 0?void 0:li.isTypeSupported)===null||fs===void 0?void 0:fs.call(li,'video/webm; codecs="vp9"')),aac:Boolean((ps=(ui=window.MediaSource)===null||ui===void 0?void 0:ui.isTypeSupported)===null||ps===void 0?void 0:ps.call(ui,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((ms=(di=window.MediaSource)===null||di===void 0?void 0:di.isTypeSupported)===null||ms===void 0?void 0:ms.call(di,'audio/webm; codecs="opus"'))},Ct=(Fe.h264||Fe.h265)&&Fe.aac,Ri=Me.hls&&Te.mp4,rp=Boolean(window.WebSocket),ap=()=>Object.keys(Fe).filter(s=>Fe[s]),np=(s,e=!1)=>s.filter(t=>{switch(t){case exports.VideoFormat.DASH:return Me.mse&&Te.mp4&&Ct;case exports.VideoFormat.DASH_SEP:return Me.mse&&Te.mp4&&Ct;case exports.VideoFormat.DASH_WEBM:return Me.mse&&Te.webm&&Fe.vp9&&Fe.opus;case exports.VideoFormat.DASH_LIVE:return Me.mse&&Te.mp4&&Ct;case exports.VideoFormat.DASH_ONDEMAND:return Me.mse&&Te.mp4&&Ct;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return Ri||e&&Me.mse&&Te.mp4&&Ct;case exports.VideoFormat.MPEG:return Te.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Me.webrtc&&rp&&Fe.h264&&(Te.mp4||Te.webm);default:return a.assertNever(t)}}),op=()=>Pn?[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]:Ri?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.DASH_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],lp=()=>Pn?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE]:Ri?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.HLS_LIVE],ua=s=>s?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var up=s=>new a.Observable(e=>{const t=new a.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),r=s.desiredPlaybackState$.stateChangeEnded$,n=s.providerChanged$,o=new a.Subject;let l=0,d="unknown";return t.add(i.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(l),d="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),s.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const da={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},dp={cacheDuration:12e4},cp={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},hp={maxPausedTime:3e4},fp={maxPausedTime:3e4};class pp{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([]),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=np([...lp(),...op()],this.params.tuning.useHlsJs).filter(o=>a.isNonNullable(e.sources[o])),{formatsToAvoid:i}=this.params.tuning,r=i.length?[...t.filter(o=>!i.includes(o)),...t.filter(o=>i.includes(o))]:t;this.screenFormatsIterator=new la(r);const n=[...ua(!0),...ua(!1)];this.chromecastFormatsIterator=new la(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 i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;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,i=this.params.desiredState.seekState.getState(),r=i.state!==D.None;this.params.desiredState.seekState.setState({state:D.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case le.SCREEN:return this.createScreenProvider(t);case le.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,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 Pf({...o,source:l,config:dp})}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 rf({...o,source:l,format:e,config:fp}):new Yf({...o,source:l})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),Ri||!this.params.tuning.useHlsJs?new Kf({...o,source:l}):new Qf({...o,source:l})}case exports.VideoFormat.HLS_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Jf({...o,source:l,config:hp})}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Xf({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new yf({...o,source:l,config:cp})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new ip({container:i,source:l,desiredState:r,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:i,desiredState:r,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new wh({connection:l,meta:n,container:i,source:t,format:e,desiredState:r,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?le.CHROMECAST:le.SCREEN}chooseFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case le.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.next();case le.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case le.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case le.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const n=new URL(r);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Ut(Object.entries(e).map(([r,n])=>[r,i(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,i=0;return e.add(a.merge(this.providerOutput.error$,up({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:da.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(a.filter(({type:r})=>r!==void 0))}).pipe(a.map(r=>({id:`ProviderHangup:${r}`,category:a.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{if(this.current$.getValue().destination===le.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===a.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<da.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(i++,this.reinitProvider()):this.switchToNextProvider()}})),e}}const ca=(s,e,t)=>t*e+(1-t)*s;class ha{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ee(`raw_${i}`),this.smoothedSeries$=new Ee(`smoothed_${i}`),this.reportedSeries$=new Ee(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let d=0;d<this.pastMeasures.length;d++)this.pastMeasures[d]!==void 0&&(t+=(this.pastMeasures[d]-this.smoothed)**2,i++);t/=i;const r=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*r,o=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.slow=ca(this.slow,e,this.params.emaAlphaSlow),this.fast=ca(this.fast,e,this.params.emaAlphaFast);const l=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=l(this.slow,this.fast),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))}}var fe;(function(s){s[s.LOCAL_STORAGE=0]="LOCAL_STORAGE",s[s.SESSION_STORAGE=1]="SESSION_STORAGE",s[s.RUNTIME=2]="RUNTIME"})(fe||(fe={}));const wn=new Map;let Ke=fe.RUNTIME;const Ss=`vk-videoplayer-dummy-key-${Math.random()}`,mp=()=>{try{localStorage.setItem(Ss,"test"),localStorage.removeItem(Ss),Ke=fe.LOCAL_STORAGE}catch(s){if(s instanceof DOMException||s instanceof TypeError)try{sessionStorage.getItem(Ss),Ke=fe.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)Ke=fe.RUNTIME;else throw e}else throw s}};mp();const Sp=s=>{var e,t;switch(Ke){case fe.LOCAL_STORAGE:return(e=localStorage.getItem(s))!==null&&e!==void 0?e:void 0;case fe.SESSION_STORAGE:return(t=sessionStorage.getItem(s))!==null&&t!==void 0?t:void 0;case fe.RUNTIME:return wn.get(s);default:a.assertNever(Ke)}},fa=(s,e)=>{switch(Ke){case fe.LOCAL_STORAGE:try{localStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case fe.SESSION_STORAGE:try{sessionStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case fe.RUNTIME:return void wn.set(s,e);default:a.assertNever(Ke)}},bp=5e3,pa="one_video_throughput",ma="one_video_rtt",Ne=window.navigator.connection,Sa=()=>{const s=Ne==null?void 0:Ne.downlink;if(a.isNonNullable(s)&&s!==10)return s*1e3},ba=()=>{const s=Ne==null?void 0:Ne.rtt;if(a.isNonNullable(s)&&s!==3e3)return s},va=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class Ot{constructor(e){var t,i;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Ot.load(pa)||(e.useBrowserEstimation?Sa():void 0)||bp,n=(i=(t=Ot.load(ma))!==null&&t!==void 0?t:e.useBrowserEstimation?ba():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new a.ValueSubject(r),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(va(r,n,e.rttPenaltyRequestSize)),this.throughput=new ha({initial:r,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"throughput"}),this.rtt=new ha({initial:n,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"rtt"}),e.useBrowserEstimation){const o=()=>{const d=Sa();d&&this.throughput.next(d);const u=ba();a.isNonNullable(u)&&this.rtt.next(u)};Ne&&"onchange"in Ne&&this.subscription.add(a.fromEvent(Ne,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{fa(pa,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{fa(ma,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})=>va(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,i=a.now();const r=new a.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,i=a.now()}));break;case 1:case 0:r.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=a.now()}));break}r.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const r=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=async({done:u,value:c})=>{u?(this.addRawSpeed(i,a.now()-r,1),this.concurrentDownloads.delete(e)):c&&(i+=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()),await(t==null?void 0:t.read().then(d,l)))};this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,i=1){if(Ot.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=Sp(e);if(a.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const ga={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},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,webrtc:{connectionRetryMaxNumber:3}},vp=s=>{const e={};for(const t of Object.keys(ga)){const i=ga[t],r=s[t];Array.isArray(i)&&Array.isArray(r)?e[t]=r:typeof i=="object"&&typeof r=="object"?e[t]={...i,...r}:e[t]=r!=null?r:i}return e};var gp=({seekState:s,position$:e})=>a.merge(s.stateChangeEnded$.pipe(a.map(({to:t})=>{var i;return t.state===D.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>s.getState().state===D.None))),yp=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return a.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};const ya=({playbackState:s,seekState:e,playbackAbort$:t,looped$:i,position$:r})=>new a.Observable(n=>{let o;const l=s.transitionEnded$.pipe(a.filter(p=>(p.from===exports.PlaybackState.PAUSED||p.from===exports.PlaybackState.STOPPED)&&p.to===exports.PlaybackState.PLAYING)),d=s.stateChangeEnded$.pipe(a.filter(p=>p.from===exports.PlaybackState.PLAYING&&p.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(a.filter(({to:p})=>{var S,m;return p.state===D.Requested&&((m=(S=s.getTransition())===null||S===void 0?void 0:S.from)!==null&&m!==void 0?m:s.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(a.filter(({from:p,to:S})=>{var m,b;return p.state===D.Applying&&S.state===D.None&&((b=(m=s.getTransition())===null||m===void 0?void 0:m.from)!==null&&b!==void 0?b:s.getState())===exports.PlaybackState.PLAYING})),h=a.merge(l,c).pipe(a.map(()=>r.getValue()),a.filter(a.isNonNullable)),f=a.merge(a.merge(d,u,t),i).pipe(a.map(()=>r.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 S={from:o,to:p};o=void 0,n.next(S)}))});class Tp{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:D.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({}),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:Kh},this.initLogs(),this.tuning=vp(e),this.chromecastInitializer=new to({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ot(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const n=Reflect.get(t,i,r);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 S=typeof p;return["number","string","boolean"].includes(S)?p:p===null?null:`<${S}>`})),u=`Player.${String(i)}`,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,i,r;return this.config=e,this.domContainer=yp(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new pp({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],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.initDebugTelemetry(),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()}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:D.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){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:this.desiredState.volume.getState().muted}),this}setMuted(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(e):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:e}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(r=>r.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(i=>i.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){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(),i=t.state===D.None?void 0:t.position;return a.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}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.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():(this.initedAt=a.now(),this.events.inited$.next());break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const d=this.desiredState.seekState.getState();d.state===D.Requested?this.desiredState.seekState.setState({...d,state:D.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===D.Applying&&(this.desiredState.seekState.setState({state:D.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)=>yi(u)?1:yi(c)?-1:pi(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.currentVideoTrack$.subscribe(d=>{this.info.currentQuality$.next(d==null?void 0:d.quality),this.info.videoBitrate$.next(d==null?void 0:d.bitrate);const u=e.providerOutput.element$.getValue();u&&this.info.intrinsicVideoSize$.next({width:u.videoWidth,height:u.videoHeight})})).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(gp({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 i=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:d})=>d===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>i.next(!1)));let r=0;const n=a.merge(e.providerOutput.isBuffering$,t,i).pipe(a.map(()=>{const d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return d&&!u}),a.filterChanged());this.subscription.add(n.subscribe(d=>{d?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),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(ya({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(ya({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}})}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((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(i=>i.length>0),a.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=jt(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),Jh(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Wh(i)),this.providerContainer.current$.subscribe(({type:i})=>ii("provider",i)),t.duration$.subscribe(i=>ii("duration",i)),t.availableVideoTracks$.pipe(a.filter(i=>!!i.length),a.once()).subscribe(i=>ii("tracks",i)),this.events.fatalError$.subscribe(new Ee("fatalError")),this.events.managedError$.subscribe(new Ee("managedError")),t.position$.subscribe(new Ee("position")),t.currentVideoTrack$.pipe(a.map(i=>i==null?void 0:i.quality)).subscribe(new Ee("quality")),this.info.currentBuffer$.subscribe(new Ee("buffer")),t.isBuffering$.subscribe(new Ee("isBuffering"))].forEach(i=>this.subscription.add(i)),ii("codecs",ap())}}const Ep=`${Zn}@${Xn}`;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=Tp;exports.SDK_VERSION=Ep;
|