rx-player 4.3.0-dev.2024112900 → 4.3.0-dev.2025012900
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/CHANGELOG.md +30 -8
- package/VERSION +1 -1
- package/dist/commonjs/__GENERATED_CODE/embedded_dash_wasm.d.ts +1 -1
- package/dist/commonjs/__GENERATED_CODE/embedded_dash_wasm.d.ts.map +1 -1
- package/dist/commonjs/__GENERATED_CODE/embedded_worker.d.ts.map +1 -1
- package/dist/commonjs/__GENERATED_CODE/embedded_worker.js +1 -1
- package/dist/commonjs/compat/browser_compatibility_types.d.ts +7 -2
- package/dist/commonjs/compat/browser_compatibility_types.d.ts.map +1 -1
- package/dist/commonjs/compat/browser_compatibility_types.js +0 -1
- package/dist/commonjs/compat/browser_detection.js +1 -1
- package/dist/commonjs/compat/event_listeners.d.ts.map +1 -1
- package/dist/commonjs/compat/event_listeners.js +2 -4
- package/dist/commonjs/compat/has_mse_in_worker.d.ts.map +1 -1
- package/dist/commonjs/core/cmcd/cmcd_data_builder.d.ts.map +1 -1
- package/dist/commonjs/core/cmcd/cmcd_data_builder.js +1 -2
- package/dist/commonjs/core/main/worker/send_message.d.ts.map +1 -1
- package/dist/commonjs/core/main/worker/send_message.js +0 -1
- package/dist/commonjs/core/main/worker/worker_main.js +1 -1
- package/dist/commonjs/core/stream/adaptation/adaptation_stream.d.ts.map +1 -1
- package/dist/commonjs/core/stream/adaptation/adaptation_stream.js +4 -8
- package/dist/commonjs/core/stream/period/period_stream.js +1 -3
- package/dist/commonjs/core/stream/period/utils/get_adaptation_switch_strategy.js +1 -2
- package/dist/commonjs/experimental/tools/mediaCapabilitiesProber/api/index.d.ts.map +1 -1
- package/dist/commonjs/main_thread/api/public_api.js +4 -4
- package/dist/commonjs/main_thread/decrypt/clear_on_stop.d.ts.map +1 -1
- package/dist/commonjs/main_thread/decrypt/clear_on_stop.js +60 -14
- package/dist/commonjs/main_thread/decrypt/content_decryptor.d.ts.map +1 -1
- package/dist/commonjs/main_thread/decrypt/content_decryptor.js +21 -9
- package/dist/commonjs/main_thread/decrypt/dispose_decryption_resources.d.ts.map +1 -1
- package/dist/commonjs/main_thread/decrypt/dispose_decryption_resources.js +2 -18
- package/dist/commonjs/main_thread/decrypt/find_key_system.d.ts.map +1 -1
- package/dist/commonjs/main_thread/decrypt/find_key_system.js +134 -68
- package/dist/commonjs/main_thread/decrypt/get_key_system_configuration.js +2 -2
- package/dist/commonjs/main_thread/decrypt/get_media_keys.js +5 -3
- package/dist/commonjs/main_thread/decrypt/init_media_keys.d.ts.map +1 -1
- package/dist/commonjs/main_thread/decrypt/init_media_keys.js +2 -2
- package/dist/{es2017/main_thread/decrypt/utils/media_keys_infos_store.d.ts → commonjs/main_thread/decrypt/utils/media_keys_attacher.d.ts} +31 -9
- package/dist/commonjs/main_thread/decrypt/utils/media_keys_attacher.d.ts.map +1 -0
- package/dist/commonjs/main_thread/decrypt/utils/media_keys_attacher.js +282 -0
- package/dist/commonjs/main_thread/init/utils/rebuffering_controller.d.ts.map +1 -1
- package/dist/commonjs/main_thread/init/utils/rebuffering_controller.js +20 -9
- package/dist/commonjs/main_thread/text_displayer/html/text_track_cues_store.js +1 -1
- package/dist/commonjs/main_thread/tracks_store/track_dispatcher.d.ts.map +1 -1
- package/dist/commonjs/main_thread/tracks_store/track_dispatcher.js +3 -4
- package/dist/commonjs/main_thread/tracks_store/tracks_store.d.ts.map +1 -1
- package/dist/commonjs/main_thread/tracks_store/tracks_store.js +1 -1
- package/dist/commonjs/manifest/classes/representation.d.ts +15 -1
- package/dist/commonjs/manifest/classes/representation.d.ts.map +1 -1
- package/dist/commonjs/manifest/classes/representation.js +17 -0
- package/dist/commonjs/manifest/utils.d.ts +15 -0
- package/dist/commonjs/manifest/utils.d.ts.map +1 -1
- package/dist/commonjs/manifest/utils.js +28 -5
- package/dist/commonjs/parsers/manifest/dash/common/parse_representations.js +2 -2
- package/dist/commonjs/playback_observer/media_element_playback_observer.js +1 -1
- package/dist/commonjs/public_types.d.ts +44 -0
- package/dist/commonjs/public_types.d.ts.map +1 -1
- package/dist/commonjs/utils/flat_map.d.ts +2 -2
- package/dist/commonjs/utils/flat_map.js +2 -2
- package/dist/commonjs/utils/url-utils.d.ts.map +1 -1
- package/dist/commonjs/utils/url-utils.js +11 -10
- package/dist/commonjs/utils/xml-parser.d.ts.map +1 -1
- package/dist/commonjs/utils/xml-parser.js +10 -8
- package/dist/es2017/__GENERATED_CODE/embedded_dash_wasm.d.ts +1 -1
- package/dist/es2017/__GENERATED_CODE/embedded_dash_wasm.d.ts.map +1 -1
- package/dist/es2017/__GENERATED_CODE/embedded_worker.d.ts.map +1 -1
- package/dist/es2017/__GENERATED_CODE/embedded_worker.js +1 -1
- package/dist/es2017/compat/browser_compatibility_types.d.ts +7 -2
- package/dist/es2017/compat/browser_compatibility_types.d.ts.map +1 -1
- package/dist/es2017/compat/browser_compatibility_types.js +0 -1
- package/dist/es2017/compat/browser_detection.js +1 -1
- package/dist/es2017/compat/event_listeners.d.ts.map +1 -1
- package/dist/es2017/compat/event_listeners.js +2 -4
- package/dist/es2017/compat/has_mse_in_worker.d.ts.map +1 -1
- package/dist/es2017/core/cmcd/cmcd_data_builder.d.ts.map +1 -1
- package/dist/es2017/core/cmcd/cmcd_data_builder.js +1 -2
- package/dist/es2017/core/main/worker/send_message.d.ts.map +1 -1
- package/dist/es2017/core/main/worker/send_message.js +0 -1
- package/dist/es2017/core/main/worker/worker_main.js +1 -1
- package/dist/es2017/core/stream/adaptation/adaptation_stream.d.ts.map +1 -1
- package/dist/es2017/core/stream/adaptation/adaptation_stream.js +4 -6
- package/dist/es2017/core/stream/period/period_stream.js +1 -3
- package/dist/es2017/core/stream/period/utils/get_adaptation_switch_strategy.js +1 -2
- package/dist/es2017/experimental/tools/mediaCapabilitiesProber/api/index.d.ts.map +1 -1
- package/dist/es2017/main_thread/api/public_api.js +4 -4
- package/dist/es2017/main_thread/decrypt/clear_on_stop.d.ts.map +1 -1
- package/dist/es2017/main_thread/decrypt/clear_on_stop.js +3 -3
- package/dist/es2017/main_thread/decrypt/content_decryptor.d.ts.map +1 -1
- package/dist/es2017/main_thread/decrypt/content_decryptor.js +21 -9
- package/dist/es2017/main_thread/decrypt/dispose_decryption_resources.d.ts.map +1 -1
- package/dist/es2017/main_thread/decrypt/dispose_decryption_resources.js +2 -12
- package/dist/es2017/main_thread/decrypt/find_key_system.d.ts.map +1 -1
- package/dist/es2017/main_thread/decrypt/find_key_system.js +102 -56
- package/dist/es2017/main_thread/decrypt/get_key_system_configuration.js +2 -2
- package/dist/es2017/main_thread/decrypt/get_media_keys.js +2 -2
- package/dist/es2017/main_thread/decrypt/init_media_keys.d.ts.map +1 -1
- package/dist/es2017/main_thread/decrypt/init_media_keys.js +2 -2
- package/dist/{commonjs/main_thread/decrypt/utils/media_keys_infos_store.d.ts → es2017/main_thread/decrypt/utils/media_keys_attacher.d.ts} +31 -9
- package/dist/es2017/main_thread/decrypt/utils/media_keys_attacher.d.ts.map +1 -0
- package/dist/es2017/main_thread/decrypt/utils/media_keys_attacher.js +180 -0
- package/dist/es2017/main_thread/init/utils/rebuffering_controller.d.ts.map +1 -1
- package/dist/es2017/main_thread/init/utils/rebuffering_controller.js +20 -9
- package/dist/es2017/main_thread/text_displayer/html/text_track_cues_store.js +1 -1
- package/dist/es2017/main_thread/tracks_store/track_dispatcher.d.ts.map +1 -1
- package/dist/es2017/main_thread/tracks_store/track_dispatcher.js +3 -4
- package/dist/es2017/main_thread/tracks_store/tracks_store.d.ts.map +1 -1
- package/dist/es2017/main_thread/tracks_store/tracks_store.js +2 -2
- package/dist/es2017/manifest/classes/representation.d.ts +15 -1
- package/dist/es2017/manifest/classes/representation.d.ts.map +1 -1
- package/dist/es2017/manifest/classes/representation.js +17 -0
- package/dist/es2017/manifest/utils.d.ts +15 -0
- package/dist/es2017/manifest/utils.d.ts.map +1 -1
- package/dist/es2017/manifest/utils.js +27 -5
- package/dist/es2017/parsers/manifest/dash/common/parse_representations.js +2 -2
- package/dist/es2017/playback_observer/media_element_playback_observer.js +1 -1
- package/dist/es2017/public_types.d.ts +44 -0
- package/dist/es2017/public_types.d.ts.map +1 -1
- package/dist/es2017/utils/flat_map.d.ts +2 -2
- package/dist/es2017/utils/flat_map.js +2 -2
- package/dist/es2017/utils/url-utils.d.ts.map +1 -1
- package/dist/es2017/utils/url-utils.js +11 -10
- package/dist/es2017/utils/xml-parser.d.ts.map +1 -1
- package/dist/es2017/utils/xml-parser.js +10 -8
- package/dist/rx-player.js +505 -372
- package/dist/rx-player.min.js +18 -18
- package/dist/worker.js +6 -6
- package/package.json +21 -19
- package/src/__GENERATED_CODE/embedded_worker.ts +1 -1
- package/src/compat/browser_compatibility_types.ts +22 -4
- package/src/compat/browser_detection.ts +1 -1
- package/src/compat/event_listeners.ts +2 -4
- package/src/compat/has_mse_in_worker.ts +1 -1
- package/src/core/cmcd/cmcd_data_builder.ts +1 -4
- package/src/core/main/worker/send_message.ts +4 -2
- package/src/core/main/worker/worker_main.ts +1 -1
- package/src/core/stream/adaptation/adaptation_stream.ts +4 -7
- package/src/core/stream/period/period_stream.ts +3 -3
- package/src/core/stream/period/utils/get_adaptation_switch_strategy.ts +1 -2
- package/src/main_thread/api/public_api.ts +4 -4
- package/src/main_thread/decrypt/__tests__/__global__/media_key_system_access.test.ts +239 -6
- package/src/main_thread/decrypt/__tests__/find_key_system.test.ts +325 -0
- package/src/main_thread/decrypt/clear_on_stop.ts +3 -3
- package/src/main_thread/decrypt/content_decryptor.ts +26 -8
- package/src/main_thread/decrypt/dispose_decryption_resources.ts +2 -13
- package/src/main_thread/decrypt/find_key_system.ts +120 -81
- package/src/main_thread/decrypt/get_key_system_configuration.ts +2 -2
- package/src/main_thread/decrypt/get_media_keys.ts +2 -2
- package/src/main_thread/decrypt/init_media_keys.ts +2 -2
- package/src/main_thread/decrypt/utils/media_keys_attacher.ts +284 -0
- package/src/main_thread/init/utils/rebuffering_controller.ts +20 -10
- package/src/main_thread/text_displayer/html/text_track_cues_store.ts +1 -1
- package/src/main_thread/tracks_store/track_dispatcher.ts +3 -6
- package/src/main_thread/tracks_store/tracks_store.ts +2 -1
- package/src/manifest/classes/representation.ts +18 -1
- package/src/manifest/utils.ts +30 -9
- package/src/parsers/manifest/dash/common/parse_representations.ts +2 -2
- package/src/playback_observer/media_element_playback_observer.ts +1 -1
- package/src/public_types.ts +45 -0
- package/src/utils/__tests__/flat_map.test.ts +7 -20
- package/src/utils/flat_map.ts +2 -2
- package/src/utils/url-utils.ts +11 -10
- package/src/utils/xml-parser.ts +13 -8
- package/vitest.config.mjs +9 -23
- package/dist/commonjs/main_thread/decrypt/attach_media_keys.d.ts +0 -60
- package/dist/commonjs/main_thread/decrypt/attach_media_keys.d.ts.map +0 -1
- package/dist/commonjs/main_thread/decrypt/attach_media_keys.js +0 -124
- package/dist/commonjs/main_thread/decrypt/utils/media_keys_infos_store.d.ts.map +0 -1
- package/dist/commonjs/main_thread/decrypt/utils/media_keys_infos_store.js +0 -45
- package/dist/es2017/main_thread/decrypt/attach_media_keys.d.ts +0 -60
- package/dist/es2017/main_thread/decrypt/attach_media_keys.d.ts.map +0 -1
- package/dist/es2017/main_thread/decrypt/attach_media_keys.js +0 -73
- package/dist/es2017/main_thread/decrypt/utils/media_keys_infos_store.d.ts.map +0 -1
- package/dist/es2017/main_thread/decrypt/utils/media_keys_infos_store.js +0 -43
- package/src/main_thread/decrypt/attach_media_keys.ts +0 -125
- package/src/main_thread/decrypt/utils/media_keys_infos_store.ts +0 -88
package/dist/rx-player.min.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
"use strict";(()=>{var up=Object.defineProperty,lp=Object.defineProperties;var cp=Object.getOwnPropertyDescriptors;var wl=Object.getOwnPropertySymbols;var fp=Object.prototype.hasOwnProperty,mp=Object.prototype.propertyIsEnumerable;var Ol=(n,e,t)=>e in n?up(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,oe=(n,e)=>{for(var t in e||(e={}))fp.call(e,t)&&Ol(n,t,e[t]);if(wl)for(var t of wl(e))mp.call(e,t)&&Ol(n,t,e[t]);return n},ue=(n,e)=>lp(n,cp(e));var h={PRODUCTION:0,DEV:1,CURRENT_ENV:0};var S={CURRENT_LEVEL:"NONE"};function wn(){return typeof __RX_PLAYER_DEBUG_MODE__=="boolean"&&__RX_PLAYER_DEBUG_MODE__}function _(n){return n==null}var re=class{constructor(){this._listeners={}}addEventListener(e,t,r){let i=this._listeners[e];Array.isArray(i)?i.push(t):this._listeners[e]=[t],r!==void 0&&r.register(()=>{this.removeEventListener(e,t)})}removeEventListener(e,t){if(_(e)){this._listeners={};return}let r=this._listeners[e];if(!Array.isArray(r))return;if(_(t)){delete this._listeners[e];return}let i=r.indexOf(t);i!==-1&&r.splice(i,1),r.length===0&&delete this._listeners[e]}trigger(e,t){let r=this._listeners[e];Array.isArray(r)&&r.slice().forEach(i=>{try{i(t)}catch(o){if(h.CURRENT_ENV===h.DEV)throw o instanceof Error?o:new Error("EventEmitter: listener error");console.error("RxPlayer: EventEmitter error",o instanceof Error?o:null)}})}};var Vt=typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope;var hp=typeof window=="undefined"&&!Vt,zt=hp;var co;Vt?co=self:zt?co=global:co=window;var J=co;var Et=typeof queueMicrotask=="function"?queueMicrotask:function(e){Promise.resolve().then(e,()=>e())};function Na(){if(!zt&&!_(J.WebKitSourceBuffer)&&J.WebKitSourceBuffer.prototype.addEventListener===void 0){let e=J.WebKitSourceBuffer.prototype;for(let t in re.prototype)re.prototype.hasOwnProperty(t)&&(e[t]=re.prototype[t]);e._listeners=[],e._emitUpdate=function(t,r){Et(()=>{this.trigger(t,r),this.updating=!1,this.trigger("updateend",new Event("updateend"))})},e.appendBuffer=function(t){var r,i;if(this.updating)throw new Error("updating");this.trigger("updatestart",new Event("updatestart")),this.updating=!0;try{this.append(t)}catch(o){(r=this._emitUpdate)==null||r.call(this,"error",o);return}(i=this._emitUpdate)==null||i.call(this,"update",new Event("update"))}}}function he(n,e,t){if(typeof Array.prototype.findIndex=="function")return n.findIndex(e,t);let r=n.length>>>0;for(let i=0;i<r;i++)if(e.call(t,n[i],i,n))return i;return-1}function X(){}var fo=class{constructor(e,t){this._value=e,this._listeners=[],this._isFinished=!1,this._onFinishCbs=[],t!==void 0&&(this._deregisterCancellation=t.register(()=>this.finish()))}getValue(){return this._value}setValue(e){if(this._isFinished){h.CURRENT_ENV===h.DEV&&console.error("Finished shared references cannot be updated");return}if(this._value=e,this._listeners.length===0)return;let t=this._listeners.slice();for(let r of t)try{r.hasBeenCleared||r.trigger(e,r.complete)}catch(i){}}setValueIfChanged(e){e!==this._value&&this.setValue(e)}onUpdate(e,t){let r=()=>{if(t.clearSignal!==void 0&&t.clearSignal.deregister(r),i.hasBeenCleared)return;i.hasBeenCleared=!0;let o=this._listeners.indexOf(i);o>=0&&this._listeners.splice(o,1)},i={trigger:e,complete:r,hasBeenCleared:!1};if(this._listeners.push(i),t.emitCurrentValue===!0&&e(this._value,r),this._isFinished||i.hasBeenCleared){r();return}t.clearSignal.register(r)}waitUntilDefined(e,t){this.onUpdate((r,i)=>{r!==void 0&&(i(),e(this._value))},{clearSignal:t.clearSignal,emitCurrentValue:!0})}_onFinished(e,t){if(t.isCancelled())return X;let r=()=>{let a=he(this._onFinishCbs,s=>s.trigger===i);a>=0&&(this._onFinishCbs[a].hasBeenCleared=!0,this._onFinishCbs.splice(a,1))},i=()=>{r(),e()},o=t.register(r);return this._onFinishCbs.push({trigger:i,hasBeenCleared:!1}),o}finish(){this._deregisterCancellation!==void 0&&this._deregisterCancellation(),this._isFinished=!0;let e=this._listeners.slice();for(let t of e)try{t.hasBeenCleared||(t.complete(),t.hasBeenCleared=!0)}catch(r){}if(this._listeners.length=0,this._onFinishCbs.length>0){let t=this._onFinishCbs.slice();for(let r of t)try{r.hasBeenCleared||(r.trigger(),r.hasBeenCleared=!0)}catch(i){}this._onFinishCbs.length=0}}};function an(n,e,t){let r=new fo(e(n.getValue()),t);return n.onUpdate(function(o){r.setValue(e(o))},{clearSignal:t}),n._onFinished(()=>{r.finish()},t),r}var H=fo;var Dl=new H(0);var yp=typeof performance!="undefined"?()=>performance.now()+Dl.getValue():()=>Date.now()+Dl.getValue(),F=yp;var Ip="NONE",ar=class extends re{constructor(){super(),this.error=X,this.warn=X,this.info=X,this.debug=X,this._levels={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4},this._currentFormat="standard",this._currentLevel=Ip}setLevel(e,t,r){let i,o=this._levels[e];typeof o=="number"?(i=o,this._currentLevel=e):(i=0,this._currentLevel="NONE");let a;if(t==="standard"||t==="full"?a=t:a="standard",a==="full"&&a!==this._currentFormat){let d=F();console.log(String(d.toFixed(2)),"[Init]",`Local-Date: ${Date.now()}`)}this._currentFormat=a;let s=this._currentFormat==="full"?(d,u)=>(...l)=>{let c=F();return u(String(c.toFixed(2)),`[${d}]`,...l)}:(d,u)=>u;if(r===void 0)this.error=i>=this._levels.ERROR?s("error",console.error.bind(console)):X,this.warn=i>=this._levels.WARNING?s("warn",console.warn.bind(console)):X,this.info=i>=this._levels.INFO?s("info",console.info.bind(console)):X,this.debug=i>=this._levels.DEBUG?s("log",console.log.bind(console)):X;else{let d=u=>i>=this._levels[u]?(...l)=>r(u,l):X;this.error=d("ERROR"),this.warn=d("WARNING"),this.info=d("INFO"),this.debug=d("DEBUG")}this.trigger("onLogLevelChange",{level:this._currentLevel,format:this._currentFormat})}getLevel(){return this._currentLevel}getFormat(){return this._currentFormat}hasLevel(e){return this._levels[e]>=this._levels[this._currentLevel]}};var bp=new ar,m=bp;var we=J,Ll,Nl,Ul,Bl,Fl,vt=(Fl=(Bl=(Ul=(Nl=(Ll=we==null?void 0:we.MediaSource)!=null?Ll:we==null?void 0:we.MozMediaSource)!=null?Nl:we==null?void 0:we.WebKitMediaSource)!=null?Ul:we==null?void 0:we.MSMediaSource)!=null?Bl:we==null?void 0:we.ManagedMediaSource)!=null?Fl:void 0,Kl=vt!==void 0&&vt===(we==null?void 0:we.ManagedMediaSource);var Sp=200,mo=new Map;function Ua(n){if(_(vt))return Vt&&m.error("Compat: Cannot request codec support in a worker without MSE."),!1;if(typeof vt.isTypeSupported=="function"){let e=mo.get(n);if(e!==void 0)return e;{let t=vt.isTypeSupported(n);return mo.size>=Sp&&mo.clear(),mo.set(n,t),t}}return!0}var sr=!1,sn=!1,Ht=!1,dn=!1,Ba=!1,un=!1,Fa=!1,dr=!1,ur=!1,Tp=!1,_p=!1,Ka=!1,Va=!1,za=!1,ln=!1,Ep=!1,Ha=!1;(function(){var e,t,r;zt||(typeof J.MSInputMethodContext!="undefined"&&typeof document.documentMode!="undefined"?(sn=!0,Ht=!0):navigator.appName==="Microsoft Internet Explorer"||navigator.appName==="Netscape"&&/(Trident|Edge)\//.test(navigator.userAgent)?Ht=!0:navigator.userAgent.toLowerCase().indexOf("edg/")!==-1?sr=!0:navigator.userAgent.toLowerCase().indexOf("firefox")!==-1?dn=!0:typeof navigator.platform=="string"&&/iPad|iPhone|iPod/.test(navigator.platform)?un=!0:(Object.prototype.toString.call(J.HTMLElement).indexOf("Constructor")>=0||((t=(e=J.safari)==null?void 0:e.pushNotification)==null?void 0:t.toString())==="[object SafariRemoteNotification]"||/Safari\/(\d+)/.test(navigator.userAgent)&&/Version\/(\d+)/.test(navigator.userAgent)&&((r=navigator.vendor)==null?void 0:r.indexOf("Apple"))!==-1&&!/Chrome\/(\d+)/.test(navigator.userAgent)&&!/Chromium\/(\d+)/.test(navigator.userAgent))&&(Ba=!0),/SamsungBrowser/.test(navigator.userAgent)&&(Fa=!0),navigator.userAgent.indexOf("PlayStation 4")!==-1?za=!0:navigator.userAgent.indexOf("PlayStation 5")!==-1?ln=!0:/Tizen/.test(navigator.userAgent)?dr=!0:/[Ww]eb[O0]S/.test(navigator.userAgent)?(ur=!0,/[Ww]eb[O0]S.TV-2022/.test(navigator.userAgent)||/[Cc]hr[o0]me\/87/.test(navigator.userAgent)?_p=!0:(/[Ww]eb[O0]S.TV-2021/.test(navigator.userAgent)||/[Cc]hr[o0]me\/79/.test(navigator.userAgent))&&(Tp=!0)):navigator.userAgent.indexOf("NETTV")!==-1&&navigator.userAgent.indexOf("Philips")!==-1?Va=!0:/[Pp]anasonic/.test(navigator.userAgent)?Ka=!0:navigator.userAgent.indexOf("Xbox")!==-1?Ep=!0:navigator.userAgent.indexOf("Model/a1-kstb40xx")&&(Ha=!0))})();var vp=ln,Vl=vp;function Wa(n){return n===void 0||n.indexOf("widevine")<0}var zl={DEFAULT_REQUEST_TIMEOUT:3e4,DEFAULT_CONNECTION_TIMEOUT:15e3,DEFAULT_TEXT_TRACK_MODE:"native",DEFAULT_ENABLE_FAST_SWITCHING:!0,DELTA_POSITION_AFTER_RELOAD:{bitrateSwitch:-.1,trackSwitch:{audio:0,video:0,other:0}},DEFAULT_CODEC_SWITCHING_BEHAVIOR:"continue",DEFAULT_AUTO_PLAY:!1,DEFAULT_WANTED_BUFFER_AHEAD:30,DEFAULT_MAX_BUFFER_AHEAD:1/0,DEFAULT_MAX_BUFFER_BEHIND:1/0,DEFAULT_MAX_VIDEO_BUFFER_SIZE:1/0,MAXIMUM_MAX_BUFFER_AHEAD:{text:18e3},MINIMUM_MAX_BUFFER_AHEAD:{text:120},MAXIMUM_MAX_BUFFER_BEHIND:{text:18e3},DEFAULT_BASE_BANDWIDTH:0,INACTIVITY_DELAY:6e4,DEFAULT_THROTTLE_VIDEO_BITRATE_WHEN_HIDDEN:!1,DEFAULT_VIDEO_RESOLUTION_LIMIT:"none",DEFAULT_LIVE_GAP:{DEFAULT:10,LOW_LATENCY:3.5},BUFFER_DISCONTINUITY_THRESHOLD:.2,BITRATE_REBUFFERING_RATIO:1.5,DEFAULT_MAX_MANIFEST_REQUEST_RETRY:4,DEFAULT_CDN_DOWNGRADE_TIME:60,DEFAULT_MAX_REQUESTS_RETRY_ON_ERROR:4,INITIAL_BACKOFF_DELAY_BASE:{REGULAR:200,LOW_LATENCY:50},MAX_BACKOFF_DELAY_BASE:{REGULAR:3e3,LOW_LATENCY:1e3},SAMPLING_INTERVAL_MEDIASOURCE:1e3,SAMPLING_INTERVAL_LOW_LATENCY:500,SAMPLING_INTERVAL_NO_MEDIASOURCE:500,ABR_ENTER_BUFFER_BASED_ALGO:10,ABR_EXIT_BUFFER_BASED_ALGO:5,ABR_MINIMUM_TOTAL_BYTES:15e4,ABR_MINIMUM_CHUNK_SIZE:16e3,ABR_STARVATION_FACTOR:{DEFAULT:.72,LOW_LATENCY:.72},ABR_REGULAR_FACTOR:{DEFAULT:.72,LOW_LATENCY:.72},ABR_STARVATION_GAP:{DEFAULT:5,LOW_LATENCY:5},OUT_OF_STARVATION_GAP:{DEFAULT:7,LOW_LATENCY:7},ABR_STARVATION_DURATION_DELTA:.1,ABR_FAST_EMA:2,ABR_SLOW_EMA:10,RESUME_GAP_AFTER_SEEKING:{DEFAULT:1.5,LOW_LATENCY:.5},RESUME_GAP_AFTER_NOT_ENOUGH_DATA:{DEFAULT:.5,LOW_LATENCY:.5},RESUME_GAP_AFTER_BUFFERING:{DEFAULT:5,LOW_LATENCY:.5},REBUFFERING_GAP:{DEFAULT:.5,LOW_LATENCY:.2},MINIMUM_BUFFER_AMOUNT_BEFORE_FREEZING:2,UNFREEZING_SEEK_DELAY:6e3,FREEZING_STALLED_DELAY:600,UNFREEZING_DELTA_POSITION:.001,SEGMENT_SYNCHRONIZATION_DELAY:1500,MISSING_DATA_TRIGGER_SYNC_DELAY:.1,MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:.15,MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:.4,MAX_MANIFEST_BUFFERED_DURATION_DIFFERENCE:.3,MINIMUM_SEGMENT_SIZE:.001,APPEND_WINDOW_SECURITIES:{START:.2,END:.1},MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:50,TEXT_TRACK_SIZE_CHECKS_INTERVAL:250,BUFFER_PADDING:{audio:1,video:3,other:1},SEGMENT_PRIORITIES_STEPS:[2,4,8,12,18,25],MAX_HIGH_PRIORITY_LEVEL:1,MIN_CANCELABLE_PRIORITY:3,EME_DEFAULT_VIDEO_CODECS:['video/mp4;codecs="avc1.4d401e"','video/mp4;codecs="avc1.42e01e"','video/mp4;codecs="hvc1.1.6.L93.B0"','video/webm;codecs="vp8"'],EME_DEFAULT_AUDIO_CODECS:['audio/mp4;codecs="mp4a.40.2"',"audio/webm;codecs=opus"],EME_DEFAULT_WIDEVINE_ROBUSTNESSES:["HW_SECURE_ALL","HW_SECURE_DECODE","HW_SECURE_CRYPTO","SW_SECURE_DECODE","SW_SECURE_CRYPTO"],EME_DEFAULT_PLAYREADY_RECOMMENDATION_ROBUSTNESSES:["3000","2000"],EME_KEY_SYSTEMS:{clearkey:["webkit-org.w3.clearkey","org.w3.clearkey"],widevine:["com.widevine.alpha"],playready:["com.microsoft.playready.recommendation","com.microsoft.playready","com.chromecast.playready","com.youtube.playready"],fairplay:["com.apple.fps.1_0"]},MAX_CONSECUTIVE_MANIFEST_PARSING_IN_UNSAFE_MODE:10,MIN_MANIFEST_PARSING_TIME_TO_ENTER_UNSAFE_MODE:200,MIN_DASH_S_ELEMENTS_TO_PARSE_UNSAFELY:300,OUT_OF_SYNC_MANIFEST_REFRESH_DELAY:3e3,FAILED_PARTIAL_UPDATE_MANIFEST_REFRESH_DELAY:3e3,DASH_FALLBACK_LIFETIME_WHEN_MINIMUM_UPDATE_PERIOD_EQUAL_0:3,EME_DEFAULT_MAX_SIMULTANEOUS_MEDIA_KEY_SESSIONS:15,EME_MAX_STORED_PERSISTENT_SESSION_INFORMATION:1e3,EME_WAITING_DELAY_LOADED_SESSION_EMPTY_KEYSTATUSES:100,FORCED_ENDED_THRESHOLD:8e-4,ADAP_REP_SWITCH_BUFFER_PADDINGS:{video:{before:5,after:5},audio:{before:2,after:2.5},text:{before:0,after:0}},SOURCE_BUFFER_FLUSHING_INTERVAL:500,CONTENT_REPLACEMENT_PADDING:1.2,CACHE_LOAD_DURATION_THRESHOLDS:{video:50,audio:10},STREAM_EVENT_EMITTER_POLL_INTERVAL:250,DEFAULT_MAXIMUM_TIME_ROUNDING_ERROR:.001,BUFFERED_HISTORY_RETENTION_TIME:6e4,BUFFERED_HISTORY_MAXIMUM_ENTRIES:200,MIN_BUFFER_AHEAD:5,UPTO_CURRENT_POSITION_CLEANUP:5,DEFAULT_VIDEO_REPRESENTATIONS_SWITCHING_MODE:"seamless",DEFAULT_AUDIO_REPRESENTATIONS_SWITCHING_MODE:"seamless",DEFAULT_VIDEO_TRACK_SWITCHING_MODE:"reload",DEFAULT_AUDIO_TRACK_SWITCHING_MODE:"seamless"},Hl=zl;function Rp(n,...e){if(n==null)throw new TypeError("Cannot convert undefined or null to object");let t=Object(n);for(let r of e)for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i]);return t}var G=typeof Object.assign=="function"?Object.assign:Rp;function Ga(n){return n!=null&&!Array.isArray(n)&&typeof n=="object"}function lr(n,...e){if(e.length===0)return n;let t=e.shift();if(Ga(n)&&Ga(t))for(let r in t)if(Ga(t[r])){let i=n[r];i===void 0&&(i={},n[r]=i),lr(i,t[r])}else G(n,{[r]:t[r]});return lr(n,...e)}var qa=class extends re{constructor(){super(...arguments);this.updated=!1;this._config=Hl}update(t){let r=lr(this._config,t);this._config=r,this.updated=!0,this.trigger("update",t)}getCurrent(){return this._config}},kp=new qa,U=kp;var Cp=.016666666666666666;function Wl(n,e){return Math.abs(n-e)<Cp}function ql(n,e){let t=Math.min(n.start,e.start),r=Math.max(n.end,e.end);return{start:t,end:r}}function Pp(n){for(let e=0;e<n.length;e++){let t=n[e];t.start===t.end&&n.splice(e--,1)}return n}function Mp(n){for(let e=1;e<n.length;e++){let t=n[e-1],r=n[e];if(Yl(t,r)){let i=ql(t,r);n.splice(--e,2,i)}}return n}function ja(n,e){return n.end<=e.start}function Gl({start:n,end:e},t){return n<=t&&t<e}function jl(n,e){return Gl(n,e.start)||n.start<e.end&&e.end<n.end||Gl(e,n.start)}function Yl(n,e){return Wl(e.start,n.end)||Wl(e.end,n.start)}function Pe(n){let e=[];for(let t=0;t<n.length;t++)e.push({start:n.start(t),end:n.end(t)});return e}function Ya(n,e){for(let t=n.length-1;t>=0;t--){let r=n.start(t);if(e>=r){let i=n.end(t);if(e<i)return{start:r,end:i}}}return null}function Ap(n,e){for(let t=n.length-1;t>=0;t--){let r=n[t].start;if(e>=r){let i=n[t].end;if(e<i)return n[t]}}return null}function $l(n,e){let t=n.length;for(let r=0;r<t;r++){let i=n.start(r);if(e<i)return i-e}return 1/0}function Ql(n,e){let t=null,r=[];for(let i=0;i<n.length;i++){let o=n[i].start,a=n[i].end;e<o||e>=a?r.push({start:o,end:a}):t={start:o,end:a}}return{outerRanges:r,innerRange:t}}function Xl(n,e){let t=Ya(n,e);return t!==null?t.end-e:1/0}function po(n,e){let t=Ap(n,e);return t!==null?t.end-e:1/0}function Wt(n,e){if(e.start===e.end)return n;let t=e,r=0;for(;r<n.length;r++){let i=n[r],o=jl(t,i),a=Yl(t,i);if(o||a)t=ql(t,i),n.splice(r--,1);else if(r===0){if(ja(t,n[0]))break}else if(ja(n[r-1],t)&&ja(t,i))break}return n.splice(r,0,t),Mp(Pp(n))}function Zl(n,e){let t=[];for(let r=0;r<e.length;r++)jl(n,e[r])&&t.push(e[r]);return t}function Jl(n,e){let t=[];for(let r=0;r<n.length;r++){let i=n[r],o=Zl(i,e);if(o.length>0)for(let a=0;a<o.length;a++){let s=o[a];t.push({start:Math.max(i.start,s.start),end:Math.min(i.end,s.end)})}}return t}function go(n,e){let t=[];for(let r=0;r<n.length;r++){let i=n[r],o=[],a=Zl(i,e);if(a.length>0)for(let s=0;s<a.length;s++){let d=a[s];o.push({start:Math.max(i.start,d.start),end:Math.min(i.end,d.end)})}if(o.length===0)t.push(i);else{let s=i.start;for(let d=0;d<o.length;d++)o[d].start>s&&t.push({start:s,end:o[d].start}),s=o[d].end;s<i.end&&t.push({start:s,end:i.end})}}return t}var ho=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype),this.name="AssertionError"}};function ee(n,e){if(h.DEV===h.CURRENT_ENV&&!n)throw new ho(e===void 0?"invalid assertion":e)}function ec(n,e,t="object"){ee(!_(n),`${t} should be an object`);for(let r in e)e.hasOwnProperty(r)&&ee(typeof n[r]===e[r],`${t} should have property ${r} as a ${e[r]}`)}function Xe(n){throw new ho("Unreachable path taken")}var B=class{constructor(){let[e,t]=xp();this._isUsed=!1,this._trigger=e,this.signal=new cr(t)}isUsed(){return this._isUsed}linkToSignal(e){let t=e.register(()=>{this.cancel()});return this.signal.register(t),t}cancel(e){if(this._isUsed)return;this._isUsed=!0;let t=e!=null?e:new Me;this._trigger(t)}static isCancellationError(e){return e instanceof Me}},cr=class{constructor(e){this._isCancelled=!1,this.cancellationError=null,this._listeners=[],e(t=>{for(this.cancellationError=t,this._isCancelled=!0;this._listeners.length>0;)try{let r=this._listeners.pop();r==null||r(t)}catch(r){m.error("Error while calling clean up listener",r instanceof Error?r.toString():"Unknown error")}})}isCancelled(){return this._isCancelled}register(e){return this._isCancelled?(ee(this.cancellationError!==null),e(this.cancellationError),X):(this._listeners.push(e),()=>this.deregister(e))}deregister(e){for(let t=this._listeners.length-1;t>=0;t--)this._listeners[t]===e&&this._listeners.splice(t,1)}},Me=class n extends Error{constructor(){super("This task was cancelled."),Object.setPrototypeOf(this,n.prototype),this.name="CancellationError"}};function xp(){let n=X;return[function(t){n(t)},function(t){n=t}]}function $a(n){let e=n.map(a=>Math.log(a/n[0])),t=e.map(a=>a-e[0]+1),r=(t[t.length-1]-1)/(n.length*2+10),i=1/r;return n.map((a,s)=>o(s));function o(a){if(a===0)return 0;let s=Math.min(Math.max(1,a),n.length-1);return n[s]===n[s-1]?o(a-1):i*(r+(n[s]*t[s-1]-n[s-1]*t[s])/(n[s]-n[s-1]))+4}}var nt=class{constructor(e){this._alpha=Math.exp(Math.log(.5)/e),this._lastEstimate=0,this._totalWeight=0}addSample(e,t){let r=Math.pow(this._alpha,e),i=t*(1-r)+r*this._lastEstimate;isNaN(i)||(this._lastEstimate=i,this._totalWeight+=e)}getEstimate(){let e=1-Math.pow(this._alpha,this._totalWeight);return this._lastEstimate/e}};var fr=class{constructor(){this._currentRepresentationData=null,this._lastRepresentationWithGoodScore=null}addSample(e,t,r){let i=r/t,o=this._currentRepresentationData,a;o!==null&&o.representation.id===e.id?(a=o.ewma,o.ewma.addSample(t,i),o.loadedDuration+=r,o.loadedSegments++):(a=new nt(5),a.addSample(t,i),this._currentRepresentationData={representation:e,ewma:a,loadedDuration:r,loadedSegments:0}),a.getEstimate()>1&&this._lastRepresentationWithGoodScore!==e&&(m.debug("ABR: New last stable representation",e.bitrate),this._lastRepresentationWithGoodScore=e)}getEstimate(e){if(this._currentRepresentationData===null||this._currentRepresentationData.representation.id!==e.id)return;let{ewma:t,loadedSegments:r,loadedDuration:i}=this._currentRepresentationData,o=t.getEstimate(),a=r>=5&&i>=10?1:0;return{score:o,confidenceLevel:a}}getLastStableRepresentation(){return this._lastRepresentationWithGoodScore}};var tc=6e3,wp=15e3,Op=3e3,Dp=1e3,Lp=9e3,mr=class{constructor(e){this._levelsMap=$a(e).map(t=>t+4),this._bitrates=e,this._lastUnsuitableQualityTimestamp=void 0,this._blockRaiseDelay=tc,m.debug("ABR: Steps for buffer based chooser.",this._levelsMap.map((t,r)=>`bufferLevel: ${t}, bitrate: ${e[r]}`).join(" ,"))}onAddedSegment(e){let t=this._levelsMap,r=this._bitrates,{bufferGap:i,currentBitrate:o,currentScore:a,speed:s}=e;if(_(o)){this._currentEstimate=r[0];return}let d=-1;for(let p=0;p<r.length;p++){let I=r[p];if(I===o)d=p;else if(I>o)break}if(d<0||r.length!==t.length){m.info("ABR: Current Bitrate not found in the calculated levels"),this._currentEstimate=r[0];return}let u;a!==void 0&&(u=s===0?a.score:a.score/s);let l=isFinite(i)?i:0,c=F();if(l<t[d]||u!==void 0&&u<1&&(a==null?void 0:a.confidenceLevel)===1){if((this._lastUnsuitableQualityTimestamp===void 0?-1:c-this._lastUnsuitableQualityTimestamp)<this._blockRaiseDelay+Lp){let y=this._blockRaiseDelay+Op;this._blockRaiseDelay=Math.min(y,wp),m.debug("ABR: Incrementing blocking raise in BufferBasedChooser due to unstable quality",this._blockRaiseDelay)}else{let y=this._blockRaiseDelay-Dp;this._blockRaiseDelay=Math.max(tc,y),m.debug("ABR: Lowering quality in BufferBasedChooser",this._blockRaiseDelay)}this._lastUnsuitableQualityTimestamp=c;let I=he(r,y=>y===o);for(let y=I-1;y>=0;y--)if(l>=t[y]){this._currentEstimate=r[y];return}this._currentEstimate=r[0];return}if(this._lastUnsuitableQualityTimestamp!==void 0&&c-this._lastUnsuitableQualityTimestamp<this._blockRaiseDelay||u===void 0||u<1.15||(a==null?void 0:a.confidenceLevel)!==1){this._currentEstimate=o;return}let f=t[d],g=(()=>{for(let p=d+1;p<t.length;p++)if(t[p]>f)return p})();if(g!==void 0){let p=t[g];if(i>=p){m.debug("ABR: Raising quality in BufferBasedChooser",r[g]),this._currentEstimate=r[g];return}}this._currentEstimate=o}getLastEstimate(){return this._currentEstimate}};function Z(n,e,t){if(typeof Array.prototype.find=="function")return n.find(e,t);let r=n.length>>>0;for(let i=0;i<r;i++){let o=n[i];if(e.call(t,o,i,n))return o}}function Np(n,e){let t=-1;for(let a=0;a<n.length;a++){let{segment:s}=n[a].content;if(s.duration<=0)continue;let d=s.time+s.duration;if(!s.complete&&a===n.length-1&&e-s.time>-1.2){t=a;break}if(d>e&&e-s.time>-1.2){t=a;break}}if(t<0)return[];let r=n[t],i=r.content.segment.time,o=[r];for(let a=t+1;a<n.length&&n[a].content.segment.time===i;a++)o.push(n[a]);return o}function yo(n){if(n.progress.length<5)return;let e=new nt(2),{progress:t}=n;for(let r=1;r<t.length;r++){let i=t[r].size-t[r-1].size,o=t[r].timestamp-t[r-1].timestamp,a=i*8/(o/1e3);e.addSample(o/1e3,a)}return e.getEstimate()}function nc(n,e){let t=(n.totalSize-n.size)*8;return Math.max(t/e,0)}function Up(n,e,t,r,i){if(r)return;let{bufferGap:o,speed:a,position:s}=e,d=isFinite(o)?o:0,u=s.getWanted()+d,l=Np(n,u);if(l.length!==1)return;let c=l[0],f=F(),g=c.content.segment.duration*1.5;if(g=Math.min(g,3e3),g=Math.max(g,12e3),f-c.requestTimestamp<g)return;let p=c.progress.length>0?c.progress[c.progress.length-1]:void 0,I=yo(c);if(p!==void 0&&I!==void 0){let R=nc(p,I);if((f-p.timestamp)/1e3<=R&&R-d/a>2500)return I}if(!c.content.segment.complete)return;let y=c.content.segment.duration,b=(f-c.requestTimestamp)/1e3,T=b<=(y*1.5+2)/a;if(_(t)||T)return;let v=y/b,E=t.bitrate*Math.min(.7,v);if(i===void 0||E<i)return E}function Bp(n,e,t){if(t)return!0;let r=isFinite(n.bufferGap)?n.bufferGap:0,i=n.position.getWanted()+r,o=Z(e,({content:c})=>c.segment.duration>0&&c.segment.time+c.segment.duration>i);if(o===void 0)return!0;let a=F(),s=o.progress.length>0?o.progress[o.progress.length-1]:void 0,d=yo(o);if(s===void 0||d===void 0)return!0;let u=nc(s,d);return(a-s.timestamp)/1e3>u*1.2?!0:u-r/n.speed>-1.5}var pr=class{constructor(e,t){let{ABR_STARVATION_GAP:r,OUT_OF_STARVATION_GAP:i,ABR_STARVATION_FACTOR:o,ABR_REGULAR_FACTOR:a}=U.getCurrent();this._initialBitrate=e,this._inStarvationMode=!1,this._lowLatencyMode=t,t?this._config={starvationGap:r.LOW_LATENCY,outOfStarvationGap:i.LOW_LATENCY,starvationBitrateFactor:o.LOW_LATENCY,regularBitrateFactor:a.LOW_LATENCY}:this._config={starvationGap:r.DEFAULT,outOfStarvationGap:i.DEFAULT,starvationBitrateFactor:o.DEFAULT,regularBitrateFactor:a.DEFAULT}}getBandwidthEstimate(e,t,r,i,o){let a,s,d=this._config,{bufferGap:u,position:l,duration:c}=e,f=isFinite(u)?u:0,{ABR_STARVATION_DURATION_DELTA:g}=U.getCurrent();return isNaN(c)||f+l.getWanted()<c-g?!this._inStarvationMode&&f<=d.starvationGap?(m.info("ABR: enter starvation mode."),this._inStarvationMode=!0):this._inStarvationMode&&f>=d.outOfStarvationGap&&(m.info("ABR: exit starvation mode."),this._inStarvationMode=!1):this._inStarvationMode&&(m.info("ABR: exit starvation mode."),this._inStarvationMode=!1),this._inStarvationMode&&(s=Up(i,e,r,this._lowLatencyMode,o),s!==void 0&&(m.info("ABR: starvation mode emergency estimate:",s),t.reset(),a=_(r)?s:Math.min(s,r.bitrate))),_(a)&&(s=t.getEstimate(),s!==void 0?a=s*(this._inStarvationMode?d.starvationBitrateFactor:d.regularBitrateFactor):o!==void 0?a=o*(this._inStarvationMode?d.starvationBitrateFactor:d.regularBitrateFactor):a=this._initialBitrate),e.speed>1&&(a/=e.speed),{bandwidthEstimate:s,bitrateChosen:a}}isUrgent(e,t,r,i){return t===null?!0:e>=t.bitrate?!1:Bp(i,r,this._lowLatencyMode)}};var gr=class{constructor(){this.bandwidth=void 0,this.representation=null,this.algorithmType=3}update(e,t,r){this.representation=e,this.bandwidth=t,this.algorithmType=r}};var hr=class{constructor(e,t){this._scoreCalculator=e,this._lastAbrEstimate=t,this._consecutiveWrongGuesses=0,this._blockGuessesUntil=0,this._lastMaintanableBitrate=null}getGuess(e,t,r,i,o){let{bufferGap:a,speed:s}=t,d=this._lastAbrEstimate.representation;if(d===null)return null;if(i>d.bitrate)return this._lastAbrEstimate.algorithmType===2&&(this._lastAbrEstimate.representation!==null&&(this._lastMaintanableBitrate=this._lastAbrEstimate.representation.bitrate),this._consecutiveWrongGuesses=0),null;let u=this._scoreCalculator.getEstimate(r);if(this._lastAbrEstimate.algorithmType!==2){if(u===void 0)return null;if(this._canGuessHigher(a,s,u)){let c=rc(e,r);if(c!==null)return c}return null}if(this._isLastGuessValidated(d,i,u)&&(m.debug("ABR: Guessed Representation validated",d.bitrate),this._lastMaintanableBitrate=d.bitrate,this._consecutiveWrongGuesses=0),r.id!==d.id)return d;if(this._shouldStopGuess(r,u,a,o))return this._consecutiveWrongGuesses++,this._blockGuessesUntil=F()+Math.min(this._consecutiveWrongGuesses*15e3,12e4),Fp(e,r);if(u===void 0)return r;if(this._canGuessHigher(a,s,u)){let c=rc(e,r);if(c!==null)return c}return r}_canGuessHigher(e,t,{score:r,confidenceLevel:i}){return isFinite(e)&&e>=2.5&&F()>this._blockGuessesUntil&&i===1&&r/t>1.01}_shouldStopGuess(e,t,r,i){if(t!==void 0&&t.score<1.01)return!0;if((t===void 0||t.score<1.2)&&r<.6)return!0;let o=i.filter(s=>s.content.representation.id===e.id),a=F();for(let s of o){let d=a-s.requestTimestamp;if(s.content.segment.isInit){if(d>1e3)return!0}else{if(d>s.content.segment.duration*1e3+200)return!0;{let u=yo(s);if(u!==void 0&&u<e.bitrate*.8)return!0}}}return!1}_isLastGuessValidated(e,t,r){return r!==void 0&&r.confidenceLevel===1&&r.score>1.5?!0:t>=e.bitrate&&(this._lastMaintanableBitrate===null||this._lastMaintanableBitrate<e.bitrate)}};function rc(n,e){let t=n.length,r=he(n,({id:i})=>i===e.id);if(r<0)return m.error("ABR: Current Representation not found."),null;for(;++r<t;)if(n[r].bitrate>e.bitrate)return n[r];return null}function Fp(n,e){let t=he(n,({id:r})=>r===e.id);if(t<0)return m.error("ABR: Current Representation not found."),null;for(;--t>=0;)if(n[t].bitrate<e.bitrate)return n[t];return null}var yr=class{constructor(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=U.getCurrent();this._fastEWMA=new nt(e),this._slowEWMA=new nt(t),this._bytesSampled=0}addSample(e,t){let{ABR_MINIMUM_CHUNK_SIZE:r}=U.getCurrent();if(t<r)return;let i=t*8e3/e,o=e/1e3;this._bytesSampled+=t,this._fastEWMA.addSample(o,i),this._slowEWMA.addSample(o,i)}getEstimate(){let{ABR_MINIMUM_TOTAL_BYTES:e}=U.getCurrent();if(!(this._bytesSampled<e))return Math.min(this._fastEWMA.getEstimate(),this._slowEWMA.getEstimate())}reset(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=U.getCurrent();this._fastEWMA=new nt(e),this._slowEWMA=new nt(t),this._bytesSampled=0}};function Qa(n,e){if(n.length===0)return[];n.sort((o,a)=>o.bitrate-a.bitrate);let t=n[0].bitrate,r=Math.max(e,t),i=he(n,o=>o.bitrate>r);return i===-1?n:n.slice(0,i)}function Xa(n,e){if(e.width===void 0||e.height===void 0)return n;let t=e.width*e.pixelRatio,r=e.height*e.pixelRatio,i=n.slice().sort((s,d)=>{var u,l;return((u=s.width)!=null?u:0)-((l=d.width)!=null?l:0)}),o=Z(i,s=>typeof s.width=="number"&&s.width>=t&&typeof s.height=="number"&&s.height>=r);if(o===void 0)return n;let a=typeof o.width=="number"?o.width:0;return n.filter(s=>typeof s.width=="number"?s.width<=a:!0)}function Ir(n){return Object.keys(n).map(e=>n[e])}var On=typeof Object.values=="function"?Object.values:Ir;var br=class{constructor(){this._currentRequests={}}add(e){let{id:t,requestTimestamp:r,content:i}=e;this._currentRequests[t]={requestTimestamp:r,progress:[],content:i}}addProgress(e){let t=this._currentRequests[e.id];if(_(t)){if(h.CURRENT_ENV===h.DEV)throw new Error("ABR: progress for a request not added");m.warn("ABR: progress for a request not added");return}t.progress.push(e)}remove(e){if(_(this._currentRequests[e])){if(h.CURRENT_ENV===h.DEV)throw new Error("ABR: can't remove unknown request");m.warn("ABR: can't remove unknown request")}delete this._currentRequests[e]}getRequests(){return On(this._currentRequests).filter(e=>!_(e)).sort((e,t)=>e.content.segment.time-t.content.segment.time)}};function Io(n,e){let t=he(n,r=>r.bitrate>e);return t===-1?n[n.length-1]:t===0?n[0]:n[t-1]}var ic=new H(void 0);ic.finish();var oc=new H(1/0);oc.finish();function Za(n){let e={},{initialBitrates:t,throttlers:r,lowLatencyMode:i}=n;return function(s,d,u,l,c){var y,b,T;let{type:f}=s.adaptation,g=o(f),p=(y=t[f])!=null?y:0,I={limitResolution:(b=r.limitResolution[f])!=null?b:ic,throttleBitrate:(T=r.throttleBitrate[f])!=null?T:oc};return Kp({bandwidthEstimator:g,context:s,currentRepresentation:d,filters:I,initialBitrate:p,playbackObserver:l,representations:u,lowLatencyMode:i},c)};function o(a){let s=e[a];if(_(s)){m.debug("ABR: Creating new BandwidthEstimator for ",a);let d=new yr;return e[a]=d,d}return s}}function Kp({bandwidthEstimator:n,context:e,currentRepresentation:t,filters:r,initialBitrate:i,lowLatencyMode:o,playbackObserver:a,representations:s},d){let u=new fr,l=new pr(i!=null?i:0,o),c=new br,f=X,g={metrics:T,requestBegin:v,requestProgress:E,requestEnd:R,addedSegment(k){f(k)}},p=new B;p.linkToSignal(d);let I=y(s.getValue(),p.signal);return s.onUpdate(b,{clearSignal:d}),{estimates:I,callbacks:g};function y(k,x){if(k.length<=1)return new H({bitrate:void 0,representation:k[0],urgent:!0,knownStableBitrate:void 0});let M=!1,P=k.sort((V,$)=>V.bitrate-$.bitrate),N=new mr(P.map(V=>V.bitrate)),O=new gr,K=new hr(u,O),A=a.getReference().getValue(),C=new H(L());return a.listen(V=>{A=V,D()},{includeLastObservation:!1,clearSignal:x}),f=function(V){if(A===null)return;let{position:$,speed:j}=A,z=V.buffered,q=po(z,$.getWanted()),{representation:W}=V.content,se=u.getEstimate(W),ae=W.bitrate,de={bufferGap:q,currentBitrate:ae,currentScore:se,speed:j};N.onAddedSegment(de),D()},x.register(()=>{f=X}),r.throttleBitrate.onUpdate(D,{clearSignal:x}),r.limitResolution.onUpdate(D,{clearSignal:x}),C;function D(){C.setValue(L())}function L(){let{bufferGap:V,position:$,maximumPosition:j}=A,z=r.limitResolution.getValue(),q=r.throttleBitrate.getValue(),W=t.getValue(),se=Vp(P,z,q),ae=c.getRequests(),{bandwidthEstimate:de,bitrateChosen:Se}=l.getBandwidthEstimate(A,n,W,ae,O.bandwidth),Y=u.getLastStableRepresentation(),ce=Y===null?void 0:Y.bitrate/(A.speed>0?A.speed:1),{ABR_ENTER_BUFFER_BASED_ALGO:ye,ABR_EXIT_BUFFER_BASED_ALGO:Kt}=U.getCurrent();M&&V<=Kt?M=!1:!M&&isFinite(V)&&V>=ye&&(M=!0);let Qe=Io(se,Se),Be=N.getLastEstimate(),_t=Qe.bitrate,yt=null;M&&Be!==void 0&&Be>_t&&(yt=Io(se,Be),_t=yt.bitrate);let De=null;return o&&W!==null&&e.manifest.isDynamic&&j-$.getWanted()<40&&(De=K.getGuess(P,A,W,_t,ae)),De!==null&&De.bitrate>_t?(m.debug("ABR: Choosing representation with guess-based estimation.",De.bitrate,De.id),O.update(De,de,2),{bitrate:de,representation:De,urgent:W===null||De.bitrate<W.bitrate,knownStableBitrate:ce}):yt!==null?(m.debug("ABR: Choosing representation with buffer-based estimation.",yt.bitrate,yt.id),O.update(yt,de,0),{bitrate:de,representation:yt,urgent:l.isUrgent(yt.bitrate,W,ae,A),knownStableBitrate:ce}):(m.debug("ABR: Choosing representation with bandwidth estimation.",Qe.bitrate,Qe.id),O.update(Qe,de,1),{bitrate:de,representation:Qe,urgent:l.isUrgent(Qe.bitrate,W,ae,A),knownStableBitrate:ce})}}function b(){let k=s.getValue();p.cancel(),p=new B,p.linkToSignal(d),y(k,p.signal).onUpdate(function(P){I.setValue(P)},{clearSignal:p.signal,emitCurrentValue:!0})}function T(k){let{requestDuration:x,segmentDuration:M,size:P,content:N}=k;if(n.addSample(x,P),!N.segment.isInit){let{segment:O,representation:K}=N;if(M===void 0&&!O.complete)return;let A=M!=null?M:O.duration;u.addSample(K,x/1e3,A)}}function v(k){c.add(k)}function E(k){c.addProgress(k)}function R(k){c.remove(k.id)}}function Vp(n,e,t){let r=n;return t!==void 0&&t<1/0&&(r=Qa(r,t)),e!==void 0&&(r=Xa(r,e)),r}var ac=Za;function bo(){var t;if(typeof((t=J.crypto)==null?void 0:t.randomUUID)=="function")return J.crypto.randomUUID();let n=new Date().getTime(),e=F();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let i=Math.random()*16;return n>0?(i=(n+i)%16|0,n=Math.floor(n/16)):(i=(e+i)%16|0,e=Math.floor(e/16)),(r==="x"?i:i&3|8).toString(16)})}function Ze(n,e,t){if(typeof String.prototype.startsWith=="function")return n.startsWith(e,t);let r=typeof t=="number"?Math.max(t,0):0;return n.substring(r,r+e.length)===e}var zp=/^(?:[a-z]+:)?\/\//i,Hp=/^(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/;function _r(n){let e=n.lastIndexOf("/");if(e<0)return n.length;if(zp.test(n)){let r=n.indexOf("/");if(r>=0&&e===r+1)return n.length}let t=n.indexOf("?");return t>=0&&t<e?_r(n.substring(0,t)):e+1}function sc(n,e){let t=So(n),r=So(e);if(t.scheme!==r.scheme||t.authority!==r.authority||t.path[0]!==void 0&&t.path[0]!=="/"&&r.path[0]==="/"||r.path[0]!==void 0&&r.path[0]!=="/"&&t.path[0]==="/")return null;let i=Tr(t.path),o=Tr(r.path),a;if(i===o)a="";else{let d=i.split("/");d.pop();let u=o.split("/");for(;d.length>0&&u.length>0&&d[0]===u[0];)d.shift(),u.shift();for(;d.length>0;)d.shift(),u.unshift("..");let l=u.join("/");(l.endsWith("../")||l.endsWith("./"))&&(l=l.slice(0,l.length-1)),a=l===""?".":l}let s=a;return a===""&&r.query===t.query||r.query&&(s+="?",s+=r.query),r.fragment&&(s+="#",s+=r.fragment),s}function Wp(n,e){let t=So(n),r=So(e);if(r.scheme)return Ja(r);let i={scheme:t.scheme,authority:t.authority,path:"",query:r.query,fragment:r.fragment};return r.authority?(i.authority=r.authority,i.path=Tr(r.path),Ja(i)):(r.path===""?(i.path=t.path,r.query||(i.query=t.query)):Ze(r.path,"/")?i.path=Tr(r.path):i.path=Tr(qp(t,r.path)),Ja(i))}var Sr=new Map,Gp=200;function So(n){var r,i,o,a,s;if(Sr.has(n))return Sr.get(n);let e=n.match(Hp),t;return e===null?t={scheme:"",authority:"",path:"",query:"",fragment:""}:t={scheme:(r=e[1])!=null?r:"",authority:(i=e[2])!=null?i:"",path:(o=e[3])!=null?o:"",query:(a=e[4])!=null?a:"",fragment:(s=e[5])!=null?s:""},Sr.size>=Gp&&Sr.clear(),Sr.set(n,t),t}function Ja(n){let e="";return n.scheme&&(e+=n.scheme+":"),n.authority&&(e+="//"+n.authority),e+=n.path,n.query&&(e+="?"+n.query),n.fragment&&(e+="#"+n.fragment),e}function Tr(n){let e=n.split(/(?=\/)/),t=[];for(let r=0;r<e.length;r++){let i=e[r];if(!(i===".."||i==="."||i==="")){if(i==="/.."){t.pop(),r===e.length-1&&t.push("/");continue}if(i==="/."){r===e.length-1&&t.push("/");continue}t.push(i)}}return t.join("")}function qp(n,e){if(n.authority&&n.path==="")return"/"+e;let t=n.path;return t.substring(0,t.lastIndexOf("/")+1)+e}function cn(...n){var r,i,o;let e=n.filter(a=>a!==""),t=e.length;if(t===0)return"";if(t===1)return(r=e[0])!=null?r:"";{let a=(i=e[0])!=null?i:"",s=(o=e[1])!=null?o:"",d=Wp(a,s),u=e.slice(2);return cn(d,...u)}}var jp=4,Er=class{constructor(e){var t,r;this._sessionId=(t=e.sessionId)!=null?t:bo(),this._contentId=(r=e.contentId)!=null?r:bo(),this._typePreference=e.communicationType==="headers"?0:1,this._bufferStarvationToggle=!1,this._playbackObserver=null,this._lastThroughput={},this._canceller=null}startMonitoringPlayback(e){var t;(t=this._canceller)==null||t.cancel(),this._canceller=new B,this._playbackObserver=e,e.listen(r=>{r.rebuffering!==null&&(this._bufferStarvationToggle=!0)},{includeLastObservation:!0,clearSignal:this._canceller.signal})}stopMonitoringPlayback(){var e;(e=this._canceller)==null||e.cancel(),this._canceller=null,this._playbackObserver=null}updateThroughput(e,t){this._lastThroughput[e]=t}_getCommonCmcdData(e){var i;let t={};t.bs=this._bufferStarvationToggle,this._bufferStarvationToggle=!1,t.cid=this._contentId,t.mtp=e!==void 0?Math.floor(Math.round(e/1e3/100)*100):void 0,t.sid=this._sessionId;let r=(i=this._playbackObserver)==null?void 0:i.getReference().getValue();return t.pr=r===void 0||r.speed===1?void 0:r.speed,r!==void 0&&(t.su=r.rebuffering!==null),t}getCmcdDataForManifest(e){var r;let t=this._getCommonCmcdData((r=this._lastThroughput.video)!=null?r:this._lastThroughput.audio);switch(t.ot="m",e){case"dash":t.sf="d";break;case"smooth":t.sf="s";break;default:t.sf="o";break}return this._producePayload(t)}getCmcdDataForSegmentRequest(e){var a,s,d,u;let t=(a=this._playbackObserver)==null?void 0:a.getReference().getValue(),r=this._getCommonCmcdData(this._lastThroughput[e.adaptation.type]);switch(r.br=Math.round(e.representation.bitrate/1e3),r.d=Math.round(e.segment.duration*1e3),e.adaptation.type){case"video":r.ot="v";break;case"audio":r.ot="a";break;case"text":r.ot="c";break}if(e.segment.isInit&&(r.ot="i"),!_(e.nextSegment)&&e.segment.url!==null&&e.nextSegment.url!==null&&(!e.nextSegment.isInit||e.nextSegment.indexRange===void 0)){let l=e.segment.url,c=e.nextSegment.url,f=sc(l,c);f!==null&&(f!=="."&&(r.nor=encodeURIComponent(f)),e.nextSegment.range!==void 0&&(r.nrr=String(e.nextSegment.range[0])+"-",isFinite(e.nextSegment.range[1])&&(r.nrr+=String(e.nextSegment.range[1]))))}let i;if(t!==void 0&&(r.ot==="v"||r.ot==="a"||r.ot==="av")){let l=t.buffered[e.adaptation.type];if(!_(l)){let c=(u=(d=(s=this._playbackObserver)==null?void 0:s.getCurrentTime())!=null?d:t.position.getWanted())!=null?u:t.position.getPolled();for(let f of l)if(c>=f.start&&c<f.end){i=(f.end-c)*1e3,r.bl=Math.floor(Math.round(i/100)*100);break}}}let o=i===void 0||t===void 0?void 0:i/t.speed;if(r.dl=o===void 0?void 0:Math.floor(Math.round(o/100)*100),o!==void 0){let c=e.representation.bitrate*e.segment.duration/1e3/(o/1e3);r.rtp=Math.floor(Math.round(c*jp/100)*100)}switch(e.manifest.transport){case"dash":r.sf="d";break;case"smooth":r.sf="s";break;default:r.sf="o";break}return r.st=e.manifest.isDynamic?"l":"v",r.tb=e.adaptation.representations.reduce((l,c)=>c.isSupported!==!0||c.decipherable===!1?l:l===void 0?Math.round(c.bitrate/1e3):Math.max(l,Math.round(c.bitrate/1e3)),void 0),this._producePayload(r)}_producePayload(e){let t={object:"",request:"",session:"",status:""},r="",i=(u,l)=>{this._typePreference===0?t[l]+=u:r+=u},o=(u,l)=>{let c=e[u];if(c!==void 0){let f=`${u}=${String(c)},`;i(f,l)}},a=(u,l)=>{if(e[u]===!0){let c=`${u},`;i(c,l)}},s=(u,l)=>{let c=e[u];if(c!==void 0){let g=`prop=${`"${c.replace("\\","\\\\").replace('"','\\"')}"`},`;i(g,l)}},d=(u,l)=>{let c=e[u];if(c!==void 0){let f=`prop=${c},`;i(f,l)}};return o("bl","request"),o("br","object"),a("bs","status"),s("cid","session"),o("d","object"),o("dl","request"),o("mtp","request"),s("nor","request"),s("nrr","request"),d("ot","object"),o("pr","session"),o("rtp","status"),d("sf","session"),s("sid","session"),d("st","session"),a("su","request"),o("tb","object"),this._typePreference===0?(t.object[t.object.length-1]===","&&(t.object=t.object.substring(0,t.object.length-1)),t.request[t.request.length-1]===","&&(t.request=t.request.substring(0,t.request.length-1)),t.session[t.session.length-1]===","&&(t.session=t.session.substring(0,t.session.length-1)),t.status[t.status.length-1]===","&&(t.status=t.status.substring(0,t.status.length-1)),m.debug("CMCD: proposing headers payload"),{type:"headers",value:{"CMCD-Object":t.object,"CMCD-Request":t.request,"CMCD-Session":t.session,"CMCD-Status":t.status}}):(r[r.length-1]===","&&(r=r.substring(0,r.length-1)),r=encodeURIComponent(r),m.debug("CMCD: proposing query string payload",r),{type:"query",value:[["CMCD",r]]})}};var dc=Er;var rt=class n extends Error{constructor(e,t,r){super(e),Object.setPrototypeOf(this,n.prototype),this.name="CustomLoaderError",this.canRetry=t,this.xhr=r}};var Ee=class n extends Error{constructor(e,t,r){let i;switch(r){case"TIMEOUT":i="The request timed out";break;case"ERROR_EVENT":i="An error prevented the request to be performed successfully";break;case"PARSE_ERROR":i="An error happened while formatting the response data";break;case"ERROR_HTTP_CODE":i="An HTTP status code indicating failure was received: "+String(t);break}super(i),Object.setPrototypeOf(this,n.prototype),this.name="RequestError",this.url=e,this.status=t,this.type=r}serialize(){return{url:this.url,status:this.status,type:this.type}}},Fe={TIMEOUT:"TIMEOUT",ERROR_EVENT:"ERROR_EVENT",ERROR_HTTP_CODE:"ERROR_HTTP_CODE",PARSE_ERROR:"PARSE_ERROR"};var es=typeof Headers=="function"?Headers:null,ts=typeof AbortController=="function"?AbortController:null;function To(n){var f,g;let e;if(!_(n.headers))if(_(es))e=n.headers;else{e=new es;let p=Object.keys(n.headers);for(let I=0;I<p.length;I++){let y=p[I];e.append(y,n.headers[y])}}m.debug("Fetch: Called with URL",n.url);let t=null,r=!1,i=!1,o=F(),a=_(ts)?null:new ts;function s(){if(_(a)){m.warn("Fetch: AbortController API not available.");return}a.abort()}let d;n.timeout!==void 0&&(d=setTimeout(()=>{r=!0,u!==void 0&&clearTimeout(u),s()},n.timeout));let u;n.connectionTimeout!==void 0&&(u=setTimeout(()=>{i=!0,d!==void 0&&clearTimeout(d),s()},n.connectionTimeout));let l=n.cancelSignal.register(function(I){t=I,s()}),c={method:"GET"};if(e!==void 0&&(c.headers=e),c.signal=_(a)?null:a.signal,m.hasLevel("DEBUG")){let p="FETCH: Sending GET "+n.url;n.timeout!==void 0&&(p+=" to="+String(n.timeout/1e3)),n.connectionTimeout!==void 0&&(p+=" cto="+String(n.connectionTimeout/1e3)),((f=n.headers)==null?void 0:f.Range)!==void 0&&(p+=" Range="+((g=n.headers)==null?void 0:g.Range)),m.debug(p)}return fetch(n.url,c).then(p=>{if(u!==void 0&&clearTimeout(u),p.status>=300)throw m.warn("Fetch: Request HTTP Error",p.status,p.url),new Ee(p.url,p.status,Fe.ERROR_HTTP_CODE);if(_(p.body))throw new Ee(p.url,p.status,Fe.PARSE_ERROR);let I=p.headers.get("Content-Length"),y=!_(I)&&!isNaN(+I)?+I:void 0,b=p.body.getReader(),T=0;return v();async function v(){let E=await b.read();if(!E.done&&!_(E.value)){T+=E.value.byteLength;let R=F(),k={url:p.url,currentTime:R,duration:R-o,sendingTime:o,chunkSize:E.value.byteLength,chunk:E.value.buffer,size:T,totalSize:y};return n.onData(k),v()}else if(E.done){d!==void 0&&clearTimeout(d),l();let R=F();return{requestDuration:R-o,receivedTime:R,sendingTime:o,size:T,status:p.status,url:p.url}}return v()}}).catch(p=>{throw t!==null?t:(l(),r?(m.warn("Fetch: Request timed out."),new Ee(n.url,0,Fe.TIMEOUT)):i?(m.warn("Fetch: Request connection timed out."),new Ee(n.url,0,Fe.TIMEOUT)):p instanceof Ee?p:(m.warn("Fetch: Request Error",p instanceof Error?p.toString():""),new Ee(n.url,0,Fe.ERROR_EVENT)))})}function vr(){return typeof J.fetch=="function"&&!_(ts)&&!_(es)}function w(n){return typeof n=="string"&&n.length>0}var Yp="json";function ns(n){let e={url:n.url,headers:n.headers,responseType:_(n.responseType)?Yp:n.responseType,timeout:n.timeout,connectionTimeout:n.connectionTimeout};return new Promise((t,r)=>{let{onProgress:i,cancelSignal:o}=n,{url:a,headers:s,responseType:d,timeout:u,connectionTimeout:l}=e,c=new XMLHttpRequest;c.open("GET",a,!0);let f;u!==void 0&&(c.timeout=u,f=setTimeout(()=>{y(),r(new Ee(a,c.status,Fe.TIMEOUT))},u+3e3));let g;if(l!==void 0&&(g=setTimeout(()=>{y(),c.readyState!==XMLHttpRequest.DONE&&c.abort(),r(new Ee(a,c.status,Fe.TIMEOUT))},l)),c.responseType=d,c.responseType==="document"&&c.overrideMimeType("text/xml"),!_(s)){let b=s;for(let T in b)b.hasOwnProperty(T)&&c.setRequestHeader(T,b[T])}let p=F(),I=null;if(o!==void 0&&(I=o.register(function(T){y(),c.readyState!==XMLHttpRequest.DONE&&c.abort(),r(T)}),o.isCancelled()))return;if(c.onerror=function(){y(),r(new Ee(a,c.status,Fe.ERROR_EVENT))},c.ontimeout=function(){y(),r(new Ee(a,c.status,Fe.TIMEOUT))},l!==void 0&&(c.onreadystatechange=function(){c.readyState>=XMLHttpRequest.HEADERS_RECEIVED&&clearTimeout(g)}),i!==void 0&&(c.onprogress=function(T){let v=F();i({url:a,duration:v-p,sendingTime:p,currentTime:v,size:T.loaded,totalSize:T.total})}),c.onload=function(T){if(c.readyState===XMLHttpRequest.DONE)if(y(),c.status>=200&&c.status<300){let v=F(),E=c.response instanceof ArrayBuffer?c.response.byteLength:T.total,R=c.status,k=c.responseType,x=w(c.responseURL)?c.responseURL:a,M;if(k==="json"?M=typeof c.response=="object"?c.response:$p(c.responseText):M=c.response,_(M)){r(new Ee(a,c.status,Fe.PARSE_ERROR));return}t({status:R,url:x,responseType:k,sendingTime:p,receivedTime:v,requestDuration:v-p,size:E,responseData:M})}else r(new Ee(a,c.status,Fe.ERROR_HTTP_CODE))},m.hasLevel("DEBUG")){let b="XHR: Sending GET "+a;n.responseType!==void 0&&(b+=" type="+n.responseType),u!==void 0&&(b+=" to="+String(u/1e3)),l!==void 0&&(b+=" cto="+String(l/1e3)),(s==null?void 0:s.Range)!==void 0&&(b+=" Range="+(s==null?void 0:s.Range)),m.debug(b)}c.send();function y(){f!==void 0&&clearTimeout(f),g!==void 0&&clearTimeout(g),I!==null&&I()}})}function $p(n){try{return JSON.parse(n)}catch(e){return null}}var Te=ns;var fn=Fe,Je={NETWORK_ERROR:"NETWORK_ERROR",MEDIA_ERROR:"MEDIA_ERROR",ENCRYPTED_MEDIA_ERROR:"ENCRYPTED_MEDIA_ERROR",OTHER_ERROR:"OTHER_ERROR"},rs={PIPELINE_LOAD_ERROR:"PIPELINE_LOAD_ERROR",PIPELINE_PARSE_ERROR:"PIPELINE_PARSE_ERROR",INTEGRITY_ERROR:"INTEGRITY_ERROR",MANIFEST_PARSE_ERROR:"MANIFEST_PARSE_ERROR",MANIFEST_INCOMPATIBLE_CODECS_ERROR:"MANIFEST_INCOMPATIBLE_CODECS_ERROR",MANIFEST_UPDATE_ERROR:"MANIFEST_UPDATE_ERROR",MANIFEST_UNSUPPORTED_ADAPTATION_TYPE:"MANIFEST_UNSUPPORTED_ADAPTATION_TYPE",MEDIA_STARTING_TIME_NOT_FOUND:"MEDIA_STARTING_TIME_NOT_FOUND",MEDIA_TIME_BEFORE_MANIFEST:"MEDIA_TIME_BEFORE_MANIFEST",MEDIA_TIME_AFTER_MANIFEST:"MEDIA_TIME_AFTER_MANIFEST",MEDIA_TIME_NOT_FOUND:"MEDIA_TIME_NOT_FOUND",NO_PLAYABLE_REPRESENTATION:"NO_PLAYABLE_REPRESENTATION",MEDIA_IS_ENCRYPTED_ERROR:"MEDIA_IS_ENCRYPTED_ERROR",CREATE_MEDIA_KEYS_ERROR:"CREATE_MEDIA_KEYS_ERROR",MEDIA_KEYS_ATTACHMENT_ERROR:"MEDIA_KEYS_ATTACHMENT_ERROR",KEY_ERROR:"KEY_ERROR",KEY_STATUS_CHANGE_ERROR:"KEY_STATUS_CHANGE_ERROR",KEY_UPDATE_ERROR:"KEY_UPDATE_ERROR",KEY_LOAD_ERROR:"KEY_LOAD_ERROR",KEY_LOAD_TIMEOUT:"KEY_LOAD_TIMEOUT",KEY_GENERATE_REQUEST_ERROR:"KEY_GENERATE_REQUEST_ERROR",INCOMPATIBLE_KEYSYSTEMS:"INCOMPATIBLE_KEYSYSTEMS",INVALID_ENCRYPTED_EVENT:"INVALID_ENCRYPTED_EVENT",INVALID_KEY_SYSTEM:"INVALID_KEY_SYSTEM",LICENSE_SERVER_CERTIFICATE_ERROR:"LICENSE_SERVER_CERTIFICATE_ERROR",MULTIPLE_SESSIONS_SAME_INIT_DATA:"MULTIPLE_SESSIONS_SAME_INIT_DATA",BUFFER_APPEND_ERROR:"BUFFER_APPEND_ERROR",BUFFER_FULL_ERROR:"BUFFER_FULL_ERROR",BUFFER_TYPE_UNKNOWN:"BUFFER_TYPE_UNKNOWN",MEDIA_ERR_BLOCKED_AUTOPLAY:"MEDIA_ERR_BLOCKED_AUTOPLAY",MEDIA_ERR_PLAY_NOT_ALLOWED:"MEDIA_ERR_PLAY_NOT_ALLOWED",MEDIA_ERR_NOT_LOADED_METADATA:"MEDIA_ERR_NOT_LOADED_METADATA",MEDIA_ERR_ABORTED:"MEDIA_ERR_ABORTED",MEDIA_ERR_NETWORK:"MEDIA_ERR_NETWORK",MEDIA_ERR_DECODE:"MEDIA_ERR_DECODE",MEDIA_ERR_SRC_NOT_SUPPORTED:"MEDIA_ERR_SRC_NOT_SUPPORTED",MEDIA_ERR_UNKNOWN:"MEDIA_ERR_UNKNOWN",MEDIA_SOURCE_NOT_SUPPORTED:"MEDIA_SOURCE_NOT_SUPPORTED",MEDIA_KEYS_NOT_SUPPORTED:"MEDIA_KEYS_NOT_SUPPORTED",DISCONTINUITY_ENCOUNTERED:"DISCONTINUITY_ENCOUNTERED",NONE:"NONE"};function ct(n,e){return`${n}: ${e}`}var pe=class n extends Error{constructor(e,t,r){super(ct(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="EncryptedMediaError",this.type=Je.ENCRYPTED_MEDIA_ERROR,this.code=e,this._originalMessage=t,this.fatal=!1,typeof(r==null?void 0:r.keyStatuses)=="string"&&(this.keyStatuses=r.keyStatuses)}serialize(){return{name:this.name,code:this.code,reason:this._originalMessage,keyStatuses:this.keyStatuses}}};var te=class n extends Error{constructor(e,t,r){super(ct(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="MediaError",this.type=Je.MEDIA_ERROR,this._originalMessage=t,this.code=e,this.fatal=!1,(r==null?void 0:r.tracks)!==void 0&&(r==null?void 0:r.tracks.length)>0&&(this.tracksInfo=r.tracks)}serialize(){return{name:this.name,code:this.code,reason:this._originalMessage,tracks:this.tracksInfo}}};var it=class n extends Error{constructor(e,t){super(ct(e,t.message)),Object.setPrototypeOf(this,n.prototype),this.name="NetworkError",this.type=Je.NETWORK_ERROR,this.url=t.url,this.status=t.status,this.errorType=t.type,this._baseError=t,this.code=e,this.fatal=!1}isHttpError(e){return this.errorType===fn.ERROR_HTTP_CODE&&this.status===e}serialize(){return{name:this.name,code:this.code,baseError:this._baseError.serialize()}}};var Le=class n extends Error{constructor(e,t){super(ct(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="OtherError",this.type=Je.OTHER_ERROR,this.code=e,this.fatal=!1,this._originalMessage=t}serialize(){return{name:this.name,code:this.code,reason:this._originalMessage}}};function Gt(n){return(n instanceof pe||n instanceof te||n instanceof Le||n instanceof it)&&Object.keys(Je).indexOf(n.type)>=0}function Oe(n,{defaultCode:e,defaultReason:t}){if(Gt(n))return n;let r=n instanceof Error?n.toString():t;return new Le(e,r)}var ot=class n extends Error{constructor(e,t,r){super(t),Object.setPrototypeOf(this,n.prototype),this.name="SourceBufferError",this.errorName=e,this.isBufferFull=r}serialize(){return{errorName:this.name,message:this.message,isBufferFull:this.isBufferFull}}toString(){return`${this.errorName}: ${this.message}`}};var Qp={aa:"aar",ab:"abk",ae:"ave",af:"afr",ak:"aka",am:"amh",an:"arg",ar:"ara",as:"asm",av:"ava",ay:"aym",az:"aze",ba:"bak",be:"bel",bg:"bul",bi:"bis",bm:"bam",bn:"ben",bo:"bod",br:"bre",bs:"bos",ca:"cat",ce:"che",ch:"cha",co:"cos",cr:"cre",cs:"ces",cu:"chu",cv:"chv",cy:"cym",da:"dan",de:"deu",dv:"div",dz:"dzo",ee:"ewe",el:"ell",en:"eng",eo:"epo",es:"spa",et:"est",eu:"eus",fa:"fas",ff:"ful",fi:"fin",fj:"fij",fo:"fao",fr:"fra",fy:"fry",ga:"gle",gd:"gla",gl:"glg",gn:"grn",gu:"guj",gv:"glv",ha:"hau",he:"heb",hi:"hin",ho:"hmo",hr:"hrv",ht:"hat",hu:"hun",hy:"hye",hz:"her",ia:"ina",id:"ind",ie:"ile",ig:"ibo",ii:"iii",ik:"ipk",io:"ido",is:"isl",it:"ita",iu:"iku",ja:"jpn",jv:"jav",ka:"kat",kg:"kon",ki:"kik",kj:"kua",kk:"kaz",kl:"kal",km:"khm",kn:"kan",ko:"kor",kr:"kau",ks:"kas",ku:"kur",kv:"kom",kw:"cor",ky:"kir",la:"lat",lb:"ltz",lg:"lug",li:"lim",ln:"lin",lo:"lao",lt:"lit",lu:"lub",lv:"lav",mg:"mlg",mh:"mah",mi:"mri",mk:"mkd",ml:"mal",mn:"mon",mr:"mar",ms:"msa",mt:"mlt",my:"mya",na:"nau",nb:"nob",nd:"nde",ne:"nep",ng:"ndo",nl:"nld",nn:"nno",no:"nor",nr:"nbl",nv:"nav",ny:"nya",oc:"oci",oj:"oji",om:"orm",or:"ori",os:"oss",pa:"pan",pi:"pli",pl:"pol",ps:"pus",pt:"por",qu:"que",rm:"roh",rn:"run",ro:"ron",ru:"rus",rw:"kin",sa:"san",sc:"srd",sd:"snd",se:"sme",sg:"sag",si:"sin",sk:"slk",sl:"slv",sm:"smo",sn:"sna",so:"som",sq:"sqi",sr:"srp",ss:"ssw",st:"sot",su:"sun",sv:"swe",sw:"swa",ta:"tam",te:"tel",tg:"tgk",th:"tha",ti:"tir",tk:"tuk",tl:"tgl",tn:"tsn",to:"ton",tr:"tur",ts:"tso",tt:"tat",tw:"twi",ty:"tah",ug:"uig",uk:"ukr",ur:"urd",uz:"uzb",ve:"ven",vi:"vie",vo:"vol",wa:"wln",wo:"wol",xh:"xho",yi:"yid",yo:"yor",za:"zha",zh:"zho",zu:"zul"},uc=Qp;var Xp={alb:"sqi",arm:"hye",baq:"eus",bur:"mya",chi:"zho",cze:"ces",dut:"nld",fre:"fra",geo:"kat",ger:"deu",gre:"ell",ice:"isl",mac:"mkd",mao:"mri",may:"msa",per:"fas",slo:"slk",rum:"ron",tib:"bod",wel:"cym"},lc=Xp;function Zp(n){if(_(n)||n==="")return"und";let t=(""+n).toLowerCase().split("-")[0],r=Jp(t);return w(r)?r:n}function Jp(n){let e;switch(n.length){case 2:e=uc[n];break;case 3:e=lc[n];break}return e}var cc=Zp;var Rr=cc;function ge(n,e){if(n.length!==e.length)return!1;if(n===e)return!0;for(let t=n.length-1;t>=0;t--)if(n[t]!==e[t])return!1;return!0}function et(){let n="",e=-1;return function(){return e++,e>=Number.MAX_SAFE_INTEGER&&(n+="0",e=0),n+String(e)}}var eg=et(),is=class{constructor(e,t,r){var o,a,s,d,u;this.id=e.id,this.uniqueId=eg(),this.bitrate=e.bitrate,this.codecs=[],this.trackType=t,e.isSpatialAudio!==void 0&&(this.isSpatialAudio=e.isSpatialAudio),e.height!==void 0&&(this.height=e.height),e.width!==void 0&&(this.width=e.width),e.mimeType!==void 0&&(this.mimeType=e.mimeType),e.contentProtections!==void 0&&(this.contentProtections=e.contentProtections),e.frameRate!==void 0&&(this.frameRate=e.frameRate),e.hdrInfo!==void 0&&(this.hdrInfo=e.hdrInfo),this.cdnMetadata=e.cdnMetadata,this.index=e.index;let i=this.contentProtections!==void 0;if(t==="audio"||t==="video"){if(e.supplementalCodecs!==void 0){let l=r.isSupported((o=this.mimeType)!=null?o:"",(a=e.supplementalCodecs)!=null?a:"",i);l!==!1&&(this.codecs=[e.supplementalCodecs],this.isSupported=l)}this.isSupported!==!0&&(this.codecs.length>0?this.codecs.push((s=e.codecs)!=null?s:""):(this.codecs=e.codecs===void 0?[]:[e.codecs],this.isSupported=r.isSupported((d=this.mimeType)!=null?d:"",(u=e.codecs)!=null?u:"",i)))}else e.codecs!==void 0&&this.codecs.push(e.codecs),this.isSupported=!0}refreshCodecSupport(e){var s,d;if(this.isSupported!==void 0)return;let t=this.contentProtections!==void 0,r=!1,i=(s=this.mimeType)!=null?s:"",o=(d=this.codecs)!=null?d:[];o.length===0&&(o=[""]);let a=!1;for(let u of o){if(r=e.isSupported(i,u,t),r===!0){this.codecs=[u];break}r===void 0&&(a=!0)}r===!0?this.isSupported=!0:a?this.isSupported=void 0:this.isSupported=!1}getMimeTypeString(){var e,t,r;return`${(e=this.mimeType)!=null?e:""};codecs="${(r=(t=this.codecs)==null?void 0:t[0])!=null?r:""}"`}getEncryptionData(e){var i;let t=this.getAllEncryptionData(),r=[];for(let o=0;o<t.length;o++){let a=!1,s=t[o];for(let d=0;d<s.values.length;d++)if(s.values[d].systemId.toLowerCase()===e.toLowerCase())if(a)r[r.length-1].values.push(s.values[d]);else{let u=(i=this.contentProtections)==null?void 0:i.keyIds;r.push({type:s.type,keyIds:u,values:[s.values[d]]}),a=!0}}return r}getAllEncryptionData(){var t;if(this.contentProtections===void 0||this.contentProtections.initData.length===0)return[];let e=(t=this.contentProtections)==null?void 0:t.keyIds;return this.contentProtections.initData.map(r=>({type:r.type,keyIds:e,values:r.values}))}addProtectionData(e,t,r){let i=!1;if(this.contentProtections===void 0)return this.contentProtections={keyIds:t!==void 0?[t]:[],initData:[{type:e,values:r}]},!0;if(t!==void 0){let a=this.contentProtections.keyIds;if(a===void 0)this.contentProtections.keyIds=[t];else{let s=!1;for(let d of a)ge(d,t)&&(s=!0);s||(m.warn("Manifest: found unanounced key id."),a.push(t))}}let o=this.contentProtections.initData;for(let a=0;a<o.length;a++)if(o[a].type===e){let s=o[a].values;for(let d=0;d<r.length;d++){let u=r[d],l;for(l=0;l<s.length;l++)if(u.systemId===s[l].systemId){if(ge(u.data,s[l].data))break;m.warn("Manifest: different init data for the same system ID")}l===s.length&&(s.push(u),i=!0)}return i}return this.contentProtections.initData.push({type:e,values:r}),!0}getMetadataSnapshot(){return{id:this.id,uniqueId:this.uniqueId,bitrate:this.bitrate,codecs:this.codecs,mimeType:this.mimeType,width:this.width,height:this.height,frameRate:this.frameRate,isSupported:this.isSupported,hdrInfo:this.hdrInfo,contentProtections:this.contentProtections,decipherable:this.decipherable}}},fc=is;var kr=class n{constructor(e,t,r={}){let{trickModeTracks:i}=e,{representationFilter:o,isManuallyAdded:a}=r;this.id=e.id,this.type=e.type,e.isTrickModeTrack!==void 0&&(this.isTrickModeTrack=e.isTrickModeTrack),e.language!==void 0&&(this.language=e.language,this.normalizedLanguage=Rr(e.language)),e.closedCaption!==void 0&&(this.isClosedCaption=e.closedCaption),e.audioDescription!==void 0&&(this.isAudioDescription=e.audioDescription),e.isDub!==void 0&&(this.isDub=e.isDub),e.forcedSubtitles!==void 0&&(this.isForcedSubtitles=e.forcedSubtitles),e.isSignInterpreted!==void 0&&(this.isSignInterpreted=e.isSignInterpreted),e.label!==void 0&&(this.label=e.label),i!==void 0&&i.length>0&&(this.trickModeTracks=i.map(u=>new n(u,t)));let s=e.representations,d=[];this.supportStatus={hasSupportedCodec:!1,hasCodecWithUndefinedSupport:!1,isDecipherable:!1};for(let u=0;u<s.length;u++){let l=new fc(s[u],this.type,t),c=!0;if(!_(o)){let f={id:l.id,bitrate:l.bitrate,codecs:l.codecs,height:l.height,width:l.width,frameRate:l.frameRate,hdrInfo:l.hdrInfo};if(l.contentProtections!==void 0&&(f.contentProtections={},l.contentProtections.keyIds!==void 0)){let g=l.contentProtections.keyIds;f.contentProtections.keyIds=g}c=o(f,{trackType:this.type,language:this.language,normalizedLanguage:this.normalizedLanguage,isClosedCaption:this.isClosedCaption,isDub:this.isDub,isAudioDescription:this.isAudioDescription,isSignInterpreted:this.isSignInterpreted})}c?(d.push(l),l.isSupported===void 0?(this.supportStatus.hasCodecWithUndefinedSupport=!0,this.supportStatus.hasSupportedCodec===!1&&(this.supportStatus.hasSupportedCodec=void 0)):l.isSupported&&(this.supportStatus.hasSupportedCodec=!0),l.decipherable===void 0?this.supportStatus.isDecipherable===!1&&(this.supportStatus.isDecipherable=void 0):l.decipherable&&(this.supportStatus.isDecipherable=!0)):m.debug("Filtering Representation due to representationFilter",this.type,`Adaptation: ${this.id}`,`Representation: ${l.id}`,`(${l.bitrate})`)}d.sort((u,l)=>u.bitrate-l.bitrate),this.representations=d,this.manuallyAdded=a===!0}refreshCodecSupport(e){let t=!1,r=!1;for(let i of this.representations)i.refreshCodecSupport(e),i.isSupported===void 0?t=!0:i.isSupported&&(r=!0);r?this.supportStatus.hasSupportedCodec=!0:t?this.supportStatus.hasSupportedCodec=void 0:this.supportStatus.hasSupportedCodec=!1,this.supportStatus.hasCodecWithUndefinedSupport=t}getRepresentation(e){return Z(this.representations,({id:t})=>e===t)}getMetadataSnapshot(){let e=[],t=this.representations;for(let r of t)e.push(r.getMetadataSnapshot());return{id:this.id,type:this.type,supportStatus:this.supportStatus,language:this.language,isForcedSubtitles:this.isForcedSubtitles,isClosedCaption:this.isClosedCaption,isAudioDescription:this.isAudioDescription,isSignInterpreted:this.isSignInterpreted,normalizedLanguage:this.normalizedLanguage,representations:e,label:this.label,isDub:this.isDub}}};function os(){return sn}function mn(n){return new Promise(e=>{setTimeout(e,n)})}function as(){return ur}function Cr(n,e,t){let r=n.setMediaKeys(e,t).then(()=>{m.info("Compat: MediaKeys updated with success")}).catch(i=>{if(t===null){m.error("Compat: Could not reset MediaKeys",i instanceof Error?i:"Unknown Error");return}throw m.error("Compat: Could not update MediaKeys",i instanceof Error?i:"Unknown Error"),i});return as()?r:Promise.race([r,mn(1e3)])}var ss=new WeakMap,Ke={setState(n,e){ss.set(n,e)},getState(n){let e=ss.get(n);return e===void 0?null:e},clearState(n){ss.set(n,null)}};async function Dn(n){let e=Ke.getState(n);if(e===null)return;m.info("DRM: Disposing of the current MediaKeys");let{loadedSessionsStore:t}=e;return Ke.clearState(n),await t.closeAllSessions(),Cr(e.emeImplementation,n,null)}function _o(n){if(m.info("DRM: Clearing-up DRM session."),os())return m.info("DRM: disposing current MediaKeys."),Dn(n);let e=Ke.getState(n);return e!==null&&e.keySystemOptions.closeSessionsOnStop===!0?(m.info("DRM: closing all current sessions."),e.loadedSessionsStore.closeAllSessions()):(m.info("DRM: Nothing to clear. Returning right away. No state =",e===null),Promise.resolve())}function at(n,e){let t;return new Promise((r,i)=>{if(n.cancellationError!==null)return i(n.cancellationError);let o=!1;t=e(function(d){n.deregister(a),o=!0,r(d)},function(d){n.deregister(a),o=!0,i(d)}),o||n.register(a);function a(s){t!==void 0&&t(),i(s)}})}function qt(n,e){return at(e,t=>{let r=setTimeout(()=>t(),n);return()=>clearTimeout(r)})}function Eo(n){let e=new B;return Promise.race([n.close().then(()=>{e.cancel()}),n.closed.then(()=>{e.cancel()}),t()]);async function t(){try{await qt(1e3,e.signal),await r()}catch(i){if(i instanceof Me)return;let o=i instanceof Error?i.message:"Unknown error made it impossible to close the session";m.error(`DRM: ${o}`)}}async function r(){try{await n.update(new Uint8Array(1))}catch(i){if(e.isUsed()||i instanceof Error&&i.message==="The session is already closed.")return;await qt(1e3,e.signal)}if(!e.isUsed())throw new Error("Compat: Couldn't know if session is closed")}}var tg=["","webkit","moz","ms"];function ng(n,e){let t=document.createElement(n.tagName),r="on"+e;return r in t?!0:(t.setAttribute(r,"return;"),typeof t[r]=="function")}function rg(n,e){return e.filter(t=>ng(n,t))[0]}function ig(n,e){return n.reduce((t,r)=>t.concat((e===void 0?tg:e).map(i=>i+r)),[])}function _e(n,e){let t,r=ig(n,e);return(i,o,a)=>{if(!a.isCancelled()){if(typeof HTMLElement!="undefined"&&i instanceof HTMLElement)if(typeof t=="undefined"&&(t=rg(i,r)),w(t))i.addEventListener(t,o),a.register(()=>{t!==void 0&&i.removeEventListener(t,o)});else{h.CURRENT_ENV===h.DEV&&m.warn(`compat: element ${i.tagName} does not support any of these events: `+r.join(", "));return}r.forEach(s=>{let d=!1;typeof i.addEventListener=="function"?i.addEventListener(s,o):(d=!0,i["on"+s]=o),a.register(()=>{typeof i.removeEventListener=="function"&&i.removeEventListener(s,o),d&&delete i["on"+s]})})}}}function og(n){let e,t=document;_(t.hidden)?_(t.mozHidden)?_(t.msHidden)?_(t.webkitHidden)||(e="webkit"):e="ms":e="moz":e="";let r=w(e)?e+"Hidden":"hidden",i=w(e)?e+"visibilitychange":"visibilitychange",o=document[r],a=new H(!o,n);return pn(document,i,()=>{let s=!document[r];a.setValueIfChanged(s)},n),a}function mc(n,e){if(n.webkitSupportsPresentationMode===!0&&typeof n.webkitSetPresentationMode=="function"){let i=n.webkitPresentationMode==="picture-in-picture",o=new H({isEnabled:i,pipWindow:null},e);return pn(n,"webkitpresentationmodechanged",()=>{let a=n.webkitPresentationMode==="picture-in-picture";o.setValue({isEnabled:a,pipWindow:null})},e),o}let t=document.pictureInPictureElement===n,r=new H({isEnabled:t,pipWindow:null},e);return pn(n,"enterpictureinpicture",i=>{var o;r.setValue({isEnabled:!0,pipWindow:(o=i.pictureInPictureWindow)!=null?o:null})},e),pn(n,"leavepictureinpicture",()=>{r.setValue({isEnabled:!1,pipWindow:null})},e),r}function pc(n,e){let t=og(e),r,i=new H(!0,e);return e.register(()=>{clearTimeout(r),r=void 0}),t.onUpdate(o,{clearSignal:e}),n.onUpdate(o,{clearSignal:e}),o(),i;function o(){if(clearTimeout(r),r=void 0,n.getValue().isEnabled||t.getValue())i.setValueIfChanged(!0);else{let{INACTIVITY_DELAY:a}=U.getCurrent();r=setTimeout(()=>{i.setValueIfChanged(!1)},a)}}}function gc(n){var o,a;let e=_(J.devicePixelRatio)||J.devicePixelRatio===0?1:J.devicePixelRatio,t=new H({width:(o=J.screen)==null?void 0:o.width,height:(a=J.screen)==null?void 0:a.height,pixelRatio:e},n),r=setInterval(i,2e4);return n.register(function(){clearInterval(r)}),t;function i(){let s=t.getValue();(s.width!==screen.width||s.height!==screen.height||s.pixelRatio!==e)&&t.setValue({width:screen.width,height:screen.height,pixelRatio:e})}}function hc(n,e,t){let r=_(J.devicePixelRatio)||J.devicePixelRatio===0?1:J.devicePixelRatio,i=new H({width:n.clientWidth,height:n.clientHeight,pixelRatio:r},t),o=X;e.onUpdate(s,{clearSignal:t}),pn(J,"resize",s,t),pn(n,"enterpictureinpicture",s,t),pn(n,"leavepictureinpicture",s,t);let a=setInterval(s,2e4);return s(),t.register(function(){o(),clearInterval(a)}),i;function s(){o();let d=e.getValue(),{pipWindow:u}=d;if(d.isEnabled)if(_(u)){let c=i.getValue();(c.width!==void 0||c.height!==void 0||c.pixelRatio!==r)&&i.setValue({width:void 0,height:void 0,pixelRatio:r})}else{let c=()=>{l()};u.addEventListener("resize",c),o=()=>{u.removeEventListener("resize",c),o=X},l()}else{let c=i.getValue();(c.width!==n.clientWidth||c.height!==n.clientHeight||c.pixelRatio!==r)&&i.setValue({width:n.clientWidth,height:n.clientHeight,pixelRatio:r})}function l(){let c=i.getValue();(c.width!==(u==null?void 0:u.width)||c.height!==(u==null?void 0:u.height)||c.pixelRatio!==r)&&i.setValue({width:u==null?void 0:u.width,height:u==null?void 0:u.height,pixelRatio:r})}}}var $k=_e(["loadedmetadata"]),Qk=_e(["timeupdate"]),Xk=_e(["addtrack"]),Zk=_e(["removetrack"]),Ln=_e(["sourceopen","webkitsourceopen"]),vo=_e(["sourceclose","webkitsourceclose"]),Ro=_e(["sourceended","webkitsourceended"]),yc=_e(["update"]),Ic=_e(["removesourcebuffer"]),ko=_e(["keymessage","message"]),bc=_e(["keyadded","ready"]),Co=_e(["keyerror","error"]),Sc=_e(["keystatuseschange"]),Tc=_e(["seeking"]),_c=_e(["seeked"]),Ec=_e(["ended"]);function pn(n,e,t,r){n.addEventListener(e,t),r.register(()=>{n.removeEventListener(e,t)})}var ft,{WebKitMediaKeys:Po}=J;Po!==void 0&&typeof Po.isTypeSupported=="function"&&typeof Po.prototype.createSession=="function"&&typeof HTMLMediaElement.prototype.webkitSetMediaKeys=="function"&&(ft=Po);function ds(){return(Ba||un)&&ft!==void 0}var Pr=class{constructor(e,t,r){this._keyType=e;this._mediaKeys=t;this._configuration=r}get keySystem(){return this._keyType}createMediaKeys(){return new Promise(e=>e(this._mediaKeys))}getConfiguration(){return this._configuration}};function Rt(n){try{let e=n();return typeof e=="object"&&e!==null&&typeof e.then=="function"?e:Promise.resolve(e)}catch(e){return Promise.reject(e)}}var kt,{MSMediaKeys:Mr}=J;Mr!==void 0&&Mr.prototype!==void 0&&typeof Mr.isTypeSupported=="function"&&typeof Mr.prototype.createSession=="function"&&(kt=Mr);var us=class extends re{constructor(e){super(),this.expiration=NaN,this.keyStatuses=new Map,this._mk=e,this._sessionClosingCanceller=new B,this.closed=new Promise(t=>{this._sessionClosingCanceller.signal.register(()=>t())}),this.update=t=>new Promise((r,i)=>{if(this._ss===void 0)return i("MediaKeySession not set.");try{r(this._ss.update(t,""))}catch(o){i(o)}})}generateRequest(e,t){return new Promise(r=>{let i;t instanceof Uint8Array?i=t:t instanceof ArrayBuffer?i=new Uint8Array(t):i=new Uint8Array(t.buffer),this._ss=this._mk.createSession("video/mp4",i),ko(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"message",o)},this._sessionClosingCanceller.signal),bc(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"keyadded",o)},this._sessionClosingCanceller.signal),Co(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"keyerror",o)},this._sessionClosingCanceller.signal),r()})}close(){return new Promise(e=>{_(this._ss)||(this._ss.close(),this._ss=void 0),this._sessionClosingCanceller.cancel(),e()})}load(){return Promise.resolve(!1)}remove(){return Promise.resolve()}get sessionId(){var e,t;return(t=(e=this._ss)==null?void 0:e.sessionId)!=null?t:""}},Mo=class{constructor(e){if(kt===void 0)throw new Error("No MSMediaKeys API.");this._mediaKeys=new kt(e)}_setVideo(e){return Rt(()=>{this._videoElement=e,this._videoElement.msSetMediaKeys!==void 0&&this._videoElement.msSetMediaKeys(this._mediaKeys)})}createSession(){if(this._videoElement===void 0||this._mediaKeys===void 0)throw new Error("Video not attached to the MediaKeys");return new us(this._mediaKeys)}setServerCertificate(){throw new Error("Server certificate is not implemented in your browser")}};function ls(){return{isTypeSupported:(r,i)=>{if(kt===void 0)throw new Error("No MSMediaKeys API.");return i!==void 0?kt.isTypeSupported(r,i):kt.isTypeSupported(r)},createCustomMediaKeys:r=>new Mo(r),setMediaKeys:(r,i)=>{if(i===null)return Promise.resolve(void 0);if(!(i instanceof Mo))throw new Error("Custom setMediaKeys is supposed to be called with IE11 custom MediaKeys.");return i._setVideo(r)}}}var jt,{MozMediaKeys:Ar}=J;Ar!==void 0&&Ar.prototype!==void 0&&typeof Ar.isTypeSupported=="function"&&typeof Ar.prototype.createSession=="function"&&(jt=Ar);function cs(){return{isTypeSupported:(r,i)=>{if(jt===void 0)throw new Error("No MozMediaKeys API.");return i!==void 0?jt.isTypeSupported(r,i):jt.isTypeSupported(r)},createCustomMediaKeys:r=>{if(jt===void 0)throw new Error("No MozMediaKeys API.");return new jt(r)},setMediaKeys:(r,i)=>Rt(()=>{if(r.mozSetMediaKeys===void 0||typeof r.mozSetMediaKeys!="function")throw new Error("Can't set video on MozMediaKeys.");return r.mozSetMediaKeys(i)})}}var Ct=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"],vc=[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,62,255,255,255,63,52,53,54,55,56,57,58,59,60,61,255,255,255,0,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51];function Ao(n){if(n>=vc.length)throw new Error("Unable to parse base64 string.");let e=vc[n];if(e===255)throw new Error("Unable to parse base64 string.");return e}function xo(n){let e="",t,r=n.length;for(t=2;t<r;t+=3)e+=Ct[n[t-2]>>2],e+=Ct[(n[t-2]&3)<<4|n[t-1]>>4],e+=Ct[(n[t-1]&15)<<2|n[t]>>6],e+=Ct[n[t]&63];return t===r+1&&(e+=Ct[n[t-2]>>2],e+=Ct[(n[t-2]&3)<<4],e+="=="),t===r&&(e+=Ct[n[t-2]>>2],e+=Ct[(n[t-2]&3)<<4|n[t-1]>>4],e+=Ct[(n[t-1]&15)<<2],e+="="),e}function mt(n){let e=n.length%4,t=n;e!==0&&(m.warn("base64ToBytes: base64 given miss padding"),t+=e===3?"=":e===2?"==":"===");let r=t.indexOf("=");if(r!==-1&&r<t.length-2)throw new Error("Unable to parse base64 string.");let i=t.endsWith("==")?2:t.endsWith("=")?1:0,o=t.length,a=new Uint8Array(o/4*3),s;for(let d=0,u=0;d<o;d+=4,u+=3)s=Ao(t.charCodeAt(d))<<18|Ao(t.charCodeAt(d+1))<<12|Ao(t.charCodeAt(d+2))<<6|Ao(t.charCodeAt(d+3)),a[u]=s>>16,a[u+1]=s>>8&255,a[u+2]=s&255;return a.subarray(0,a.length-i)}var kc=typeof J=="object"&&typeof J.TextDecoder=="function",sg=typeof J=="object"&&typeof J.TextEncoder=="function";function wo(n){let e=new ArrayBuffer(n.length*2),t=new Uint8Array(e);for(let r=0;r<t.length;r+=2){let i=n.charCodeAt(r/2);t[r]=i&255,t[r+1]=i>>8&255}return t}function Oo(n){if(kc)try{return new TextDecoder("utf-16le").decode(n)}catch(t){let r=t instanceof Error?t:"";m.warn("Utils: could not use TextDecoder to parse UTF-16LE, fallbacking to another implementation",r)}let e="";for(let t=0;t<n.length;t+=2)e+=String.fromCharCode((n[t+1]<<8)+n[t]);return e}function ve(n){if(sg)try{return new TextEncoder().encode(n)}catch(i){let o=i instanceof Error?i:"";m.warn("Utils: could not use TextEncoder to encode string into UTF-8, fallbacking to another implementation",o)}let e,t=encodeURIComponent(n);if(typeof unescape=="function")e=unescape(t);else{let i=/[0-9a-fA-F]/,o=t.length;e="";for(let a=0;a<t.length;a++){let s=!1;if(t[a]==="%"){if(a<=o-6&&t[a+1]==="u"&&i.test(t[a+2])&&i.test(t[a+3])&&i.test(t[a+4])&&i.test(t[a+5])){let d=parseInt(t.substring(a+1,a+6),16);e+=String.fromCharCode(d),s=!0,a+=5}else if(a<=o-3&&i.test(t[a+1])&&i.test(t[a+2])){let d=parseInt(t.substring(a+1,a+3),16);e+=String.fromCharCode(d),s=!0,a+=2}}s||(e+=t[a])}}let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i)&255;return r}function dg(n){let t="";for(let r=0;r<n.length;r+=16e3){let i=n.subarray(r,r+16e3);t+=String.fromCharCode.apply(null,i)}return t}function Rc(n,e){let t=n.toString(16);return t.length>=e?t:new Array(e-t.length+1).join("0")+t}function Ne(n){if(kc)try{return new TextDecoder().decode(n)}catch(i){let o=i instanceof Error?i:"";m.warn("Utils: could not use TextDecoder to parse UTF-8, fallbacking to another implementation",o)}let e=n;e[0]===239&&e[1]===187&&e[2]===191&&(e=e.subarray(3));let t=dg(e),r;if(typeof escape=="function")r=escape(t);else{let i=/[A-Za-z0-9*_\+-\.\/]/;r="";for(let o=0;o<t.length;o++)if(i.test(t[o]))r+=t[o];else{let a=t.charCodeAt(o);r+=a>=256?"%u"+Rc(a,4):"%"+Rc(a,2)}}return decodeURIComponent(r)}function je(n){let e=n.length,t=new Uint8Array(e/2);for(let r=0,i=0;r<e;r+=2,i++)t[i]=parseInt(n.substring(r,r+2),16)&255;return t}function Ue(n,e=""){let t="";for(let r=0;r<n.byteLength;r++)t+=(n[r]>>>4).toString(16),t+=(n[r]&15).toString(16),e.length>0&&r<n.byteLength-1&&(t+=e);return t}function Do(n){ee(n.length===16,"GUID length should be 16");let e=n[0],t=n[1],r=n[2],i=n[3],o=n[4],a=n[5],s=n[6],d=n[7],u=new Uint8Array(16);return u[0]=i,u[1]=r,u[2]=t,u[3]=e,u[4]=a,u[5]=o,u[6]=d,u[7]=s,u.set(n.subarray(8,16),8),u}function fs(n,e){let t=e;for(;t<n.length&&n[t]!==0;)t+=1;let r=n.subarray(e,t);return{end:t+1,string:Ne(r)}}function ps(n){return typeof(n==null?void 0:n.webkitGenerateKeyRequest)=="function"}var ms=class extends re{constructor(e,t){super(),this._vid=e,this._key=t,this.sessionId="",this._closeSession=X,this.keyStatuses=new Map,this.expiration=NaN;let r=i=>{this.trigger(i.type,i)};this.closed=new Promise(i=>{this._closeSession=()=>{["keymessage","message","keyadded","ready","keyerror","error"].forEach(o=>{e.removeEventListener(o,r),e.removeEventListener(`webkit${o}`,r)}),i()}}),["keymessage","message","keyadded","ready","keyerror","error"].forEach(i=>{e.addEventListener(i,r),e.addEventListener(`webkit${i}`,r)})}update(e){return new Promise((t,r)=>{try{if(this._key.indexOf("clearkey")>=0){let i=e instanceof ArrayBuffer?new Uint8Array(e):e,o=JSON.parse(Ne(i)),a=mt(o.keys[0].k),s=mt(o.keys[0].kid);t(this._vid.webkitAddKey(this._key,a,s,""))}else t(this._vid.webkitAddKey(this._key,e,null,""))}catch(i){r(i)}})}generateRequest(e,t){return new Promise(r=>{this._vid.webkitGenerateKeyRequest(this._key,t),r()})}close(){return new Promise(e=>{this._closeSession(),e()})}load(){return Promise.resolve(!1)}remove(){return Promise.resolve()}},Lo=class{constructor(e){this._keySystem=e}_setVideo(e){return Rt(()=>{if(!ps(e))throw new Error("Video not attached to the MediaKeys");this._videoElement=e})}createSession(){if(_(this._videoElement))throw new Error("Video not attached to the MediaKeys");return new ms(this._videoElement,this._keySystem)}setServerCertificate(){throw new Error("Server certificate is not implemented in your browser")}};function gs(){return{isTypeSupported:function(r){let i=document.querySelector("video");return _(i)&&(i=document.createElement("video")),!_(i)&&typeof i.canPlayType=="function"?!!i.canPlayType("video/mp4",r):!1},createCustomMediaKeys:r=>new Lo(r),setMediaKeys:(r,i)=>{if(i===null)return Promise.resolve(void 0);if(!(i instanceof Lo))throw new Error("Custom setMediaKeys is supposed to be called with old webkit custom MediaKeys.");return i._setVideo(r)}}}function ie(...n){let e=n.length,t=-1,r=0,i;for(;++t<e;)i=n[t],r+=typeof i=="number"?i:i.length;let o=new Uint8Array(r),a=0;for(t=-1;++t<e;)i=n[t],typeof i=="number"?a+=i:i.length>0&&(o.set(i,a),a+=i.length);return o}function No(n,e){return(n[e+0]<<8)+(n[e+1]<<0)}function hs(n,e){return n[e+0]*65536+n[e+1]*256+n[e+2]}function ne(n,e){return n[e+0]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3]}function Ve(n,e){return(n[e+0]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3])*4294967296+n[e+4]*16777216+n[e+5]*65536+n[e+6]*256+n[e+7]}function fe(n){return new Uint8Array([n>>>8&255,n&255])}function Ie(n){return new Uint8Array([n>>>24&255,n>>>16&255,n>>>8&255,n&255])}function Yt(n){let e=n%4294967296,t=(n-e)/4294967296;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255])}function Cc(n,e){return(n[e+0]<<0)+(n[e+1]<<8)}function Pc(n,e){return n[e+0]+n[e+1]*256+n[e+2]*65536+n[e+3]*16777216}function Mc(n){return new Uint8Array([n&255,n>>>8&255])}function xr(n){return new Uint8Array([n&255,n>>>8&255,n>>>16&255,n>>>24&255])}function ys(n,e){let t=n instanceof Uint8Array?n:new Uint8Array(n),r=e instanceof Uint8Array?e:new Uint8Array(e);if(Pc(t,0)+4!==t.length)throw new Error("Unsupported WebKit initData.");let o=Oo(t),a=o.indexOf("skd://"),s=a>-1?o.substring(a+6):o,d=wo(s),u=0,l=new Uint8Array(t.byteLength+4+d.byteLength+4+r.byteLength);return l.set(t),u+=t.length,l.set(xr(d.byteLength),u),u+=4,l.set(d,u),u+=d.byteLength,l.set(xr(r.byteLength),u),u+=4,l.set(r,u),l}function ug(n){return Ze(n,"com.apple.fps")}function Ac(n,e){return Rt(()=>{if(n.webkitSetMediaKeys===void 0)throw new Error("No webKitMediaKeys API.");n.webkitSetMediaKeys(e)})}var Is=class extends re{constructor(e,t,r){super(),this._serverCertificate=r,this._videoElement=e,this._keyType=t,this._unbindSession=X,this._closeSession=X,this.closed=new Promise(i=>{this._closeSession=i}),this.keyStatuses=new Map,this.expiration=NaN}update(e){return new Promise((t,r)=>{if(this._nativeSession===void 0||this._nativeSession.update===void 0||typeof this._nativeSession.update!="function")return r("Unavailable WebKit key session.");try{let i;e instanceof ArrayBuffer?i=new Uint8Array(e):e instanceof Uint8Array?i=e:i=new Uint8Array(e.buffer),t(this._nativeSession.update(i))}catch(i){r(i)}})}generateRequest(e,t){return new Promise(r=>{var s;let i=this._videoElement;if(((s=i.webkitKeys)==null?void 0:s.createSession)===void 0)throw new Error("No WebKitMediaKeys API.");let o;if(ug(this._keyType)){if(this._serverCertificate===void 0)throw new Error("A server certificate is needed for creating fairplay session.");o=ys(t,this._serverCertificate)}else o=t;let a=i.webkitKeys.createSession("video/mp4",o);if(a==null)throw new Error("Impossible to get the key sessions");this._listenEvent(a),this._nativeSession=a,r()})}close(){return new Promise((e,t)=>{if(this._unbindSession(),this._closeSession(),this._nativeSession===void 0){t("No session to close.");return}this._nativeSession.close(),e()})}load(){return Promise.resolve(!1)}remove(){return Promise.resolve()}get sessionId(){var e,t;return(t=(e=this._nativeSession)==null?void 0:e.sessionId)!=null?t:""}_listenEvent(e){this._unbindSession();let t=r=>{this.trigger(r.type,r)};["keymessage","message","keyadded","ready","keyerror","error"].forEach(r=>{e.addEventListener(r,t),e.addEventListener(`webkit${r}`,t)}),this._unbindSession=()=>{["keymessage","message","keyadded","ready","keyerror","error"].forEach(r=>{e.removeEventListener(r,t),e.removeEventListener(`webkit${r}`,t)})}}},Uo=class{constructor(e){if(ft===void 0)throw new Error("No WebKitMediaKeys API.");this._keyType=e,this._mediaKeys=new ft(e)}_setVideo(e){if(this._videoElement=e,this._videoElement===void 0)throw new Error("Video not attached to the MediaKeys");return Ac(this._videoElement,this._mediaKeys)}createSession(){if(this._videoElement===void 0||this._mediaKeys===void 0)throw new Error("Video not attached to the MediaKeys");return new Is(this._videoElement,this._keyType,this._serverCertificate)}setServerCertificate(e){return this._serverCertificate=e,Promise.resolve()}};function Bo(){if(ft===void 0)throw new Error("No WebKitMediaKeys API.");return{isTypeSupported:ft.isTypeSupported,createCustomMediaKeys:r=>new Uo(r),setMediaKeys:(r,i)=>{if(i===null)return Ac(r,i);if(!(i instanceof Uo))throw new Error("Custom setMediaKeys is supposed to be called with webkit custom MediaKeys.");return i._setVideo(r)}}}var lg=cg("auto"),wc=lg;function cg(n){var o;let e,t,r=fg,i;if((n==="standard"||n==="auto"&&!ds())&&(zt||!_(navigator.requestMediaKeySystemAccess)))e=(...a)=>navigator.requestMediaKeySystemAccess(...a),t=_e(["encrypted"]),i="standard";else{let a,s;if(n==="webkit"&&ft!==void 0){let d=Bo();t=xc(),a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="webkit"}else if(ps((o=J.HTMLVideoElement)==null?void 0:o.prototype)){t=_e(["needkey"]);let d=gs();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="older-webkit"}else if(ft!==void 0){t=xc();let d=Bo();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="webkit"}else if(sn&&kt!==void 0){t=_e(["encrypted","needkey"]);let d=ls();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="ms"}else if(jt!==void 0){t=_e(["encrypted","needkey"]);let d=cs();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="moz"}else{t=_e(["encrypted","needkey"]);let d=J.MediaKeys,u=()=>{if(d===void 0)throw new te("MEDIA_KEYS_NOT_SUPPORTED","No `MediaKeys` implementation found in the current browser.");if(typeof d.isTypeSupported=="undefined"){let l="This browser seems to be unable to play encrypted contents currently.Note: Some browsers do not allow decryption in some situations, like when not using HTTPS.";throw new Error(l)}};a=l=>(u(),ee(typeof d.isTypeSupported=="function"),d.isTypeSupported(l)),s=l=>(u(),new d(l)),i="unknown"}e=function(d,u){if(!a(d))return Promise.reject(new Error("Unsupported key type"));for(let l=0;l<u.length;l++){let c=u[l],{videoCapabilities:f,audioCapabilities:g,initDataTypes:p,distinctiveIdentifier:I}=c,y=!0;if(y=y&&(_(p)||p.some(b=>b==="cenc")),y=y&&I!=="required",y){let b={initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",persistentState:"required",sessionTypes:["temporary","persistent-license"]};f!==void 0&&(b.videoCapabilities=f),g!==void 0&&(b.audioCapabilities=g);let T=s(d);return Promise.resolve(new Pr(d,T,b))}}return Promise.reject(new Error("Unsupported configuration"))}}return{requestMediaKeySystemAccess:e,onEncrypted:t,setMediaKeys:r,implementation:i}}function xc(){let n=_e(["needkey"],void 0);return(t,r,i)=>{n(t,o=>{let a=G(o,{forceSessionRecreation:!0});r(a)},i)}}function fg(n,e){try{let t;return typeof n.setMediaKeys=="function"?t=n.setMediaKeys(e):typeof n.webkitSetMediaKeys=="function"?t=n.webkitSetMediaKeys(e):typeof n.mozSetMediaKeys=="function"?t=n.mozSetMediaKeys(e):typeof n.msSetMediaKeys=="function"&&e!==null&&(t=n.msSetMediaKeys(e)),typeof t=="object"&&t!==null&&typeof t.then=="function"?t:Promise.resolve(t)}catch(t){return Promise.reject(t)}}function It(n,e){let t=n.length,r=0;for(;r+8<=t;){let i=ne(n,r);if(i===0)i=t-r;else if(i===1){if(r+16>t)return-1;i=Ve(n,r+8)}if(isNaN(i)||i<=0)return-1;if(ne(n,r+4)===e)return r+i<=t?r:-1;r+=i}return-1}function Fo(n){let e=0,t=[],r=null;for(;e<=n.length;){if(e===n.length){r=null;break}r=n.subarray(e,1/0);let i=It(r,1836019558);if(i<0)break;let o=ne(n,i+e),a=e+i+o;if(a>n.length)break;let s=It(r,1835295092);if(s<0)break;let d=ne(n,s+e),u=e+s+d;if(u>n.length)break;let l=Math.max(a,u),c=n.subarray(e,l);t.push(c),e=l}return t.length===0?[null,r]:[t,r]}function mg(n,e,t){return new Uint8Array(Array.prototype.slice.call(n,e,t))}function pg(n,e,t){return n.slice(e,t)}var bs=typeof Uint8Array.prototype.slice=="function"?pg:mg;function Ss(n,e){let t=n;for(let r of e){let i=Re(t,r);if(i===null)return null;t=i}return t}function Re(n,e){let t=ze(n,e);return t!==null?n.subarray(t[1],t[2]):null}function Oc(n,e){let t=[],r=n;for(;;){let i=ze(r,e);if(i===null)return t;ee(i[2]!==0&&r.length!==0),t.push(r.subarray(i[1],i[2])),r=r.subarray(i[2])}}function Ts(n,e){let t=ze(n,e);return t!==null?n.subarray(t[0],t[2]):null}function ze(n,e){let t=n.length,r=0,i,o=0,a;for(;r+8<=t;){if(a=r,o=ne(n,a),a+=4,i=ne(n,a),a+=4,o===0)o=t-r;else if(o===1){if(a+8>t)return null;o=Ve(n,a),a+=8}if(o<0)throw new Error("ISOBMFF: Size out of range");if(i===e)return e===1970628964&&(a+=16),[r,a,r+o];r+=o}return null}function gn(n,e,t,r,i){let o=n.length,a;for(let s=0;s<o;s+=a){let d=s;a=ne(n,d),d+=4;let u=ne(n,d);if(d+=4,a===0)a=o-s;else if(a===1){if(d+8>o)return;a=Ve(n,d),d+=8}if(u===1970628964&&d+16<=o&&ne(n,d)===e&&ne(n,d+4)===t&&ne(n,d+8)===r&&ne(n,d+12)===i)return d+=16,n.subarray(d,s+a)}}function _s(n){let e=n.length;if(e<8)return m.warn("ISOBMFF: box inferior to 8 bytes, cannot find offsets"),null;let t=0,r=ne(n,t);t+=4;let i=ne(n,t);if(t+=4,r===0)r=e;else if(r===1){if(t+8>e)return m.warn("ISOBMFF: box too short, cannot find offsets"),null;r=Ve(n,t),t+=8}if(r<0)throw new Error("ISOBMFF: Size out of range");return i===1970628964&&(t+=16),[0,t,r]}function Ko(n){let e=0,t=Re(n,1836019574);if(t===null)return[];let r=[];for(;e<t.length;){let i;try{i=ze(t,1886614376)}catch(s){let d=s instanceof Error?s:"";return m.warn("Error while removing PSSH from ISOBMFF",d),r}if(i===null)return r;let o=bs(t,i[0],i[2]),a=Vo(o,i[1]-i[0]);a!==void 0&&r.push({systemId:a,data:o}),t[i[0]+4]=102,t[i[0]+5]=114,t[i[0]+6]=101,t[i[0]+7]=101,e=i[2]}return r}function Vo(n,e){if(n[e]>1){m.warn("ISOBMFF: un-handled PSSH version");return}let t=e+4;if(t+16>n.length)return;let r=bs(n,t,t+16);return Ue(r)}var wr=Math.pow(2,32)-1;var Es={};function Dc(n){if(Es[n]!==void 0)return Es[n];let e=ve(n);return Es[n]=e,e}function le(n,e){let t=e.length+8;return t<=wr?ie(Ie(t),Dc(n),e):ie(Ie(1),Dc(n),Yt(t+8),e)}function Ae(n,e){return le(n,ie(...e))}function Or(n){let e=Re(n,1836019558);return e===null?null:Re(e,1953653094)}function Lc(n){return Oc(n,1836019558).reduce((t,r)=>{let i=Re(r,1953653094);return i!==null&&t.push(i),t},[])}function Dr(n){return Re(n,1835295092)}function vs(n){let e=Re(n,1836019574);if(e===null)return null;let t=Re(e,1953653099);return t===null?null:Re(t,1835297121)}function Nc(n,e=0){return Re(n.subarray(e),1701671783)}function Lr(n){let e=Cc(n,8),t=Oo(n.subarray(10,e+10)),i=new DOMParser().parseFromString(t,"application/xml").querySelector("KID");if(i===null)throw new Error("Cannot parse PlayReady private data: invalid XML");let o=i.textContent===null?"":i.textContent,a=Do(mt(o));return Ue(a).toLowerCase()}function Nr(n,e){let t=ze(n,1936286840);if(t===null)return null;let r=e,i=t[2]-t[0],o=t[1],a=n[o];o+=8;let s=ne(n,o);o+=4;let d;if(a===0)d=ne(n,o),o+=4,r+=ne(n,o)+i,o+=4;else if(a===1)d=Ve(n,o),o+=8,r+=Ve(n,o)+i,o+=8;else return null;let u=[];o+=2;let l=No(n,o);for(o+=2;--l>=0;){let c=ne(n,o);o+=4;let f=(c&2147483648)>>>31,g=c&2147483647;if(f===1)throw new Error("sidx with reference_type `1` not yet implemented");let p=ne(n,o);o+=4,o+=4,u.push({time:d,duration:p,timescale:s,range:[r,r+g-1]}),d+=p,r+=g}return u}function Rs(n){let e=Or(n);if(e===null)return;let t=Re(e,1952867444);if(t===null)return;let r=t[0];if(r===1)return Ve(t,4);if(r===0)return ne(t,4)}function gg(n){let e=Re(n,1952868452);if(e===null)return;let t=1,r=hs(e,t);t+=3;let i=(r&1)>0,o=(r&2)>0;return(r&8)>0?(t+=4,i&&(t+=8),o&&(t+=4),ne(e,t)):void 0}function Ur(n){let e=Lc(n);if(e.length===0)return;let t=0;for(let r of e){let i=Re(r,1953658222);if(i===null)return;let o=0,a=i[o];if(o+=1,a>1)return;let s=hs(i,o);o+=3;let d=(s&256)>0,u=0;if(!d&&(u=gg(r),u===void 0))return;let l=(s&1)>0,c=(s&4)>0,f=(s&512)>0,g=(s&1024)>0,p=(s&2048)>0,I=ne(i,o);o+=4,l&&(o+=4),c&&(o+=4);let y=I,b=0;for(;y-- >0;)d?(b+=ne(i,o),o+=4):b+=u,f&&(o+=4),g&&(o+=4),p&&(o+=4);t+=b}return t}function Br(n){let e=vs(n);if(e===null)return;let t=Re(e,1835296868);if(t===null)return;let r=0,i=t[r];if(r+=4,i===1)return ne(t,r+16);if(i===0)return ne(t,r+8)}function ks(n){let e=n.length;if(e<4)throw new Error("Cannot update box length: box too short");let t=ne(n,0);if(t===0)if(e>wr){let r=new Uint8Array(e+8);return r.set(Ie(1),0),r.set(n.subarray(4,8),4),r.set(Yt(e+8),8),r.set(n.subarray(8,e),16),r}else return n.set(Ie(e),0),n;else if(t===1){if(e<16)throw new Error("Cannot update box length: box too short");return n.set(Yt(e),8),n}else{if(e<=wr)return n.set(Ie(e),0),n;{let r=new Uint8Array(e+8);return r.set(Ie(1),0),r.set(n.subarray(4,8),4),r.set(Yt(e+8),8),r.set(n.subarray(8,e),16),r}}}function Uc(n){let e=[],t=0;for(;t<n.length;){let r=Nc(n,t);if(r===null)break;let i=r.length;t+=i;let o=r[0];if(o!==0)m.warn("ISOBMFF: EMSG version "+o.toString()+" not supported.");else{let a=4,{end:s,string:d}=fs(r,a);a=s;let{end:u,string:l}=fs(r,a);a=u;let c=ne(r,a);a+=4;let f=ne(r,a);a+=4;let g=ne(r,a);a+=4;let p=ne(r,a);a+=4;let I=r.subarray(a,i),y={schemeIdUri:d,value:l,timescale:c,presentationTimeDelta:f,eventDuration:g,id:p,messageData:I};e.push(y)}}if(e.length!==0)return e}function Bc(n){let e=Ss(n,[1836019574,1953653099,1835297121,1835626086,1937007212,1937011556]);if(e===null)return null;let t=e.subarray(8),r=Re(t,1701733238),i=0;if(r===null?(i=28,r=Re(t,1701733217)):i=78,r===null)return null;let o=Ss(r.subarray(i),[1936289382,1935894633,1952804451]);if(o===null||o.byteLength<24)return null;let a=o.subarray(8,24);return a.every(s=>s===0)?null:a}var zo=ne(ve("pssh"),0);function hg(n){m.info("Compat: Trying to move CENC PSSH from init data at the end of it.");let e=!1,t=new Uint8Array,r=new Uint8Array,i=0;for(;i<n.length;){if(n.length<i+8||ne(n,i+4)!==zo)throw m.warn("Compat: unrecognized initialization data. Cannot patch it."),new Error("Compat: unrecognized initialization data. Cannot patch it.");let o=ne(new Uint8Array(n),i);if(i+o>n.length)throw m.warn("Compat: unrecognized initialization data. Cannot patch it."),new Error("Compat: unrecognized initialization data. Cannot patch it.");let a=n.subarray(i,i+o);if(n[i+12]===16&&n[i+13]===119&&n[i+14]===239&&n[i+15]===236&&n[i+16]===192&&n[i+17]===178&&n[i+18]===77&&n[i+19]===2&&n[i+20]===172&&n[i+21]===227&&n[i+22]===60&&n[i+23]===30&&n[i+24]===82&&n[i+25]===226&&n[i+26]===251&&n[i+27]===75){let s=_s(a),d=s===null?void 0:a[s[1]];m.info("Compat: CENC PSSH found with version",d),d===void 0?m.warn("Compat: could not read version of CENC PSSH"):e===(d===1)?t=ie(t,a):d===1?(m.warn("Compat: cenc version 1 encountered, removing every other cenc pssh box."),t=a,e=!0):m.warn("Compat: filtering out cenc pssh box with wrong version",d)}else r=ie(r,a);i+=o}if(i!==n.length)throw m.warn("Compat: unrecognized initialization data. Cannot patch it."),new Error("Compat: unrecognized initialization data. Cannot patch it.");return ie(r,t)}function Fr(n,e,t){m.debug("Compat: Calling generateRequest on the MediaKeySession");let r;try{r=hg(t)}catch(o){r=t}let i=e!=null?e:"";return n.generateRequest(i,r).catch(o=>{if(i!==""||!(o instanceof TypeError))throw o;return m.warn('Compat: error while calling `generateRequest` with an empty initialization data type. Retrying with a default "cenc" value.',o),n.generateRequest("cenc",r)})}function yg(n){let e=[],t=0;for(;t<n.length;){if(n.length<t+8||ne(n,t+4)!==zo)return m.warn("Compat: Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}];let r=ne(new Uint8Array(n),t);if(t+r>n.length)return m.warn("Compat: Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}];let i=n.subarray(t,t+r),a={systemId:Vo(i,8),data:i};Ig(e,a)?m.warn("Compat: Duplicated PSSH found in initialization data, removing it."):e.push(a),t+=r}return t!==n.length?(m.warn("Compat: Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}]):e}function Ig(n,e){for(let t=0;t<n.length;t++){let r=n[t];if((e.systemId===void 0||r.systemId===void 0||e.systemId===r.systemId)&&ge(e.data,r.data))return!0}return!1}function Ho(n){let{initData:e,initDataType:t,forceSessionRecreation:r}=n;if(_(e))return m.warn("Compat: No init data found on media encrypted event."),null;let i=new Uint8Array(e),o=yg(i);return{type:t,values:o,forceSessionRecreation:r}}var bg=100;async function Kr(n,e){m.info("DRM: Load persisted session",e);let t=await n.load(e);return!t||n.keyStatuses.size>0?t:new Promise(r=>{n.addEventListener("keystatuseschange",o);let i=setTimeout(o,bg);function o(){a(),r(t)}function a(){clearTimeout(i),n.removeEventListener("keystatuseschange",o)}})}var bt=wc;function Q(n,e,t){if(typeof Array.prototype.includes=="function")return n.includes(e,t);let r=n.length>>>0;if(r===0)return!1;let i=t|0,o=i>=0?Math.min(i,r-1):Math.max(r+i,0),a=(s,d)=>s===d||typeof s=="number"&&typeof d=="number"&&isNaN(s)&&isNaN(d);for(;o<r;){if(a(n[o],e))return!0;o++}return!1}function Fc(n){var t;let e=Ke.getState(n);return Ke.setState(n,null),Cr((t=e==null?void 0:e.emeImplementation)!=null?t:bt,n,null)}async function Cs(n,{emeImplementation:e,keySystemOptions:t,askedConfiguration:r,loadedSessionsStore:i,mediaKeySystemAccess:o,mediaKeys:a},s){let d=Ke.getState(n);if(await(d!==null&&d.loadedSessionsStore!==i?d.loadedSessionsStore.closeAllSessions():Promise.resolve()),s.isCancelled())throw s.cancellationError;if(Ke.setState(n,{emeImplementation:e,keySystemOptions:t,mediaKeySystemAccess:o,mediaKeys:a,loadedSessionsStore:i,askedConfiguration:r}),n.mediaKeys!==a)return m.info("DRM: Attaching MediaKeys to the media element"),Cr(e,n,a).then(()=>{m.info("DRM: MediaKeys attached with success")}).catch(l=>{let c=l instanceof Error?l.toString():"Unknown Error";throw new pe("MEDIA_KEYS_ATTACHMENT_ERROR","Could not attach the MediaKeys to the media element: "+c)})}function Vr(n){if(n.sessionId==="")return!1;let e=n.keyStatuses,t=[];return e.forEach(r=>{t.push(r)}),t.length<=0?(m.debug("DRM: isSessionUsable: MediaKeySession given has an empty keyStatuses",n.sessionId),!1):Q(t,"expired")?(m.debug("DRM: isSessionUsable: MediaKeySession given has an expired key",n.sessionId),!1):Q(t,"internal-error")?(m.debug("DRM: isSessionUsable: MediaKeySession given has a key with an internal-error",n.sessionId),!1):(m.debug("DRM: isSessionUsable: MediaKeySession is usable",n.sessionId),!0)}function Ps(n,e,t,r){let{loadedSessionsStore:i,persistentSessionsStore:o}=n;return t==="temporary"?Kc(i,e):o===null?(m.warn("DRM: Cannot create persistent MediaKeySession, PersistentSessionsStore not created."),Kc(i,e)):Sg(i,o,e,r)}function Kc(n,e){m.info("DRM: Creating a new temporary session");let t=n.createSession(e,"temporary");return Promise.resolve({type:"created-session",value:t})}async function Sg(n,e,t,r){if(r.cancellationError!==null)throw r.cancellationError;m.info("DRM: Creating persistent MediaKeySession");let i=n.createSession(t,"persistent-license"),o=e.getAndReuse(t);if(o===null)return{type:"created-session",value:i};try{let s=await n.loadPersistentSession(i.mediaKeySession,o.sessionId);if(!s){m.warn("DRM: No data stored for the loaded session"),e.delete(o.sessionId),n.removeSessionWithoutClosingIt(i.mediaKeySession);let d=n.createSession(t,"persistent-license");return{type:"created-session",value:d}}return s&&Vr(i.mediaKeySession)?(e.add(t,t.keyIds,i.mediaKeySession),m.info("DRM: Succeeded to load persistent session."),{type:"loaded-persistent-session",value:i}):(m.warn("DRM: Previous persistent session not usable anymore."),a())}catch(s){return m.warn("DRM: Unable to load persistent session: "+(s instanceof Error?s.toString():"Unknown Error")),a()}async function a(){if(r.cancellationError!==null)throw r.cancellationError;m.info("DRM: Removing previous persistent session.");let s=e.get(t);s!==null&&e.delete(s.sessionId);try{await n.closeSession(i.mediaKeySession)}catch(u){if(i.mediaKeySession.sessionId!=="")throw u;n.removeSessionWithoutClosingIt(i.mediaKeySession)}if(r.cancellationError!==null)throw r.cancellationError;let d=n.createSession(t,"persistent-license");return{type:"created-session",value:d}}}async function Ms(n,e){if(e<0||e>=n.getLength())return;m.info("DRM: LSS cache limit exceeded",e,n.getLength());let t=[],r=n.getAll().slice(),i=r.length-e;for(let o=0;o<i;o++){let a=r[o];t.push(n.closeSession(a.mediaKeySession))}await Promise.all(t)}async function As(n,e,t,r,i){let o=null,{loadedSessionsStore:a,persistentSessionsStore:s}=e,d=a.reuse(n);if(d!==null){if(o=d.mediaKeySession,Vr(o))return m.info("DRM: Reuse loaded session",o.sessionId),{type:"loaded-open-session",value:{mediaKeySession:o,sessionType:d.sessionType,keySessionRecord:d.keySessionRecord}};s!==null&&d.mediaKeySession.sessionId!==""&&s.delete(d.mediaKeySession.sessionId)}if(o!==null&&(await a.closeSession(o),i.cancellationError!==null)||(await Ms(a,r<=0?r:r-1),i.cancellationError!==null))throw i.cancellationError;let u=await Ps(e,n,t,i);return{type:u.type,value:{mediaKeySession:u.value.mediaKeySession,sessionType:u.value.sessionType,keySessionRecord:u.value.keySessionRecord}}}function xs(){return!ur&&!Va&&!Ka&&!Ha}function Vc(n){return!(sr&&n.indexOf("playready")!==-1)}var zc='<WRMHEADER xmlns="http://schemas.microsoft.com/DRM/2007/03/PlayReadyHeader" version="4.0.0.0"><DATA><PROTECTINFO><KEYLEN>16</KEYLEN><ALGID>AESCTR</ALGID></PROTECTINFO><KID>ckB07BNLskeUq0qd83fTbA==</KID><DS_ID>yYIPDBca1kmMfL60IsfgAQ==</DS_ID><CUSTOMATTRIBUTES xmlns=""><encryptionref>312_4024_2018127108</encryptionref></CUSTOMATTRIBUTES><CHECKSUM>U/tsUYRgMzw=</CHECKSUM></DATA></WRMHEADER>';function Hc(n){let e=wo(n),t=Mc(e.length),r=new Uint8Array([1,0]),i=new Uint8Array([1,0]),o=xr(e.length+6),a=ie(o,i,r,t,e),s=je("9a04f07998404286ab92e65be0885f95");return Tg(a,s)}function Tg(n,e){let t=ve("pssh"),r=new Uint8Array([0,0,0,0]),i=Ie(n.length),o=Ie(32+n.length);return ie(o,t,r,e,i,n)}function ws(){return sn}function _g(n,e){let{mimeType:t,codecs:r}=Wo(n),{mimeType:i,codecs:o}=Wo(e);if(t!==i||r===""||o==="")return!1;let a=r.split(".")[0];a=a==="hev1"?"hvc1":a;let s=o.split(".")[0];return s=s==="hev1"?"hvc1":s,a===s}var Eg=7;function Wo(n){var i;let[e,...t]=n.split(";"),r=(i=Z(t,o=>Ze(o,"codecs=")))!=null?i:"";return r=r.substring(Eg),r[0]==='"'&&(r=r.substring(1,r.length-2)),{mimeType:e,codecs:r}}var Go=_g;function Nn(n,e){return typeof Array.prototype.flatMap=="function"?n.flatMap(e):n.reduce((t,r)=>{let i=e(r);return Array.isArray(i)?(t.push(...i),t):(t.push(i),t)},[])}function vg(n,e,t,r){let i=t.getConfiguration();return ws()||_(i)||n.type!==r.type||(!_(n.persistentLicenseConfig)||n.persistentState==="required")&&i.persistentState!=="required"||n.distinctiveIdentifier==="required"&&i.distinctiveIdentifier!=="required"?null:{keySystemOptions:n,keySystemAccess:t,askedConfiguration:e}}function Rg(n){let{EME_KEY_SYSTEMS:e}=U.getCurrent();for(let t of Object.keys(e))if(Q(e[t],n))return t}function kg(n){let{keyName:e,keyType:t,keySystemOptions:r}=n,i=["temporary"],o="optional",a="optional";_(r.persistentLicenseConfig)||(o="required",i.push("persistent-license")),_(r.persistentState)||(o=r.persistentState),_(r.distinctiveIdentifier)||(a=r.distinctiveIdentifier);let{EME_DEFAULT_AUDIO_CODECS:s,EME_DEFAULT_VIDEO_CODECS:d,EME_DEFAULT_WIDEVINE_ROBUSTNESSES:u,EME_DEFAULT_PLAYREADY_RECOMMENDATION_ROBUSTNESSES:l}=U.getCurrent(),c,f,{audioCapabilitiesConfig:g,videoCapabilitiesConfig:p}=r;if((g==null?void 0:g.type)==="full")c=g.value;else{let y;(g==null?void 0:g.type)==="robustness"?y=g.value:e==="widevine"?y=u:t==="com.microsoft.playready.recommendation"?y=l:y=[],y.length===0&&y.push(void 0);let b=(g==null?void 0:g.type)==="contentType"?g.value:s;c=Nn(y,T=>b.map(v=>T!==void 0?{contentType:v,robustness:T}:{contentType:v}))}if((p==null?void 0:p.type)==="full")f=p.value;else{let y;(p==null?void 0:p.type)==="robustness"?y=p.value:e==="widevine"?y=u:t==="com.microsoft.playready.recommendation"?y=l:y=[],y.length===0&&y.push(void 0);let b=(p==null?void 0:p.type)==="contentType"?p.value:d;f=Nn(y,T=>b.map(v=>T!==void 0?{contentType:v,robustness:T}:{contentType:v}))}let I={initDataTypes:["cenc"],videoCapabilities:f,audioCapabilities:c,distinctiveIdentifier:a,persistentState:o,sessionTypes:i};return g!==void 0?p!==void 0?[I]:[I,ue(oe({},I),{videoCapabilities:void 0})]:p!==void 0?[I,ue(oe({},I),{audioCapabilities:void 0})]:[I,ue(oe({},I),{audioCapabilities:void 0,videoCapabilities:void 0})]}function Wc(n,e){var u,l,c,f,g,p;let t=(l=(u=n.audioCapabilities)==null?void 0:u.map(I=>I.contentType))!=null?l:[],r=(f=(c=n.videoCapabilities)==null?void 0:c.map(I=>I.contentType))!=null?f:[],i=t.concat(r).filter(I=>I!==void 0),o=(g=e.videoCapabilities)==null?void 0:g.map(I=>I.contentType),a=(p=e.audioCapabilities)==null?void 0:p.map(I=>I.contentType),s=[...o!=null?o:[],...a!=null?a:[]].filter(I=>I!==void 0);return s.length===0?[]:i.map(I=>{let{codecs:y,mimeType:b}=Wo(I),T=Q(s,I);return{codec:y,mimeType:b,result:T}})}function Os(n,e,t){m.info("DRM: Searching for compatible MediaKeySystemAccess");let r=e.reduce((o,a)=>{let{EME_KEY_SYSTEMS:s}=U.getCurrent(),d=s[a.type],u;if(!_(d))u=d.map(l=>({keyName:a.type,keyType:l,keySystemOptions:a}));else{let l=Rg(a.type),c=a.type;u=[{keyName:l,keyType:c,keySystemOptions:a}]}return o.concat(u)},[]);return i(0);async function i(o){if(o>=r.length)throw new pe("INCOMPATIBLE_KEYSYSTEMS","No key system compatible with your wanted configuration has been found in the current browser.");if(_(bt.requestMediaKeySystemAccess))throw new Error("requestMediaKeySystemAccess is not implemented in your browser.");let a=r[o],s=Ke.getState(n);if(s!==null&&bt.implementation===s.emeImplementation.implementation){let f=vg(a.keySystemOptions,s.askedConfiguration,s.mediaKeySystemAccess,s.keySystemOptions);if(f!==null)return m.info("DRM: Found cached compatible keySystem"),Promise.resolve({type:"reuse-media-key-system-access",value:{mediaKeySystemAccess:f.keySystemAccess,askedConfiguration:f.askedConfiguration,options:f.keySystemOptions,codecSupport:Wc(f.askedConfiguration,f.keySystemAccess.getConfiguration())}})}let{keyType:d,keySystemOptions:u}=a,l=kg(a);m.debug(`DRM: Request keysystem access ${d},${o+1} of ${r.length}`);let c;for(let f=0;f<l.length;f++){let g=l[f];try{return c=await Cg(d,[g]),m.info("DRM: Found compatible keysystem",d,o+1),{type:"create-media-key-system-access",value:{options:u,mediaKeySystemAccess:c,askedConfiguration:g,codecSupport:Wc(g,c.getConfiguration())}}}catch(p){if(m.debug("DRM: Rejected access to keysystem",d,o+1,f),t.cancellationError!==null)throw t.cancellationError}}return i(o+1)}}async function Cg(n,e){let t=await bt.requestMediaKeySystemAccess(n,e);if(!Vc(n))try{let i=(await t.createMediaKeys()).createSession(),o=Hc(zc);await i.generateRequest("cenc",o),i.close().catch(()=>{m.warn("DRM: Failed to close the dummy session")})}catch(r){throw m.debug("DRM: KeySystemAccess was granted but it is not usable"),r}return t}function Un(n,e){for(let t of n)if(!e.some(i=>ge(i,t)))return!1;return!0}function Gc(n,e){for(let t of n)if(e.some(i=>ge(i,t)))return!0;return!1}var zr=class{constructor(e){this._initializationData=e,this._keyIds=null}associateKeyIds(e){this._keyIds===null&&(this._keyIds=[]);let t=Array.from(e);for(let r of t)this.isAssociatedWithKeyId(r)||this._keyIds.push(r)}isAssociatedWithKeyId(e){if(this._keyIds===null)return!1;for(let t of this._keyIds)if(ge(t,e))return!0;return!1}getAssociatedKeyIds(){return this._keyIds===null?[]:this._keyIds}isCompatibleWith(e){let{keyIds:t}=e;if(t!==void 0&&t.length>0){if(this._keyIds!==null&&Un(t,this._keyIds))return!0;if(this._initializationData.keyIds!==void 0)return Un(t,this._initializationData.keyIds)}return this._checkInitializationDataCompatibility(e)}_checkInitializationDataCompatibility(e){return e.keyIds!==void 0&&e.keyIds.length>0&&this._initializationData.keyIds!==void 0?Un(e.keyIds,this._initializationData.keyIds):this._initializationData.type!==e.type?!1:this._initializationData.values.isCompatibleWith(e.values)}};var Hr=class{constructor(e){this._mediaKeys=e,this._storage=[]}createSession(e,t){let r=new zr(e);m.debug("DRM-LSS: calling `createSession`",t);let i=this._mediaKeys.createSession(t),o={mediaKeySession:i,sessionType:t,keySessionRecord:r,isGeneratingRequest:!1,isLoadingPersistentSession:!1,closingStatus:{type:"none"}};return _(i.closed)||i.closed.then(()=>{m.info("DRM-LSS: session was closed, removing it.",i.sessionId);let a=this.getIndex(r);a>=0&&this._storage[a].mediaKeySession===i&&this._storage.splice(a,1)}).catch(a=>{m.warn(`DRM-LSS: MediaKeySession.closed rejected: ${a}`)}),this._storage.push(oe({},o)),m.debug("DRM-LSS: MediaKeySession added",o.sessionType,this._storage.length),o}reuse(e){for(let t=this._storage.length-1;t>=0;t--){let r=this._storage[t];if(r.keySessionRecord.isCompatibleWith(e))return this._storage.splice(t,1),this._storage.push(r),m.debug("DRM-LSS: Reusing session:",r.mediaKeySession.sessionId,r.sessionType),oe({},r)}return null}getEntryForSession(e){for(let t=this._storage.length-1;t>=0;t--){let r=this._storage[t];if(r.mediaKeySession===e)return oe({},r)}return null}async generateLicenseRequest(e,t,r){let i;for(let o of this._storage)if(o.mediaKeySession===e){i=o;break}if(i===void 0)return m.error("DRM-LSS: generateRequest error. No MediaKeySession found with the given initData and initDataType"),Fr(e,t,r);if(i.isGeneratingRequest=!0,i.closingStatus.type!=="none")throw new Error("The `MediaKeySession` is being closed.");try{await Fr(e,t,r)}catch(o){throw i===void 0||(i.isGeneratingRequest=!1,i.closingStatus.type==="awaiting"&&i.closingStatus.start()),o}i!==void 0&&(i.isGeneratingRequest=!1,i.closingStatus.type==="awaiting"&&i.closingStatus.start())}async loadPersistentSession(e,t){let r;for(let o of this._storage)if(o.mediaKeySession===e){r=o;break}if(r===void 0)return m.error("DRM-LSS: loadPersistentSession error. No MediaKeySession found with the given initData and initDataType"),Kr(e,t);if(r.isLoadingPersistentSession=!0,r.closingStatus.type!=="none")throw new Error("The `MediaKeySession` is being closed.");let i;try{i=await Kr(e,t)}catch(o){throw r===void 0||(r.isLoadingPersistentSession=!1,r.closingStatus.type==="awaiting"&&r.closingStatus.start()),o}return r===void 0||(r.isLoadingPersistentSession=!1,r.closingStatus.type==="awaiting"&&r.closingStatus.start()),i}async closeSession(e){let t;for(let r of this._storage)if(r.mediaKeySession===e){t=r;break}return t===void 0?(m.warn("DRM-LSS: No MediaKeySession found with the given initData and initDataType"),Promise.resolve(!1)):this._closeEntry(t)}getLength(){return this._storage.length}getAll(){return this._storage}async closeAllSessions(){let e=this._storage;m.debug("DRM-LSS: Closing all current MediaKeySessions",e.length),this._storage=[];let t=e.map(r=>this._closeEntry(r));await Promise.all(t)}removeSessionWithoutClosingIt(e){ee(e.sessionId==="","Initialized `MediaKeySession`s should always be properly closed");for(let t=this._storage.length-1;t>=0;t--)if(this._storage[t].mediaKeySession===e)return m.debug("DRM-LSS: Removing session without closing it",e.sessionId),this._storage.splice(t,1),!0;return!1}getIndex(e){for(let t=0;t<this._storage.length;t++)if(this._storage[t].keySessionRecord===e)return t;return-1}async _closeEntry(e){let{mediaKeySession:t}=e;return new Promise((r,i)=>{e!==void 0&&(e.isLoadingPersistentSession||e.isGeneratingRequest)?e.closingStatus={type:"awaiting",start:o}:o();function o(){e!==void 0&&(e.closingStatus={type:"pending"}),Pg(t).then(()=>{e!==void 0&&(e.closingStatus={type:"done"}),r(!0)}).catch(a=>{e!==void 0&&(e.closingStatus={type:"failed"}),i(a)})}})}};async function Pg(n){m.debug("DRM: Trying to close a MediaKeySession",n.sessionId);try{await Eo(n),m.debug("DRM: Succeeded to close MediaKeySession");return}catch(e){m.error("DRM: Could not close MediaKeySession: "+(e instanceof Error?e.toString():"Unknown error"));return}}function $t(n){let e=0,t;for(let r=0;r<n.length;r++)t=n[r],e=(e<<5)-e+t,e=e&e;return e}var st=class{constructor(e){this.initData=e}toJSON(){return xo(this.initData)}static decode(e){return mt(e)}};function Bn(n,e){var t,r;return(r=(t=qc(n,e))!=null?t:qc(e,n))!=null?r:!1}function qc(n,e){if(n.length===0)return!1;if(e.length<n.length)return null;let t=n[0],r=0,i=0;for(;i<e.length;i++){let o=e[i];if(o.systemId!==t.systemId)continue;if(o.hash!==t.hash)return!1;let a;t.data instanceof Uint8Array?a=t.data:typeof t.data=="string"?a=st.decode(t.data):a=t.data.initData;let s;if(o.data instanceof Uint8Array?s=o.data:typeof o.data=="string"?s=st.decode(o.data):s=o.data.initData,!ge(a,s))return!1;if(e.length-i<n.length)return null;for(r=1;r<n.length;r++){let d=n[r];for(i+=1;i<e.length;i++){let u=e[i];if(d.systemId!==u.systemId)continue;if(d.hash!==u.hash)return!1;let l;d.data instanceof Uint8Array?l=d.data:typeof d.data=="string"?l=st.decode(d.data):l=d.data.initData;let c;if(u.data instanceof Uint8Array?c=u.data:typeof u.data=="string"?c=st.decode(u.data):c=u.data.initData,!ge(l,c))return!1;break}if(r===e.length)return null}return!0}return null}function Mg(n){ec(n,{save:"function",load:"function"},"persistentLicenseConfig")}var Wr=class{constructor(e){Mg(e),this._entries=[],this._storage=e;try{let t=this._storage.load();Array.isArray(t)||(t=[]),this._entries=t}catch(t){m.warn("DRM-PSS: Could not get entries from license storage",t instanceof Error?t:""),this.dispose()}}getLength(){return this._entries.length}getAll(){return this._entries}get(e){let t=this._getIndex(e);return t===-1?null:this._entries[t]}getAndReuse(e){let t=this._getIndex(e);if(t===-1)return null;let r=this._entries.splice(t,1)[0];return this._entries.push(r),r}add(e,t,r){var s;if(_(r)||!w(r.sessionId)){m.warn("DRM-PSS: Invalid Persisten Session given.");return}let{sessionId:i}=r,o=this._getIndex(e);if(o>=0){let d=t===void 0?3:4,u=this._entries[o];if(((s=u.version)!=null?s:-1)>=d&&i===u.sessionId)return;m.info("DRM-PSS: Updating session info.",i),this._entries.splice(o,1)}else m.info("DRM-PSS: Add new session",i);let a=Ag(e.values.getFormattedValues());t===void 0?this._entries.push({version:3,sessionId:i,values:a,initDataType:e.type}):this._entries.push({version:4,sessionId:i,keyIds:t.map(d=>new st(d)),values:a,initDataType:e.type}),this._save()}delete(e){let t=-1;for(let i=0;i<this._entries.length;i++)if(this._entries[i].sessionId===e){t=i;break}if(t===-1){m.warn("DRM-PSS: initData to delete not found.");return}let r=this._entries[t];m.warn("DRM-PSS: Delete session from store",r.sessionId),this._entries.splice(t,1),this._save()}deleteOldSessions(e){m.info(`DRM-PSS: Deleting last ${e} sessions.`),!(e<=0)&&(e<=this._entries.length?this._entries.splice(0,e):(m.warn("DRM-PSS: Asked to remove more information that it contains",e,this._entries.length),this._entries=[]),this._save())}dispose(){this._entries=[],this._save()}_getIndex(e){let t=null;function r(){if(t===null){let i=e.values.constructRequestData();t={initData:i,initDataHash:$t(i)}}return t}for(let i=0;i<this._entries.length;i++){let o=this._entries[i];if(o.initDataType===e.type)switch(o.version){case 4:if(e.keyIds!==void 0){if(e.keyIds.every(s=>{let d=xo(s);for(let u of o.keyIds)if(typeof u=="string"){if(d===u)return!0}else if(ge(u.initData,s))return!0;return!1}))return i}else{let a=e.values.getFormattedValues();if(Bn(a,o.values))return i}break;case 3:{let a=e.values.getFormattedValues();if(Bn(a,o.values))return i;break}case 2:{let{initData:a,initDataHash:s}=r();if(o.initDataHash===s)try{let d=typeof o.initData=="string"?st.decode(o.initData):o.initData.initData;if(ge(d,a))return i}catch(d){m.warn("DRM-PSS: Could not decode initialization data.",d instanceof Error?d:"")}break}case 1:{let{initData:a,initDataHash:s}=r();if(o.initDataHash===s){if(typeof o.initData.length=="undefined")return i;if(ge(o.initData,a))return i}break}default:{let{initDataHash:a}=r();if(o.initData===a)return i}}}return-1}_save(){try{this._storage.save(this._entries)}catch(e){let t=e instanceof Error?e:void 0;m.warn("DRM-PSS: Could not save MediaKeySession information",t)}}};function Ag(n){return n.map(({systemId:e,data:t,hash:r})=>({systemId:e,hash:r,data:new st(t)}))}var qo=new WeakMap,hn={prepare(n){qo.set(n,null)},set(n,e){let t=e instanceof Uint8Array?e:new Uint8Array(e instanceof ArrayBuffer?e:e.buffer),r=$t(t);qo.set(n,{hash:r,serverCertificate:t})},hasOne(n){let e=qo.get(n);if(e===void 0)return!1;if(e!==null)return!0},has(n,e){let t=qo.get(n);if(t==null)return!1;let{hash:r,serverCertificate:i}=t,o=e instanceof Uint8Array?e:new Uint8Array(e instanceof ArrayBuffer?e:e.buffer);if($t(o)!==r||i.length!==o.length)return!1;for(let s=0;s<i.length;s++)if(i[s]!==o[s])return!1;return!0}};function xg(n){let{persistentLicenseConfig:e}=n;return _(e)?null:(m.debug("DRM: Set the given license storage"),new Wr(e))}async function Ds(n,e,t){let r=await Os(n,e,t);if(t.cancellationError!==null)throw t.cancellationError;let{options:i,mediaKeySystemAccess:o,askedConfiguration:a,codecSupport:s}=r.value,d=Ke.getState(n),u=xg(i);if(r.value.options.reuseMediaKeys!==!1&&xs()&&d!==null&&r.type==="reuse-media-key-system-access"){m.debug("DRM: Reusing already created MediaKeys");let{mediaKeys:f,loadedSessionsStore:g}=d;if(hn.hasOne(f)===!1||!_(i.serverCertificate)&&hn.has(f,i.serverCertificate))return{mediaKeys:f,mediaKeySystemAccess:o,askedConfiguration:a,stores:{loadedSessionsStore:g,persistentSessionsStore:u},options:i,codecSupport:s}}let l=await wg(o);m.info("DRM: MediaKeys created with success");let c=new Hr(l);return{mediaKeys:l,mediaKeySystemAccess:o,askedConfiguration:a,stores:{loadedSessionsStore:c,persistentSessionsStore:u},options:i,codecSupport:s}}async function wg(n){m.info("DRM: Calling createMediaKeys on the MediaKeySystemAccess");try{return await n.createMediaKeys()}catch(e){let t=e instanceof Error?e.message:"Unknown error when creating MediaKeys.";throw new pe("CREATE_MEDIA_KEYS_ERROR",t)}}async function Ls(n,e,t){let r=await Ds(n,e,t),{mediaKeys:i}=r;return n.mediaKeys!==null&&n.mediaKeys!==void 0&&i!==n.mediaKeys&&(m.debug("DRM: Disabling old MediaKeys"),await Fc(n)),r}function Gr(n){let e=(Math.random()*2-1)*.3;return n*(e+1)}function Ns(n,e,t){let{baseDelay:r,maxDelay:i,totalRetry:o,shouldRetry:a,onRetry:s}=e,d=0;return u();async function u(){if(t.cancellationError!==null)throw t.cancellationError;try{return await n()}catch(l){if(t.cancellationError!==null)throw t.cancellationError;if(!_(a)&&!a(l)||d++>=o)throw l;typeof s=="function"&&s(l,d);let c=Og(r,d,i);return await mn(c),u()}}}function Og(n,e,t){let r=n*Math.pow(2,e-1),i=Gr(r);return Math.min(i,t)}function Us(n,e){return n.indexOf("playready")!==-1&&(Ht||sr)?Do(e):e}var Fn=class n extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,n.prototype),this.reason=e}},Bs={EXPIRED:"expired",INTERNAL_ERROR:"internal-error",OUTPUT_RESTRICTED:"output-restricted"};function Fs(n,e,t){let{onKeyInternalError:r,onKeyOutputRestricted:i,onKeyExpiration:o}=e,a=[],s=[],d=[];n.keyStatuses.forEach((l,c)=>{let[f,g]=typeof l=="string"?[l,c]:[c,l],p=Us(t,new Uint8Array(g)),I={keyId:p.buffer,keyStatus:f};switch(m.hasLevel("DEBUG")&&m.debug(`DRM: key status update (${Ue(p)}): ${f}`),f){case Bs.EXPIRED:{let y=new pe("KEY_STATUS_CHANGE_ERROR",`A decryption key expired (${Ue(p)})`,{keyStatuses:[I,...d]});if(o==="error"||o===void 0)throw y;switch(o){case"close-session":throw new Fn(y);case"fallback":a.push(p);break;default:o==="continue"||o===void 0?s.push(p):Xe(o);break}d.push(I);break}case Bs.INTERNAL_ERROR:{let y=new pe("KEY_STATUS_CHANGE_ERROR",`A "${f}" status has been encountered (${Ue(p)})`,{keyStatuses:[I,...d]});switch(r){case void 0:case"error":throw y;case"close-session":throw new Fn(y);case"fallback":a.push(p);break;case"continue":s.push(p);break;default:if(r!==void 0)Xe(r);else throw y}d.push(I);break}case Bs.OUTPUT_RESTRICTED:{let y=new pe("KEY_STATUS_CHANGE_ERROR",`A "${f}" status has been encountered (${Ue(p)})`,{keyStatuses:[I,...d]});switch(i){case void 0:case"error":throw y;case"fallback":a.push(p);break;case"continue":s.push(p);break;default:if(i!==void 0)Xe(i);else throw y}d.push(I);break}default:s.push(p);break}});let u;return d.length>0&&(u=new pe("KEY_STATUS_CHANGE_ERROR","One or several problematic key statuses have been encountered",{keyStatuses:d})),{warning:u,blacklistedKeyIds:a,whitelistedKeyIds:s}}function Ks(n,e,t,r,i){m.info("DRM: Binding session events",n.sessionId);let{getLicenseConfig:o={}}=e,a=new B;a.linkToSignal(i),_(n.closed)||n.closed.then(()=>a.cancel()).catch(l=>{i.isCancelled()||(a.cancel(),r.onError(l))}),Co(n,l=>{a.cancel(),r.onError(new pe("KEY_ERROR",l.type))},a.signal),Sc(n,()=>{m.info("DRM: keystatuseschange event received",n.sessionId);try{s()}catch(l){if(i.isCancelled()||a.isUsed()&&l instanceof cr)return;a.cancel(),r.onError(l)}},a.signal),ko(n,l=>{let c=l,f=new Uint8Array(c.message),g=w(c.messageType)?c.messageType:"license-request";m.info(`DRM: Received message event, type ${g}`,n.sessionId);let p=u(o.retry);Ns(()=>d(f,g),p,a.signal).then(I=>{if(a.isUsed())return Promise.resolve();if(_(I))m.info("DRM: No license given, skipping session.update");else try{return Dg(n,I)}catch(y){a.cancel(),r.onError(y)}}).catch(I=>{if(a.isUsed())return;a.cancel();let y=jc(I);if(!_(I)){let{fallbackOnLastTry:b}=I;if(b===!0){m.warn("DRM: Last `getLicense` attempt failed. Blacklisting the current session."),r.onError(new Kn(y));return}}r.onError(y)})},a.signal),m.info("DRM: transmitting current keystatuses",n.sessionId),s();return;function s(){if(a.isUsed()||n.keyStatuses.size===0)return;let{warning:l,blacklistedKeyIds:c,whitelistedKeyIds:f}=Fs(n,e,t);l!==void 0&&(r.onWarning(l),a.isUsed())||r.onKeyUpdate({whitelistedKeyIds:f,blacklistedKeyIds:c})}function d(l,c){let f;return new Promise((g,p)=>{try{m.debug("DRM: Calling `getLicense`",c);let b=e.getLicense(l,c),T=_(o.timeout)?10*1e3:o.timeout;T>=0&&(f=setTimeout(()=>{p(new qr(`"getLicense" timeout exceeded (${T} ms)`))},T)),Promise.resolve(b).then(I,y)}catch(b){y(b)}function I(b){f!==void 0&&clearTimeout(f),g(b)}function y(b){f!==void 0&&clearTimeout(f),p(b)}})}function u(l){return{totalRetry:l!=null?l:2,baseDelay:200,maxDelay:3e3,shouldRetry:c=>c instanceof qr||_(c)||c.noRetry!==!0,onRetry:c=>r.onWarning(jc(c))}}}function jc(n){if(n instanceof qr)return new pe("KEY_LOAD_TIMEOUT","The license server took too much time to respond.");let e=new pe("KEY_LOAD_ERROR","An error occured when calling `getLicense`.");return!_(n)&&w(n.message)&&(e.message=n.message),e}async function Dg(n,e){m.info("DRM: Updating MediaKeySession with message");try{await n.update(e)}catch(t){let r=t instanceof Error?t.toString():"`session.update` failed";throw new pe("KEY_UPDATE_ERROR",r)}m.info("DRM: MediaKeySession update succeeded.")}var Kn=class n extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,n.prototype),this.sessionError=e}},qr=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Kn.prototype),this.message=e}};async function Lg(n,e){try{return await n.setServerCertificate(e)}catch(t){m.warn("DRM: mediaKeys.setServerCertificate returned an error",t instanceof Error?t:"");let r=t instanceof Error?t.toString():"`setServerCertificate` error";throw new pe("LICENSE_SERVER_CERTIFICATE_ERROR",r)}}async function Vs(n,e){if(hn.hasOne(n)===!0)return m.info("DRM: The MediaKeys already has a server certificate, skipping..."),{type:"already-has-one"};if(typeof n.setServerCertificate!="function")return m.warn("DRM: Could not set the server certificate. mediaKeys.setServerCertificate is not a function"),{type:"method-not-implemented"};m.info("DRM: Setting server certificate on the MediaKeys"),hn.prepare(n);try{let t=await Lg(n,e);return hn.set(n,e),{type:"success",value:t}}catch(t){return{type:"error",value:Gt(t)?t:new pe("LICENSE_SERVER_CERTIFICATE_ERROR","Unknown error when setting the server certificate.")}}}function zs(n,e){if(isNaN(e)||e<0||e>=n.getLength())return;let t=n.getLength(),r=t-e;m.info("DRM: Too many stored persistent sessions, removing some.",t,r),n.deleteOldSessions(r)}function Hs(n){if(Ze(n,"com.microsoft.playready")||n==="com.chromecast.playready"||n==="com.youtube.playready")return"9a04f07998404286ab92e65be0885f95";if(n==="com.widevine.alpha")return"edef8ba979d64acea3c827dcd51d21ed";if(Ze(n,"com.apple.fps"))return"94ce86fb07ff4f43adb893d2fa968ca2";if(Ze(n,"com.nagra."))return"adb41c242dbf4a6d958b4457c0d27b95"}var jr=class n{constructor(e){this._innerValues=e,this._lazyFormattedValues=null}constructRequestData(){return ie(...this._innerValues.map(e=>e.data))}isCompatibleWith(e){let t=e instanceof n?e.getFormattedValues():e;return Bn(this.getFormattedValues(),t)}getFormattedValues(){return this._lazyFormattedValues===null&&(this._lazyFormattedValues=Ng(this._innerValues)),this._lazyFormattedValues}};function Ng(n){return n.slice().sort((e,t)=>e.systemId===t.systemId?0:e.systemId===void 0?1:t.systemId===void 0||e.systemId<t.systemId?-1:1).map(({systemId:e,data:t})=>({systemId:e,data:t,hash:$t(t)}))}function Ws(n,e,t){let r=`${n};codecs="${e}"`,i=t.filter(o=>o.mimeType===n);if(i.length!==0)for(let{codec:o,mimeType:a,result:s}of i){let d=`${a};codecs="${o}"`;if(Go(r,d))return s}}var Yr=class extends re{static hasEmeApis(){return!_(bt.requestMediaKeySystemAccess)}constructor(e,t){super(),m.debug("DRM: Starting ContentDecryptor logic.");let r=new B;this._currentSessions=[],this._canceller=r,this._initDataQueue=[],this._stateData={state:0,isMediaKeysAttached:0,isInitDataQueueLocked:!0,data:null},this._supportedCodecWhenEncrypted=[],this.error=null,bt.onEncrypted(e,i=>{m.debug("DRM: Encrypted event received from media element.");let o=Ho(i);o!==null&&this.onInitializationData(o)},r.signal),Ls(e,t,r.signal).then(i=>{let{options:o,mediaKeySystemAccess:a}=i;this._supportedCodecWhenEncrypted=i.codecSupport;let s;(_(o.persistentLicenseConfig)||o.persistentLicenseConfig.disableRetroCompatibility===!0)&&(s=Hs(a.keySystem)),this.systemId=s,this._stateData.state===0&&(m.debug("DRM: Waiting for attachment."),this._stateData={state:1,isInitDataQueueLocked:!0,isMediaKeysAttached:0,data:{mediaKeysInfo:i,mediaElement:e}},this.trigger("stateChange",this._stateData.state))}).catch(i=>{this._onFatalError(i)})}getState(){return this._stateData.state}attach(){if(this._stateData.state!==1)throw new Error("`attach` should only be called when in the WaitingForAttachment state");if(this._stateData.isMediaKeysAttached!==0){m.warn("DRM: ContentDecryptor's `attach` method called more than once.");return}let{mediaElement:e,mediaKeysInfo:t}=this._stateData.data,{options:r,mediaKeys:i,mediaKeySystemAccess:o,stores:a,askedConfiguration:s}=t;if(r.disableMediaKeysAttachmentLock===!0&&(m.debug("DRM: disabling MediaKeys attachment lock. Ready for content"),this._stateData={state:2,isInitDataQueueLocked:!0,isMediaKeysAttached:1,data:{mediaKeysInfo:t,mediaElement:e}},this.trigger("stateChange",this._stateData.state),this._isStopped()))return;this._stateData.isMediaKeysAttached=1;let u={emeImplementation:bt,loadedSessionsStore:a.loadedSessionsStore,mediaKeySystemAccess:o,mediaKeys:i,askedConfiguration:s,keySystemOptions:r};m.debug("DRM: Attaching current MediaKeys"),Cs(e,u,this._canceller.signal).then(async()=>{this._stateData.isMediaKeysAttached=2;let{serverCertificate:l}=r;if(!_(l)){let f=await Vs(i,l);f.type==="error"&&this.trigger("warning",f.value)}if(this._isStopped())return;let c=this._stateData.state;this._stateData={state:2,isMediaKeysAttached:2,isInitDataQueueLocked:!1,data:{mediaKeysData:t}},c!==2&&this.trigger("stateChange",2),this._isStopped()||this._processCurrentInitDataQueue()}).catch(l=>{this._onFatalError(l)})}dispose(){this.removeEventListener(),this._stateData={state:4,isMediaKeysAttached:void 0,isInitDataQueueLocked:void 0,data:null},this._canceller.cancel(),this.trigger("stateChange",this._stateData.state)}isCodecSupported(e,t){if(this._stateData.state===0){m.error("DRM: Asking for codec support while the ContentDecryptor is still initializing");return}return(this._stateData.state===3||this._stateData.state===4)&&m.error("DRM: Asking for codec support while the ContentDecryptor is disposed"),Ws(e,t,this._supportedCodecWhenEncrypted)}onInitializationData(e){if(this._stateData.isInitDataQueueLocked!==!1){if(this._isStopped())throw new Error("ContentDecryptor either disposed or stopped.");this._initDataQueue.push(e);return}let{mediaKeysData:t}=this._stateData.data,r=ue(oe({},e),{values:new jr(e.values)});this._processInitializationData(r,t).catch(i=>{this._onFatalError(i)})}async _processInitializationData(e,t){var I,y,b;m.hasLevel("DEBUG")&&m.debug("DRM: processing init data",(I=e.content)==null?void 0:I.adaptation.type,(y=e.content)==null?void 0:y.representation.bitrate,((b=e.keyIds)!=null?b:[]).map(T=>Ue(T)).join(", "));let{mediaKeySystemAccess:r,stores:i,options:o}=t;if(this._tryToUseAlreadyCreatedSession(e,t)||this._isStopped())return;if(o.singleLicensePer==="content"){let T=Z(this._currentSessions,v=>v.source==="created-session");if(T!==void 0){let v=e.keyIds;if(v===void 0){e.content===void 0?m.warn("DRM: Unable to fallback from a non-decipherable quality."):(m.debug("DRM: Blacklisting new init data (due to singleLicensePer content policy)"),this.trigger("blackListProtectionData",e));return}if(T.record.associateKeyIds(v),e.content===void 0)m.warn("DRM: Unable to fallback from a non-decipherable quality.");else{if(m.hasLevel("DEBUG")){let E=v.reduce((R,k)=>`${R}, ${Ue(k)}`,"");m.debug("DRM: Blacklisting new key ids",E)}this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:v,delistedKeyIds:[]})}return}}else if(o.singleLicensePer==="periods"&&e.content!==void 0){let{period:T}=e.content,v=this._currentSessions.filter(R=>R.source==="created-session"),E=new Set;qs(E,T);for(let R of v){let k=Array.from(E);for(let x of k)if(R.record.isAssociatedWithKeyId(x)){R.record.associateKeyIds(E.values());for(let M of k)!R.keyStatuses.whitelisted.some(P=>ge(P,M))&&!R.keyStatuses.blacklisted.some(P=>ge(P,M))&&R.keyStatuses.blacklisted.push(M);m.hasLevel("DEBUG")&&m.debug("DRM: Session already created for",Ue(x),'under singleLicensePer "periods" policy'),this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:R.keyStatuses.whitelisted,blacklistedKeyIds:R.keyStatuses.blacklisted,delistedKeyIds:[]});return}}}this._lockInitDataQueue();let a;_(o.persistentLicenseConfig)?a="temporary":Ug(r)?a="persistent-license":(m.warn('DRM: Cannot create "persistent-license" session: not supported'),a="temporary");let{EME_DEFAULT_MAX_SIMULTANEOUS_MEDIA_KEY_SESSIONS:s,EME_MAX_STORED_PERSISTENT_SESSION_INFORMATION:d}=U.getCurrent(),u=typeof o.maxSessionCacheSize=="number"?o.maxSessionCacheSize:s,l=await As(e,i,a,u,this._canceller.signal);if(this._isStopped())return;let c={record:l.value.keySessionRecord,source:l.type,keyStatuses:{whitelisted:[],blacklisted:[]},blacklistedSessionError:null};this._currentSessions.push(c);let{mediaKeySession:f,sessionType:g}=l.value,p=!1;if(Ks(f,o,r.keySystem,{onKeyUpdate:T=>{let v=Kg(e,c.record,o.singleLicensePer,c.source==="created-session",T.whitelistedKeyIds,T.blacklistedKeyIds);if(c.record.associateKeyIds(v.whitelisted),c.record.associateKeyIds(v.blacklisted),c.keyStatuses={whitelisted:v.whitelisted,blacklisted:v.blacklisted},c.record.getAssociatedKeyIds().length!==0&&g==="persistent-license"&&i.persistentSessionsStore!==null&&!p){let{persistentSessionsStore:E}=i;zs(E,d-1),E.add(e,c.record.getAssociatedKeyIds(),f),p=!0}e.content!==void 0&&this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:v.whitelisted,blacklistedKeyIds:v.blacklisted,delistedKeyIds:[]}),this._unlockInitDataQueue()},onWarning:T=>{this.trigger("warning",T)},onError:T=>{var v;if(T instanceof Fn){m.warn("DRM: A session's closing condition has been triggered"),this._lockInitDataQueue();let E=this._currentSessions.indexOf(c);E>=0&&this._currentSessions.splice(E),e.content!==void 0&&this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:[],delistedKeyIds:c.record.getAssociatedKeyIds()}),(v=i.persistentSessionsStore)==null||v.delete(f.sessionId),i.loadedSessionsStore.closeSession(f).catch(R=>{let k=R instanceof Error?R:"unknown error";m.warn("DRM: failed to close expired session",k)}).then(()=>this._unlockInitDataQueue()).catch(R=>this._onFatalError(R)),this._isStopped()||this.trigger("warning",T.reason);return}if(!(T instanceof Kn)){this._onFatalError(T);return}c.blacklistedSessionError=T,e.content!==void 0&&(m.info("DRM: blacklisting Representations based on protection data."),this.trigger("blackListProtectionData",e)),this._unlockInitDataQueue()}},this._canceller.signal),(o.singleLicensePer===void 0||o.singleLicensePer==="init-data")&&this._unlockInitDataQueue(),l.type==="created-session"){let T=e.values.constructRequestData();try{await i.loadedSessionsStore.generateLicenseRequest(f,e.type,T)}catch(v){let E=i.loadedSessionsStore.getEntryForSession(f);if(E===null||E.closingStatus.type!=="none"){let R=this._currentSessions.indexOf(c);return R>=0&&this._currentSessions.splice(R,1),Promise.resolve()}throw new pe("KEY_GENERATE_REQUEST_ERROR",v instanceof Error?v.toString():"Unknown error")}}return Promise.resolve()}_tryToUseAlreadyCreatedSession(e,t){let{stores:r,options:i}=t,o=Z(this._currentSessions,l=>l.record.isCompatibleWith(e));if(o===void 0)return!1;if(e.forceSessionRecreation===!0)return this.removeSessionForInitData(e,t),!1;let s=o.blacklistedSessionError;if(!_(s))return e.type===void 0||e.content===void 0?(m.error("DRM: This initialization data has already been blacklisted but the current content is not known."),!0):(m.info("DRM: This initialization data has already been blacklisted. Blacklisting the related content."),this.trigger("blackListProtectionData",e),!0);if(e.keyIds!==void 0){let l;if(i.singleLicensePer===void 0||i.singleLicensePer==="init-data"){let{blacklisted:c}=o.keyStatuses;l=Gc(e.keyIds,c)}else{let{whitelisted:c}=o.keyStatuses;l=!Un(e.keyIds,c)}if(l)return e.content===void 0?(m.error("DRM: Cannot forbid key id, the content is unknown."),!0):(m.info("DRM: Current initialization data is linked to blacklisted keys. Marking Representations as not decipherable"),this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:e.keyIds,delistedKeyIds:[]}),!0)}if(r.loadedSessionsStore.reuse(e)!==null)return m.debug("DRM: Init data already processed. Skipping it."),!0;let u=this._currentSessions.indexOf(o);return u===-1?m.error("DRM: Unable to remove processed init data: not found."):(m.debug("DRM: A session from a processed init data is not available anymore. Re-processing it."),this._currentSessions.splice(u,1)),!1}removeSessionForInitData(e,t){let{stores:r}=t,i=r.loadedSessionsStore.reuse(e);i!==null&&r.loadedSessionsStore.closeSession(i.mediaKeySession).catch(()=>m.error("DRM: Cannot close the session from the loaded session store"));let o=Z(this._currentSessions,s=>s.record.isCompatibleWith(e));if(o===void 0)return;let a=this._currentSessions.indexOf(o);a!==-1&&(m.debug("DRM: A session from a processed init is removed due to forceSessionRecreation policy."),this._currentSessions.splice(a,1))}_onFatalError(e){if(this._canceller.isUsed())return;let t=e instanceof Error?e:new Le("NONE","Unknown decryption error");this.error=t,this._initDataQueue.length=0,this._stateData={state:3,isMediaKeysAttached:void 0,isInitDataQueueLocked:void 0,data:null},this._canceller.cancel(),this.trigger("error",t),this._stateData.state===3&&this.trigger("stateChange",this._stateData.state)}_isStopped(){return this._stateData.state===4||this._stateData.state===3}_processCurrentInitDataQueue(){for(;this._stateData.isInitDataQueueLocked===!1;){let e=this._initDataQueue.shift();if(e===void 0)return;this.onInitializationData(e)}}_lockInitDataQueue(){this._stateData.isInitDataQueueLocked===!1&&(this._stateData.isInitDataQueueLocked=!0)}_unlockInitDataQueue(){if(this._stateData.isMediaKeysAttached!==2){m.error("DRM: Trying to unlock in the wrong state");return}this._stateData.isInitDataQueueLocked=!1,this._processCurrentInitDataQueue()}};function Ug(n){let{sessionTypes:e}=n.getConfiguration();return e!==void 0&&Q(e,"persistent-license")}function Yc(n,e){return n.filter(t=>!e.some(r=>ge(r,t)))}function Bg(n,e){let t=n.getAssociatedKeyIds(),r=Yc(t,e);return r.length>0&&m.hasLevel("DEBUG")&&m.debug("DRM: KeySessionRecord's keys missing in the license, blacklisting them",r.map(i=>Ue(i)).join(", ")),r}function Fg(n,e){let t=[],{keyIds:r}=n;return r!==void 0&&(t=Yc(r,e)),t.length>0&&m.hasLevel("DEBUG")&&m.debug("DRM: init data keys missing in the license, blacklisting them",t.map(i=>Ue(i)).join(", ")),t}function Kg(n,e,t,r,i,o){var u;let a=[...i,...o],s=Bg(e,a),d=a.concat(s);if(t!==void 0&&t!=="init-data"){let l=Fg(n,d);d.push(...l);let{content:c}=n;if(r&&c!==void 0){if(t==="content"){let f=new Set,{manifest:g}=c;for(let p of g.periods)qs(f,p);Gs(f,d)}else if(t==="periods"){let{manifest:f}=c;for(let g of f.periods){let p=new Set;if(qs(p,g),((u=n.content)==null?void 0:u.period.id)===g.id)Gs(p,d);else{let I=Array.from(p);for(let y of I)if(d.some(T=>ge(T,y))){Gs(p,d);break}}}}}}return{whitelisted:i,blacklisted:d.slice(i.length)}}function Gs(n,e){let t=Array.from(n.values());for(let r of t)e.some(o=>ge(o,r))||e.push(r)}function qs(n,e){let t=e.adaptations,r=Ir(t).reduce((i,o)=>_(o)?i:i.concat(o),[]);for(let i of r)for(let o of i.representations)if(o.contentProtections!==void 0&&o.contentProtections.keyIds!==void 0)for(let a of o.contentProtections.keyIds)n.add(a)}function Vn(n){let e=Ke.getState(n);return e===null?null:[e.mediaKeySystemAccess.keySystem,e.mediaKeySystemAccess.getConfiguration()]}var $c=Yr;function Qc(n){var t,r,i,o,a;let e=[];for(let s of n.periods){let d=[...(t=s.adaptations.video)!=null?t:[],...(r=s.adaptations.audio)!=null?r:[]];for(let u of d)if(u.supportStatus.hasCodecWithUndefinedSupport)for(let l of u.representations)l.isSupported===void 0&&e.push({mimeType:(i=l.mimeType)!=null?i:"",codec:(a=(o=l.codecs)==null?void 0:o[0])!=null?a:""})}return e}var Xc=[];function Pt(n){Q(Xc,n)||(console.warn(n),Xc.push(n))}var Qt=["audio","video","text"];function yn(n){var o,a;let e=n.timeBounds;if(e.timeshiftDepth===null)return(o=e.minimumSafePosition)!=null?o:0;let{maximumTimeData:t}=e,r;if(!e.maximumTimeData.isLinear)r=t.maximumSafePosition;else{let s=F()-t.time;r=t.maximumSafePosition+s/1e3}let i=r-e.timeshiftDepth;return Math.max((a=e.minimumSafePosition)!=null?a:0,i)}function In(n){let{maximumTimeData:e}=n.timeBounds;if(!n.isLive||e.livePosition===void 0)return;if(!e.isLinear)return e.livePosition;let t=F()-e.time;return e.livePosition+t/1e3}function St(n){let{maximumTimeData:e}=n.timeBounds;if(!e.isLinear)return e.maximumSafePosition;let t=F()-e.time;return e.maximumSafePosition+t/1e3}function pt(n,e){if(e===void 0)return Ys(n).filter(r=>r.supportStatus.hasSupportedCodec!==!1&&r.supportStatus.isDecipherable!==!1);let t=n.adaptations[e];return t===void 0?[]:t.filter(r=>r.supportStatus.hasSupportedCodec!==!1&&r.supportStatus.isDecipherable!==!1)}function Jc(n,e){let t=null;for(let r of n.periods){if(js(r,e,t))return r;t=r}}function jo(n,e){let t=e.end;if(t===void 0)return null;let r=Z(n.periods,i=>i.end===void 0||t<i.end);return r===void 0?null:r}function js(n,e,t){return e>=n.start&&(n.end===void 0||e<n.end)?!0:e===n.end&&(t===null||t.start>n.end)}function Ys(n){let e=n.adaptations;return Ir(e).reduce((t,r)=>_(r)?t:t.concat(r),[])}function Yo(n,e){var r,i;let t={language:(r=n.language)!=null?r:"",normalized:(i=n.normalizedLanguage)!=null?i:"",audioDescription:n.isAudioDescription===!0,id:n.id,representations:(e?n.representations.filter(o=>o.isSupported===!0&&o.decipherable!==!1):n.representations).map(Vg),label:n.label};return n.isDub===!0&&(t.dub=!0),t}function $o(n){var e,t;return{language:(e=n.language)!=null?e:"",normalized:(t=n.normalizedLanguage)!=null?t:"",closedCaption:n.isClosedCaption===!0,id:n.id,label:n.label,forced:n.isForcedSubtitles}}function Qo(n,e){let t=n.trickModeTracks!==void 0?n.trickModeTracks.map(i=>{let o=(e?i.representations.filter(s=>s.isSupported===!0&&s.decipherable!==!1):i.representations).map(Zc),a={id:i.id,representations:o,isTrickModeTrack:!0};return i.isSignInterpreted===!0&&(a.signInterpreted=!0),a}):void 0,r={id:n.id,representations:(e?n.representations.filter(i=>i.isSupported===!0&&i.decipherable!==!1):n.representations).map(Zc),label:n.label};return n.isSignInterpreted===!0&&(r.signInterpreted=!0),n.isTrickModeTrack===!0&&(r.isTrickModeTrack=!0),t!==void 0&&(r.trickModeTracks=t),r}function Vg(n){let{id:e,bitrate:t,codecs:r,isSpatialAudio:i,isSupported:o,decipherable:a}=n;return{id:e,bitrate:t,codec:r==null?void 0:r[0],isSpatialAudio:i,isCodecSupported:o,decipherable:a}}function Zc(n){let{id:e,bitrate:t,frameRate:r,width:i,height:o,codecs:a,hdrInfo:s,isSupported:d,decipherable:u,contentProtections:l}=n;return{id:e,bitrate:t,frameRate:r,width:i,height:o,codec:a==null?void 0:a[0],hdrInfo:s,isCodecSupported:d,decipherable:u,contentProtections:l!==void 0?{keyIds:l.keyIds}:void 0}}function Xt(n){switch(n.type){case"audio":return{type:"audio",track:Yo(n,!1)};case"video":return{type:"video",track:Qo(n,!1)};case"text":return{type:"text",track:$o(n)}}}function ef(n){return new Function(`return (${n}(arguments[0], arguments[1]))`)}var $r=class{constructor(e){this.supportMap=new Map,this.addCodecs(e)}addCodecs(e){for(let t of e){let r=this.supportMap.get(t.mimeType);r===void 0&&(r=new Map,this.supportMap.set(t.mimeType,r)),r.set(t.codec,{supported:t.supported,supportedIfEncrypted:t.supportedIfEncrypted})}}isSupported(e,t,r){let i=this.supportMap.get(e);if(i===void 0)return;let o=i.get(t);if(o!==void 0)return r?o.supportedIfEncrypted:o.supported}};var Qr=class{constructor(e,t,r,i){if(this.id=e.id,this.adaptations=Object.keys(e.adaptations).reduce((o,a)=>{let s=e.adaptations[a];if(_(s))return o;let d=s.map(u=>{let l=new kr(u,r,{representationFilter:i});return l.representations.length>0&&l.supportStatus.hasSupportedCodec===!1&&t.push(l),l}).filter(u=>u.representations.length>0);if(d.every(u=>u.supportStatus.hasSupportedCodec===!1)&&s.length>0&&(a==="video"||a==="audio"))throw new te("MANIFEST_INCOMPATIBLE_CODECS_ERROR","No supported "+a+" adaptations",{tracks:void 0});return d.length>0&&(o[a]=d),o},{}),!Array.isArray(this.adaptations.video)&&!Array.isArray(this.adaptations.audio))throw new te("MANIFEST_PARSE_ERROR","No supported audio and video tracks.");this.duration=e.duration,this.start=e.start,!_(this.duration)&&!_(this.start)&&(this.end=this.start+this.duration),this.streamEvents=e.streamEvents===void 0?[]:e.streamEvents}refreshCodecSupport(e,t){Object.keys(this.adaptations).forEach(r=>{let i=this.adaptations[r];if(i===void 0)return;let o=!1;for(let a of i){if(!a.supportStatus.hasCodecWithUndefinedSupport){a.supportStatus.hasSupportedCodec===!0&&(o=!0);continue}let s=a.supportStatus.hasSupportedCodec;a.refreshCodecSupport(t),s!==!1&&a.supportStatus.hasSupportedCodec===!1&&e.push(a),o===!1?o=a.supportStatus.hasSupportedCodec:o===void 0&&a.supportStatus.hasSupportedCodec===!0&&(o=!0)}if((r==="video"||r==="audio")&&o===!1)throw new te("MANIFEST_INCOMPATIBLE_CODECS_ERROR","No supported "+r+" adaptations",{tracks:void 0})},{})}getAdaptations(){return Ys(this)}getAdaptationsForType(e){let t=this.adaptations[e];return t!=null?t:[]}getAdaptation(e){return Z(this.getAdaptations(),({id:t})=>e===t)}getSupportedAdaptations(e){return pt(this,e)}containsTime(e,t){return js(this,e,t)}getMetadataSnapshot(){let e={},t=this.getAdaptations();for(let r of t){let i=e[r.type];i===void 0&&(i=[],e[r.type]=i),i.push(r.getMetadataSnapshot())}return{start:this.start,end:this.end,id:this.id,streamEvents:this.streamEvents,adaptations:e}}};function Xr(n,e,t){let r={updatedAdaptations:[],removedAdaptations:[],addedAdaptations:[]};n.start=e.start,n.end=e.end,n.duration=e.duration,n.streamEvents=e.streamEvents;let i=n.getAdaptations(),o=e.getAdaptations();for(let a=0;a<i.length;a++){let s=i[a],d=he(o,u=>u.id===s.id);if(d===-1){m.warn('Manifest: Adaptation "'+i[a].id+'" not found when merging.');let[u]=i.splice(a,1);a--,r.removedAdaptations.push({id:u.id,trackType:u.type})}else{let[u]=o.splice(d,1),l=[],c=[],f=[];r.updatedAdaptations.push({adaptation:s.id,trackType:s.type,updatedRepresentations:l,addedRepresentations:c,removedRepresentations:f});let g=s.representations,p=u.representations.slice();for(let I=0;I<g.length;I++){let y=g[I],b=he(p,T=>T.id===y.id);if(b===-1){m.warn(`Manifest: Representation "${g[I].id}" not found when merging.`);let[T]=g.splice(I,1);I--,f.push(T.id)}else{let[T]=p.splice(b,1);l.push(y.getMetadataSnapshot()),y.cdnMetadata=T.cdnMetadata,t===0?y.index._replace(T.index):y.index._update(T.index)}}p.length>0&&(m.warn(`Manifest: ${p.length} new Representations found when merging.`),s.representations.push(...p),c.push(...p.map(I=>I.getMetadataSnapshot())))}}if(o.length>0){m.warn(`Manifest: ${o.length} new Adaptations found when merging.`);for(let a of o){let s=n.adaptations[a.type];s===void 0?n.adaptations[a.type]=[a]:s.push(a),r.addedAdaptations.push(a.getMetadataSnapshot())}}return r}function tf(n,e){let t={updatedPeriods:[],addedPeriods:[],removedPeriods:[]},r=0;for(let o=0;o<e.length;o++){let a=e[o],s=r,d=n[s];for(;d!==void 0&&d.id!==a.id;)s++,d=n[s];if(d!==void 0){let u=Xr(d,a,0);t.updatedPeriods.push({period:{id:d.id,start:d.start,end:d.end,duration:d.duration,streamEvents:d.streamEvents},result:u});let l=e.slice(r,o),c=s-r,f=n.splice(r,c,...l);t.removedPeriods.push(...f.map(g=>({id:g.id,start:g.start,end:g.end}))),t.addedPeriods.push(...l.map(g=>g.getMetadataSnapshot())),r=o+1}}if(r>n.length)return m.error("Manifest: error when updating Periods"),t;if(r<n.length){let o=n.splice(r,n.length-r);t.removedPeriods.push(...o.map(a=>({id:a.id,start:a.start,end:a.end})))}let i=e.slice(r,e.length);return i.length>0&&(n.push(...i),t.addedPeriods.push(...i.map(o=>o.getMetadataSnapshot()))),t}function nf(n,e){let t={updatedPeriods:[],addedPeriods:[],removedPeriods:[]};if(n.length===0)return n.splice(0,0,...e),t.addedPeriods.push(...e.map(s=>s.getMetadataSnapshot())),t;if(e.length===0)return t;let r=n[n.length-1];if(r.start<e[0].start){if(r.end!==e[0].start)throw new te("MANIFEST_UPDATE_ERROR","Cannot perform partial update: not enough data");return n.push(...e),t.addedPeriods.push(...e.map(s=>s.getMetadataSnapshot())),t}let i=he(n,({id:s})=>s===e[0].id);if(i<0)throw new te("MANIFEST_UPDATE_ERROR","Cannot perform partial update: incoherent data");let o=Xr(n[i],e[0],1);t.updatedPeriods.push({period:G(n[i].getMetadataSnapshot(),{adaptations:void 0}),result:o});let a=i+1;for(let s=1;s<e.length;s++){let d=e[s],u=-1;for(let l=a;l<n.length;l++)if(d.id===n[l].id){u=l;break}if(u<0){let l=-1;for(let g=a;g<n.length;g++)if(d.start<n[g].start){l=g;break}let c=l-a,f=n.splice(a,c,d);t.addedPeriods.push(d.getMetadataSnapshot()),t.removedPeriods.push(...f.map(g=>({id:g.id,start:g.start,end:g.end})))}else{if(u>a){m.warn("Manifest: old Periods not found in new when updating, removing");let c=n.splice(a,u-a);t.removedPeriods.push(...c.map(f=>({id:f.id,start:f.start,end:f.end}))),u=a}let l=Xr(n[u],d,0);t.updatedPeriods.push({period:G(n[u].getMetadataSnapshot(),{adaptations:void 0}),result:l})}a++}if(a<n.length){m.warn("Manifest: Ending Periods not found in new when updating, removing");let s=n.splice(a,n.length-a);t.removedPeriods.push(...s.map(d=>({id:d.id,start:d.start,end:d.end})))}return t}var zg=et(),Zr=class extends re{constructor(e,t,r){var s;super();let{representationFilter:i,manifestUpdateUrl:o}=t;this.manifestFormat=0,this.id=zg(),this.expired=(s=e.expired)!=null?s:null,this.transport=e.transportType,this.clockOffset=e.clockOffset,this._cachedCodecSupport=new $r([]);let a=[];if(this.periods=e.periods.map(d=>new Qr(d,a,this._cachedCodecSupport,i)).sort((d,u)=>d.start-u.start),a.length>0){let d=new te("MANIFEST_INCOMPATIBLE_CODECS_ERROR","An Adaptation contains only incompatible codecs.",{tracks:a.map(Xt)});r.push(d)}this.adaptations=this.periods[0]===void 0?{}:this.periods[0].adaptations,this.timeBounds=e.timeBounds,this.isDynamic=e.isDynamic,this.isLive=e.isLive,this.isLastPeriodKnown=e.isLastPeriodKnown,this.uris=e.uris===void 0?[]:e.uris,this.updateUrl=o,this.lifetime=e.lifetime,this.clockOffset=e.clockOffset,this.suggestedPresentationDelay=e.suggestedPresentationDelay,this.availabilityStartTime=e.availabilityStartTime,this.publishTime=e.publishTime}updateCodecSupport(e=[]){if(e.length===0)return null;this._cachedCodecSupport.addCodecs(e);let t=[];for(let r of this.periods)r.refreshCodecSupport(t,this._cachedCodecSupport);return this.trigger("supportUpdate",null),t.length>0?new te("MANIFEST_INCOMPATIBLE_CODECS_ERROR","An Adaptation contains only incompatible codecs.",{tracks:t.map(Xt)}):null}getPeriod(e){return Z(this.periods,t=>e===t.id)}getPeriodForTime(e){return Jc(this,e)}getNextPeriod(e){return Z(this.periods,t=>t.start>e)}getPeriodAfter(e){return jo(this,e)}getUrls(){return this.uris}replace(e){this._performUpdate(e,0)}update(e){this._performUpdate(e,1)}getMinimumSafePosition(){return yn(this)}getLivePosition(){return In(this)}getMaximumSafePosition(){return St(this)}updateCodecSupportList(e){this._cachedCodecSupport=e}updateRepresentationsDeciperability(e){let t=Hg(this,e);t.length>0&&this.trigger("decipherabilityUpdate",t)}getAdaptations(){Pt("manifest.getAdaptations() is deprecated. Please use manifest.period[].getAdaptations() instead");let e=this.periods[0];if(e===void 0)return[];let t=e.adaptations,r=[];for(let i in t)if(t.hasOwnProperty(i)){let o=t[i];r.push(...o)}return r}getAdaptationsForType(e){Pt("manifest.getAdaptationsForType(type) is deprecated. Please use manifest.period[].getAdaptationsForType(type) instead");let t=this.periods[0];if(t===void 0)return[];let r=t.adaptations[e];return r===void 0?[]:r}getAdaptation(e){return Pt("manifest.getAdaptation(id) is deprecated. Please use manifest.period[].getAdaptation(id) instead"),Z(this.getAdaptations(),({id:t})=>e===t)}getMetadataSnapshot(){let e=[];for(let t of this.periods)e.push(t.getMetadataSnapshot());return{manifestFormat:1,id:this.id,periods:e,isDynamic:this.isDynamic,isLive:this.isLive,isLastPeriodKnown:this.isLastPeriodKnown,suggestedPresentationDelay:this.suggestedPresentationDelay,clockOffset:this.clockOffset,uris:this.uris,availabilityStartTime:this.availabilityStartTime,timeBounds:this.timeBounds}}getCodecsWithUnknownSupport(){return Qc(this)}_performUpdate(e,t){this.availabilityStartTime=e.availabilityStartTime,this.expired=e.expired,this.isDynamic=e.isDynamic,this.isLive=e.isLive,this.isLastPeriodKnown=e.isLastPeriodKnown,this.lifetime=e.lifetime,this.clockOffset=e.clockOffset,this.suggestedPresentationDelay=e.suggestedPresentationDelay,this.transport=e.transport,this.publishTime=e.publishTime;let r;if(t===0)this.timeBounds=e.timeBounds,this.uris=e.uris,r=tf(this.periods,e.periods);else{this.timeBounds.maximumTimeData=e.timeBounds.maximumTimeData,this.updateUrl=e.uris[0],r=nf(this.periods,e.periods);let i=this.getMinimumSafePosition();for(;this.periods.length>0;){let o=this.periods[0];if(o.end===void 0||o.end>i)break;this.periods.shift()}}this.updateCodecSupport(),this.adaptations=this.periods[0]===void 0?{}:this.periods[0].adaptations,this.trigger("manifestUpdate",r)}};function Hg(n,e){let t=[];for(let r of n.periods)for(let i of r.getAdaptations()){let o=!0;for(let a of i.representations){let s={manifest:n,period:r,adaptation:i,representation:a},d=e(s);d!==!1&&(o=!1),d!==a.decipherable&&(t.push(s),a.decipherable=d,d===!0?i.supportStatus.isDecipherable=!0:d===void 0&&i.supportStatus.isDecipherable===!1&&(i.supportStatus.isDecipherable=void 0),m.debug(`Decipherability changed for "${a.id}"`,`(${a.bitrate})`,String(a.decipherable)))}o&&(i.supportStatus.isDecipherable=!1)}return t}function Mt(n,e){return n.segment.id===e.segment.id&&n.representation.uniqueId===e.representation.uniqueId}function bn(n){if(_(n))return"";let{period:e,adaptation:t,representation:r,segment:i}=n,o;return i.isInit?o="init":i.complete?o=`${i.time}-${i.duration}`:o=`${i.time}`,`${t.type} P: ${e.id} A: ${t.id} R: ${r.id} S: ${o}`}var zn=Zr;function At(n){return n instanceof Ee?new it("PIPELINE_LOAD_ERROR",n):Oe(n,{defaultCode:"PIPELINE_LOAD_ERROR",defaultReason:"Unknown error when fetching the Manifest"})}function Wg(n){return n instanceof Ee?n.type===fn.ERROR_HTTP_CODE?n.status>=500||n.status===404||n.status===415||n.status===412:n.type===fn.TIMEOUT||n.type===fn.ERROR_EVENT:n instanceof rt?typeof n.canRetry=="boolean"?n.canRetry:n.xhr!==void 0?n.xhr.status>=500||n.xhr.status===404||n.xhr.status===415||n.xhr.status===412:!1:Gt(n)&&n.code==="INTEGRITY_ERROR"}async function $s(n,e,t,r,i){if(i.cancellationError!==null)return Promise.reject(i.cancellationError);let{baseDelay:o,maxDelay:a,maxRetry:s,onRetry:d}=r;n!==null&&n.length===0&&m.warn("Fetchers: no CDN given to `scheduleRequestWithCdns`.");let u=new Map,l=c();if(l===void 0)throw new Error("No CDN to request");return f(l);function c(){if(n===null){let y=u.get(null);return y!==void 0&&y.isBlacklisted?void 0:null}else{if(e===null)return I(n);{let y=e.getCdnPreferenceForResource(n);return I(y)}}}async function f(y){try{return await t(y,i)}catch(b){if(B.isCancellationError(b))throw b;y!==null&&e!==null&&e.downgradeCdn(y);let T=u.get(y);if(T===void 0?(T={errorCounter:1,blockedUntil:void 0,isBlacklisted:!1},u.set(y,T)):T.errorCounter++,!Wg(b))return T.blockedUntil=void 0,T.isBlacklisted=!0,g(b);if(T.errorCounter>s)T.blockedUntil=void 0,T.isBlacklisted=!0;else{let v=T.errorCounter,E=Math.min(o*Math.pow(2,v-1),a),R=Gr(E);T.blockedUntil=F()+R}return g(b)}}async function g(y){let b=c();if(i.isCancelled())throw i.cancellationError;if(b===void 0)throw y;if(d(y),i.isCancelled())throw i.cancellationError;return p(b,y)}function p(y,b){let T=u.get(y);if(T===void 0||T.blockedUntil===void 0)return f(y);let v=F(),E=T.blockedUntil-v;if(E<=0)return f(y);let R=new B,k=R.linkToSignal(i);return new Promise((x,M)=>{e==null||e.addEventListener("priorityChange",()=>{let O=c();if(i.isCancelled())throw i.cancellationError;if(O===void 0)return N(b);O!==y&&(R.cancel(),p(O,b).then(P,N))},R.signal),qt(E,R.signal).then(()=>f(y).then(P,N),X);function P(O){k(),x(O)}function N(O){k(),M(O)}})}function I(y){var T;if(u.size===0)return y[0];let b=F();return(T=y.filter(v=>{var E;return((E=u.get(v))==null?void 0:E.isBlacklisted)!==!0}).reduce((v,E)=>{var k;let R=(k=u.get(E))==null?void 0:k.blockedUntil;return R!==void 0&&R<=b&&(R=void 0),v===void 0?[E,R]:v[1]===void 0?v:R===void 0?[E,void 0]:R<v[1]?[E,R]:v},void 0))==null?void 0:T[0]}}function Qs(n,e,t){return $s(null,null,n,e,t)}var Jr=class extends re{constructor(e,t,r){super(),this.scheduleManualRefresh=X,this._manifestUrls=e,this._pipelines=t.manifest,this._transportName=t.transportName,this._settings=r,this._canceller=new B,this._isStarted=!1,this._isRefreshPending=!1,this._consecutiveUnsafeMode=0,this._prioritizedContentUrl=null}dispose(){this._canceller.cancel(),this.removeEventListener()}start(){if(this._isStarted)return;this._isStarted=!0;let e,t=this._settings.initialManifest;t instanceof zn?e=Promise.resolve({manifest:t}):t!==void 0?e=this.parse(t,{previousManifest:null,unsafeMode:!1},void 0):e=this._fetchManifest(void 0).then(r=>r.parse({previousManifest:null,unsafeMode:!1})),e.then(r=>{this.trigger("manifestReady",r.manifest),this._canceller.isUsed()||this._recursivelyRefreshManifest(r.manifest,r)}).catch(r=>this._onFatalError(r))}updateContentUrls(e,t){var r;this._prioritizedContentUrl=(r=e==null?void 0:e[0])!=null?r:void 0,t&&this.scheduleManualRefresh({enablePartialRefresh:!1,delay:0,canUseUnsafeMode:!1})}async _fetchManifest(e){var u;let t=this._canceller.signal,r=this._settings,i=this._transportName,o=this._pipelines,a=e!=null?e:(u=this._manifestUrls)==null?void 0:u[0],s=this._getBackoffSetting(l=>{this.trigger("warning",At(l))});try{let l=await d(a);return{parse:c=>this._parseLoadedManifest(l,c,a)}}catch(l){throw At(l)}function d(l){var y;let{loadManifest:c}=o,f=r.requestTimeout===void 0?U.getCurrent().DEFAULT_REQUEST_TIMEOUT:r.requestTimeout,g=r.connectionTimeout===void 0?U.getCurrent().DEFAULT_CONNECTION_TIMEOUT:r.connectionTimeout;f<0&&(f=void 0),g<0&&(g=void 0);let p={timeout:f,connectionTimeout:g,cmcdPayload:(y=r.cmcdDataBuilder)==null?void 0:y.getCmcdDataForManifest(i)};return Qs(()=>c(l,p,t),s,t)}}parse(e,t,r){return this._parseLoadedManifest({responseData:e,size:void 0,requestDuration:void 0},t,r)}async _parseLoadedManifest(e,t,r){var I;let i=F(),o=this._canceller.signal,a=this.trigger.bind(this),{sendingTime:s,receivedTime:d}=e,u=this._getBackoffSetting(y=>{this.trigger("warning",At(y))}),l=r!=null?r:(I=this._manifestUrls)==null?void 0:I[0],c={externalClockOffset:t.externalClockOffset,unsafeMode:t.unsafeMode,previousManifest:t.previousManifest,originalUrl:l};try{let y=this._pipelines.parseManifest(e,c,g,o,f);if(Gg(y)){let{manifest:b,warnings:T}=await y;return p(b,T)}else return p(y.manifest,y.warnings)}catch(y){throw Oe(y,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"})}async function f(y){try{return await Qs(y,u,o)}catch(b){throw At(b)}}function g(y){for(let b of y){if(o.isCancelled())return;let T=Oe(b,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"});a("warning",T)}}function p(y,b){g(b);let T=F()-i;return m.info(`MF: Manifest parsed in ${T}ms`),{manifest:y,sendingTime:s,receivedTime:d,parsingTime:T}}}_getBackoffSetting(e){let{DEFAULT_MAX_MANIFEST_REQUEST_RETRY:t,INITIAL_BACKOFF_DELAY_BASE:r,MAX_BACKOFF_DELAY_BASE:i}=U.getCurrent(),{lowLatencyMode:o,maxRetry:a}=this._settings,s=o?r.LOW_LATENCY:r.REGULAR,d=o?i.LOW_LATENCY:i.REGULAR,u=a!=null?a:t;return{onRetry:e,baseDelay:s,maxDelay:d,maxRetry:u}}_recursivelyRefreshManifest(e,{sendingTime:t,parsingTime:r,updatingTime:i}){let{MAX_CONSECUTIVE_MANIFEST_PARSING_IN_UNSAFE_MODE:o,MIN_MANIFEST_PARSING_TIME_TO_ENTER_UNSAFE_MODE:a}=U.getCurrent(),s=r!==void 0?r+(i!=null?i:0):void 0,d=!1;this._consecutiveUnsafeMode>0?d=this._consecutiveUnsafeMode<o:s!==void 0&&(d=s>=a);let u=t===void 0?0:F()-t,l=Math.max(this._settings.minimumManifestUpdateInterval-u,0),c=new B;if(c.linkToSignal(this._canceller.signal),this.scheduleManualRefresh=f=>{let{enablePartialRefresh:g,delay:p,canUseUnsafeMode:I}=f,y=I&&d,b=t===void 0?0:F()-t,T=Math.max(this._settings.minimumManifestUpdateInterval-b,0),v=setTimeout(()=>{c.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:g,unsafeMode:y})},Math.max((p!=null?p:0)-b,T));c.signal.register(()=>{clearTimeout(v)})},e.expired!==null){let f=setTimeout(()=>{var g;(g=e.expired)==null||g.then(()=>{c.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},X)},l);c.signal.register(()=>{clearTimeout(f)})}if(e.lifetime!==void 0&&e.lifetime>=0){let f=e.lifetime*1e3-u,g;s===void 0?g=f:e.lifetime<3&&s>=100?(g=Math.min(Math.max(3e3-u,Math.max(f,0)+s),f*6),m.info("MUS: Manifest update rythm is too frequent. Postponing next request.",f,g)):s>=e.lifetime*1e3/10?(g=Math.min(Math.max(f,0)+s,f*6),m.info("MUS: Manifest took too long to parse. Postponing next request",g,g)):g=f;let p=setTimeout(()=>{c.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},Math.max(g,l));c.signal.register(()=>{clearTimeout(p)})}}_triggerNextManifestRefresh(e,{enablePartialRefresh:t,unsafeMode:r}){let i=e.updateUrl,o,a;this._prioritizedContentUrl!==null?(o=!0,a=this._prioritizedContentUrl,this._prioritizedContentUrl=null):(o=!t||i===void 0,a=o?e.getUrls()[0]:i);let s=e.clockOffset;r?(this._consecutiveUnsafeMode+=1,m.info('Init: Refreshing the Manifest in "unsafeMode" for the '+String(this._consecutiveUnsafeMode)+" consecutive time.")):this._consecutiveUnsafeMode>0&&(m.info('Init: Not parsing the Manifest in "unsafeMode" anymore after '+String(this._consecutiveUnsafeMode)+" consecutive times."),this._consecutiveUnsafeMode=0),!this._isRefreshPending&&(this._isRefreshPending=!0,this._fetchManifest(a).then(d=>d.parse({externalClockOffset:s,previousManifest:e,unsafeMode:r})).then(d=>{this._isRefreshPending=!1;let{manifest:u,sendingTime:l,parsingTime:c}=d,f=F();if(o)e.replace(u);else try{e.update(u)}catch(p){let I=p instanceof Error?p.message:"unknown error";m.warn(`MUS: Attempt to update Manifest failed: ${I}`,"Re-downloading the Manifest fully");let{FAILED_PARTIAL_UPDATE_MANIFEST_REFRESH_DELAY:y}=U.getCurrent(),b=l===void 0?0:F()-l,T=Math.max(this._settings.minimumManifestUpdateInterval-b,0),v=X,E=setTimeout(()=>{v(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:!1})},Math.max(y-b,T));v=this._canceller.signal.register(()=>{clearTimeout(E)});return}let g=F()-f;this._recursivelyRefreshManifest(e,{sendingTime:l,parsingTime:c,updatingTime:g})}).catch(d=>{this._isRefreshPending=!1,this._onFatalError(d)}))}_onFatalError(e){this._canceller.isUsed()||(this.trigger("error",e),this.dispose())}};function Gg(n){return n instanceof Promise}var Xs=Jr;var ei=class extends re{constructor(e){super(),this._downgradedCdnList={metadata:[],timeouts:[]},e.register(()=>{for(let t of this._downgradedCdnList.timeouts)clearTimeout(t);this._downgradedCdnList={metadata:[],timeouts:[]}})}getCdnPreferenceForResource(e){return e.length<=1?e:this._innerGetCdnPreferenceForResource(e)}downgradeCdn(e){let t=rf(this._downgradedCdnList.metadata,e);t>=0&&this._removeIndexFromDowngradeList(t);let{DEFAULT_CDN_DOWNGRADE_TIME:r}=U.getCurrent(),i=r;this._downgradedCdnList.metadata.push(e);let o=setTimeout(()=>{let a=rf(this._downgradedCdnList.metadata,e);a>=0&&this._removeIndexFromDowngradeList(a),this.trigger("priorityChange",null)},i);this._downgradedCdnList.timeouts.push(o),this.trigger("priorityChange",null)}_innerGetCdnPreferenceForResource(e){let[t,r]=e.reduce((i,o)=>(this._downgradedCdnList.metadata.some(a=>a.id===o.id&&a.baseUrl===o.baseUrl)?i[1].push(o):i[0].push(o),i),[[],[]]);return t.concat(r)}_removeIndexFromDowngradeList(e){this._downgradedCdnList.metadata.splice(e,1);let t=this._downgradedCdnList.timeouts.splice(e,1);clearTimeout(t[0])}};function rf(n,e){return n.length===0?-1:e.id!==void 0?he(n,t=>t.id===e.id):he(n,t=>t.baseUrl===e.baseUrl)}function Zs(n,e){let t=new WeakMap;return{createRequest(r,i,o,a){let s=u=>e(r,o,u),d=n.create(s,i,o,a);return t.set(d,s),d},updatePriority(r,i){let o=t.get(r);if(o===void 0){m.warn("Fetchers: Cannot update the priority of a request: task not found.");return}n.updatePriority(o,i)}}}var Js=class{constructor(){this._cache=new WeakMap}add({representation:e,segment:t},r){t.isInit&&this._cache.set(e,r)}get({representation:e,segment:t}){if(t.isInit){let r=this._cache.get(e);if(r!==void 0)return r}return null}},of=Js;var qg=et();function ed({bufferType:n,pipeline:e,cdnPrioritizer:t,cmcdDataBuilder:r,eventListeners:i,requestOptions:o}){let a;o.connectionTimeout===void 0||o.connectionTimeout<0?a=void 0:a=o.connectionTimeout;let s={timeout:o.requestTimeout<0?void 0:o.requestTimeout,connectionTimeout:a,cmcdPayload:void 0},d=Q(["audio","video"],n)?new of:void 0,{loadSegment:u,parseSegment:l}=e;return async function(f,g,p){var $,j,z;let{segment:I,adaptation:y,representation:b,manifest:T,period:v}=f,E=bn(f),R=qg(),k,x=[],M=0,P=!1,N={segment:I,type:y.type,language:y.language,isLive:T.isLive,periodStart:v.start,periodEnd:v.end,mimeType:b.mimeType,codecs:b.codecs[0],manifestPublishTime:T.publishTime},O={onProgress(q){var W;k===void 0&&q.totalSize!==void 0&&q.size<q.totalSize&&((W=i.onProgress)==null||W.call(i,{duration:q.duration,size:q.size,totalSize:q.totalSize,timestamp:F(),id:R}))},onNewChunk(q){g.onChunk(D(q,!0))}},K=d!==void 0?d.get(f):null;if(K!==null)return m.debug("SF: Found wanted segment in cache",E),g.onChunk(D(K,!1)),Promise.resolve();m.debug("SF: Beginning request",E),($=i.onRequestBegin)==null||$.call(i,{requestTimestamp:F(),id:R,content:f}),p.register(A);try{let q=await $s(f.representation.cdnMetadata,t,C,G({onRetry:L},o),p);if(q.resultType==="segment-loaded"){let W=q.resultData.responseData;d!==void 0&&d.add(f,q.resultData.responseData),g.onChunk(D(W,!1))}else q.resultType==="segment-created"&&g.onChunk(D(q.resultData,!1));m.debug("SF: Segment request ended with success",E),g.onAllChunksReceived(),q.resultType!=="segment-created"?(k=q.resultData,V()):k=null,p.isCancelled()||(j=i.onRequestEnd)==null||j.call(i,{id:R}),p.deregister(A)}catch(q){throw p.deregister(A),k=null,q instanceof Me?(m.debug("SF: Segment request aborted",E),q):(m.debug("SF: Segment request failed",E),(z=i.onRequestEnd)==null||z.call(i,{id:R}),At(q))}function A(){var q;k===void 0&&(m.debug("SF: Segment request cancelled",E),k=null,(q=i.onRequestEnd)==null||q.call(i,{id:R}))}function C(q){return s.cmcdPayload=r==null?void 0:r.getCmcdDataForSegmentRequest(f),u(q,N,s,p,O)}function D(q,W){x.push(!1);let se=x.length-1;return function(de){let Se={data:q,isChunked:W};try{let Y=l(Se,N,de);return x[se]||(M=M!==void 0&&Y.segmentType==="media"&&Y.chunkInfos!==null&&Y.chunkInfos.duration!==void 0?M+Y.chunkInfos.duration:void 0,x[se]=!0,V()),Y}catch(Y){throw Oe(Y,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}}}function L(q){g.onRetry(At(q))}function V(){var q;P||!_(k)&&k.size!==void 0&&k.requestDuration!==void 0&&x.length>0&&x.every(W=>W)&&(P=!0,(q=i.onMetrics)==null||q.call(i,{size:k.size,requestDuration:k.requestDuration,content:f,segmentDuration:M}))}}}function af({maxRetry:n,lowLatencyMode:e,requestTimeout:t,connectionTimeout:r}){let{DEFAULT_MAX_REQUESTS_RETRY_ON_ERROR:i,DEFAULT_REQUEST_TIMEOUT:o,DEFAULT_CONNECTION_TIMEOUT:a,INITIAL_BACKOFF_DELAY_BASE:s,MAX_BACKOFF_DELAY_BASE:d}=U.getCurrent();return{maxRetry:n!=null?n:i,baseDelay:e?s.LOW_LATENCY:s.REGULAR,maxDelay:e?d.LOW_LATENCY:d.REGULAR,requestTimeout:t===void 0?o:t,connectionTimeout:r===void 0?a:r}}var ti=class extends re{constructor(e,t){super(),this._segmentFetcher=e,this._currentContentInfo=null,this.isMediaSegmentQueueInterrupted=t}getRequestedInitSegment(){var e,t,r;return(r=(t=(e=this._currentContentInfo)==null?void 0:e.initSegmentRequest)==null?void 0:t.segment)!=null?r:null}getRequestedMediaSegment(){var e,t,r;return(r=(t=(e=this._currentContentInfo)==null?void 0:e.mediaSegmentRequest)==null?void 0:t.segment)!=null?r:null}resetForContent(e,t){var a;(a=this._currentContentInfo)==null||a.currentCanceller.cancel();let r=new H({initSegment:null,segmentQueue:[]}),i=new B;i.signal.register(()=>{r.finish()});let o={content:e,downloadQueue:r,initSegmentInfoRef:t?new H(void 0):new H(null),currentCanceller:i,initSegmentRequest:null,mediaSegmentRequest:null,mediaSegmentAwaitingInitMetadata:null};return this._currentContentInfo=o,this.isMediaSegmentQueueInterrupted.onUpdate(s=>{s||(m.debug("SQ: Media segment can be loaded again, restarting queue.",e.adaptation.type),this._restartMediaSegmentDownloadingQueue(o))},{clearSignal:i.signal}),r.onUpdate(s=>{let{segmentQueue:d}=s;if(d.length>0&&d[0].segment.id===o.mediaSegmentAwaitingInitMetadata)return;let u=o.mediaSegmentRequest;if(d.length===0){if(u===null)return;m.debug("SQ: no more media segment to request. Cancelling queue.",e.adaptation.type),this._restartMediaSegmentDownloadingQueue(o);return}else if(u===null){m.debug("SQ: Media segments now need to be requested. Starting queue.",e.adaptation.type,d.length),this._restartMediaSegmentDownloadingQueue(o);return}else{let l=d[0];if(u.segment.id!==l.segment.id){m.debug("SQ: Next media segment changed, cancelling previous",e.adaptation.type),this._restartMediaSegmentDownloadingQueue(o);return}u.priority!==l.priority&&(m.debug("SQ: Priority of next media segment changed, updating",e.adaptation.type,u.priority,l.priority),this._segmentFetcher.updatePriority(u.request,l.priority));return}},{emitCurrentValue:!0,clearSignal:i.signal}),r.onUpdate(s=>{var u;let d=o.initSegmentRequest;if(s.initSegment!==null&&d!==null){s.initSegment.priority!==d.priority&&this._segmentFetcher.updatePriority(d.request,s.initSegment.priority);return}else if(((u=s.initSegment)==null?void 0:u.segment.id)===(d==null?void 0:d.segment.id))return;s.initSegment===null&&m.debug("SQ: no more init segment to request. Cancelling queue.",e.adaptation.type),this._restartInitSegmentDownloadingQueue(o,s.initSegment)},{emitCurrentValue:!0,clearSignal:i.signal}),r}stop(){var e;(e=this._currentContentInfo)==null||e.currentCanceller.cancel(),this._currentContentInfo=null}_restartMediaSegmentDownloadingQueue(e){e.mediaSegmentRequest!==null&&e.mediaSegmentRequest.canceller.cancel();let{downloadQueue:t,content:r,initSegmentInfoRef:i,currentCanceller:o}=e,a=()=>{var v;if(this.isMediaSegmentQueueInterrupted.getValue()){m.debug("SQ: Segment fetching postponed because it cannot stream now.");return}let{segmentQueue:s}=t.getValue(),d=s[0];if(o!==null&&o.isUsed()){e.mediaSegmentRequest=null;return}if(d===void 0){e.mediaSegmentRequest=null,this.trigger("emptyQueue",null);return}let u=new B,l=o===null?X:u.linkToSignal(o.signal),{segment:c,priority:f}=d,g=G({segment:c,nextSegment:(v=s[1])==null?void 0:v.segment},r),p=!1,I=!1;u.signal.register(()=>{e.mediaSegmentRequest=null,!p&&(e.mediaSegmentAwaitingInitMetadata===c.id&&(e.mediaSegmentAwaitingInitMetadata=null),p=!0,I=!1)});let y=E=>{ee(E.segmentType==="media","Should have loaded a media segment."),this.trigger("parsedMediaSegment",G({},E,{segment:c}))},b=()=>{let E=t.getValue().segmentQueue;if(E.length===0){p=!0,this.trigger("emptyQueue",null);return}else E[0].segment.id===c.id&&E.shift();p=!0,a()},T=this._segmentFetcher.createRequest(g,f,{onRetry:E=>{this.trigger("requestRetry",{segment:c,error:E})},beforeInterrupted(){m.info("SQ: segment request interrupted temporarly.",c.id,c.time)},onChunk:E=>{let R=i.getValue();R!==void 0?y(E(R!=null?R:void 0)):(I=!0,i.waitUntilDefined(k=>{y(E(k!=null?k:void 0))},{clearSignal:u.signal}))},onAllChunksReceived:()=>{I?(e.mediaSegmentAwaitingInitMetadata=c.id,i.waitUntilDefined(()=>{e.mediaSegmentAwaitingInitMetadata=null,I=!1,this.trigger("fullyLoadedSegment",c)},{clearSignal:u.signal})):this.trigger("fullyLoadedSegment",c)},beforeEnded:()=>{l(),e.mediaSegmentRequest=null,I?i.waitUntilDefined(b,{clearSignal:u.signal}):b()}},u.signal);T.catch(E=>{l(),p||(p=!0,this.stop(),this.trigger("error",E))}),e.mediaSegmentRequest={segment:c,priority:f,request:T,canceller:u}};a()}_restartInitSegmentDownloadingQueue(e,t){let{content:r,initSegmentInfoRef:i}=e;if(e.initSegmentRequest!==null&&e.initSegmentRequest.canceller.cancel(),t===null)return;let o=new B,a=e.currentCanceller===null?X:o.linkToSignal(e.currentCanceller.signal),{segment:s,priority:d}=t,u=G({segment:s,nextSegment:void 0},r),l=!1,c=this._segmentFetcher.createRequest(u,d,{onRetry:f=>{this.trigger("requestRetry",{segment:s,error:f})},beforeInterrupted:()=>{m.info("SQ: init segment request interrupted temporarly.",s.id)},beforeEnded:()=>{a(),e.initSegmentRequest=null,l=!0},onChunk:f=>{var p;let g=f(void 0);ee(g.segmentType==="init","Should have loaded an init segment."),this.trigger("parsedInitSegment",G({},g,{segment:s})),g.segmentType==="init"&&i.setValue((p=g.initTimescale)!=null?p:null)},onAllChunksReceived:()=>{this.trigger("fullyLoadedSegment",s)}},o.signal);c.catch(f=>{a(),l||(l=!0,this.stop(),this.trigger("error",f))}),o.signal.register(()=>{e.initSegmentRequest=null,!l&&(l=!0)}),e.initSegmentRequest={segment:s,priority:d,request:c,canceller:o}}};var ri=class{constructor({prioritySteps:e}){if(this._minPendingPriority=null,this._waitingQueue=[],this._pendingTasks=[],this._prioritySteps=e,this._prioritySteps.high>=this._prioritySteps.low)throw new Error("TP: the max high level priority should be given a lowerpriority number than the min low priority.")}create(e,t,r,i){let o;return at(i,(a,s)=>(o={hasEnded:!1,priority:t,trigger:()=>{if(o.hasEnded)return;let u=()=>{g(),this._endTask(o)},l=p=>{r.beforeEnded(),u(),a(p)},c=p=>{u(),s(p)},f=new B,g=f.linkToSignal(i);o.interrupter=f,f.signal.register(()=>{o.interrupter=null,i.isCancelled()||r.beforeInterrupted()}),this._minPendingPriority=this._minPendingPriority===null?o.priority:Math.min(this._minPendingPriority,o.priority),this._pendingTasks.push(o),o.taskFn(f.signal).then(l).catch(p=>{!i.isCancelled()&&f.isUsed()&&p instanceof Me||c(p)})},taskFn:e,interrupter:null},this._canBeStartedNow(o)?(o.trigger(),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks()):this._waitingQueue.push(o),()=>this._endTask(o)))}_endTask(e){e.hasEnded=!0;let t=ni(e.taskFn,this._waitingQueue);if(t>=0)this._waitingQueue.splice(t,1);else{let r=ni(e.taskFn,this._pendingTasks);if(r<0)return;this._pendingTasks.splice(r,1),this._pendingTasks.length>0?this._minPendingPriority===e.priority&&(this._minPendingPriority=Math.min(...this._pendingTasks.map(i=>i.priority))):this._minPendingPriority=null,this._loopThroughWaitingQueue()}}updatePriority(e,t){let r=ni(e,this._waitingQueue);if(r>=0){let s=this._waitingQueue[r];if(s.priority===t||(s.priority=t,!this._canBeStartedNow(s)))return;this._findAndRunWaitingQueueTask(r),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks();return}let i=ni(e,this._pendingTasks);if(i<0){m.warn("TP: request to update the priority of a non-existent task");return}let o=this._pendingTasks[i];if(o.priority===t)return;let a=o.priority;o.priority=t,this._minPendingPriority===null||t<this._minPendingPriority?this._minPendingPriority=t:this._minPendingPriority===a&&(this._pendingTasks.length===1?this._minPendingPriority=t:this._minPendingPriority=Math.min(...this._pendingTasks.map(s=>s.priority)),this._loopThroughWaitingQueue()),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks()}_loopThroughWaitingQueue(){let e=this._waitingQueue.reduce((t,r)=>t===null||t>r.priority?r.priority:t,null);if(!(e===null||this._minPendingPriority!==null&&this._minPendingPriority<e))for(let t=0;t<this._waitingQueue.length;t++){let r=this._minPendingPriority===null?e:Math.min(this._minPendingPriority,e);this._waitingQueue[t].priority<=r&&(this._findAndRunWaitingQueueTask(t),t--)}}_interruptCancellableTasks(){for(let e of this._pendingTasks)if(e.priority>=this._prioritySteps.low)return this._interruptPendingTask(e),this._interruptCancellableTasks()}_findAndRunWaitingQueueTask(e){return e>=this._waitingQueue.length||e<0?(m.warn("TP : Tried to start a non existing task"),!1):(this._waitingQueue.splice(e,1)[0].trigger(),!0)}_interruptPendingTask(e){var r;let t=ni(e.taskFn,this._pendingTasks);if(t<0){m.warn("TP: Interrupting a non-existent pending task. Aborting...");return}this._pendingTasks.splice(t,1),this._waitingQueue.push(e),this._pendingTasks.length===0?this._minPendingPriority=null:this._minPendingPriority===e.priority&&(this._minPendingPriority=Math.min(...this._pendingTasks.map(i=>i.priority))),(r=e.interrupter)==null||r.cancel()}_canBeStartedNow(e){return this._minPendingPriority===null||e.priority<=this._minPendingPriority}_isRunningHighPriorityTasks(){return this._minPendingPriority!==null&&this._minPendingPriority<=this._prioritySteps.high}};function ni(n,e){return he(e,t=>t.taskFn===n)}var ii=class{constructor(e,t,r,i){let o=new ei(i),{MIN_CANCELABLE_PRIORITY:a,MAX_HIGH_PRIORITY_LEVEL:s}=U.getCurrent();this._transport=e,this._prioritizer=new ri({prioritySteps:{high:s,low:a}}),this._cdnPrioritizer=o,this._backoffOptions=r,this._cmcdDataBuilder=t}createSegmentQueue(e,t,r){let i=af(this._backoffOptions),o=this._transport[e],a=ed({bufferType:e,pipeline:o,cdnPrioritizer:this._cdnPrioritizer,cmcdDataBuilder:this._cmcdDataBuilder,eventListeners:t,requestOptions:i}),s=Zs(this._prioritizer,a);return new ti(s,r)}};var td=ii;var Sn=class{constructor(e){this._array=[],this._sortingFn=e}add(...e){e.sort(this._sortingFn);let t=0;for(let r=0;r<e.length;r++){let i=e[r],o=!1;for(;!o&&t<this._array.length;)this._sortingFn(i,this._array[t])<0?(this._array.splice(t,0,i),o=!0):t++;o||this._array.push(i)}}length(){return this._array.length}get(e){if(e<0||e>=this._array.length)throw new Error("Invalid index.");return this._array[e]}toArray(){return this._array.slice()}findFirst(e){return Z(this._array,e)}has(e){return Q(this._array,e)}removeElement(e){let t=this._array.indexOf(e);if(t>=0)return this._array.splice(t,1),t}head(){return this._array[0]}last(){return this._array[this._array.length-1]}shift(){return this._array.shift()}pop(){return this._array.pop()}};var oi=class extends re{constructor(e,t,r){super(),this._canceller=new B,this._manifest=e,this._activeStreams=new Map,this._allBufferTypes=r,this._lastCurrentPeriodId=null;let i=new nd(e);this._maximumPositionCalculator=i;let o=this._canceller.signal;t.listen(({position:a})=>{let s=a.getWanted();if(s<e.getMinimumSafePosition()){let d=new te("MEDIA_TIME_BEFORE_MANIFEST","The current position is behind the earliest time announced in the Manifest.");this.trigger("warning",d)}else if(s>i.getMaximumAvailablePosition()){let d=new te("MEDIA_TIME_AFTER_MANIFEST","The current position is after the latest time announced in the Manifest.");this.trigger("warning",d)}},{includeLastObservation:!0,clearSignal:o}),e.addEventListener("manifestUpdate",()=>{this.trigger("endingPositionChange",this._getManifestEndTime()),!o.isCancelled()&&this._checkEndOfStream()},o)}getCurrentEndingTime(){return this._getManifestEndTime()}onAdaptationChange(e,t,r){if(this._manifest.isLastPeriodKnown){let i=this._manifest.periods[this._manifest.periods.length-1];if(t.id===(i==null?void 0:i.id)&&(e==="audio"||e==="video")){e==="audio"?this._maximumPositionCalculator.updateLastAudioAdaptation(r):this._maximumPositionCalculator.updateLastVideoAdaptation(r);let o=this._maximumPositionCalculator.getEndingPosition(),a=o!==void 0?{isEnd:!0,endingPosition:o}:{isEnd:!1,endingPosition:this._maximumPositionCalculator.getMaximumAvailablePosition()};this.trigger("endingPositionChange",a)}}this._canceller.isUsed()||r===null&&this._addActivelyLoadedPeriod(t,e)}onRepresentationChange(e,t){this._addActivelyLoadedPeriod(t,e)}onPeriodCleared(e,t){this._removeActivelyLoadedPeriod(t,e)}onLastSegmentFinishedLoading(e){let t=this._lazilyCreateActiveStreamInfo(e);t.hasFinishedLoadingLastPeriod||(t.hasFinishedLoadingLastPeriod=!0,this._checkEndOfStream())}onLastSegmentLoadingResume(e){let t=this._lazilyCreateActiveStreamInfo(e);t.hasFinishedLoadingLastPeriod&&(t.hasFinishedLoadingLastPeriod=!1,this._checkEndOfStream())}dispose(){this.removeEventListener(),this._canceller.cancel()}_addActivelyLoadedPeriod(e,t){let r=this._lazilyCreateActiveStreamInfo(t);r.activePeriods.has(e)||(r.activePeriods.add(e),this._checkCurrentPeriod())}_removeActivelyLoadedPeriod(e,t){let r=this._activeStreams.get(t);r!==void 0&&r.activePeriods.has(e)&&(r.activePeriods.removeElement(e),this._checkCurrentPeriod())}_checkCurrentPeriod(){if(this._allBufferTypes.length===0)return;let e=this._activeStreams.get(this._allBufferTypes[0]);if(e!==void 0)for(let t of e.activePeriods.toArray()){let r=!0;for(let i of this._allBufferTypes){let o=this._activeStreams.get(i);if(o===void 0)return;if(!o.activePeriods.toArray().some(d=>d.id===t.id)){r=!1;break}}if(r){this._lastCurrentPeriodId!==t.id&&(this._lastCurrentPeriodId=t.id,this.trigger("periodChange",t));return}}}_getManifestEndTime(){let e=this._maximumPositionCalculator.getEndingPosition();return e!==void 0?{isEnd:!0,endingPosition:e}:{isEnd:!1,endingPosition:this._maximumPositionCalculator.getMaximumAvailablePosition()}}_lazilyCreateActiveStreamInfo(e){let t=this._activeStreams.get(e);return t===void 0&&(t={activePeriods:new Sn((r,i)=>r.start-i.start),hasFinishedLoadingLastPeriod:!1},this._activeStreams.set(e,t)),t}_checkEndOfStream(){if(!this._manifest.isLastPeriodKnown)return;this._allBufferTypes.every(t=>{let r=this._activeStreams.get(t);return r!==void 0&&r.hasFinishedLoadingLastPeriod})?this.trigger("endOfStream",null):this.trigger("resumeStream",null)}},nd=class{constructor(e){this._manifest=e,this._lastAudioAdaptation=void 0,this._lastVideoAdaptation=void 0}updateLastAudioAdaptation(e){this._lastAudioAdaptation=e}updateLastVideoAdaptation(e){this._lastVideoAdaptation=e}getMaximumAvailablePosition(){if(this._manifest.isDynamic)return this._manifest.getMaximumSafePosition();if(this._lastVideoAdaptation===void 0||this._lastAudioAdaptation===void 0)return this._manifest.getMaximumSafePosition();if(this._lastAudioAdaptation===null){if(this._lastVideoAdaptation===null)return this._manifest.getMaximumSafePosition();{let e=Xo(this._lastVideoAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}}else if(this._lastVideoAdaptation===null){let e=Xo(this._lastAudioAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}else{let e=Xo(this._lastAudioAdaptation),t=Xo(this._lastVideoAdaptation);return typeof e!="number"||typeof t!="number"?this._manifest.getMaximumSafePosition():Math.min(e,t)}}getEndingPosition(){var e,t;if(!this._manifest.isDynamic)return this.getMaximumAvailablePosition();if(!(this._lastVideoAdaptation===void 0||this._lastAudioAdaptation===void 0)){if(this._lastAudioAdaptation===null)return this._lastVideoAdaptation===null?void 0:(e=Zo(this._lastVideoAdaptation))!=null?e:void 0;if(this._lastVideoAdaptation===null)return(t=Zo(this._lastAudioAdaptation))!=null?t:void 0;{let r=Zo(this._lastAudioAdaptation),i=Zo(this._lastVideoAdaptation);return typeof r!="number"||typeof i!="number"?void 0:Math.min(r,i)}}}};function Xo(n){let{representations:e}=n,t=null,r;for(let i of e)if(i.index!==r){r=i.index;let o=i.index.getLastAvailablePosition();if(o===void 0)return;o!==null&&(t=_(t)?o:Math.min(t,o))}return t}function Zo(n){let{representations:e}=n,t=null,r;for(let i of e)if(i.index!==r){r=i.index;let o=i.index.getEnd();if(o===void 0)return;o!==null&&(t=_(t)?o:Math.min(t,o))}return t}function rd(n,e,t,r,i,o){o.register(()=>{e.interruptDurationSetting()});let a=new oi(n,t,r.getBufferTypes());o.register(()=>{a.dispose()}),a.addEventListener("warning",d=>i.onWarning(d)),a.addEventListener("periodChange",d=>i.onPeriodChanged(d)),a.addEventListener("endingPositionChange",d=>{e.setDuration(d.endingPosition,d.isEnd)}),a.addEventListener("endOfStream",()=>{m.debug("Init: end-of-stream order received."),e.maintainEndOfStream()}),a.addEventListener("resumeStream",()=>{e.stopEndOfStream()});let s=a.getCurrentEndingTime();return e.setDuration(s.endingPosition,s.isEnd),a}var ai=class{constructor(e){this._segmentSinksStore=e,this._currentFreezeTimestamp=null}needToReload(e){let{readyState:t,rebuffering:r,freezing:i}=e;if((e.bufferGap!==void 0&&isFinite(e.bufferGap)?e.bufferGap:0)<6||r===null&&i===null||t>1)return this._currentFreezeTimestamp=null,!1;let a=F();this._currentFreezeTimestamp===null&&(this._currentFreezeTimestamp=a);let s=r!==null&&a-r.timestamp>4e3,d=i!==null&&a-i.timestamp>4e3;if((s||d)&&F()-this._currentFreezeTimestamp>4e3){let u=this._segmentSinksStore.getStatus("audio"),l=this._segmentSinksStore.getStatus("video"),c=!0,f=!0;for(let g of[u,l])if(g.type==="initialized")for(let p of g.value.getLastKnownInventory()){let{representation:I}=p.infos;if(I.decipherable===!1)return m.warn("Init: we have undecipherable segments left in the buffer, reloading"),this._currentFreezeTimestamp=null,!0;I.contentProtections!==void 0&&(f=!1,I.decipherable!==!0&&(c=!1))}if(!f&&c)return m.warn("Init: we are frozen despite only having decipherable segments left in the buffer, reloading"),this._currentFreezeTimestamp=null,!0}return!1}};function Jo({segmentSink:n,playbackObserver:e,maxBufferBehind:t,maxBufferAhead:r},i){let o,a=[];e.listen(d=>{o=d.position.getWanted(),a=d.buffered[n.bufferType],s()},{includeLastObservation:!0,clearSignal:i});function s(){a!==null&&jg(n,o,a,t.getValue(),r.getValue(),i).catch(d=>{let u=d instanceof Error?d.message:"Unknown error";m.error("Could not run BufferGarbageCollector:",u)})}t.onUpdate(s,{clearSignal:i}),r.onUpdate(s,{clearSignal:i}),s()}async function jg(n,e,t,r,i,o){if(!isFinite(r)&&!isFinite(i))return Promise.resolve();let a=[],{innerRange:s,outerRanges:d}=Ql(t,e),u=()=>{if(isFinite(r)){for(let c of d)e-r>=c.end?a.push(c):e>=c.end&&e-r>c.start&&e-r<c.end&&a.push({start:c.start,end:e-r});_(s)||e-r>s.start&&a.push({start:s.start,end:e-r})}},l=()=>{if(isFinite(i)){for(let c of d)e+i<=c.start?a.push(c):e<=c.start&&e+i<c.end&&e+i>c.start&&a.push({start:e+i,end:c.end});_(s)||e+i<s.end&&a.push({start:e+i,end:s.end})}};u(),l();for(let c of a)if(c.start<c.end){if(m.debug("GC: cleaning range from SegmentSink",c.start,c.end),o.cancellationError!==null)throw o.cancellationError;await n.removeBuffer(c.start,c.end)}}var si=class{constructor(e,t){this._history=[],this._lifetime=e,this._maxHistoryLength=t}addBufferedSegment(e,t){let r=F();this._history.push({date:r,buffered:t,context:e}),this._cleanHistory(r)}getHistoryFor(e){return this._history.filter(t=>Mt(t.context,e))}_cleanHistory(e){let t=e-this._lifetime,r=0;for(let i of this._history)if(i.date<t)r++;else break;if(r>0&&(this._history=this._history.splice(r)),this._history.length>this._maxHistoryLength){let i=this._history.length-this._maxHistoryLength;this._history=this._history.splice(i)}}};var di=class{constructor(){let{BUFFERED_HISTORY_RETENTION_TIME:e,BUFFERED_HISTORY_MAXIMUM_ENTRIES:t}=U.getCurrent();this._inventory=[],this._bufferedHistory=new si(e,t)}reset(){this._inventory.length=0}synchronizeBuffered(e){var d,u,l,c,f,g,p;let t=this._inventory,r=0,i=t[0],{MINIMUM_SEGMENT_SIZE:o}=U.getCurrent(),a=i==null?void 0:i.infos.adaptation.type;if(m.hasLevel("DEBUG")){let I=e.map(y=>`${y.start}-${y.end}`).join(",");m.debug(`SI: synchronizing ${a!=null?a:"unknown"} buffered ranges:`,I)}let s=e.length;for(let I=0;I<s;I++){if(i===void 0)return;let y=e[I].start,b=e[I].end;if(b-y<o){m.warn("SI: skipped range when synchronizing because it was too small",a,y,b);continue}let T=r;for(;i!==void 0&&((d=i.bufferedEnd)!=null?d:i.end)-y<o;)i=t[++r];let v=null,E=r-T;if(E>0){let k=t[T+E-1];v={end:(u=k.bufferedEnd)!=null?u:k.end,precizeEnd:k.precizeEnd},m.debug(`SI: ${E} segments GCed.`,a);let x=t.splice(T,E);for(let M of x)M.bufferedStart===void 0&&M.bufferedEnd===void 0&&M.status!==2&&this._bufferedHistory.addBufferedSegment(M.infos,null);r=T}if(i===void 0)return;if(b-((l=i.bufferedStart)!=null?l:i.start)>=o){if(Yg(i,y,v,a),r===t.length-1){df(i,b,a);return}i=t[++r];let k=(c=i.bufferedStart)!=null?c:i.start,x=(f=i.bufferedEnd)!=null?f:i.end,M=I<s-1?e[I+1].start:void 0;for(;i!==void 0&&!(b<k||b-k<o&&x-b>=o||M!==void 0&&b-k<x-M);){let P=t[r-1];P.bufferedEnd===void 0&&(i.precizeStart?P.bufferedEnd=i.start:P.infos.segment.complete?P.bufferedEnd=P.end:P.bufferedEnd=i.start,m.debug("SI: calculating buffered end of contiguous segment",a,P.bufferedEnd,P.end)),i.bufferedStart=P.bufferedEnd,i=t[++r],i!==void 0&&(k=(g=i.bufferedStart)!=null?g:i.start,x=(p=i.bufferedEnd)!=null?p:i.end)}}let R=t[r-1];R!==void 0&&df(R,b,a)}if(!_(i)){let{SEGMENT_SYNCHRONIZATION_DELAY:I}=U.getCurrent(),y=F();for(let b=r;b<t.length;b++){let T=t[b];y-T.insertionTs>=I&&(m.debug("SI: A segment at the end has been completely GCed",a,`${T.start}-${T.end}`),T.bufferedStart===void 0&&T.bufferedEnd===void 0&&T.status!==2&&this._bufferedHistory.addBufferedSegment(T.infos,null),t.splice(b,1),b--)}}a!==void 0&&m.hasLevel("DEBUG")&&m.debug(`SI: current ${a} inventory timeline:
|
|
2
|
-
|
|
3
|
-
[${d.letter}] P: ${d.periodId} || R: ${d.representationId}(${(u=d.bitrate)!=null?u:"unknown bitrate"})`}),s}function Hn(n,e){for(let t=0;t<n.length;t++)if(n[t].infos.period.start>=e.start)return t>0?n[t-1]:null;return n.length>0?n[n.length-1]:null}function Wn(n,e){for(let t of n)if(t.infos.period.start>e.start)return t;return null}var uf=di;var Gn=class{constructor(){this._segmentInventory=new uf}synchronizeInventory(e){this._segmentInventory.synchronizeBuffered(e)}getLastKnownInventory(){return this._segmentInventory.getInventory()}getSegmentHistory(e){return this._segmentInventory.getHistoryFor(e)}};var ui=class extends Gn{constructor(e,t,r){super(),m.info("AVSB: calling `mediaSource.addSourceBuffer`",t);let i=r.addSourceBuffer(e,t);this.bufferType=e,this._sourceBuffer=i,this._lastInitSegmentUniqueId=null,this.codec=t,this._initSegmentsMap=new Map,this._pendingOperations=[]}declareInitSegment(e,t){lf(t),this._initSegmentsMap.set(e,t)}freeInitSegment(e){this._initSegmentsMap.delete(e)}async pushChunk(e){lf(e.data.chunk),m.debug("AVSB: receiving order to push data to the SourceBuffer",this.bufferType,bn(e.inventoryInfos));let t=this._getActualDataToPush(e.data);t.length===0&&t.push(new Uint8Array);let r=Promise.all(t.map(a=>{let{codec:s,timestampOffset:d,appendWindow:u}=e.data;return m.debug("AVSB: pushing segment",this.bufferType,bn(e.inventoryInfos)),this._sourceBuffer.appendBuffer(a,{codec:s,timestampOffset:d,appendWindow:u})}));this._addToOperationQueue(r,{type:0,value:e});let i;try{i=await r}catch(a){throw this._segmentInventory.insertChunk(e.inventoryInfos,!1,F()),a}e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,F());let o=i[i.length-1];return this._segmentInventory.synchronizeBuffered(o),o}async removeBuffer(e,t){m.debug("AVSB: receiving order to remove data from the SourceBuffer",this.bufferType,e,t);let r=this._sourceBuffer.remove(e,t);this._addToOperationQueue(r,{type:1,value:{start:e,end:t}});let i=await r;return this._segmentInventory.synchronizeBuffered(i),i}async signalSegmentComplete(e){if(this._pendingOperations.length>0){let{promise:t}=this._pendingOperations[this._pendingOperations.length-1];this._addToOperationQueue(t,{type:2,value:e});try{await t}catch(r){}}this._segmentInventory.completeSegment(e)}getPendingOperations(){return this._pendingOperations.map(e=>e.operation)}dispose(){try{m.debug("AVSB: Calling `dispose` on the SourceBufferInterface"),this._sourceBuffer.dispose()}catch(e){m.debug(`AVSB: Failed to dispose a ${this.bufferType} SourceBufferInterface:`,e instanceof Error?e:"")}}_getActualDataToPush(e){let t=[];if(e.initSegmentUniqueId!==null&&!this._isLastInitSegment(e.initSegmentUniqueId)){let r=this._initSegmentsMap.get(e.initSegmentUniqueId);if(r===void 0)throw new Error("Invalid initialization segment uniqueId");let i=new ArrayBuffer(r.byteLength),o=new Uint8Array(i);o.set(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer)),r=o,t.push(r),this._lastInitSegmentUniqueId=e.initSegmentUniqueId}return e.chunk!==null&&t.push(e.chunk),t}_isLastInitSegment(e){return this._lastInitSegmentUniqueId===null?!1:this._lastInitSegmentUniqueId===e}_addToOperationQueue(e,t){let r={operation:t,promise:e};this._pendingOperations.push(r);let i=()=>{let o=this._pendingOperations.indexOf(r);o>=0&&this._pendingOperations.splice(o,1)};e.then(i,i)}};function lf(n){if(h.CURRENT_ENV!==h.PRODUCTION&&(typeof n!="object"||n!==null&&!(n instanceof ArrayBuffer)&&!(n.buffer instanceof ArrayBuffer)))throw new Error("Invalid data given to the AudioVideoSegmentSink")}var ta=ui;var li=class extends Gn{constructor(e){m.debug("HTSB: Creating TextSegmentSink"),super(),this.bufferType="text",this._sender=e,this._pendingOperations=[],this._sender.reset()}declareInitSegment(e){m.warn("HTSB: Declaring initialization segment for Text SegmentSink",e)}freeInitSegment(e){m.warn("HTSB: Freeing initialization segment for Text SegmentSink",e)}async pushChunk(e){let{data:t}=e;Xg(t.chunk);let r=this._sender.pushTextData(ue(oe({},t),{chunk:t.chunk}));this._addToOperationQueue(r,{type:0,value:e});let i=await r;return e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,F()),this._segmentInventory.synchronizeBuffered(i),i}async removeBuffer(e,t){let r=this._sender.remove(e,t);this._addToOperationQueue(r,{type:1,value:{start:e,end:t}});let i=await r;return this._segmentInventory.synchronizeBuffered(i),i}async signalSegmentComplete(e){if(this._pendingOperations.length>0){let{promise:t}=this._pendingOperations[this._pendingOperations.length-1];this._addToOperationQueue(t,{type:2,value:e});try{await t}catch(r){}}this._segmentInventory.completeSegment(e)}getPendingOperations(){return this._pendingOperations.map(e=>e.operation)}dispose(){m.debug("HTSB: Disposing TextSegmentSink"),this._sender.reset()}_addToOperationQueue(e,t){let r={operation:t,promise:e};this._pendingOperations.push(r);let i=()=>{let o=this._pendingOperations.indexOf(r);o>=0&&this._pendingOperations.splice(o,1)};e.then(i,i)}};function Xg(n){if(h.CURRENT_ENV!==h.PRODUCTION&&(typeof n!="object"||n===null||typeof n.data!="string"||typeof n.type!="string"||n.language!==void 0&&typeof n.language!="string"||n.start!==void 0&&typeof n.start!="number"||n.end!==void 0&&typeof n.end!="number"))throw new Error("Invalid format given to a TextSegmentSink")}h.CURRENT_ENV===h.DEV&&(Zg=function(e){function t(r){}});var Zg;var cf=li;var Jg=["audio","video","text"],ci=class n{static isNative(e){return ff(e)}constructor(e,t,r){this._mediaSource=e,this._textInterface=r,this._hasVideo=t,this._initializedSegmentSinks={},this._onNativeBufferAddedOrDisabled=[]}getBufferTypes(){let e=this.getNativeBufferTypes();return this._textInterface!==null&&e.push("text"),e}getNativeBufferTypes(){return this._hasVideo?["video","audio"]:["audio"]}getStatus(e){let t=this._initializedSegmentSinks[e];return t===void 0?{type:"uninitialized"}:t===null?{type:"disabled"}:{type:"initialized",value:t}}waitForUsableBuffers(e){return this._areNativeBuffersUsable()?Promise.resolve():at(e,t=>{let r=X,i=()=>{let o=this._onNativeBufferAddedOrDisabled.indexOf(r);o>=0&&this._onNativeBufferAddedOrDisabled.splice(o,1)};return r=()=>{this._areNativeBuffersUsable()&&(i(),t())},this._onNativeBufferAddedOrDisabled.push(r),i})}disableSegmentSink(e){let t=this._initializedSegmentSinks[e];if(t===null){m.warn(`SBS: The ${e} SegmentSink was already disabled.`);return}if(t!==void 0)throw new Error("Cannot disable an active SegmentSink.");this._initializedSegmentSinks[e]=null,n.isNative(e)&&(this._onNativeBufferAddedOrDisabled.slice().forEach(r=>r()),ee(this._onNativeBufferAddedOrDisabled.length===0))}createSegmentSink(e,t){let r=this._initializedSegmentSinks[e];if(ff(e)){if(!_(r))return r instanceof ta&&r.codec!==t?m.warn("SB: Reusing native SegmentSink with codec",r.codec,"for codec",t):m.info("SB: Reusing native SegmentSink with codec",t),r;m.info("SB: Adding native SegmentSink with codec",t);let o=e==="audio"?"audio":"video",a=new ta(o,t,this._mediaSource);return this._initializedSegmentSinks[e]=a,this._onNativeBufferAddedOrDisabled.slice().forEach(s=>s()),ee(this._onNativeBufferAddedOrDisabled.length===0),a}if(!_(r))return m.info("SB: Reusing a previous custom SegmentSink for the type",e),r;let i;if(e==="text"){if(m.info("SB: Creating a new text SegmentSink"),this._textInterface===null)throw new Error("HTML Text track feature not activated");return i=new cf(this._textInterface),this._initializedSegmentSinks.text=i,i}throw m.error("SB: Unknown buffer type:",e),new te("BUFFER_TYPE_UNKNOWN","The player wants to create a SegmentSink of an unknown type.")}disposeSegmentSink(e){let t=this._initializedSegmentSinks[e];if(_(t)){m.warn("SB: Trying to dispose a SegmentSink that does not exist");return}m.info("SB: Aborting SegmentSink",e),t.dispose(),delete this._initializedSegmentSinks[e]}disposeAll(){Jg.forEach(e=>{this.getStatus(e).type==="initialized"&&this.disposeSegmentSink(e)})}_areNativeBuffersUsable(){let e=this.getNativeBufferTypes();return!(e.some(i=>this._initializedSegmentSinks[i]===void 0)||e.every(i=>this._initializedSegmentSinks[i]===null))}createSegmentSinkMetricsForType(e){var i,o;let t=(i=this._initializedSegmentSinks[e])==null?void 0:i.getLastKnownInventory(),r;if(t!==void 0){r=0;for(let a of t){if(a.chunkSize===void 0||r===void 0){r=void 0;break}r+=a.chunkSize}}return{bufferType:e,sizeEstimate:r,codec:(o=this._initializedSegmentSinks[e])==null?void 0:o.codec,segmentInventory:t==null?void 0:t.map(a=>ue(oe({},a),{infos:eh(a.infos)}))}}getSegmentSinksMetrics(){return{segmentSinks:{audio:this.createSegmentSinkMetricsForType("audio"),video:this.createSegmentSinkMetricsForType("video"),text:this.createSegmentSinkMetricsForType("text")}}}};function ff(n){return n==="audio"||n==="video"}function eh(n){return{adaptation:n.adaptation.getMetadataSnapshot(),period:n.period.getMetadataSnapshot(),representation:n.representation.getMetadataSnapshot()}}var Zt=ci;var fi=class{constructor(e){this._weakMap=new WeakMap,this._fn=e}get(e){let t=this._weakMap.get(e);if(t===void 0){let r=this._fn(e);return this._weakMap.set(e,r),r}else return t}destroy(e){this._weakMap.delete(e)}};function od(n,e,t,r,i){let{period:o,adaptation:a,representation:s}=n,d=th(i,e);if(d===null){if(t===null){if(r&&o.end!==void 0&&e.end>=o.end)return{start:void 0,end:null};let c=s.index.checkDiscontinuity(e.start);if(c!==null)return{start:void 0,end:c}}return null}let u=i[d];if(u.bufferedStart!==void 0&&u.bufferedStart>e.start&&(t===null||u.infos.segment.end<=t)){let c=u.bufferedStart;return!r&&s.index.awaitSegmentBetween(e.start,c)!==!1?null:(m.debug("RS: current discontinuity encountered",a.type,u.bufferedStart),{start:void 0,end:c})}let l=nh(i,e,d+1);if(l!==null){let c=i[l-1],f=i[l];if(t===null||f.infos.segment.end<=t){if(!r&&s.index.awaitSegmentBetween(c.infos.segment.end,f.infos.segment.time)!==!1)return null;let g=c.bufferedEnd,p=f.bufferedStart;return m.debug("RS: future discontinuity encountered",a.type,g,p),{start:g,end:p}}}if(t===null){if(r&&o.end!==void 0){if(e.end<o.end)return null;let c=rh(i,o.end);if(c!==null){let f=i[c];if(f.bufferedEnd!==void 0&&f.bufferedEnd<o.end)return m.debug("RS: discontinuity encountered at the end of the current period",a.type,f.bufferedEnd,o.end),{start:f.bufferedEnd,end:null}}}if(o.end!==void 0&&e.end>=o.end)return null;for(let c=i.length-1;c>=0;c--){let f=i[c];if(f.bufferedStart===void 0)break;if(f.bufferedStart<e.end){if(f.bufferedEnd!==void 0&&f.bufferedEnd<e.end){let g=s.index.checkDiscontinuity(e.end);if(g!==null)return{start:f.bufferedEnd,end:g}}return null}}}return null}function th(n,e){for(let t=0;t<n.length;t++){let r=n[t];if(r.bufferedStart===void 0||r.bufferedEnd===void 0||r.bufferedStart>=e.end)return null;if(r.bufferedEnd>e.start)return t}return null}function nh(n,e,t){if(t<=0)return m.error("RS: Asked to check a discontinuity before the first chunk."),null;for(let r=t;r<n.length;r++){let i=n[r],o=n[r-1];if(i.bufferedStart===void 0||o.bufferedEnd===void 0||i.bufferedStart>=e.end)return null;if(i.bufferedStart-o.bufferedEnd>0)return r}return null}function rh(n,e){for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.bufferedStart===void 0)return null;if(r.bufferedStart<e)return t}return null}function ad({bufferedSegments:n,content:e,currentPlaybackTime:t,fastSwitchThreshold:r,getBufferedHistory:i,neededRange:o,segmentsBeingPushed:a,maxBufferSize:s}){let{adaptation:d,representation:u}=e,l=ih(n,a,s),c=u.index.getSegments(o.start,o.end-o.start),f=n.filter(R=>!mf(R.infos,e,t,r)),g=ch(f,o,i),{MINIMUM_SEGMENT_SIZE:p,MIN_BUFFER_AHEAD:I}=U.getCurrent(),y=!1,b=Math.min(1/60,p),T=!1,v=[];return{segmentsToLoad:c.filter(R=>{let k=G({segment:R},e);if(a.length>0&&a.some(A=>Mt(k,A)))return!1;let{duration:x,time:M,end:P}=R;if(R.isInit)return!0;if(y)return v.push(R),!1;if(R.complete&&x<p||a.length>0&&a.some(A=>{if(A.period.id!==e.period.id||A.adaptation.id!==e.adaptation.id)return!1;let{segment:C}=A;if(C.time-b>M)return!1;if(C.complete){if(C.end+b<P)return!1}else if(Math.abs(M-C.time)>M)return!1;return!mf(A,k,t,r)}))return!1;for(let K of g){let A=K.infos.period.id===e.period.id;if(K.status===1&&A){let C=K.infos.segment;if(M-C.time>-b){if(C.complete){if(C.end-P>-b)return!1}else if(Math.abs(M-C.time)<b)return!1}}}let N=x*e.representation.bitrate;if(l-N<0&&(T=!0,M>o.start+I))return y=!0,v.push(R),!1;let O=i(k);if(O.length>1){let K=O[O.length-1],A=O[O.length-2];if(K.buffered===null&&A.buffered===null)return m.warn("Stream: Segment GCed multiple times in a row, ignoring it.","If this happens a lot and lead to unpleasant experience, please check your device's available memory. If it's low when this message is emitted, you might want to update the RxPlayer's settings (`maxBufferAhead`, `maxVideoBufferSize` etc.) so less memory is used by regular media data buffering."+d.type,u.id,R.time),!1}for(let K=0;K<g.length;K++){let A=g[K];if(A.end+b>M){let C=A.start>M+b||oh(g,K).end<P-b;return C&&(l-=N),C}}return l-=N,!0}),segmentsOnHold:v,isBufferFull:T}}function ih(n,e,t){let r=t*8e3;return r-=e.reduce((i,o)=>{let{bitrate:a}=o.representation,{duration:s}=o.segment;return i+a*s},0),n.reduce((i,o)=>o.chunkSize!==void 0?i-o.chunkSize*8:i,r)}function oh(n,e){let t=e+1,{MINIMUM_SEGMENT_SIZE:r}=U.getCurrent(),i=Math.min(1/60,r);for(;t<n.length-1&&n[t-1].end+i>n[t].start;)t++;return t--,n[t]}function mf(n,e,t,r){let{CONTENT_REPLACEMENT_PADDING:i}=U.getCurrent();if(n.period.id!==e.period.id)return!1;let{segment:o}=n;return o.time<t+i?!1:n.adaptation.id!==e.adaptation.id?!0:ah(n.representation,e.representation,r)}function ah(n,e,t){let r=n.bitrate,{BITRATE_REBUFFERING_RATIO:i}=U.getCurrent();if(t===void 0){let o=r*i;return e.bitrate>o}return r<t&&e.bitrate>r}function sh(n,e,t){let{MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:r}=U.getCurrent();return n.bufferedStart===void 0||e!==null&&e.bufferedEnd!==void 0&&n.bufferedStart-e.bufferedEnd<.1?!1:t<n.bufferedStart&&n.bufferedStart-n.start>r?(m.info("Stream: The start of the wanted segment has been garbage collected",n.start,n.bufferedStart),!0):!1}function dh(n,e,t){let{MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:r}=U.getCurrent();return n.bufferedEnd===void 0||e!==null&&e.bufferedStart!==void 0&&e.bufferedStart-n.bufferedEnd<.1?!1:t>n.bufferedEnd&&n.end-n.bufferedEnd>r?(m.info("Stream: The end of the wanted segment has been garbage collected",n.end,n.bufferedEnd),!0):!1}function uh(n,e){var a,s;if(n.length<2)return!0;let r=(a=n[n.length-1].buffered)==null?void 0:a.start;if(e!==void 0&&r!==void 0&&e-r>.05)return!0;let o=(s=n[n.length-2].buffered)==null?void 0:s.start;return o===void 0||r===void 0?!0:Math.abs(o-r)>.01}function lh(n,e){var a,s;if(n.length<2)return!0;let r=(a=n[n.length-1].buffered)==null?void 0:a.end;if(e!==void 0&&r!==void 0&&r-e>.05)return!0;let o=(s=n[n.length-2].buffered)==null?void 0:s.end;return o===void 0||r===void 0?!0:Math.abs(o-r)>.01}function ch(n,e,t){return n.filter((r,i,o)=>{let a=i===0?null:o[i-1],s=i>=o.length-1?null:o[i+1],d=null;if(sh(r,a,e.start)){if(d=t(r.infos),uh(d,r.bufferedStart))return!1;m.debug("Stream: skipping segment gc-ed at the start",r.start,r.bufferedStart)}if(dh(r,s,e.end)){if(d=d!=null?d:t(r.infos),lh(d,r.bufferedEnd))return!1;m.debug("Stream: skipping segment gc-ed at the end",r.end,r.bufferedEnd)}return!0})}function mi(n,e){let t=n-e,{SEGMENT_PRIORITIES_STEPS:r}=U.getCurrent();for(let i=0;i<r.length;i++)if(t<r[i])return i;return r.length}function sd(n,e,t,r,i,o,a){var M,P,N;let{representation:s}=n,d=(P=(M=t.getIsPaused())!=null?M:t.getReference().getValue().paused.pending)!=null?P:t.getReference().getValue().paused.last,u=(N=t.getPlaybackRate())!=null?N:t.getReference().getValue().speed,l=e;(d===void 0||u===void 0||d||u<=0)&&(l-=.1);let c=fh(n,l,i),f=s.index.shouldRefresh(c.start,c.end),g=a.getPendingOperations().filter(O=>O.type===2).map(O=>O.value),p=a.getLastKnownInventory(),I=t.getCurrentTime();I===void 0&&(I=t.getReference().getValue().position.getWanted());let y=a.getSegmentHistory.bind(a),{segmentsToLoad:b,segmentsOnHold:T,isBufferFull:v}=ad({content:n,bufferedSegments:p,currentPlaybackTime:I,fastSwitchThreshold:r,getBufferedHistory:y,neededRange:c,segmentsBeingPushed:g,maxBufferSize:o}),E=b.map(O=>({priority:mi(O.time,l),segment:O})),R=s.index.isInitialized()&&!s.index.isStillAwaitingFutureSegments()&&c.hasReachedPeriodEnd&&E.length===0&&T.length===0,k=null;return g.length>0&&(k=Math.min(...g.map(O=>O.segment.time))),T.length>0&&(k=k!==null?Math.min(k,T[0].time):T[0].time),E.length>0&&(k=k!==null?Math.min(k,E[0].segment.time):E[0].segment.time),{imminentDiscontinuity:od(n,c,k,R,p),hasFinishedLoading:R,neededSegments:E,isBufferFull:v,shouldRefreshManifest:f}}function fh(n,e,t){var c;let r,{manifest:i,period:o,representation:a}=n,s=a.index.getLastAvailablePosition(),d=a.index;!_(s)&&Zt.isNative(n.adaptation.type)&&e>=s&&d.isInitialized()&&!d.isStillAwaitingFutureSegments()&&mh(i,o,e)?r=s-1:r=e-.1;let u=r+t,l;return!a.index.isInitialized()||a.index.isStillAwaitingFutureSegments()||o.end===void 0?l=!1:s===void 0?l=u>=o.end:s===null?l=!0:l=u>=s,{start:Math.max(r,o.start),end:Math.min(u,(c=o.end)!=null?c:1/0),hasReachedPeriodEnd:l}}function mh(n,e,t){var i;let r=n.getPeriodAfter(e);return e.containsTime(t,r)&&n.isLastPeriodKnown&&e.id===((i=n.periods[n.periods.length-1])==null?void 0:i.id)}async function pi(n,e,t,r,i){try{return await e.pushChunk(t)}catch(o){if(i.isCancelled()&&o instanceof Me)throw o;if(!(o instanceof ot)||!o.isBufferFull){let d=o instanceof Error?o.toString():"An unknown error happened when pushing content";throw new te("BUFFER_APPEND_ERROR",d,{tracks:[Xt(t.inventoryInfos.adaptation)]})}let{position:a}=n.getReference().getValue(),s=a.getWanted();try{m.warn("Stream: Running garbage collector");let d=Math.max(s-5,0),u=s+r.getValue()+12;if(d>0&&await e.removeBuffer(0,d),u<Number.MAX_VALUE&&await e.removeBuffer(u,Number.MAX_VALUE),await mn(200),i.cancellationError!==null)throw i.cancellationError;return await e.pushChunk(t)}catch(d){if(d instanceof Me)throw d;let u=d instanceof Error?d.toString():"Could not clean the buffer";throw new te("BUFFER_FULL_ERROR",u,{tracks:[Xt(t.inventoryInfos.adaptation)]})}}}async function dd({playbackObserver:n,content:e,initSegmentUniqueId:t,segment:r,segmentSink:i,bufferGoal:o},a){if(a.cancellationError!==null)throw a.cancellationError;let s=e.representation.getMimeTypeString(),d={initSegmentUniqueId:t,chunk:null,timestampOffset:0,appendWindow:[void 0,void 0],codec:s},u=G({segment:r,chunkSize:void 0,start:0,end:0},e),l=await pi(n,i,{data:d,inventoryInfos:u},o,a);return{content:e,segment:r,buffered:l}}async function ud({playbackObserver:n,bufferGoal:e,content:t,initSegmentUniqueId:r,parsedSegment:i,segment:o,segmentSink:a},s){var k,x;if(i.chunkData===null)return null;if(s.cancellationError!==null)throw s.cancellationError;let{chunkData:d,chunkInfos:u,chunkOffset:l,chunkSize:c,appendWindow:f}=i,g=t.representation.getMimeTypeString(),{APPEND_WINDOW_SECURITIES:p}=U.getCurrent(),I=[f[0]!==void 0?Math.max(0,f[0]-p.START):void 0,f[1]!==void 0?f[1]+p.END:void 0],y={initSegmentUniqueId:r,chunk:d,timestampOffset:l,appendWindow:I,codec:g},b=(k=u==null?void 0:u.time)!=null?k:o.time,T=(x=u==null?void 0:u.duration)!=null?x:o.duration,v=b+T;I[0]!==void 0&&(b=Math.max(b,I[0])),I[1]!==void 0&&(v=Math.min(v,I[1]));let E=G({segment:o,chunkSize:c,start:b,end:v},t),R=await pi(n,a,{data:y,inventoryInfos:E},e,s);return{content:t,segment:o,buffered:R}}function ld({content:n,options:e,playbackObserver:t,segmentSink:r,segmentQueue:i,terminate:o},a,s){m.debug("Stream: Creating RepresentationStream",n.adaptation.type,n.representation.bitrate);let{period:d,adaptation:u,representation:l}=n,{bufferGoal:c,maxBufferSize:f,drmSystemId:g,fastSwitchThreshold:p}=e,I=u.type,y=new B;y.linkToSignal(s);let b=new B;b.linkToSignal(y.signal);let T={segment:l.index.getInitSegment(),uniqueId:null,isLoaded:!1};y.signal.register(()=>{T.uniqueId!==null&&r.freeInitSegment(T.uniqueId)});let v=T.segment!==null;v||(T.isLoaded=!0);let E=!1;if(g!==void 0){let P=l.getEncryptionData(g);if(P.length>0&&P.every(N=>N.keyIds!==void 0)&&(E=!0,a.encryptionDataEncountered(P.map(N=>G({content:n},N))),y.isUsed()))return}i.addEventListener("error",P=>{b.signal.isCancelled()||(y.cancel(),a.error(P))}),i.addEventListener("parsedInitSegment",x,b.signal),i.addEventListener("parsedMediaSegment",x,b.signal),i.addEventListener("emptyQueue",k,b.signal),i.addEventListener("requestRetry",P=>{if(a.warning(P.error),b.signal.isCancelled())return;let N=P.segment,{index:O}=l;O.isSegmentStillAvailable(N)===!1?k():O.canBeOutOfSyncError(P.error,N)&&a.manifestMightBeOufOfSync()},b.signal),i.addEventListener("fullyLoadedSegment",P=>{r.signalSegmentComplete(G({segment:P},n)).catch(M)},b.signal);let R=i.resetForContent(n,v);b.signal.register(()=>{i.stop()}),t.listen(k,{includeLastObservation:!1,clearSignal:b.signal}),n.manifest.addEventListener("manifestUpdate",k,b.signal),c.onUpdate(k,{emitCurrentValue:!1,clearSignal:b.signal}),f.onUpdate(k,{emitCurrentValue:!1,clearSignal:b.signal}),o.onUpdate(k,{emitCurrentValue:!1,clearSignal:b.signal}),k();return;function k(){if(b.isUsed())return;let P=t.getReference().getValue(),N=P.position.getWanted(),O=sd(n,N,t,p.getValue(),c.getValue(),f.getValue(),r),{neededSegments:K}=O,A=null;if(l.index.isInitialized()){if(K.length>0&&!T.isLoaded&&T.segment!==null){let L=K[0].priority;A={segment:T.segment,priority:L}}}else if(T.segment===null)m.warn("Stream: Uninitialized index without an initialization segment");else if(T.isLoaded)m.warn("Stream: Uninitialized index with an already loaded initialization segment");else{let L=P.position.getWanted();A={segment:T.segment,priority:mi(d.start,L)}}let C=o.getValue();if(C===null)R.setValue({initSegment:A,segmentQueue:K});else if(C.urgent){m.debug("Stream: Urgent switch, terminate now.",I),R.setValue({initSegment:null,segmentQueue:[]}),R.finish(),b.cancel(),a.terminating();return}else{let L=K[0],V=i.getRequestedInitSegment(),$=i.getRequestedMediaSegment(),j=$===null||L===void 0||$.id!==L.segment.id?[]:[L],z=V===null?null:A;if(R.setValue({initSegment:z,segmentQueue:j}),j.length===0&&z===null){m.debug("Stream: No request left, terminate",I),R.finish(),b.cancel(),a.terminating();return}}if(a.streamStatusUpdate({period:d,position:P.position.getWanted(),bufferType:I,imminentDiscontinuity:O.imminentDiscontinuity,isEmptyStream:!1,hasFinishedLoading:O.hasFinishedLoading,neededSegments:O.neededSegments}),b.signal.isCancelled())return;let{UPTO_CURRENT_POSITION_CLEANUP:D}=U.getCurrent();if(O.isBufferFull){let L=Math.max(0,N-D);L>0&&r.removeBuffer(0,L).catch(M)}O.shouldRefreshManifest&&a.needsManifestRefresh()}function x(P){if(!y.isUsed()){for(let N of P.protectionData)l.addProtectionData(N.initDataType,N.keyId,N.initData);if(!E){let N=l.getAllEncryptionData();if(N.length>0&&(a.encryptionDataEncountered(N.map(O=>G({content:n},O))),E=!0,y.isUsed()))return}if(P.segmentType==="init"){if(!l.index.isInitialized()&&P.segmentList!==void 0&&l.index.initialize(P.segmentList),T.isLoaded=!0,P.initializationData!==null){let N=l.uniqueId;T.uniqueId=N,r.declareInitSegment(N,P.initializationData),dd({playbackObserver:t,bufferGoal:c,content:n,initSegmentUniqueId:N,segment:P.segment,segmentData:P.initializationData,segmentSink:r},y.signal).then(O=>{O!==null&&a.addedSegment(O)}).catch(M)}k();return}else{let{inbandEvents:N,predictedSegments:O,needsManifestRefresh:K}=P;if(O!==void 0&&l.index.addPredictedSegments(O,P.segment),K===!0&&(a.needsManifestRefresh(),y.isUsed())||N!==void 0&&N.length>0&&(a.inbandEvent(N),y.isUsed()))return;let A=T.uniqueId;ud({playbackObserver:t,bufferGoal:c,content:n,initSegmentUniqueId:A,parsedSegment:P,segment:P.segment,segmentSink:r},y.signal).then(C=>{C!==null&&a.addedSegment(C)}).catch(M)}}}function M(P){y.isUsed()&&P instanceof Me||(m.warn("Stream: Received fatal buffer error",u.type,l.bitrate,P instanceof Error?P:null),y.cancel(),a.error(P))}}var pf=ld;function cd(n,e,t,r,i){var f,g,p,I;if(t.switchingMode==="lazy")return{type:"continue",value:void 0};let o=r.getLastKnownInventory(),a=[];for(let y of o)y.infos.period.id===n.id&&(y.infos.adaptation.id!==e.id||!Q(t.representationIds,y.infos.representation.id))&&Wt(a,{start:(f=y.bufferedStart)!=null?f:y.start,end:(g=y.bufferedEnd)!=null?g:y.end});let s=r.getPendingOperations();for(let y of s)if(y.type===0){let b=y.value.inventoryInfos;if(b.period.id===n.id&&(b.adaptation.id!==e.id||!Q(t.representationIds,b.representation.id))){let T=b.segment.time,v=T+b.segment.duration;Wt(a,{start:T,end:v})}}if(a.length===0)return{type:"continue",value:void 0};if(t.switchingMode==="reload"){let y=i.getReadyState();if(y===void 0||y>1)return{type:"needs-reload",value:void 0}}let d=t.switchingMode==="direct",u=[],l=Hn(o,n);if(l!==null&&(l.bufferedEnd===void 0||n.start-l.bufferedEnd<1)&&u.push({start:0,end:n.start+1}),!d){let{ADAP_REP_SWITCH_BUFFER_PADDINGS:y}=U.getCurrent(),b=e.type,T=(p=y[b].before)!=null?p:0,v=(I=y[b].after)!=null?I:0,E=i.getCurrentTime();E===void 0&&(E=i.getReference().getValue().position.getPolled()),u.push({start:E-T,end:E+v})}if(n.end!==void 0){let y=Wn(o,n);y!==null&&(y.bufferedStart===void 0||y.bufferedStart-n.end<1)&&u.push({start:n.end-1,end:Number.MAX_VALUE})}let c=go(a,u);return c.length===0?{type:"continue",value:void 0}:d?{type:"flush-buffer",value:c}:{type:"clean-buffer",value:c}}function fd({playbackObserver:n,content:e,options:t,representationEstimator:r,segmentSink:i,segmentQueueCreator:o,wantedBufferAhead:a,maxVideoBufferSize:s},d,u){let{manifest:l,period:c,adaptation:f}=e,g=new B;g.linkToSignal(u);let p=new Map,I=new H(null,g.signal),y,b=e.representations.getValue().representationIds,T=e.adaptation.representations.filter(C=>Q(b,C.id)&&C.decipherable!==!1&&C.isSupported!==!1),v=new H(T,g.signal),{estimates:E,callbacks:R}=r({manifest:l,period:c,adaptation:f},I,v,n,g.signal),k=new H(!1);n.listen(C=>{var L;let D=(L=C.canStream)!=null?L:!0;k.getValue()===D&&(m.debug("Stream: isMediaSegmentQueueInterrupted updated to",!D),k.setValue(!D))},{clearSignal:g.signal});let x=o.createSegmentQueue(f.type,{onRequestBegin:R.requestBegin,onRequestEnd:R.requestEnd,onProgress:R.requestProgress,onMetrics:R.metrics},k),M=new H(0);E.onUpdate(({bitrate:C,knownStableBitrate:D})=>{t.enableFastSwitching&&M.setValueIfChanged(D),!(C===void 0||C===y)&&(y=C,m.debug(`Stream: new ${f.type} bitrate estimate`,C),d.bitrateEstimateChange({type:f.type,bitrate:C}))},{emitCurrentValue:!0,clearSignal:g.signal});let P;e.representations.onUpdate(C=>{P!==void 0&&P.cancel();let D=e.representations.getValue().representationIds,L=e.adaptation.representations.filter(V=>Q(D,V.id));v.setValueIfChanged(L),P=new B,P.linkToSignal(g.signal),N(C,P.signal).catch(V=>{(P==null?void 0:P.isUsed())===!0&&B.isCancellationError(V)||(g.cancel(),d.error(V))})},{clearSignal:g.signal,emitCurrentValue:!0});return;async function N(C,D){let L=cd(c,f,C,i,n);switch(L.type){case"continue":break;case"needs-reload":return Et(()=>{n.listen(()=>{if(D.isCancelled())return;let{DELTA_POSITION_AFTER_RELOAD:V}=U.getCurrent(),$=V.bitrateSwitch;return d.waitingMediaSourceReload({bufferType:f.type,period:c,timeOffset:$,stayInPeriod:!0})},{includeLastObservation:!0,clearSignal:D})});case"flush-buffer":case"clean-buffer":for(let V of L.value)if(await i.removeBuffer(V.start,V.end),D.isCancelled())return;if(L.type==="flush-buffer"&&(d.needsBufferFlush(),D.isCancelled()))return;break;default:Xe(L)}O(D)}function O(C){let D=new B;D.linkToSignal(C);let{representation:L}=E.getValue();if(L===null)return;let V=new H(null,D.signal);E.onUpdate(z=>{if(!(z.representation===null||z.representation.id===L.id))return z.urgent?(m.info("Stream: urgent Representation switch",f.type),V.setValue({urgent:!0})):(m.info("Stream: slow Representation switch",f.type),V.setValue({urgent:!1}))},{clearSignal:D.signal,emitCurrentValue:!0});let $={type:f.type,adaptation:f,period:c,representation:L};if(I.setValue(L),g.isUsed()||(d.representationChange($),g.isUsed()))return;let j={streamStatusUpdate:d.streamStatusUpdate,encryptionDataEncountered:d.encryptionDataEncountered,manifestMightBeOufOfSync:d.manifestMightBeOufOfSync,needsManifestRefresh:d.needsManifestRefresh,inbandEvent:d.inbandEvent,warning:d.warning,error(z){g.cancel(),d.error(z)},addedSegment(z){R.addedSegment(z)},terminating(){if(!D.isUsed())return D.cancel(),O(C)}};K(L,V,j,C)}function K(C,D,L,V){let $=!1,j=new B;j.linkToSignal(V);let z=an(a,se=>A(C,se),j.signal),q=f.type==="video"?s:new H(1/0);m.info("Stream: changing representation",f.type,C.id,C.bitrate);let W=G({},L,{error(se){var de;if($){m.warn("Stream: Ignoring RepresentationStream error",se);return}$=!0;let ae=Oe(se,{defaultCode:"NONE",defaultReason:"Unknown `RepresentationStream` error"});if(ae.code!=="BUFFER_FULL_ERROR")L.error(se);else{m.warn("Stream: received BUFFER_FULL_ERROR",f.type,C.bitrate);let Se=a.getValue(),ce=((de=p.get(C.id))!=null?de:1)*.7;if(p.set(C.id,ce),ce<=.05||A(C,Se)<=2){L.error(ae);return}qt(4e3,g.signal).then(()=>K(C,D,L,V)).catch(X)}},terminating(){j.cancel(),L.terminating()}});pf({playbackObserver:n,content:{representation:C,adaptation:f,period:c,manifest:l},segmentSink:i,segmentQueue:x,terminate:D,options:{bufferGoal:z,maxBufferSize:q,drmSystemId:t.drmSystemId,fastSwitchThreshold:M}},W,V),l.addEventListener("manifestUpdate",se=>{for(let ae of se.updatedPeriods)if(ae.period.id===c.id){for(let de of ae.result.updatedAdaptations)if(de.adaptation===f.id){for(let Se of de.removedRepresentations)if(Se===C.id)return V.isCancelled()?void 0:d.waitingMediaSourceReload({bufferType:f.type,period:c,timeOffset:0,stayInPeriod:!0})}}else if(ae.period.start>c.start)break},V)}function A(C,D){let L=p.get(C.id),V=L!==void 0?L:1;return L===void 0&&p.set(C.id,V),V<1&&D===1/0?5*60*1e3*V:D*V}}var gf=fd;function md(n,e,t,r,i,o){var g,p,I,y;if(n.codec!==void 0&&o.onCodecSwitch==="reload"&&!ph(t,n.codec))return{type:"needs-reload",value:void 0};let a=n.getLastKnownInventory(),s=[];for(let b of a)b.infos.period.id===e.id&&b.infos.adaptation.id!==t.id&&Wt(s,{start:(g=b.bufferedStart)!=null?g:b.start,end:(p=b.bufferedEnd)!=null?p:b.end});let d=n.getPendingOperations();for(let b of d)if(b.type===0){let T=b.value.inventoryInfos;if(T.period.id===e.id&&T.adaptation.id!==t.id){let v=T.segment.time,E=v+T.segment.duration;Wt(s,{start:v,end:E})}}if(s.length===0)return{type:"continue",value:void 0};if(r==="reload"){let b=i.getReadyState();if(b===void 0||b>1)return{type:"needs-reload",value:void 0}}let u=r==="direct",l=[],c=Hn(a,e);if(c!==null&&(c.bufferedEnd===void 0||e.start-c.bufferedEnd<1)&&l.push({start:0,end:e.start+1}),!u){let b=t.type,{ADAP_REP_SWITCH_BUFFER_PADDINGS:T}=U.getCurrent(),v=(I=T[b].before)!=null?I:0,E=(y=T[b].after)!=null?y:0,R=i.getCurrentTime();R===void 0&&(R=i.getReference().getValue().position.getPolled()),l.push({start:R-v,end:R+E})}if(e.end!==void 0){let b=Wn(a,e);b!==null&&(b.bufferedStart===void 0||b.bufferedStart-e.end<1)&&l.push({start:e.end-1,end:Number.MAX_VALUE})}let f=go(s,l);return f.length===0?{type:"continue",value:void 0}:u&&t.type!=="text"?{type:"flush-buffer",value:f}:{type:"clean-buffer",value:f}}function ph(n,e){return n.representations.some(t=>t.isSupported===!0&&t.decipherable!==!1&&Go(t.getMimeTypeString(),e))}function pd({bufferType:n,content:e,garbageCollectors:t,playbackObserver:r,representationEstimator:i,segmentQueueCreator:o,segmentSinksStore:a,options:s,wantedBufferAhead:d,maxVideoBufferSize:u},l,c){let{manifest:f,period:g}=e,p=new H(void 0,c);if(l.periodStreamReady({type:n,manifest:f,period:g,adaptationRef:p}),c.isCancelled())return;let I,y=!0;p.onUpdate(v=>{(async()=>{var A;if(v===void 0)return;let E=new B;if(E.linkToSignal(c),I==null||I.cancel(),I=E,v===null){m.info(`Stream: Set no ${n} Adaptation. P:`,g.start);let C=a.getStatus(n);if(C.type==="initialized"){if(m.info(`Stream: Clearing previous ${n} SegmentSink`),Zt.isNative(n))return T(0,!0,E.signal);{let D=(A=g.end)!=null?A:1/0;if(g.start>D)m.warn("Stream: Can't free buffer: period's start is after its end");else if(await C.value.removeBuffer(g.start,D),E.isUsed())return}}else if(C.type==="uninitialized"&&(a.disableSegmentSink(n),E.isUsed()))return;return l.adaptationChange({type:n,adaptation:null,period:g}),E.isUsed()?void 0:hf(r,d,n,{period:g},l,E.signal)}let R=g.adaptations[n],k=Z(R!=null?R:[],C=>C.id===v.adaptationId);if(k===void 0){I.cancel(),m.warn("Stream: Unfound chosen Adaptation choice",v.adaptationId);return}let{DELTA_POSITION_AFTER_RELOAD:x}=U.getCurrent(),M=!1,P;if(y)P=0;else if(v.relativeResumingPosition!==void 0)P=v.relativeResumingPosition;else switch(M=!0,n){case"audio":P=x.trackSwitch.audio;break;case"video":P=x.trackSwitch.video;break;default:P=x.trackSwitch.other;break}if(y=!1,Zt.isNative(n)&&a.getStatus(n).type==="disabled")return T(P,!0,E.signal);f.addEventListener("manifestUpdate",C=>{for(let D of C.updatedPeriods)if(D.period.id===g.id){for(let L of D.result.removedAdaptations)if(L.id===k.id)return T(P,!0,E.signal)}else if(D.period.start>g.start)break},I.signal);let{representations:N}=v;if(m.info(`Stream: Updating ${n} adaptation`,`A: ${k.id}`,`P: ${g.start}`),l.adaptationChange({type:n,adaptation:k,period:g}),E.isUsed())return;let O=gh(a,n,k),K=md(O,g,k,v.switchingMode,r,s);if(K.type==="needs-reload")return T(P,!0,E.signal);if(await a.waitForUsableBuffers(E.signal),!E.isUsed()){if(K.type==="flush-buffer"||K.type==="clean-buffer"){for(let{start:C,end:D}of K.value)if(await O.removeBuffer(C,D),E.isUsed())return;if(K.type==="flush-buffer"&&(l.needsBufferFlush({relativeResumingPosition:P,relativePosHasBeenDefaulted:M}),E.isUsed()))return}t.get(O)(E.signal),b(k,N,O,E.signal)}})().catch(E=>{E instanceof Me||(I==null||I.cancel(),l.error(E))})},{clearSignal:c,emitCurrentValue:!0});function b(v,E,R,k){let x=yh(r,v.type);gf({content:{manifest:f,period:g,adaptation:v,representations:E},options:s,playbackObserver:x,representationEstimator:i,segmentSink:R,segmentQueueCreator:o,wantedBufferAhead:d,maxVideoBufferSize:u},ue(oe({},l),{error:M}),k);function M(P){if(!Zt.isNative(n)){m.error(`Stream: ${n} Stream crashed. Aborting it.`,P instanceof Error?P:""),a.disposeSegmentSink(n);let N=Oe(P,{defaultCode:"NONE",defaultReason:"Unknown `AdaptationStream` error"});return l.warning(N),k.isCancelled()?void 0:hf(r,d,n,{period:g},l,k)}m.error(`Stream: ${n} Stream crashed. Stopping playback.`,P instanceof Error?P:""),l.error(P)}}function T(v,E,R){Et(()=>{r.listen(()=>{R.isCancelled()||l.waitingMediaSourceReload({bufferType:n,period:g,timeOffset:v,stayInPeriod:E})},{includeLastObservation:!0,clearSignal:R})})}}function gh(n,e,t){let r=n.getStatus(e);if(r.type==="initialized")return m.info("Stream: Reusing a previous SegmentSink for the type",e),r.value;let i=hh(t);return n.createSegmentSink(e,i)}function hh(n){let e=n.representations.filter(t=>t.isSupported===!0&&t.decipherable!==!1);if(e.length===0)throw new te("NO_PLAYABLE_REPRESENTATION","No Representation in the chosen "+n.type+" Adaptation can be played",{tracks:[Xt(n)]});return e[0].getMimeTypeString()}function yh(n,e){return n.deriveReadOnlyObserver(function(r,i){let o=new H(a(),i);return r.onUpdate(s,{clearSignal:i,emitCurrentValue:!1}),o;function a(){let d=r.getValue(),u=d.buffered[e],l=u!==null?po(u,d.position.getWanted()):0;return G({},d,{bufferGap:l,buffered:u})}function s(){o.setValue(a())}})}function hf(n,e,t,r,i,o){let{period:a}=r,s=!1;e.onUpdate(d,{emitCurrentValue:!1,clearSignal:o}),n.listen(d,{includeLastObservation:!1,clearSignal:o}),d();function d(){let u=n.getReference().getValue(),l=e.getValue(),c=u.position.getWanted();a.end!==void 0&&c+l>=a.end&&(m.debug('Stream: full "empty" AdaptationStream',t),s=!0),i.streamStatusUpdate({period:a,bufferType:t,imminentDiscontinuity:null,position:c,isEmptyStream:!0,hasFinishedLoading:s,neededSegments:[]})}}var yf=pd;function na(n,e){if(e.length===0)return[];let t=[],r=n.getLastKnownInventory();for(let i of r)if(e.some(a=>i.infos.period.id===a.period.id&&i.infos.adaptation.id===a.adaptation.id&&i.infos.representation.id===a.representation.id)){let{bufferedStart:a,bufferedEnd:s}=i;if(a===void 0||s===void 0)return m.warn("SO: No buffered start or end found from a segment."),[{start:0,end:Number.MAX_VALUE}];let d=t[t.length-1];d!==void 0&&d.end===a?d.end=s:t.push({start:a,end:s})}return t}function gd(n,e,t,r,i,o,a,s){let{manifest:d,initialPeriod:u}=n,{maxBufferAhead:l,maxBufferBehind:c,wantedBufferAhead:f,maxVideoBufferSize:g}=o,{MINIMUM_MAX_BUFFER_AHEAD:p,MAXIMUM_MAX_BUFFER_AHEAD:I,MAXIMUM_MAX_BUFFER_BEHIND:y}=U.getCurrent(),b=new fi(E=>{var M,P;let{bufferType:R}=E,k=(M=y[R])!=null?M:1/0,x=(P=I[R])!=null?P:1/0;return N=>{Jo({segmentSink:E,playbackObserver:e,maxBufferBehind:an(c,O=>Math.min(O,k),N),maxBufferAhead:an(l,O=>{var A;let K=Math.max(O,(A=p[R])!=null?A:0);return Math.min(K,x)},N)},N)}});for(let E of r.getBufferTypes())T(E,u);function T(E,R){let k=new Sn((K,A)=>K.start-A.start),x=!1,M=new B;return M.linkToSignal(s),e.listen(({position:K})=>{var D;let A=K.getWanted();if(!x||!N(A))return;for(m.info("Stream: Destroying all PeriodStreams due to out of bounds situation",E,A),x=!1;k.length()>0;){let L=k.get(k.length()-1);k.removeElement(L),a.periodStreamCleared({type:E,manifest:d,period:L})}M.cancel(),M=new B,M.linkToSignal(s);let C=(D=d.getPeriodForTime(A))!=null?D:d.getNextPeriod(A);if(C===void 0){m.warn("Stream: The wanted position is not found in the Manifest."),x=!0;return}P(C)},{clearSignal:s,includeLastObservation:!0}),d.addEventListener("decipherabilityUpdate",K=>{s.isCancelled()||O(K).catch(A=>{s.isCancelled()||(M.cancel(),a.error(A))})},s),P(R);function P(K){let A=ue(oe({},a),{waitingMediaSourceReload(C){let D=k.head();D===void 0||D.id!==C.period.id?a.lockedStream({bufferType:C.bufferType,period:C.period}):a.needsMediaSourceReload({timeOffset:C.timeOffset,minimumPosition:C.stayInPeriod?C.period.start:void 0,maximumPosition:C.stayInPeriod?C.period.end:void 0})},periodStreamReady(C){x=!0,k.add(C.period),a.periodStreamReady(C)},periodStreamCleared(C){k.removeElement(C.period),a.periodStreamCleared(C)},error(C){M.cancel(),a.error(C)}});v(E,K,A,M.signal)}function N(K){let A=k.head(),C=k.last();return A===void 0||C===void 0?!0:A.start>K||(_(C.end)?1/0:C.end)<K}async function O(K){let A=r.getStatus(E),C=K.filter(z=>z.adaptation.type===E);if(C.length===0||A.type!=="initialized"||C.every(z=>z.representation.decipherable===!0))return;let D=A.value,L=C.filter(z=>z.representation.decipherable===void 0),V=C.filter(z=>z.representation.decipherable===!1),$=na(D,V),j=na(D,L);for(x=!1,m.info("Stream: Destroying all PeriodStreams for decipherability matters",E);k.length()>0;){let z=k.get(k.length()-1);k.removeElement(z),a.periodStreamCleared({type:E,manifest:d,period:z})}M.cancel(),M=new B,M.linkToSignal(s);for(let{start:z,end:q}of[...$,...j]){if(s.isCancelled())return;if(z<q){if(s.isCancelled())return;await D.removeBuffer(z,q)}}Et(()=>{if(s.isCancelled())return;let z=e.getReference().getValue();if(If(z,$)){if(a.needsDecipherabilityFlush(),s.isCancelled())return}else if(If(z,j)&&(a.needsBufferFlush(),s.isCancelled()))return;let q=z.position.getWanted(),W=d.getPeriodForTime(q);if(W===void 0){a.error(new te("MEDIA_TIME_NOT_FOUND","The wanted position is not found in the Manifest."));return}P(W)})}}function v(E,R,k,x){m.info("Stream: Creating new Stream for",E,R.start);let M=null,P=new B;P.linkToSignal(x),e.listen(({position:C},D)=>{if(R.end!==void 0&&C.getWanted()>=R.end){let L=d.getPeriodAfter(R);if(R.containsTime(C.getWanted(),L))return;m.info("Stream: Destroying PeriodStream as the current playhead moved above it",E,R.start,C.getWanted(),R.end),D(),k.periodStreamCleared({type:E,manifest:d,period:R}),P.cancel()}},{clearSignal:x,includeLastObservation:!0});let N={bufferType:E,content:{manifest:d,period:R},garbageCollectors:b,maxVideoBufferSize:g,segmentQueueCreator:i,segmentSinksStore:r,options:o,playbackObserver:e,representationEstimator:t,wantedBufferAhead:f},O=ue(oe({},k),{streamStatusUpdate(C){if(C.hasFinishedLoading){let D=d.getPeriodAfter(R);D!==null&&K(D)}else M!==null&&(m.info("Stream: Destroying next PeriodStream due to current one being active",E,M.period.start),k.periodStreamCleared({type:E,manifest:d,period:M.period}),M.canceller.cancel(),M=null);k.streamStatusUpdate(C)},error(C){M!==null&&(M.canceller.cancel(),M=null),P.cancel(),k.error(C)}});yf(N,O,P.signal),A(P.signal);function K(C){if(M!==null){if(M.period.id===C.id)return;m.warn("Stream: Creating next `PeriodStream` while one was already created.",E,C.id,M.period.id),k.periodStreamCleared({type:E,manifest:d,period:M.period}),M.canceller.cancel()}let D=new B;D.linkToSignal(x),M={canceller:D,period:C},v(E,C,k,M.canceller.signal)}function A(C){d.addEventListener("manifestUpdate",D=>{for(let L of D.removedPeriods)if(L.id===R.id){if(d.periods.length>0&&d.periods[0].start<=L.start)return Et(()=>{if(!C.isCancelled())return a.needsMediaSourceReload({timeOffset:0,minimumPosition:void 0,maximumPosition:void 0})})}else if(L.start>R.start)break;if(D.addedPeriods.length>0&&M!==null){let L=d.getPeriodAfter(R);(L===null||M.period.id!==L.id)&&(m.warn("Stream: Destroying next PeriodStream due to new one being added",E,M.period.start),k.periodStreamCleared({type:E,manifest:d,period:M.period}),M.canceller.cancel(),M=null)}},C)}}}function If(n,e){if(e.length===0)return!1;let t=n.position.getPolled();return n.speed>=0?e[e.length-1].end>=t-5:e[0].start<=t+5}var bf=gd;var Sf=bf;var Ih={dashParsers:{wasm:null,native:null,fastJs:null},createDebugElement:null,directfile:null,decrypt:null,htmlTextDisplayer:null,htmlTextTracksParsers:{},mainThreadMediaSourceInit:null,multithread:null,nativeTextDisplayer:null,nativeTextTracksParsers:{},transports:{}},gi=Ih;function ra(n){for(let e of n)if(typeof e=="function")e(gi);else if(!_(e)&&typeof e._addFeature=="function")e._addFeature(gi);else throw new Error("Unrecognized feature")}var me=gi;var bh={createSync(n){return{syncValue:n,getValueAsAsync(){return Promise.resolve(n)}}},createAsync(n){let e=null;return n.then(t=>{e=t},X),{get syncValue(){return e},getValueAsAsync(){return n}}}},Tf=bh;var qn=class extends re{};function hd(n,e){let t={audio:null,video:null,text:null};if(e!==null&&(t.text=e.getBufferedRanges()),n===null)return t;let r=Z(n.sourceBuffers,s=>s.type==="audio"),i=Z(n.sourceBuffers,s=>s.type==="video"),o=r==null?void 0:r.getBuffered();o!==void 0&&(t.audio=o);let a=i==null?void 0:i.getBuffered();return a!==void 0&&(t.video=a),t}function yd(n,{autoPlay:e,initialPlayPerformed:t,manifest:r,mediaSource:i,speed:o,textDisplayer:a},s){return n.deriveReadOnlyObserver(function(u,l){let c=new B;c.linkToSignal(l),c.linkToSignal(s);let f=new H(g(),c.signal);return o.onUpdate(p,{clearSignal:c.signal,emitCurrentValue:!1}),u.onUpdate(p,{clearSignal:c.signal,emitCurrentValue:!1}),i==null||i.addEventListener("streamingChanged",()=>{p()},c.signal),f;function g(){var b;let I=u.getValue(),y=o.getValue();return Sh(I,r),{maximumPosition:St(r),bufferGap:I.bufferGap,position:I.position,buffered:hd(i,a),duration:I.duration,rebuffering:I.rebuffering,freezing:I.freezing,paused:{last:I.paused,pending:Th(t,e)},readyState:I.readyState,speed:y,canStream:(b=i==null?void 0:i.streaming)!=null?b:!0}}function p(){f.setValue(g())}})}function Sh(n,e){if(!e.isDynamic||e.isLastPeriodKnown){let t=e.periods[e.periods.length-1];if(t!==void 0&&t.end!==void 0){let r=n.position.getWanted();if(r>=t.start&&r>=t.end-1){let i=n.buffered;(i.length===0||i.end(i.length-1)<n.duration-1)&&n.position.forceWantedPosition(t.end-1)}}}}function Th(n,e){return n.getValue()?void 0:!e}function jn(n){let{textTracks:e}=n;if(!_(e)){for(let t=0;t<e.length;t++)e[t].mode="disabled";if(n.hasChildNodes()){let{childNodes:t}=n;for(let r=t.length-1;r>=0;r--)if(t[r].nodeName==="track")try{n.removeChild(t[r])}catch(i){m.warn("Compat: Could not remove text track child from element.")}}}n.src="",n.removeAttribute("src")}function Id(n,e){if(typeof n.changeType=="function"){try{n.changeType(e)}catch(t){return m.warn("Could not call 'changeType' on the given SourceBuffer:",t instanceof Error?t:""),!1}return!0}return!1}function _h(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t];r.updating&&e.push(r)}return e}function hi(n,e){if(m.debug("Init: Trying to call endOfStream"),n.readyState!=="open"){m.debug("Init: MediaSource not open, cancel endOfStream");return}let{sourceBuffers:t}=n,r=_h(t);if(r.length===0){m.info("Init: Triggering end of stream");try{n.endOfStream()}catch(o){m.error("Unable to call endOfStream",o instanceof Error?o:new Error("Unknown error"))}return}m.debug("Init: Waiting SourceBuffers to be updated before calling endOfStream.");let i=new B;i.linkToSignal(e);for(let o of r)yc(o,()=>{i.cancel(),hi(n,e)},i.signal);Ic(t,()=>{i.cancel(),hi(n,e)},i.signal)}function _f(n,e){let t=new B;t.linkToSignal(e),Ln(n,()=>{m.debug("Init: MediaSource re-opened while end-of-stream is active"),t.cancel(),t=new B,t.linkToSignal(e),hi(n,t.signal)},e),hi(n,t.signal)}function bd(){return ln}var Eh=365*24*3600,yi=class{constructor(e){this._mediaSource=e,this._currentMediaSourceDurationUpdateCanceller=null}updateDuration(e,t){this._currentMediaSourceDurationUpdateCanceller!==null&&this._currentMediaSourceDurationUpdateCanceller.cancel(),this._currentMediaSourceDurationUpdateCanceller=new B;let r=this._mediaSource,i=this._currentMediaSourceDurationUpdateCanceller.signal,o=kh(r,i),a=new B;a.linkToSignal(i),o.onUpdate(s,{emitCurrentValue:!0,clearSignal:i});function s(){if(a.cancel(),!o.getValue())return;a=new B,a.linkToSignal(i);let d=Rh(r.sourceBuffers,a.signal),u=new B;return u.linkToSignal(a.signal),d.onUpdate(l=>{u.cancel(),u=new B,u.linkToSignal(a.signal),!l&&vf(r,e,t,u.signal)},{clearSignal:a.signal,emitCurrentValue:!0})}}stopUpdating(){this._currentMediaSourceDurationUpdateCanceller!==null&&(this._currentMediaSourceDurationUpdateCanceller.cancel(),this._currentMediaSourceDurationUpdateCanceller=null)}};function vh(n,e,t){let r=e;t||(r=bd()?1/0:Ef(e));let i=0;for(let o=0;o<n.sourceBuffers.length;o++){let a=n.sourceBuffers[o],s=a.buffered.length;s>0&&(i=Math.max(a.buffered.end(s-1)))}if(r===n.duration)return"success";if(i>r){if(i<n.duration)try{m.info("Init: Updating duration to what is currently buffered",i),n.duration=i}catch(o){return m.warn("Duration Updater: Can't update duration on the MediaSource.",o instanceof Error?o:""),"failed"}return"partial"}else{let o=n.duration;try{if(m.info("Init: Updating duration",r),n.duration=r,n.readyState==="open"&&!isFinite(r)){let s=Ef(e);m.info("Init: calling `mediaSource.setLiveSeekableRange`",s),n.setLiveSeekableRange(0,s)}}catch(s){return m.warn("Duration Updater: Can't update duration on the MediaSource.",s instanceof Error?s:""),"failed"}let a=Math.abs(n.duration-r);if(a>=.1){let s=Math.abs(n.duration-o);return a<s?"partial":"failed"}return"success"}}function Rh(n,e){if(n.length===0){let i=new H(!1);return i.finish(),i}let t=new H(!1,e);r();for(let i=0;i<n.length;i++){let o=n[i];o.addEventListener("updatestart",r),o.addEventListener("update",r),e.register(()=>{o.removeEventListener("updatestart",r),o.removeEventListener("update",r)})}return t;function r(){for(let i=0;i<n.length;i++)if(n[i].updating){t.setValueIfChanged(!0);return}t.setValueIfChanged(!1)}}function kh(n,e){let t=new H(n.readyState==="open",e);return Ln(n,()=>{m.debug("Init: Reacting to MediaSource open in duration updater"),t.setValueIfChanged(!0)},e),Ro(n,()=>{m.debug("Init: Reacting to MediaSource ended in duration updater"),t.setValueIfChanged(!1)},e),vo(n,()=>{m.debug("Init: Reacting to MediaSource close in duration updater"),t.setValueIfChanged(!1)},e),t}function vf(n,e,t,r){if(vh(n,e,t)==="success")return;let o=setTimeout(()=>{a(),vf(n,e,t,r)},2e3),a=r.register(()=>{clearTimeout(o)})}function Ef(n){return Math.max(Math.pow(2,32),n+Eh)}var Ii=class extends re{constructor(e){if(super(),this.id=e,this.sourceBuffers=[],this._canceller=new B,_(vt))throw new te("MEDIA_SOURCE_NOT_SUPPORTED","No MediaSource Object was found in the current browser.");m.info("Init: Creating MediaSource");let t=new vt,r=t.handle;this.handle=_(r)?{type:"media-source",value:t}:{type:"handle",value:r},this._mediaSource=t,this.readyState=t.readyState,this._durationUpdater=new yi(t),this._endOfStreamCanceller=null,Ln(t,()=>{this.readyState=t.readyState,this.trigger("mediaSourceOpen",null)},this._canceller.signal),Ro(t,()=>{this.readyState=t.readyState,this.trigger("mediaSourceEnded",null)},this._canceller.signal),vo(t,()=>{this.readyState=t.readyState,this.trigger("mediaSourceClose",null)},this._canceller.signal),this._mediaSource.streaming!==void 0&&(this.streaming=this._mediaSource.streaming),this._mediaSource.addEventListener("startstreaming",()=>{this.streaming=!0,this.trigger("streamingChanged",null)}),this._mediaSource.addEventListener("endstreaming",()=>{this.streaming=!1,this.trigger("streamingChanged",null)})}addSourceBuffer(e,t){let r=this._mediaSource.addSourceBuffer(t),i=new Sd(e,t,r);return this.sourceBuffers.push(i),i}setDuration(e,t){this._durationUpdater.updateDuration(e,t)}interruptDurationSetting(){this._durationUpdater.stopUpdating()}maintainEndOfStream(){this._endOfStreamCanceller===null&&(this._endOfStreamCanceller=new B,this._endOfStreamCanceller.linkToSignal(this._canceller.signal),m.debug("Init: end-of-stream order received."),_f(this._mediaSource,this._endOfStreamCanceller.signal))}stopEndOfStream(){this._endOfStreamCanceller!==null&&(m.debug("Init: resume-stream order received."),this._endOfStreamCanceller.cancel(),this._endOfStreamCanceller=null)}dispose(){this.sourceBuffers.forEach(e=>e.dispose()),this._canceller.cancel(),Ch(this._mediaSource)}},Sd=class{constructor(e,t,r){this.type=e,this.codec=t,this._canceller=new B,this._sourceBuffer=r,this._operationQueue=[],this._currentOperations=[];let i=this._onError.bind(this),o=this._onUpdateEnd.bind(this);r.addEventListener("updateend",o),r.addEventListener("error",i),this._canceller.signal.register(()=>{r.removeEventListener("updateend",o),r.removeEventListener("error",i)})}appendBuffer(...e){return m.debug("SBI: receiving order to push data to the SourceBuffer",this.type),this._addToQueue({operationName:0,params:e})}remove(e,t){return m.debug("SBI: receiving order to remove data from the SourceBuffer",this.type,e,t),this._addToQueue({operationName:1,params:[e,t]})}getBuffered(){try{return Pe(this._sourceBuffer.buffered)}catch(e){return m.error("Failed to get buffered time range of SourceBuffer",this.type,e instanceof Error?e:null),[]}}abort(){try{this._sourceBuffer.abort()}catch(e){m.debug("Init: Failed to abort SourceBuffer:",e instanceof Error?e:null)}this._emptyCurrentQueue()}dispose(){try{this._sourceBuffer.abort()}catch(e){}this._emptyCurrentQueue()}_onError(e){let t;e instanceof Error?t=e:e.error instanceof Error?t=e.error:t=new Error("Unknown SourceBuffer Error");let r=this._currentOperations;if(this._currentOperations=[],r.length===0)m.error("SBI: error for an unknown operation",t);else{let i=new ot(t.name,t.message,t.name==="QuotaExceededError");for(let o of r)o.reject(i)}}_onUpdateEnd(){let e=this._currentOperations;this._currentOperations=[];try{for(let t of e)t.resolve(Pe(this._sourceBuffer.buffered))}catch(t){for(let r of e)t instanceof Error&&t.name==="InvalidStateError"?r.resolve([]):r.reject(t)}this._performNextOperation()}_emptyCurrentQueue(){let e=new Me;this._currentOperations.length>0&&(this._currentOperations.forEach(t=>{t.reject(e)}),this._currentOperations=[]),this._operationQueue.length>0&&(this._operationQueue.forEach(t=>{t.reject(e)}),this._operationQueue=[])}_addToQueue(e){return new Promise((t,r)=>{let i=this._operationQueue.length===0&&this._currentOperations.length===0,o=G({resolve:t,reject:r},e);this._operationQueue.push(o),i&&this._performNextOperation()})}_performNextOperation(){var t,r,i,o,a;if(this._currentOperations.length!==0||this._sourceBuffer.updating)return;let e=this._operationQueue.shift();if(e!==void 0)if(e.operationName===0){this._currentOperations=[{operationName:0,resolve:e.resolve,reject:e.reject}];let s=e.params[0],d=e.params[1],u=s;if(this._operationQueue.length>0&&this._operationQueue[0].operationName===0){let l;s instanceof ArrayBuffer?l=new Uint8Array(s):s instanceof Uint8Array?l=s:l=new Uint8Array(s.buffer);let c=[l];for(;((t=this._operationQueue[0])==null?void 0:t.operationName)===0;){let f=this._operationQueue[0],g=(r=d.appendWindow)!=null?r:[void 0,void 0],p=(i=f.params[1].appendWindow)!=null?i:[void 0,void 0],I=(o=d.timestampOffset)!=null?o:0,y=(a=f.params[1].timestampOffset)!=null?a:0;if(g[0]===p[0]&&g[1]===p[1]&&d.codec===f.params[1].codec&&I===y){let b=f.params[0],T;b instanceof ArrayBuffer?T=new Uint8Array(b):b instanceof Uint8Array?T=b:T=new Uint8Array(b.buffer),c.push(T),this._operationQueue.splice(0,1),this._currentOperations.push({operationName:0,resolve:f.resolve,reject:f.reject})}else break}c.length>1&&(m.info(`MMSI: Merging ${c.length} segments together for perf`,this.type),u=ie(...c))}try{this._appendBufferNow(u,d)}catch(l){let c=l instanceof Error?new ot(l.name,l.message,l.name==="QuotaExceededError"):new ot("Error","Unknown SourceBuffer Error during appendBuffer",!1);this._currentOperations.forEach(f=>{f.reject(c)}),this._currentOperations=[],this._performNextOperation()}}else{this._currentOperations=[e];let[s,d]=e.params;m.debug("SBI: removing data from SourceBuffer",this.type,s,d);try{this._sourceBuffer.remove(s,d)}catch(u){let l=u instanceof Error?new ot(u.name,u.message,!1):new ot("Error","Unknown SourceBuffer Error during remove",!1);e.reject(l),this._currentOperations.forEach(c=>{c.reject(l)}),this._currentOperations=[],this._performNextOperation()}}}_appendBufferNow(e,t){let r=this._sourceBuffer,{codec:i,timestampOffset:o,appendWindow:a=[]}=t;if(i!==void 0&&i!==this.codec&&(m.debug("SBI: updating codec",i),Id(r,i)?this.codec=i:m.debug("SBI: could not update codec",i,this.codec)),o!==void 0&&r.timestampOffset!==o){let s=o;m.debug("SBI: updating timestampOffset",i,r.timestampOffset,s),r.timestampOffset=s}if(a[0]===void 0)r.appendWindowStart>0&&(m.debug("SBI: re-setting `appendWindowStart` to `0`"),r.appendWindowStart=0);else if(a[0]!==r.appendWindowStart){if(a[0]>=r.appendWindowEnd){let s=a[0]+1;m.debug("SBI: pre-updating `appendWindowEnd`",s),r.appendWindowEnd=s}m.debug("SBI: setting `appendWindowStart`",a[0]),r.appendWindowStart=a[0]}a[1]===void 0?r.appendWindowEnd!==1/0&&(m.debug("SBI: re-setting `appendWindowEnd` to `Infinity`"),r.appendWindowEnd=1/0):a[1]!==r.appendWindowEnd&&(m.debug("SBI: setting `appendWindowEnd`",a[1]),r.appendWindowEnd=a[1]),m.debug("SBI: pushing segment",this.type),r.appendBuffer(e)}};function Ch(n){if(n.readyState!=="closed"){let{readyState:e,sourceBuffers:t}=n;for(let r=t.length-1;r>=0;r--){let i=t[r];try{if(e==="open"){m.info("Init: Aborting SourceBuffer before removing");try{i.abort()}catch(o){}}m.info("Init: Removing SourceBuffer from mediaSource"),n.removeSourceBuffer(i)}catch(o){}}t.length>0&&m.info("Init: Not all SourceBuffers could have been removed.")}}var Ph=et();function Td(n,e){if(e!==null&&n.src===e&&(m.info("Init: Clearing HTMLMediaElement's src"),jn(n)),e!==null)try{m.debug("Init: Revoking previous URL"),URL.revokeObjectURL(e)}catch(t){m.warn("Init: Error while revoking the media source URL",t instanceof Error?t:"")}}function Mh(n,e){if(Kl&&"disableRemotePlayback"in n){let t=n.disableRemotePlayback;e.register(()=>{n.disableRemotePlayback=t}),n.disableRemotePlayback=!0}}function Ah(n,e){let t=w(n.src)?n.src:null;Td(n,t);let r=new Ii(Ph());return Mh(n,e),e.register(()=>{r.dispose()}),r}function ia(n,e){return at(e,t=>{let r=Ah(n,e);if(r.addEventListener("mediaSourceOpen",()=>{m.info("Init: MediaSource opened"),t(r)},e),m.info("MTCI: Attaching MediaSource URL to the media element"),r.handle.type==="handle")n.srcObject=r.handle.value,e.register(()=>{Td(n,null)});else{let i=URL.createObjectURL(r.handle.value);n.src=i,e.register(()=>{Td(n,i)})}})}function _d(n,e,t){var i;if(!_(t)){let o=yn(n),a=St(n);if(_(t.position))if(_(t.wallClockTime))if(_(t.fromFirstPosition))if(_(t.fromLastPosition))if(_(t.fromLivePosition)){if(!_(t.percentage)){m.debug("Init: using startAt.percentage");let{percentage:s}=t;if(s>100)return a;if(s<0)return o;let d=+s/100,u=a-o;return o+u*d}}else{m.debug("Init: using startAt.fromLivePosition");let s=(i=In(n))!=null?i:a,{fromLivePosition:d}=t;return d>=0?s:Math.max(o,s+d)}else{m.debug("Init: using startAt.fromLastPosition");let{fromLastPosition:s}=t;return s>=0?a:Math.max(o,a+s)}else{m.debug("Init: using startAt.fromFirstPosition");let{fromFirstPosition:s}=t;return s<=0?o:Math.min(a,o+s)}else{m.debug("Init: using startAt.wallClockTime");let s=n.availabilityStartTime===void 0?0:n.availabilityStartTime,d=t.wallClockTime-s;return Math.max(Math.min(d,a),o)}else return m.debug("Init: using startAt.minimumPosition"),Math.max(Math.min(t.position,a),o)}let r=yn(n);if(n.isLive){let{suggestedPresentationDelay:o,clockOffset:a}=n,s=St(n),d,{DEFAULT_LIVE_GAP:u}=U.getCurrent();if(a===void 0)m.info("Init: no clock offset found for a live content, starting close to maximum available position"),d=s;else{m.info("Init: clock offset found for a live content, checking if we can start close to it");let c=n.availabilityStartTime===void 0?0:n.availabilityStartTime,f=(F()+a)/1e3-c;d=Math.min(s,f)}let l=o!=null?o:e?u.LOW_LATENCY:u.DEFAULT;return m.debug(`Init: ${d} defined as the live time, applying a live gap of ${l}`),Math.max(d-l,r)}return m.info("Init: starting at the minimum available position:",r),r}function bi(){return Fa}function Ed(n){return!(n&&un)}function vd(){return ln}function Si(n,e,t,r){let i=new B;i.linkToSignal(r);let o=new H(!1,i.signal);return n.listen(a=>{if(a.rebuffering!==null||a.freezing!==null||a.readyState===0)return;if(!Ed(t)){if(isNaN(e.duration))return;if(e.duration>0){o.setValue(!0),i.cancel();return}}let s=vd()?4:3;if(a.readyState>=s&&(a.currentRange!==null||a.ended)&&(!bi()||e.duration>0)){o.setValue(!0),i.cancel();return}},{includeLastObservation:!0,clearSignal:i.signal}),o}var xh=!un,Rf=xh;var Yn=class{constructor(e,t){this._last=e,this._wanted=t}serialize(){return[this._last,this._wanted]}getPolled(){return this._last}getWanted(){var e;return(e=this._wanted)!=null?e:this._last}forceWantedPosition(e){this._wanted=e}isAwaitingFuturePosition(){return this._wanted!==null}};function Ti({mediaElement:n,playbackObserver:e,startTime:t,mustAutoPlay:r,isDirectfile:i,onWarning:o},a){let s=new H(!1,a);return{autoPlayResult:new Promise((u,l)=>{let c=a.register(b=>{l(b)});if(a.isCancelled())return;let f=!1,g=b=>{e.setCurrentTime(b),f=!0};if(!i||typeof t=="number"){let b=typeof t=="number"?t:t();b!==0&&b!==void 0&&g(b),p()}else e.listen((b,T)=>{let v=typeof t=="number"?t:t();v===void 0&&b.readyState<HTMLMediaElement.HAVE_CURRENT_DATA||b.readyState>=1&&(T(),v!==0&&v!==void 0&&(Rf?g(v):setTimeout(()=>{g(v)},0)),p())},{includeLastObservation:!0,clearSignal:a});function p(){let b=!1;e.listen((T,v)=>{if(!b&&(T.seeking!==0||T.event==="seeking"||T.event==="internal-seeking")&&(b=!0),!(f&&!b||T.readyState===0)){if(v(),bi()&&n.duration===0){let E=new te("MEDIA_ERR_NOT_LOADED_METADATA","Cannot load automatically: your browser falsely announced having loaded the content.");o(E)}a.isCancelled()||I()}},{includeLastObservation:!0,clearSignal:a})}function I(){e.listen((b,T)=>{b.seeking===0&&b.rebuffering===null&&b.readyState>=1&&(T(),y())},{includeLastObservation:!0,clearSignal:a})}function y(){var T;if(m.info("Init: Can begin to play content"),r){if(n.ended)return m.warn("Init: autoplay is enabled but the video is ended. Skipping autoplay to prevent video to start again"),s.setValue(!0),s.finish(),c(),u({type:"skipped"})}else return n.autoplay&&m.warn("Init: autoplay is enabled on HTML media element. Media will play as soon as possible."),s.setValue(!0),s.finish(),c(),u({type:"skipped"});let b;try{b=(T=n.play())!=null?T:Promise.resolve()}catch(v){return c(),l(v)}b.then(()=>{if(!a.isCancelled())return s.setValue(!0),s.finish(),c(),u({type:"autoplay"})}).catch(v=>{if(c(),!a.isCancelled())if(v instanceof Error&&v.name==="NotAllowedError"){m.warn("Init: Media element can't play. It may be due to browser auto-play policies.");let E=new te("MEDIA_ERR_BLOCKED_AUTOPLAY","Cannot trigger auto-play automatically: your browser does not allow it.");return o(E),a.isCancelled()?void 0:u({type:"autoplay-blocked"})}else l(v)})}}),initialPlayPerformed:s}}function _i(n,e,t,r){if(e.length===0)return u("No `keySystems` option given.");if(me.decrypt===null)return u("EME feature not activated.");let i=new B;i.linkToSignal(r);let o=new H({initializationState:{type:"uninitialized",value:null},drmSystemId:void 0},r),a=me.decrypt;if(!a.hasEmeApis())return u("EME API not available on the current page.");m.debug("Init: Creating ContentDecryptor");let s=new a(n,e),d=l=>{var c;l>0&&((c=t.onCodecSupportUpdate)==null||c.call(t),s.removeEventListener("stateChange",d))};return s.addEventListener("stateChange",d),s.addEventListener("stateChange",l=>{if(l===1){let c=new H(!1);c.onUpdate((f,g)=>{f&&(g(),l===1&&s.attach())},{clearSignal:i.signal}),o.setValue({initializationState:{type:"awaiting-media-link",value:{isMediaLinked:c}},drmSystemId:s.systemId})}else l===2&&(o.setValue({initializationState:{type:"initialized",value:null},drmSystemId:s.systemId}),s.removeEventListener("stateChange"))}),s.addEventListener("error",l=>{i.cancel(),t.onError(l)}),s.addEventListener("warning",l=>{t.onWarning(l)}),s.addEventListener("blackListProtectionData",l=>{t.onBlackListProtectionData(l)}),s.addEventListener("keyIdsCompatibilityUpdate",l=>{t.onKeyIdsCompatibilityUpdate(l)}),i.signal.register(()=>{s.dispose()}),{statusRef:o,contentDecryptor:{enabled:!0,value:s}};function u(l){let c=new pe("MEDIA_IS_ENCRYPTED_ERROR",l),f=new H({initializationState:{type:"initialized",value:null},drmSystemId:void 0});return f.finish(),{statusRef:f,contentDecryptor:{enabled:!1,value:c}}}}var Ei=class{constructor(e){this._displayer=e}pushTextData(e){try{return Promise.resolve(this._displayer.pushTextData(e))}catch(t){return Promise.reject(t)}}remove(e,t){try{return Promise.resolve(this._displayer.removeBuffer(e,t))}catch(r){return Promise.reject(r)}}reset(){this._displayer.reset()}stop(){this._displayer.stop()}};var wh=dr,$n=wh;var vi=1/60,Tn=class extends re{constructor(e,t,r){super(),this._playbackObserver=e,this._manifest=t,this._speed=r,this._discontinuitiesStore=[],this._isStarted=!1,this._canceller=new B}start(){if(this._isStarted)return;this._isStarted=!0;let e=new Cd(this._playbackObserver,this._speed);this._canceller.signal.register(()=>{e.dispose()});let t=null;this._playbackObserver.listen(r=>{let i=this._discontinuitiesStore,{buffered:o,position:a,readyState:s,rebuffering:d,freezing:u}=r,{BUFFER_DISCONTINUITY_THRESHOLD:l,FREEZING_STALLED_DELAY:c,UNFREEZING_SEEK_DELAY:f,UNFREEZING_DELTA_POSITION:g}=U.getCurrent();if(u!==null){let T=F(),v=t===null?u.timestamp:t.attemptTimestamp;if(T-v>f&&(m.warn("Init: trying to seek to un-freeze player"),this._playbackObserver.setCurrentTime(r.position.getWanted()+g),t={attemptTimestamp:T}),T-u.timestamp>c){d===null?e.stopRebuffering():e.startRebuffering(),this.trigger("stalled","freezing");return}}else t=null;if(d===null){if(e.stopRebuffering(),s===1){let T;r.seeking!==0?T=r.seeking===1?"internal-seek":"seeking":T="not-ready",this.trigger("stalled",T);return}this.trigger("unstalled",null);return}let p=d.reason==="seeking"&&r.seeking===1?"internal-seek":d.reason;if(a.isAwaitingFuturePosition()){e.stopRebuffering(),m.debug("Init: let rebuffering happen as we're awaiting a future position"),this.trigger("stalled",p);return}if(e.startRebuffering(),this._manifest===null||$n&&F()-d.timestamp<=1e3){this.trigger("stalled",p);return}let{position:I}=d;if(I!=null&&this._speed.getValue()>0){let T=Oh(i,this._manifest,I);if(T!==null){let v=T+.001;if(v<=this._playbackObserver.getCurrentTime())m.info("Init: position to seek already reached, no seeking",this._playbackObserver.getCurrentTime(),v);else{m.warn("SA: skippable discontinuity found in the stream",a.getPolled(),v),this._playbackObserver.setCurrentTime(v),this.trigger("warning",kd(I,v));return}}}let y=I!=null?I:a.getPolled(),b=$l(o,y);if((!$n||F()-d.timestamp>1e3)&&this._speed.getValue()>0&&b<l){let T=y+b+vi;if(this._playbackObserver.getCurrentTime()<T){m.warn("Init: discontinuity encountered inferior to the threshold",y,T,l),this._playbackObserver.setCurrentTime(T),this.trigger("warning",kd(y,T));return}}for(let T=this._manifest.periods.length-2;T>=0;T--){let v=this._manifest.periods[T];if(v.end!==void 0&&v.end<=y){if(this._manifest.periods[T+1].start>y&&this._manifest.periods[T+1].start>this._playbackObserver.getCurrentTime()){let E=this._manifest.periods[T+1];this._playbackObserver.setCurrentTime(E.start),this.trigger("warning",kd(y,E.start));return}break}}this.trigger("stalled",p)},{includeLastObservation:!0,clearSignal:this._canceller.signal})}updateDiscontinuityInfo(e){this._isStarted||this.start();let t=this._playbackObserver.getReference().getValue();Dh(this._discontinuitiesStore,e,t)}onLockedStream(e,t){var s;this._isStarted||this.start();let r=this._playbackObserver.getReference().getValue();if(!r.rebuffering||r.paused||this._speed.getValue()<=0||e!=="audio"&&e!=="video")return;let i=r.position.getWanted(),o=(s=r.rebuffering.position)!=null?s:i,a=t.start;i<a&&Math.abs(o-a)<1&&(m.warn(`Init: rebuffering because of a future locked stream.
|
|
4
|
-
Trying to unlock by seeking to the next Period`),this._playbackObserver.setCurrentTime(a+.001))}destroy(){this._canceller.cancel()}};function Oh(n,e,t){if(n.length===0)return null;let r=null;for(let i of n){let{period:o}=i;if(o.start>t)return r;let a;if(o.end===void 0||o.end>t){let{discontinuity:s,position:d}=i,{start:u,end:l}=s,c=u!=null?u:d;if(t>=c-vi)if(l===null){let f=jo(e,o);f!==null?a=f.start+vi:m.warn("Init: discontinuity at Period's end but no next Period")}else t<l+vi&&(a=l+vi);a!==void 0&&(m.info("Init: discontinuity found",t,a),r=r!==null&&r>a?r:a)}}return r}function Rd(n){return n.discontinuity!==null}function Dh(n,e,t){let r=Math.min(t.position.getPolled(),t.position.getWanted());for(;n.length>0&&n[0].period.end!==void 0&&n[0].period.end+10<r;)n.shift();let{period:i,bufferType:o}=e;if(!(o!=="audio"&&o!=="video")){for(let a=0;a<n.length;a++)if(n[a].period.id===i.id){if(n[a].bufferType===o){Rd(e)?n[a]=e:n.splice(a,1);return}}else if(n[a].period.start>i.start){Rd(e)&&n.splice(a,0,e);return}Rd(e)&&n.push(e)}}function kd(n,e){return new te("DISCONTINUITY_ENCOUNTERED","A discontinuity has been encountered at position "+String(n)+", seeking at position "+String(e))}var Cd=class{constructor(e,t){this._speedUpdateCanceller=new B,this._isRebuffering=!1,this._playbackObserver=e,this._isDisposed=!1,this._speed=t,this._updateSpeed()}startRebuffering(){this._isRebuffering||this._isDisposed||(this._isRebuffering=!0,this._speedUpdateCanceller.cancel(),m.info("Init: Pause playback to build buffer"),this._playbackObserver.setPlaybackRate(0))}stopRebuffering(){!this._isRebuffering||this._isDisposed||(this._isRebuffering=!1,this._speedUpdateCanceller=new B,this._updateSpeed())}dispose(){this._speedUpdateCanceller.cancel(),this._isDisposed=!0}_updateSpeed(){this._speed.onUpdate(e=>{m.info("Init: Resume playback speed",e),this._playbackObserver.setPlaybackRate(e)},{clearSignal:this._speedUpdateCanceller.signal,emitCurrentValue:!0})}};function Lh(n,e){return n.id===e.id&&n.start===e.start&&n.end===e.end}var kf=Lh;function Nh(n,e){let t=[],{periods:r}=e;for(let i of r){let{streamEvents:o}=i;o.forEach(({start:a,end:s,id:d,data:u})=>{for(let f of n)if(kf(f,{id:d,start:a,end:s})){t.push(f);return}let l;if(u.value.element!==void 0)l=u.value.element;else if(u.value.xmlData!==void 0){let f=u.value.xmlData.namespaces.reduce((p,I)=>p+"xmlns:"+I.key+'="'+I.value+'" ',"<toremove ");f+=">";let g=new DOMParser().parseFromString(f+u.value.xmlData.data+"</toremove>","application/xml").documentElement;l=g.children.length>0?g.children[0]:g.childNodes[0]}else return;let c={type:u.type,value:ue(oe({},u.value),{element:l})};if(s===void 0){let f={start:a,id:d,data:c,publicEvent:{start:a,data:c}};t.push(f)}else{let f={start:a,end:s,id:d,data:c,publicEvent:{start:a,end:s,data:c}};t.push(f)}})}return t}var Pd=Nh;var Ri=class extends re{constructor(e,t,r){super(),this._manifest=e,this._mediaElement=t,this._playbackObserver=r,this._canceller=null,this._scheduledEventsRef=new H([]),this._eventsBeingPlayed=new WeakMap}start(){if(this._canceller!==null)return;this._canceller=new B;let e=this._canceller.signal,t=this._playbackObserver,r=this._mediaElement,i=!1,o=new B;o.linkToSignal(e),this._scheduledEventsRef.setValue(Pd([],this._manifest)),this._scheduledEventsRef.onUpdate(({length:a})=>{if(a===0){i&&(o.cancel(),o=new B,o.linkToSignal(e),i=!1);return}else if(i)return;i=!0;let s=c(),d=()=>{let f=c();this._emitStreamEvents(this._scheduledEventsRef.getValue(),s,f,o.signal),s=f},{STREAM_EVENT_EMITTER_POLL_INTERVAL:u}=U.getCurrent(),l=setInterval(d,u);t.listen(d,{includeLastObservation:!1,clearSignal:o.signal}),o.signal.register(()=>{clearInterval(l)});function c(){let f=t.getReference().getValue(),g=r.currentTime,p=f.seeking!==0;return{currentTime:g,isSeeking:p}}},{emitCurrentValue:!0,clearSignal:e})}onManifestUpdate(e){let t=this._scheduledEventsRef.getValue();this._scheduledEventsRef.setValue(Pd(t,e))}stop(){this._canceller!==null&&(this._canceller.cancel(),this._canceller=null)}_emitStreamEvents(e,t,r,i){let{currentTime:o}=t,{isSeeking:a,currentTime:s}=r,d=[],u=[];for(let l=0;l<e.length;l++){let c=e[l],f=c.start,g=Md(c)?c.end:void 0;this._eventsBeingPlayed.has(c)?(f>s||g!==void 0&&s>=g)&&(Md(c)&&u.push(c.publicEvent),this._eventsBeingPlayed.delete(c)):f<=s&&g!==void 0&&s<g?(d.push({type:"stream-event",value:c.publicEvent}),this._eventsBeingPlayed.set(c,!0)):o<f&&s>=(g!=null?g:f)&&(a?d.push({type:"stream-event-skip",value:c.publicEvent}):(d.push({type:"stream-event",value:c.publicEvent}),Md(c)&&u.push(c.publicEvent)))}if(d.length>0){for(let l of d)if(l.type==="stream-event"?this.trigger("event",l.value):this.trigger("eventSkip",l.value),i.isCancelled())return}if(u.length>0){for(let l of u)if(typeof l.onExit=="function"&&l.onExit(),i.isCancelled())return}}};function Md(n){return n.end!==void 0}var Cf=Ri;function ki(n,e,t){if(t.isCancelled())return;n.addEventListener("error",r),t.register(()=>{n.removeEventListener("error",r)});function r(){let i=n.error,o,a;switch(_(i)||(o=i.code,a=i.message),o){case 1:return a=a!=null?a:"The fetching of the associated resource was aborted by the user's request.",e(new te("MEDIA_ERR_ABORTED",a));case 2:return a=a!=null?a:"A network error occurred which prevented the media from being successfully fetched",e(new te("MEDIA_ERR_NETWORK",a));case 3:return a=a!=null?a:"An error occurred while trying to decode the media resource",e(new te("MEDIA_ERR_DECODE",a));case 4:return a=a!=null?a:"The media resource has been found to be unsuitable.",e(new te("MEDIA_ERR_SRC_NOT_SUPPORTED",a));default:return a=a!=null?a:"The HTMLMediaElement errored due to an unknown reason.",e(new te("MEDIA_ERR_UNKNOWN",a))}}}var _n=class extends qn{constructor(e){super(),this._initSettings=e,this._initCanceller=new B,this._manifest=null,this._decryptionCapabilities={status:"uninitialized",value:null};let t=e.url===void 0?void 0:[e.url];this._cmcdDataBuilder=e.cmcd===void 0?null:new dc(e.cmcd),this._manifestFetcher=new Xs(t,e.transport,ue(oe({},e.manifestRequestSettings),{lowLatencyMode:e.lowLatencyMode,cmcdDataBuilder:this._cmcdDataBuilder}))}prepare(){this._manifest===null&&(this._manifest=Tf.createAsync(at(this._initCanceller.signal,(e,t)=>{this._manifestFetcher.addEventListener("warning",r=>this.trigger("warning",r)),this._manifestFetcher.addEventListener("error",r=>{this.trigger("error",r),t(r)}),this._manifestFetcher.addEventListener("manifestReady",r=>{e(r)})})),this._manifestFetcher.start(),this._initCanceller.signal.register(()=>{this._manifestFetcher.dispose()}))}start(e,t){this.prepare(),ki(e,r=>this._onFatalError(r),this._initCanceller.signal),this._setupInitialMediaSourceAndDecryption(e).then(r=>this._onInitialMediaSourceReady(e,r.mediaSource,t,r.drmSystemId,r.unlinkMediaSource)).catch(r=>{this._onFatalError(r)})}updateContentUrls(e,t){this._manifestFetcher.updateContentUrls(e,t)}dispose(){this._initCanceller.cancel()}_onFatalError(e){this._initCanceller.isUsed()||(this._initCanceller.cancel(),this.trigger("error",e))}_setupInitialMediaSourceAndDecryption(e){let t=this._initCanceller;return at(t.signal,r=>{let{keySystems:i}=this._initSettings,{statusRef:o,contentDecryptor:a}=_i(e,i,{onWarning:s=>this.trigger("warning",s),onError:s=>this._onFatalError(s),onBlackListProtectionData:s=>{(async()=>{var u;if(this._manifest===null)return;let d=(u=this._manifest.syncValue)!=null?u:await this._manifest.getValueAsAsync();Fh(d,s)})().catch(X)},onKeyIdsCompatibilityUpdate:s=>{(async()=>{var u;if(this._manifest===null)return;let d=(u=this._manifest.syncValue)!=null?u:await this._manifest.getValueAsAsync();Bh(d,s.whitelistedKeyIds,s.blacklistedKeyIds,s.delistedKeyIds)})().catch(X)},onCodecSupportUpdate:()=>{var d,u;let s=(d=this._manifest)==null?void 0:d.syncValue;_(s)?(u=this._manifest)==null||u.getValueAsAsync().then(l=>{this._initCanceller.isUsed()||this._refreshManifestCodecSupport(l)},X):this._refreshManifestCodecSupport(s)}},t.signal);a.enabled?this._decryptionCapabilities={status:"enabled",value:a.value}:this._decryptionCapabilities={status:"disabled",value:a.value},o.onUpdate((s,d)=>{if(s.initializationState.type==="uninitialized")return;d();let u=new B;u.linkToSignal(t.signal),ia(e,u.signal).then(l=>{let c=o.getValue();if(c.initializationState.type==="awaiting-media-link")c.initializationState.value.isMediaLinked.setValue(!0),o.onUpdate((f,g)=>{if(f.initializationState.type==="initialized"){g(),r({mediaSource:l,drmSystemId:f.drmSystemId,unlinkMediaSource:u});return}},{emitCurrentValue:!0,clearSignal:t.signal});else if(s.initializationState.type==="initialized"){r({mediaSource:l,drmSystemId:s.drmSystemId,unlinkMediaSource:u});return}}).catch(l=>{u.isUsed()||this._onFatalError(l)})},{emitCurrentValue:!0,clearSignal:t.signal})})}async _onInitialMediaSourceReady(e,t,r,i,o){var R;let{adaptiveOptions:a,autoPlay:s,bufferOptions:d,lowLatencyMode:u,segmentRequestOptions:l,speed:c,startAt:f,textTrackOptions:g,transport:p}=this._initSettings,I=this._initCanceller;ee(this._manifest!==null);let y;try{y=(R=this._manifest.syncValue)!=null?R:await this._manifest.getValueAsAsync()}catch(k){return}y.addEventListener("manifestUpdate",k=>{this.trigger("manifestUpdate",k),this._refreshManifestCodecSupport(y)},I.signal),y.addEventListener("decipherabilityUpdate",k=>{this.trigger("decipherabilityUpdate",k)},I.signal),y.addEventListener("supportUpdate",()=>{this.trigger("codecSupportUpdate",null)},I.signal),m.debug("Init: Calculating initial time");let b=_d(y,u,f);m.debug("Init: Initial time calculated:",b);let T=ac(a),v=G({textTrackOptions:g,drmSystemId:i},d),E=new td(p,this._cmcdDataBuilder,l,I.signal);this._refreshManifestCodecSupport(y),this.trigger("manifestReady",y),!I.isUsed()&&this._setupContentWithNewMediaSource({mediaElement:e,playbackObserver:r,mediaSource:t,initialTime:b,autoPlay:s,manifest:y,representationEstimator:T,segmentQueueCreator:E,speed:c,bufferOptions:v},o)}_setupContentWithNewMediaSource(e,t){this._startLoadingContentOnMediaSource(e,this._createReloadMediaSourceCallback(e,t),t.signal)}_createReloadMediaSourceCallback(e,t){let r=this._initCanceller;return i=>{if(t.cancel(),r.isUsed()||(this.trigger("reloadingMediaSource",i),r.isUsed()))return;let o=new B;o.linkToSignal(r.signal),ia(e.mediaElement,o.signal).then(a=>{this._setupContentWithNewMediaSource(ue(oe({},e),{mediaSource:a,initialTime:i.position,autoPlay:i.autoPlay}),o)}).catch(a=>{o.isUsed()||this._onFatalError(a)})}}_startLoadingContentOnMediaSource(e,t,r){var O,K;let{autoPlay:i,bufferOptions:o,initialTime:a,manifest:s,mediaElement:d,mediaSource:u,playbackObserver:l,representationEstimator:c,segmentQueueCreator:f,speed:g}=e,p=(O=s.getPeriodForTime(a))!=null?O:s.getNextPeriod(a);if(p===void 0){let A=new te("MEDIA_STARTING_TIME_NOT_FOUND","Wanted starting time not found in the Manifest.");return this._onFatalError(A)}let I=null,y=Uh(d,this._initSettings.textTrackOptions);if(y!==null){let A=new Ei(y);I=A,r.register(()=>{A.stop(),y==null||y.stop()})}let b=new Zt(u,d.nodeName==="VIDEO",I);r.register(()=>{b.disposeAll()});let{autoPlayResult:T,initialPlayPerformed:v}=Ti({mediaElement:d,playbackObserver:l,startTime:a,mustAutoPlay:i,onWarning:A=>{this.trigger("warning",A)},isDirectfile:!1},r);if(r.isCancelled())return;v.onUpdate((A,C)=>{if(A){C();let D=new Cf(s,d,l);s.addEventListener("manifestUpdate",()=>{D.onManifestUpdate(s)},r),D.addEventListener("event",L=>{this.trigger("streamEvent",L)},r),D.addEventListener("eventSkip",L=>{this.trigger("streamEventSkip",L)},r),D.start(),r.register(()=>{D.stop()})}},{clearSignal:r,emitCurrentValue:!0});let E=yd(l,{autoPlay:i,manifest:s,mediaSource:u,textDisplayer:y,initialPlayPerformed:v,speed:g},r);(K=this._cmcdDataBuilder)==null||K.startMonitoringPlayback(E),r.register(()=>{var A;(A=this._cmcdDataBuilder)==null||A.stopMonitoringPlayback()});let R=this._createRebufferingController(l,s,g,r),k=new ai(b);Vl&&s.addEventListener("decipherabilityUpdate",A=>{A.some(C=>C.representation.decipherable!==!0)&&N(0,void 0,void 0)},r),l.listen(A=>{if(k.needToReload(A)){let C,D=l.getReference().getValue();D.position.isAwaitingFuturePosition()?C=D.position.getWanted():C=l.getCurrentTime();let L=v.getValue()?!l.getIsPaused():i;t({position:C,autoPlay:L})}},{clearSignal:r}),E.listen(A=>{["video","audio","text"].forEach(C=>{var L;let D=b.getStatus(C);D.type==="initialized"&&D.value.synchronizeInventory((L=A.buffered[C])!=null?L:[])})},{clearSignal:r});let x=rd(s,u,E,b,{onWarning:A=>this.trigger("warning",A),onPeriodChanged:A=>this.trigger("activePeriodChanged",{period:A})},r);T.then(()=>{Si(l,d,!1,r).onUpdate((A,C)=>{A&&(C(),this.trigger("loaded",{getSegmentSinkMetrics:async()=>new Promise(D=>D(b.getSegmentSinksMetrics()))}))},{emitCurrentValue:!0,clearSignal:r})}).catch(A=>{r.isCancelled()||this._onFatalError(A)});let M=this;Sf({manifest:s,initialPeriod:p},E,c,b,f,o,P(),r);function P(){return{needsBufferFlush:A=>{var $;let C,D=l.getCurrentTime(),L=($=A==null?void 0:A.relativeResumingPosition)!=null?$:0,V=!!(A!=null&&A.relativePosHasBeenDefaulted);L===0&&V?C=D+.001:C=D+L,l.setCurrentTime(C),l.listen((j,z)=>{(j.currentRange!==null||j.position.getPolled()>C+.1)&&(z(),l.setCurrentTime(j.position.getWanted()+.001))},{includeLastObservation:!1,clearSignal:r})},streamStatusUpdate(A){let{period:C,bufferType:D,imminentDiscontinuity:L,position:V}=A;R.updateDiscontinuityInfo({period:C,bufferType:D,discontinuity:L,position:V}),!r.isCancelled()&&s.isLastPeriodKnown&&A.period.id===s.periods[s.periods.length-1].id&&(A.hasFinishedLoading||A.isEmptyStream?x.onLastSegmentFinishedLoading(A.bufferType):x.onLastSegmentLoadingResume(A.bufferType))},needsManifestRefresh:()=>M._manifestFetcher.scheduleManualRefresh({enablePartialRefresh:!0,canUseUnsafeMode:!0}),manifestMightBeOufOfSync:()=>{let{OUT_OF_SYNC_MANIFEST_REFRESH_DELAY:A}=U.getCurrent();M._manifestFetcher.scheduleManualRefresh({enablePartialRefresh:!1,canUseUnsafeMode:!1,delay:A})},lockedStream:A=>R.onLockedStream(A.bufferType,A.period),adaptationChange:A=>{M.trigger("adaptationChange",A),!r.isCancelled()&&x.onAdaptationChange(A.type,A.period,A.adaptation)},representationChange:A=>{M.trigger("representationChange",A),!r.isCancelled()&&x.onRepresentationChange(A.type,A.period)},inbandEvent:A=>M.trigger("inbandEvents",A),warning:A=>M.trigger("warning",A),periodStreamReady:A=>M.trigger("periodStreamReady",A),periodStreamCleared:A=>{x.onPeriodCleared(A.type,A.period),!r.isCancelled()&&M.trigger("periodStreamCleared",A)},bitrateEstimateChange:A=>{var C;(C=M._cmcdDataBuilder)==null||C.updateThroughput(A.type,A.bitrate),M.trigger("bitrateEstimateChange",A)},needsMediaSourceReload:A=>{N(A.timeOffset,A.minimumPosition,A.maximumPosition)},needsDecipherabilityFlush(){var C,D,L,V;let A=Vn(d);if(Wa(A==null?void 0:A[0])){let $=E.getReference().getValue(),j=$.position.isAwaitingFuturePosition()?$.position.getWanted():(C=E.getCurrentTime())!=null?C:$.position.getPolled(),z=(L=(D=$.paused.pending)!=null?D:E.getIsPaused())!=null?L:$.paused.last;t({position:j,autoPlay:!z})}else{let $=E.getReference().getValue(),j=$.position.isAwaitingFuturePosition()?$.position.getWanted():(V=E.getCurrentTime())!=null?V:$.position.getPolled();j+.001<$.duration?l.setCurrentTime(d.currentTime+.001):l.setCurrentTime(j)}},encryptionDataEncountered:A=>{if(M._decryptionCapabilities.status==="disabled"){M._onFatalError(M._decryptionCapabilities.value);return}else if(M._decryptionCapabilities.status==="uninitialized"){m.error("Init: received encryption data without known decryption capabilities");return}for(let C of A)if(M._decryptionCapabilities.value.onInitializationData(C),r.isCancelled())return},error:A=>M._onFatalError(A)}}function N(A,C,D){var z,q,W;let L=E.getReference().getValue(),V=L.position.isAwaitingFuturePosition()?L.position.getWanted():(z=E.getCurrentTime())!=null?z:L.position.getPolled(),$=(W=(q=L.paused.pending)!=null?q:E.getIsPaused())!=null?W:L.paused.last,j=V+A;C!==void 0&&(j=Math.max(C,j)),D!==void 0&&(j=Math.min(D,j)),t({position:j,autoPlay:!$})}}_createRebufferingController(e,t,r,i){let o=new Tn(e,t,r);return o.addEventListener("stalled",a=>this.trigger("stalled",a)),o.addEventListener("unstalled",()=>this.trigger("unstalled",null)),o.addEventListener("warning",a=>this.trigger("warning",a)),i.register(()=>o.destroy()),o.start(),o}getCodecsSupportInfo(e){return e.map(r=>{var s;let i=`${r.mimeType};codecs="${r.codec}"`,o=Ua(i);if(!o)return{mimeType:r.mimeType,codec:r.codec,supported:!1,supportedIfEncrypted:!1};let a;if(this._decryptionCapabilities.status==="uninitialized")a=void 0;else if(this._decryptionCapabilities.status==="disabled")a=!0;else{let d=this._decryptionCapabilities.value;d.getState()!==0&&(a=(s=d.isCodecSupported(r.mimeType,r.codec))!=null?s:!0)}return{mimeType:r.mimeType,codec:r.codec,supported:o,supportedIfEncrypted:a}})}_refreshManifestCodecSupport(e){let t=e.getCodecsWithUnknownSupport(),r=this.getCodecsSupportInfo(t);if(r.length>0)try{e.updateCodecSupport(r)}catch(i){this._onFatalError(i)}}};function Uh(n,e){return e.textTrackMode==="html"&&me.htmlTextDisplayer!==null?new me.htmlTextDisplayer(n,e.textTrackElement):me.nativeTextDisplayer!==null?new me.nativeTextDisplayer(n):null}function Bh(n,e,t,r){n.updateRepresentationsDeciperability(i=>{let{representation:o}=i;if(o.contentProtections===void 0)return o.decipherable;let a=o.contentProtections.keyIds;if(a!==void 0)for(let s of a){for(let d of t)if(ge(d,s))return!1;for(let d of e)if(ge(d,s))return!0;for(let d of r)if(ge(d,s))return}return o.decipherable})}function Fh(n,e){n.updateRepresentationsDeciperability(t=>{var o,a;let r=t.representation;if(r.decipherable===!1)return!1;let i=(a=(o=r.contentProtections)==null?void 0:o.initData)!=null?a:[];for(let s of i)if((e.type===void 0||s.type===e.type)&&e.values.getFormattedValues().every(u=>s.values.some(l=>(u.systemId===void 0||l.systemId===u.systemId)&&ge(l.data,u.data))))return!1;return r.decipherable})}function Ad(n,e,t){let{repeatCount:r}=n;if(r>=0)return r;let i;return _(e)?t!==void 0?i=t:i=Number.MAX_VALUE:i=e.start,Math.ceil((i-n.start)/n.duration)-1}function ke(n,e,t){let{start:r,duration:i}=n;if(i<=0)return r;let o=Ad(n,e,t);return r+(o+1)*i}function We(n,e){var t;return n*e.timescale+((t=e.indexTimeOffset)!=null?t:0)}function Tt(n,e){var t;return(n-((t=e.indexTimeOffset)!=null?t:0))/e.timescale}function Pf(n,e,t){return[n*t,(n+e)*t]}function Kh(n,e){let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i].start<=e?t=i+1:r=i}return t-1}function oa(n,e,t){let{timeline:r}=n,i=We(e,n);if(i<0)return null;let o=Kh(r,i);if(o<0||o>=r.length-1)return null;let a=r[o];if(a.duration<=0)return null;let s=r[o+1];if(s===void 0)return null;let d=s.start,u=ke(a,s,t);return i>=u&&i<d?Tt(d,n):null}function xt(n,e){var i;let{initialization:t}=n,r={};return e!==void 0&&(r.isEMSGWhitelisted=e),{id:"init",isInit:!0,time:0,end:0,duration:0,timescale:1,range:_(t)?void 0:t.range,indexRange:n.indexRange,url:(i=t==null?void 0:t.url)!=null?i:null,complete:!0,privateInfos:r,timestampOffset:-(n.indexTimeOffset/n.timescale)}}function Vh(n,e){let t=n.toString();return t.length>=e?t:(new Array(e+1).join("0")+t).slice(-e)}function xd(n){return(e,t,r)=>{let i=w(r)?parseInt(r,10):1;return Vh(String(n),i)}}function dt(n,e,t){return zh(n,e,t)}function zh(n,e,t){return n.indexOf("$")===-1?n:n.replace(/\$\$/g,"$").replace(/\$RepresentationID\$/g,String(e)).replace(/\$Bandwidth(\%0(\d+)d)?\$/g,xd(t===void 0?0:t))}function aa(n,e){return function(r){return r.indexOf("$")===-1?r:r.replace(/\$\$/g,"$").replace(/\$Number(\%0(\d+)d)?\$/g,(i,o,a)=>{if(e===void 0)throw new Error("Segment number not defined in a $Number$ scheme");return xd(e)(i,o,a)}).replace(/\$Time(\%0(\d+)d)?\$/g,(i,o,a)=>{if(n===void 0)throw new Error("Segment time not defined in a $Time$ scheme");return xd(n)(i,o,a)})}}function Hh(n,e,t){let r=t-n;return r>0?Math.floor(r/e):0}function Ci(n,e,t,r,i,o){var T;let a=r.getEstimatedMaximumPosition((T=n.availabilityTimeOffset)!=null?T:0),s=Math.min(e+t,a!=null?a:1/0),d=We(e,n),u=We(s,n),{timeline:l,timescale:c,segmentUrlTemplate:f,startNumber:g,endNumber:p}=n,I=g!=null?g:1,y=[],b=l.length;for(let v=0;v<b;v++){let E=l[v],{duration:R,start:k,range:x}=E,M;a===void 0?M=i:M=Math.min(a*c,i!=null?i:1/0);let P=Ad(E,l[v+1],M),N=n.availabilityTimeComplete!==!1||v!==b-1&&P!==0,O=Hh(k,R,d),K=k+O*R;for(;K<u&&O<=P;){let A=I+O;if(p!==void 0&&A>p)break;let C=f===null?null:aa(K,A)(f),D=K-n.indexTimeOffset,L=R;D<0&&(L=R+D,D=0);let V={id:String(K),time:D/c,end:(D+L)/c,duration:L/c,isInit:!1,range:x,timescale:1,url:C,number:A,timestampOffset:-(n.indexTimeOffset/c),complete:N,privateInfos:{isEMSGWhitelisted:o}};y.push(V),O++,K=k+O*R}if(K>=u||(I+=P+1,p!==void 0&&I>p))return y}return y}function Wh(n,e){if(e.timescale!==n.timescale){let{timescale:t}=n;n.timeline.push({start:e.time/e.timescale*t,duration:e.duration/e.timescale*t,repeatCount:e.count===void 0?0:e.count,range:e.range})}else n.timeline.push({start:e.time,duration:e.duration,repeatCount:e.count===void 0?0:e.count,range:e.range});return!0}var En=class{constructor(e,t){var p,I,y,b;let{periodStart:r,periodEnd:i,representationId:o,representationBitrate:a,isEMSGWhitelisted:s}=t,d=(p=e.timescale)!=null?p:1,l=((I=e.presentationTimeOffset)!=null?I:0)-r*d,c=((y=e.initialization)==null?void 0:y.media)===void 0?null:dt(e.initialization.media,o,a),f=e.media===void 0?null:dt(e.media,o,a),g;e.initialization!==void 0?g=e.initialization.range:e.indexRange!==void 0&&(g=[0,e.indexRange[0]-1]),this._index={indexRange:e.indexRange,indexTimeOffset:l,initialization:{url:c,range:g},segmentUrlTemplate:f,startNumber:e.startNumber,endNumber:e.endNumber,timeline:(b=e.timeline)!=null?b:[],timescale:d},this._manifestBoundsCalculator=t.manifestBoundsCalculator,this._scaledPeriodStart=We(r,this._index),this._scaledPeriodEnd=_(i)?void 0:We(i,this._index),this._isInitialized=this._index.timeline.length>0,this._isEMSGWhitelisted=s}getInitSegment(){return xt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){return Ci(this._index,e,t,this._manifestBoundsCalculator,this._scaledPeriodEnd,this._isEMSGWhitelisted)}shouldRefresh(){return!1}getFirstAvailablePosition(){let e=this._index;return e.timeline.length===0?null:Tt(Math.max(this._scaledPeriodStart,e.timeline[0].start),e)}getLastAvailablePosition(){var i;let{timeline:e}=this._index;if(e.length===0)return null;let t=e[e.length-1],r=Math.min(ke(t,null,this._scaledPeriodEnd),(i=this._scaledPeriodEnd)!=null?i:1/0);return Tt(r,this._index)}getEnd(){return this.getLastAvailablePosition()}awaitSegmentBetween(){return!1}isSegmentStillAvailable(){return!0}checkDiscontinuity(){return null}canBeOutOfSyncError(){return!1}isStillAwaitingFutureSegments(){return!1}isInitialized(){return this._isInitialized}initialize(e){if(!this._isInitialized){for(let t=0;t<e.length;t++)Wh(this._index,e[t]);this._isInitialized=!0}}addPredictedSegments(){m.warn("Cannot add predicted segments to a `BaseRepresentationIndex`")}_replace(e){this._index=e._index,this._isInitialized=e._isInitialized,this._scaledPeriodEnd=e._scaledPeriodEnd,this._isEMSGWhitelisted=e._isEMSGWhitelisted}_update(){m.error("Base RepresentationIndex: Cannot update a SegmentList")}};var vn=class{constructor(e,t){var g,p,I;if(e.duration===void 0)throw new Error("Invalid SegmentList: no duration");let{periodStart:r,periodEnd:i,representationId:o,representationBitrate:a,isEMSGWhitelisted:s}=t;this._isEMSGWhitelisted=s,this._periodStart=r,this._periodEnd=i;let d=(g=e.presentationTimeOffset)!=null?g:0,u=(p=e.timescale)!=null?p:1,l=d-r*u,c=((I=e.initialization)==null?void 0:I.media)===void 0?null:dt(e.initialization.media,o,a),f=e.list.map(y=>({url:y.media===void 0?null:dt(y.media,o,a),mediaRange:y.mediaRange}));this._index={list:f,timescale:u,duration:e.duration,indexTimeOffset:l,indexRange:e.indexRange,initialization:_(e.initialization)?void 0:{url:c,range:e.initialization.range}}}getInitSegment(){let e=xt(this._index);return e.privateInfos===void 0&&(e.privateInfos={}),e.privateInfos.isEMSGWhitelisted=this._isEMSGWhitelisted,e}getSegments(e,t){let r=this._index,{duration:i,list:o,timescale:a}=r,s=i/a,d=e-this._periodStart,[u,l]=Pf(d,t,a),c=Math.min(o.length-1,Math.floor(l/i)),f=[],g=Math.floor(u/i);for(;g<=c;){let p=o[g].mediaRange,I=o[g].url,y=g*s+this._periodStart,b={id:String(g),time:y,isInit:!1,range:p,duration:s,timescale:1,end:y+s,url:I,timestampOffset:-(r.indexTimeOffset/a),complete:!0,privateInfos:{isEMSGWhitelisted:this._isEMSGWhitelisted}};f.push(b),g++}return f}shouldRefresh(e,t){return!1}getFirstAvailablePosition(){return this._periodStart}getLastAvailablePosition(){var i;let e=this._index,{duration:t,list:r}=e;return Math.min(r.length*t/e.timescale+this._periodStart,(i=this._periodEnd)!=null?i:1/0)}getEnd(){return this.getLastAvailablePosition()}awaitSegmentBetween(){return!1}isSegmentStillAvailable(){return!0}checkDiscontinuity(){return null}canBeOutOfSyncError(){return!1}isStillAwaitingFutureSegments(){return!1}isInitialized(){return!0}initialize(){m.error("A `ListRepresentationIndex` does not need to be initialized")}addPredictedSegments(){m.warn("Cannot add predicted segments to a `ListRepresentationIndex`")}_replace(e){this._index=e._index}_update(){m.error("A `ListRepresentationIndex` cannot be updated")}};function Qn(n){return U.getCurrent().DEFAULT_MAXIMUM_TIME_ROUNDING_ERROR*n}var Rn=class{constructor(e,t){var b,T,v;let{availabilityTimeOffset:r,manifestBoundsCalculator:i,isDynamic:o,periodEnd:a,periodStart:s,representationId:d,representationBitrate:u,isEMSGWhitelisted:l}=t,c=(b=e.timescale)!=null?b:1;this._availabilityTimeOffset=r,this._manifestBoundsCalculator=i;let f=(T=e.presentationTimeOffset)!=null?T:0,g=s*c,p=f-g;if(e.duration===void 0)throw new Error("Invalid SegmentTemplate: no duration");let I=((v=e.initialization)==null?void 0:v.media)===void 0?null:dt(e.initialization.media,d,u),y=e.media===void 0?null:dt(e.media,d,u);this._index={duration:e.duration,timescale:c,indexRange:e.indexRange,indexTimeOffset:p,initialization:_(e.initialization)?void 0:{url:I,range:e.initialization.range},url:y,presentationTimeOffset:f,startNumber:e.startNumber,endNumber:e.endNumber},this._isDynamic=o,this._periodStart=s,this._scaledRelativePeriodEnd=a===void 0?void 0:(a-s)*c,this._isEMSGWhitelisted=l}getInitSegment(){return xt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){let r=this._index,{duration:i,startNumber:o,endNumber:a,timescale:s,url:d}=r,u=this._periodStart*s,l=this._scaledRelativePeriodEnd,c=e*s-u,f=(e+t)*s-u,g=this._getFirstSegmentStart(),p=this._getLastSegmentStart();if(_(g)||_(p))return[];let I=Math.max(g,c),y=Math.min(p,f);if(y+i<=I)return[];let b=[],T=o!=null?o:1,v=Math.floor(I/i);for(let E=v*i;E<=y;E+=i){let R=v+T;if(a!==void 0&&R>a)return b;let k=!_(l)&&E+i>l?l-E:i,x=E+u,M=E+this._index.presentationTimeOffset,P=d===null?null:aa(M,R)(d),N={id:String(R),number:R,time:x/s,end:(x+k)/s,duration:k/s,timescale:1,isInit:!1,scaledDuration:k/s,url:P,timestampOffset:-(r.indexTimeOffset/s),complete:!0,privateInfos:{isEMSGWhitelisted:this._isEMSGWhitelisted}};b.push(N),v++}return b}getFirstAvailablePosition(){let e=this._getFirstSegmentStart();return _(e)?e:e/this._index.timescale+this._periodStart}getLastAvailablePosition(){let e=this._getLastSegmentStart();if(_(e))return e;let t=this._estimateRelativeScaledEnd();return Math.min(e+this._index.duration,t!=null?t:1/0)/this._index.timescale+this._periodStart}getEnd(){if(!this._isDynamic)return this.getLastAvailablePosition();let e=this._estimateRelativeScaledEnd();if(e===void 0)return;let{timescale:t}=this._index;return(e+this._periodStart*t)/t}awaitSegmentBetween(e,t){if(ee(e<=t),!this._isDynamic)return!1;let{timescale:r}=this._index,i=Qn(r),o=this._periodStart*r,a=e*r-o,s=t*r-o,d=this._getLastSegmentStart();if(_(d)){let c=this._estimateRelativeScaledEnd();return c===void 0?s+i>=0:s+i>=0&&a<c-i}let u=d+this._index.duration,l=this._estimateRelativeScaledEnd();return l===void 0?s>u-i:s>u-i&&a<l-i}shouldRefresh(){return!1}checkDiscontinuity(){return null}isSegmentStillAvailable(e){if(e.isInit)return!0;let t=this.getSegments(e.time,.1);return t.length===0?!1:t[0].time===e.time&&t[0].end===e.end&&t[0].number===e.number}canBeOutOfSyncError(){return!1}isStillAwaitingFutureSegments(){if(!this._isDynamic)return!1;let e=this._estimateRelativeScaledEnd();if(e===void 0)return!0;let{timescale:t}=this._index,r=this._getLastSegmentStart();if(_(r))return!0;let i=r+this._index.duration,o=Qn(t);return i+o<e}isInitialized(){return!0}initialize(){m.error("A `TemplateRepresentationIndex` does not need to be initialized")}addPredictedSegments(){m.warn("Cannot add predicted segments to a `TemplateRepresentationIndex`")}_replace(e){this._index=e._index,this._isDynamic=e._isDynamic,this._periodStart=e._periodStart,this._scaledRelativePeriodEnd=e._scaledRelativePeriodEnd,this._manifestBoundsCalculator=e._manifestBoundsCalculator}_update(e){this._replace(e)}_getFirstSegmentStart(){var a;if(!this._isDynamic)return 0;if(this._scaledRelativePeriodEnd===0||this._scaledRelativePeriodEnd===void 0){let s=this._manifestBoundsCalculator.getEstimatedMaximumPosition((a=this._availabilityTimeOffset)!=null?a:0);if(s!==void 0&&s<this._periodStart)return null}let{duration:e,timescale:t}=this._index,r=this._manifestBoundsCalculator.getEstimatedMinimumSegmentTime(e/t);if(r===void 0)return;let i=r>this._periodStart?(r-this._periodStart)*t:0;return Math.floor(i/e)*e}_getLastSegmentStart(){var o,a;let{duration:e,timescale:t,endNumber:r,startNumber:i=1}=this._index;if(this._isDynamic){let s=this._manifestBoundsCalculator.getEstimatedLiveEdge();if(s!==void 0&&this._scaledRelativePeriodEnd!==void 0&&this._scaledRelativePeriodEnd<s-this._periodStart*this._index.timescale){let c=Math.ceil(this._scaledRelativePeriodEnd/e);return r!==void 0&&r-i+1<c&&(c=r-i+1),(c-1)*e}let d=this._manifestBoundsCalculator.getEstimatedMaximumPosition((o=this._availabilityTimeOffset)!=null?o:0);if(d===void 0)return;let u=(d-this._periodStart)*t;if(u<0)return null;let l=Math.floor(u/e);return r!==void 0&&r-i+1<l&&(l=r-i+1),l<=0?null:(l-1)*e}else{let s=(a=this._scaledRelativePeriodEnd)!=null?a:0,d=Math.ceil(s/e);r!==void 0&&r-i+1<d&&(d=r-i+1);let u=(d-1)*e,l=U.getCurrent().MINIMUM_SEGMENT_SIZE*t;return r!==void 0||s-u>l||d<2?u:(d-2)*e}}_estimateRelativeScaledEnd(){var e,t;if(this._index.endNumber!==void 0){let r=this._index.endNumber-((e=this._index.startNumber)!=null?e:1)+1;return Math.max(Math.min(r*this._index.duration,(t=this._scaledRelativePeriodEnd)!=null?t:1/0),0)}if(this._scaledRelativePeriodEnd!==void 0)return Math.max(this._scaledRelativePeriodEnd,0)}};function Pi(n,e){let t=0;for(;n.length>0;){let r=n[0];if(r.start>=e||r.repeatCount===-1)return t;if(r.repeatCount===0)n.shift(),t+=1;else{let i=n[1];if(i!==void 0&&i.start<=e)n.shift(),t+=1;else{if(r.duration<=0)return t;let o=r.start+r.duration,a=1;for(;o<e&&a<=r.repeatCount;)o+=r.duration,a++;if(a>r.repeatCount)n.shift(),t=r.repeatCount+1;else{let s=r.repeatCount-a;return r.start=o,r.repeatCount=s,t+=a,t}}}}return t}function Mi(n,e){if(n.length===0)return n.push(...e),!0;if(e.length===0)return!1;let t=n.length,r=e[0].start,i=n[t-1];if(ke(i,e[0])<r)throw new te("MANIFEST_UPDATE_ERROR","Cannot perform partial update: not enough data");for(let l=t-1;l>=0;l--){let c=n[l].start;if(c===r){let f=t-l;return n.splice(l,f,...e),!1}else if(c<r){let f=n[l];if(f.start+f.duration>r)return m.warn("RepresentationIndex: Manifest update removed all previous segments"),n.splice(0,t,...e),!0;if(f.repeatCount===void 0||f.repeatCount<=0)return f.repeatCount<0&&(f.repeatCount=Math.floor((r-f.start)/f.duration)-1),n.splice(l+1,t-(l+1),...e),!1;if(f.start+f.duration*(f.repeatCount+1)<=r)return n.splice(l+1,t-(l+1),...e),!1;let p=(r-f.start)/f.duration-1;if(p%1===0&&f.duration===e[0].duration){let I=e[0].repeatCount<0?-1:e[0].repeatCount+p+1;return n.splice(l,t-l,...e),n[l].start=f.start,n[l].repeatCount=I,!1}return m.warn("RepresentationIndex: Manifest update removed previous segments"),n[l].repeatCount=Math.floor(p),n.splice(l+1,t-(l+1),...e),!1}}let a=n[n.length-1],s=e[e.length-1];if(a.repeatCount!==void 0&&a.repeatCount<0)return a.start>s.start?(m.warn("RepresentationIndex: The new index is older than the previous one"),!1):(m.warn('RepresentationIndex: The new index is "bigger" than the previous one'),n.splice(0,t,...e),!0);let d=a.start+a.duration*(a.repeatCount+1),u=s.start+s.duration*(s.repeatCount+1);return d>=u?(m.warn("RepresentationIndex: The new index is older than the previous one"),!1):(m.warn('RepresentationIndex: The new index is "bigger" than the previous one'),n.splice(0,t,...e),!0)}function Ai(n,e,t){let r=n.start,i=n.duration,o=n.repeatCount;return r===void 0&&(e===null?r=0:_(e.duration)||(r=e.start+e.duration*(e.repeatCount+1))),(i===void 0||isNaN(i))&&t!==null&&t.start!==void 0&&!isNaN(t.start)&&r!==void 0&&!isNaN(r)&&(i=t.start-r),r!==void 0&&!isNaN(r)&&i!==void 0&&!isNaN(i)&&(o===void 0||!isNaN(o))?{start:r,duration:i,repeatCount:o===void 0?0:o}:(m.warn('DASH: A "S" Element could not have been parsed.'),null)}function xi(n){let e={};for(let t of Object.keys(n.attributes)){let r=n.attributes[t];if(!_(r))switch(t){case"t":{let i=parseInt(r,10);isNaN(i)?m.warn(`DASH: invalid t ("${r}")`):e.start=i;break}case"d":{let i=parseInt(r,10);isNaN(i)?m.warn(`DASH: invalid d ("${r}")`):e.duration=i;break}case"r":{let i=parseInt(r,10);isNaN(i)?m.warn(`DASH: invalid r ("${r}")`):e.repeatCount=i;break}}}return e}function wi(n){let e={};for(let t=0;t<n.attributes.length;t++){let r=n.attributes[t];switch(r.name){case"t":{let i=parseInt(r.value,10);isNaN(i)?m.warn(`DASH: invalid t ("${r.value}")`):e.start=i;break}case"d":{let i=parseInt(r.value,10);isNaN(i)?m.warn(`DASH: invalid d ("${r.value}")`):e.duration=i;break}case"r":{let i=parseInt(r.value,10);isNaN(i)?m.warn(`DASH: invalid r ("${r.value}")`):e.repeatCount=i;break}}}return e}function Jt(n){let e=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)e.push(xi(n[r]));else for(let r=0;r<n.length;r++)e.push(wi(n[r]));let t=[];for(let r=0;r<e.length;r++){let i=e[r],o=t[t.length-1]===void 0?null:t[t.length-1],a=e[r+1]===void 0?null:e[r+1],s=Ai(i,o,a);s!==null&&t.push(s)}return t}function wd(n,e){if(n.length===0||e.length===0)return null;let t=n[0].start,r=Array.isArray(e)?e[0].attributes.t:e[0].getAttribute("t"),i=_(r)?null:parseInt(r,10);if(i===null||Number.isNaN(i))return null;if(t===i)return{prevSegmentsIdx:0,newElementsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(t<i){let o=n[0],a=0;for(;;){if(o.repeatCount>0){let s=i-o.start;if(s%o.duration===0&&s/o.duration<=o.repeatCount)return{repeatNumberInPrevSegments:s/o.duration,prevSegmentsIdx:a,newElementsIdx:0,repeatNumberInNewElements:0}}if(a++,a>=n.length)return null;if(o=n[a],o.start===i)return{prevSegmentsIdx:a,newElementsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(o.start>i)return null}}else{let o=0,a=Array.isArray(e)?e[0]:null,s=Array.isArray(e)?null:e[0],d=i;for(;;){let u=a!==null?a.attributes.d:s==null?void 0:s.getAttribute("d"),l=_(u)?null:parseInt(u,10);if(l===null||Number.isNaN(l))return null;let c=a!==null?a.attributes.r:s==null?void 0:s.getAttribute("r"),f=_(c)?null:parseInt(c,10);if(f!==null){if(Number.isNaN(f)||f<0)return null;if(f>0){let I=t-d;if(I%l===0&&I/l<=f)return{repeatNumberInPrevSegments:0,repeatNumberInNewElements:I/l,prevSegmentsIdx:0,newElementsIdx:o}}d+=l*(f+1)}else d+=l;if(o++,o>=e.length)return null;Array.isArray(e)?a=e[o]:s=e[o];let g=a!==null?a.attributes.t:s==null?void 0:s.getAttribute("t"),p=_(g)?null:parseInt(g,10);if(p!==null){if(Number.isNaN(p))return null;d=p}if(d===t)return{newElementsIdx:o,prevSegmentsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(d>i)return null}}}function Od(n,e){var I;let t=wd(e,n);if(t===null)return m.warn('DASH: Cannot perform "based" update. Common segment not found.'),Jt(n);let{prevSegmentsIdx:r,newElementsIdx:i,repeatNumberInPrevSegments:o,repeatNumberInNewElements:a}=t,d=e.length-r+i-1;if(d>=n.length)return m.info('DASH: Cannot perform "based" update. New timeline too short'),Jt(n);let u=e.slice(r);if(o>0){let y=u[0];y.start+=y.duration*o,u[0].repeatCount-=o}if(a>0&&i!==0)return m.info('DASH: Cannot perform "based" update. The new timeline has a different form.'),Jt(n);let l=u[u.length-1],c=Array.isArray(n)?xi(n[d]):wi(n[d]),f=((I=c.repeatCount)!=null?I:0)-a;if(c.duration!==l.duration||l.repeatCount>f)return m.info('DASH: Cannot perform "based" update. The new timeline has a different form at the beginning.'),Jt(n);c.repeatCount!==void 0&&c.repeatCount>l.repeatCount&&(l.repeatCount=c.repeatCount);let g=[],p=[];if(Array.isArray(n))for(let y=d+1;y<n.length;y++)p.push(xi(n[y]));else for(let y=d+1;y<n.length;y++)p.push(wi(n[y]));for(let y=0;y<p.length;y++){let b=p[y],T=g[g.length-1]===void 0?l:g[g.length-1],v=p[y+1]===void 0?null:p[y+1],E=Ai(b,T,v);E!==null&&g.push(E)}return u.concat(g)}var Oi=class n{constructor(e,t){var E,R,k,x,M;if(!n.isTimelineIndexArgument(e))throw new Error("The given index is not compatible with a TimelineRepresentationIndex.");let{availabilityTimeComplete:r,availabilityTimeOffset:i,manifestBoundsCalculator:o,isDynamic:a,isLastPeriod:s,representationId:d,representationBitrate:u,periodStart:l,periodEnd:c,isEMSGWhitelisted:f}=t,g=(E=e.timescale)!=null?E:1,p=(R=e.presentationTimeOffset)!=null?R:0,I=l*g,y=p-I;this._manifestBoundsCalculator=o,this._isEMSGWhitelisted=f,this._isLastPeriod=s,this._lastUpdate=(k=t.receivedTime)!=null?k:F(),this._unsafelyBaseOnPreviousIndex=null,t.unsafelyBaseOnPreviousRepresentation!==null&&t.unsafelyBaseOnPreviousRepresentation.index instanceof n&&(t.unsafelyBaseOnPreviousRepresentation.index._unsafelyBaseOnPreviousIndex=null,this._unsafelyBaseOnPreviousIndex=t.unsafelyBaseOnPreviousRepresentation.index),this._isDynamic=a,this._parseTimeline=(x=e.timelineParser)!=null?x:null;let b=((M=e.initialization)==null?void 0:M.media)===void 0?null:dt(e.initialization.media,d,u),T=e.media===void 0?null:dt(e.media,d,u),v;i===void 0&&r===void 0?v=1/0:v=i!=null?i:0,this._index={availabilityTimeComplete:r!=null?r:!0,availabilityTimeOffset:v,indexRange:e.indexRange,indexTimeOffset:y,initialization:_(e.initialization)?void 0:{url:b,range:e.initialization.range},segmentUrlTemplate:T,startNumber:e.startNumber,endNumber:e.endNumber,timeline:e.timeline===void 0?null:Dd(e.timeline,e.startNumber,e.endNumber),timescale:g},this._scaledPeriodStart=We(l,this._index),this._scaledPeriodEnd=c===void 0?void 0:We(c,this._index)}getInitSegment(){return xt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){return this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),Ci(this._index,e,t,this._manifestBoundsCalculator,this._scaledPeriodEnd,this._isEMSGWhitelisted)}shouldRefresh(){return!1}getFirstAvailablePosition(){this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let e=this._index.timeline;return e.length===0?null:Tt(Math.max(this._scaledPeriodStart,e[0].start),this._index)}getLastAvailablePosition(){var r;this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let e=sa(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(e===null)return null;let t=Math.min(e.end,(r=this._scaledPeriodEnd)!=null?r:1/0);return Tt(t,this._index)}getEnd(){var r;if(this._isDynamic&&!this._isLastPeriod)return;if(this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),this._index.timeline.length<=0)return null;let e=this._index.timeline[this._index.timeline.length-1],t=Math.min(ke(e,null,this._scaledPeriodEnd),(r=this._scaledPeriodEnd)!=null?r:1/0);return Tt(t,this._index)}awaitSegmentBetween(e,t){var u,l;if(ee(e<=t),!this._isDynamic)return!1;this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let{timescale:r,timeline:i}=this._index,o=Qn(r),a=We(t,this._index),s=sa(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(s!==null&&Math.min(s.end,(u=this._scaledPeriodEnd)!=null?u:1/0)+o>=Math.min(a,(l=this._scaledPeriodEnd)!=null?l:1/0))return!1;let d=We(e,this._index);if(i.length>0&&s!==null&&!s.isLastOfTimeline){let c=i[i.length-1],g=ke(c,null,this._scaledPeriodEnd)+o;if(d<g+o)return!0}return this._isLastPeriod?this._scaledPeriodEnd===void 0?a+o>this._scaledPeriodStart?void 0:!1:d-o<this._scaledPeriodEnd&&a+o>this._scaledPeriodStart:!1}isSegmentStillAvailable(e){return e.isInit?!0:(this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),Gh(e,this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd))}checkDiscontinuity(e){this._refreshTimeline();let t=this._index.timeline;return t===null&&(t=this._getTimeline(),this._index.timeline=t),oa({timeline:t,timescale:this._index.timescale,indexTimeOffset:this._index.indexTimeOffset},e,this._scaledPeriodEnd)}canBeOutOfSyncError(e){return this._isDynamic?e instanceof it&&e.isHttpError(404):!1}_replace(e){this._parseTimeline=e._parseTimeline,this._index=e._index,this._isDynamic=e._isDynamic,this._scaledPeriodStart=e._scaledPeriodStart,this._scaledPeriodEnd=e._scaledPeriodEnd,this._lastUpdate=e._lastUpdate,this._manifestBoundsCalculator=e._manifestBoundsCalculator,this._isLastPeriod=e._isLastPeriod}_update(e){this._index.timeline===null&&(this._index.timeline=this._getTimeline()),e._index.timeline===null&&(e._index.timeline=e._getTimeline()),Mi(this._index.timeline,e._index.timeline)&&(this._index.startNumber=e._index.startNumber),this._index.availabilityTimeOffset=e._index.availabilityTimeOffset,this._index.availabilityTimeComplete=e._index.availabilityTimeComplete,this._index.endNumber=e._index.endNumber,this._isDynamic=e._isDynamic,this._scaledPeriodStart=e._scaledPeriodStart,this._scaledPeriodEnd=e._scaledPeriodEnd,this._lastUpdate=e._lastUpdate,this._isLastPeriod=e._isLastPeriod}isStillAwaitingFutureSegments(){var a;if(!this._isDynamic)return!1;this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let{timeline:e}=this._index;if(e.length===0){if(this._scaledPeriodEnd!==void 0){let s=this._manifestBoundsCalculator.getEstimatedLiveEdge();if(s!==void 0&&We(s,this._index)>this._scaledPeriodEnd)return!1}return this._isLastPeriod}let t=Qn(this._index.timescale),r=sa(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(r!==null&&!r.isLastOfTimeline){let s=Math.min(r.end,(a=this._scaledPeriodEnd)!=null?a:1/0);return!(this._scaledPeriodEnd!==void 0&&s+t>=this._scaledPeriodEnd)}if(!this._isLastPeriod)return!1;if(this._scaledPeriodEnd===void 0)return!0;let i=e[e.length-1];return ke(i,null,this._scaledPeriodEnd)+t<this._scaledPeriodEnd}isInitialized(){return!0}initialize(){m.error("A `TimelineRepresentationIndex` does not need to be initialized")}addPredictedSegments(){m.warn("Cannot add predicted segments to a `TimelineRepresentationIndex`")}static isTimelineIndexArgument(e){return typeof e.timelineParser=="function"||Array.isArray(e.timeline)}_refreshTimeline(){var i,o;if(this._index.timeline===null&&(this._index.timeline=this._getTimeline()),!this._isDynamic)return;let e=this._manifestBoundsCalculator.getEstimatedMinimumSegmentTime(((o=(i=this._index.timeline[0])==null?void 0:i.duration)!=null?o:0)/this._index.timescale);if(_(e))return;let t=We(e,this._index),r=Pi(this._index.timeline,t);this._index.startNumber!==void 0?this._index.startNumber+=r:this._index.endNumber!==void 0&&(this._index.startNumber=r+1)}_getTimeline(){if(this._parseTimeline===null)return this._index.timeline!==null?this._index.timeline:(m.error("DASH: Timeline already lazily parsed."),[]);let e=this._parseTimeline();this._parseTimeline=null;let{MIN_DASH_S_ELEMENTS_TO_PARSE_UNSAFELY:t}=U.getCurrent();if(this._unsafelyBaseOnPreviousIndex===null||e.length<t)return Dd(Jt(e),this._index.startNumber,this._index.endNumber);let r;return this._unsafelyBaseOnPreviousIndex._index.timeline===null?(r=this._unsafelyBaseOnPreviousIndex._getTimeline(),this._unsafelyBaseOnPreviousIndex._index.timeline=r):r=this._unsafelyBaseOnPreviousIndex._index.timeline,this._unsafelyBaseOnPreviousIndex=null,Dd(Od(e,r),this._index.startNumber,this._index.endNumber)}};function Dd(n,e,t){if(t===void 0)return n;let r=e!=null?e:1;for(let i=0;i<n.length;i++){let o=n[i];if(r+=o.repeatCount+1,r>t){if(r===t+1)return n.slice(0,i+1);{let a=n.slice(0,i),s=oe({},o),d=r-o.repeatCount-1;return s.repeatCount=Math.max(0,t-d),a.push(s),a}}}return n}function Gh(n,e,t,r){let i=sa(e,t,r);if(i===null)return!1;for(let o=0;o<e.timeline.length;o++){if(i.timelineIdx<o)return!1;let a=e.timeline[o],s=(a.start-e.indexTimeOffset)/e.timescale;if(s>n.time)return!1;if(s===n.time)return a.range===void 0?n.range===void 0:!_(n.range)&&a.range[0]===n.range[0]&&a.range[1]===n.range[1];if(a.repeatCount>=0&&a.duration!==void 0){let u=(s-a.start)/a.duration-1;return u%1===0&&u<=i.newRepeatCount}}return!1}function sa(n,e,t){if(n.timeline.length<=0)return null;if(n.availabilityTimeOffset===1/0){let i=n.timeline.length-1,o=n.timeline[i];return{isLastOfTimeline:!0,timelineIdx:i,newRepeatCount:o.repeatCount,end:ke(o,null,t)}}let r=e.getEstimatedMaximumPosition(n.availabilityTimeOffset);if(r===void 0){let i=n.timeline.length-1,o=n.timeline[i];return{isLastOfTimeline:!0,timelineIdx:i,newRepeatCount:o.repeatCount,end:ke(o,null,t)}}for(let i=n.timeline.length-1;i>=n.timeline.length;i--){let o=n.timeline[i],a=o.start+o.duration;if(Tt(a,n)<=r){let s=ke(o,n.timeline[i+1],t);if(Tt(s,n)<=r)return{isLastOfTimeline:i===n.timeline.length-1,timelineIdx:i,newRepeatCount:o.repeatCount,end:a};{let u=We(r,n)-o.start,l=Math.floor(u/o.duration);return ee(l>=1),{isLastOfTimeline:!1,timelineIdx:i,newRepeatCount:l-1,end:o.start+l*o.duration}}}}return null}var da=Oi;var Di=class{constructor(){this._refs=new Map,this._stored=[]}addReferences(e){for(let t of e)t.attributes.refId!==void 0&&this._refs.set(t.attributes.refId,t)}add(e,t){this._tryParsing(e,t,!1)||this._stored.push([e,t]),t.attributes.refId!==void 0&&(this._refs.set(t.attributes.refId,t),this._resolveStoredRefs(!1))}finalize(){this._resolveStoredRefs(!0)}_resolveStoredRefs(e){for(let t=this._stored.length-1;t>=0;t--){let[r,i]=this._stored[t];(this._tryParsing(r,i,e)||e)&&this._stored.splice(t,1)}return this._stored.length===0}_tryParsing(e,t,r){if(t.attributes.ref===void 0)return Ld(e,t),!0;let i=this._getReferenced(t.attributes.ref);return i===void 0?(r&&(m.warn("DASH: forcing the parsing of a referencing ContentProtection"),Ld(e,t)),!1):(t.children.cencPssh.push(...i.children.cencPssh),t.attributes.keyId===void 0&&i.attributes.keyId!==void 0&&(t.attributes.keyId=i.attributes.keyId),t.attributes.schemeIdUri===void 0&&i.attributes.schemeIdUri!==void 0&&(t.attributes.schemeIdUri=i.attributes.schemeIdUri),t.attributes.value===void 0&&i.attributes.value!==void 0&&(t.attributes.value=i.attributes.value),Ld(e,t),!0)}_getReferenced(e){return this._refs.get(e)}};function Ld(n,e){let t;if(e.attributes.schemeIdUri!==void 0&&e.attributes.schemeIdUri.substring(0,9)==="urn:uuid:"&&(t=e.attributes.schemeIdUri.substring(9).replace(/-/g,"").toLowerCase()),e.attributes.keyId!==void 0&&e.attributes.keyId.length>0){let a=e.attributes.keyId;n.contentProtections===void 0?n.contentProtections={keyIds:[a],initData:[]}:n.contentProtections.keyIds===void 0?n.contentProtections.keyIds=[a]:n.contentProtections.keyIds.push(a)}if(t===void 0)return;let{cencPssh:r}=e.children,i=[];for(let a of r)i.push({systemId:t,data:a});if(i.length===0)return;if(n.contentProtections===void 0){n.contentProtections={keyIds:[],initData:[{type:"cenc",values:i}]};return}let o=Z(n.contentProtections.initData,a=>a.type==="cenc");o===void 0?n.contentProtections.initData.push({type:"cenc",values:i}):o.values.push(...i)}function ua(n){let e=Date.parse(n)-F();if(isNaN(e)){m.warn("DASH Parser: Invalid clock received: ",n);return}return e}function Nd(n){let e=n.children.utcTimings.filter(t=>(t.schemeIdUri==="urn:mpeg:dash:utc:http-iso:2014"||t.schemeIdUri==="urn:mpeg:dash:utc:http-xsdate:2014")&&t.value!==void 0);return e.length>0?e[0].value:void 0}function la(n){let{representations:e}=n,t=null;for(let r of e){let i=r.index.getLastAvailablePosition();if(i===void 0)return;i!==null&&(t=t===null?i:Math.min(t,i))}return t===null?null:t}function Ud(n){for(let e=n.length-1;e>=0;e--){let t=n[e].adaptations,r=t.audio===void 0?void 0:t.audio[0],i=t.video===void 0?void 0:t.video[0];if(r!==void 0||i!==void 0){let o=null,a=null;if(r!==void 0){let s=la(r);if(s===void 0)return{safe:void 0,unsafe:void 0};o=s}if(i!==void 0){let s=la(i);if(s===void 0)return{safe:void 0,unsafe:void 0};a=s}if(r!==void 0&&o===null||i!==void 0&&a===null)return m.info("Parser utils: found Period with no segment. ","Going to previous one to calculate last position"),{safe:void 0,unsafe:void 0};if(a!==null)return o!==null?{safe:Math.min(o,a),unsafe:Math.max(o,a)}:{safe:a,unsafe:a};if(o!==null)return{safe:o,unsafe:o}}}return{safe:void 0,unsafe:void 0}}function ca(n){let{representations:e}=n,t=null;for(let r of e){let i=r.index.getFirstAvailablePosition();if(i===void 0)return;i!==null&&(t=t===null?i:Math.max(t,i))}return t===null?null:t}function Bd(n){for(let e=0;e<=n.length-1;e++){let t=n[e].adaptations,r=t.audio===void 0?void 0:t.audio[0],i=t.video===void 0?void 0:t.video[0];if(r!==void 0||i!==void 0){let o=null,a=null;if(r!==void 0){let s=ca(r);if(s===void 0)return;o=s}if(i!==void 0){let s=ca(i);if(s===void 0)return;a=s}if(r!==void 0&&o===null||i!==void 0&&a===null){m.info("Parser utils: found Period with no segment. ","Going to next one to calculate first position");return}if(a!==null)return o!==null?Math.max(o,a):a;if(o!==null)return o}}}function Fd(n){if(n.length===0)throw new Error("DASH Parser: no period available for a dynamic content");let e=Bd(n),t=Ud(n);return{minimumSafePosition:e,maximumSafePosition:t.safe,maximumUnsafePosition:t.unsafe}}var Li=class{constructor(e){this._isDynamic=e.isDynamic,this._timeShiftBufferDepth=!e.isDynamic||e.timeShiftBufferDepth===void 0?null:e.timeShiftBufferDepth,this._serverTimestampOffset=e.serverTimestampOffset,this._availabilityStartTime=e.availabilityStartTime}setLastPosition(e,t){this._lastPosition=e,this._positionTime=t}lastPositionIsKnown(){return this._isDynamic?this._positionTime!==void 0&&this._lastPosition!==void 0:this._lastPosition!==void 0}getEstimatedMinimumSegmentTime(e){var i;if(!this._isDynamic||this._timeShiftBufferDepth===null)return 0;let t=(i=this.getEstimatedLiveEdge())!=null?i:this.getEstimatedMaximumPosition(0);return t===void 0?void 0:t-(this._timeShiftBufferDepth+e)}getEstimatedLiveEdge(){if(!(!this._isDynamic||this._serverTimestampOffset===void 0))return(F()+this._serverTimestampOffset)/1e3-this._availabilityStartTime}getEstimatedMaximumPosition(e){if(!this._isDynamic)return this._lastPosition;let t=this.getEstimatedLiveEdge();return t!==void 0&&e!==1/0?t+e:this._positionTime!==void 0&&this._lastPosition!==void 0?Math.max(this._lastPosition-this._positionTime+F()/1e3,0):this._lastPosition}};function Kd(n,e){return n.type!=="dynamic"?0:_(n.availabilityStartTime)?e!=null?e:0:n.availabilityStartTime}function Vd(n){if(n.length===0)return[];let e=[n[0]];for(let t=1;t<n.length;t++){let r=n[t],i=e[e.length-1];for(;(i.duration===void 0||i.start+i.duration>r.start)&&(m.warn("DASH: Updating overlapping Periods.",i==null?void 0:i.start,r.start),i.duration=r.start-i.start,i.end=r.start,!(i.duration>0));){if(e.pop(),e.length===0)break;i=e[e.length-1]}e.push(r)}return e}function zd(n,e){let t=[];return n.forEach((r,i)=>{let o;if(!_(r.attributes.start))o=r.attributes.start;else if(i===0)o=!e.isDynamic||_(e.availabilityStartTime)?0:e.availabilityStartTime;else{let u=t[t.length-1];if(!_(u)&&!_(u.periodEnd))o=u.periodEnd;else throw new Error("Missing start time when parsing periods.")}let a,s=n[i+1];_(r.attributes.duration)?i===n.length-1?a=e.duration:_(s.attributes.start)||(a=s.attributes.start-o):a=r.attributes.duration;let d=_(a)?void 0:o+a;t.push({periodStart:o,periodDuration:a,periodEnd:d})}),t}function qh(n,e){for(let t of e){let{adaptation:r,trickModeAttachedAdaptationIds:i}=t;for(let o of i)for(let a of Qt){let s=n[a];if(s!==void 0)for(let d of s)d.id===o&&(d.trickModeTracks===void 0&&(d.trickModeTracks=[]),d.trickModeTracks.push(r))}}}var Mf=qh;var jh=["subtitle","caption"];function Hd(n,e,t,r){function i(a,s){let d=a.split("/")[0];if(Q(Qt,d))return d;if(a==="application/ttml+xml")return"text";if(a==="application/mp4")return s!==null&&Z(s,u=>u.schemeIdUri==="urn:mpeg:dash:role:2011"&&Q(jh,u.value))!==void 0?"text":void 0}function o(a){switch(a.substring(0,3)){case"avc":case"hev":case"hvc":case"vp8":case"vp9":case"av1":return"video";case"vtt":return"text"}switch(a.substring(0,4)){case"mp4a":return"audio";case"wvtt":case"stpp":return"text"}}if(e!==null){let a=i(e,r);if(a!==void 0)return a}if(t!==null){let a=o(t);if(a!==void 0)return a}for(let a=0;a<n.length;a++){let s=n[a],{mimeType:d,codecs:u}=s.attributes;if(d!==void 0){let l=i(d,r);if(l!==void 0)return l}if(u!==void 0){let l=o(u);if(l!==void 0)return l}}}var Yh=/[, ]+/g;function Af(n){return w(n)?n.trim().replace(Yh,", "):""}function xf(n){let[e,t,r,i,o,a,s,d]=n.split(".");if(e!=="vp08"&&e!=="vp09"&&e!=="vp10")return;let u,l,c;if((i!==void 0&&i==="10"||i==="12")&&(u=parseInt(i,10)),s!==void 0&&(s==="16"?l="pq":s==="18"&&(l="hlg")),a!==void 0&&d!==void 0&&a==="09"&&d==="09"&&(c="rec2020"),!(u===void 0||l===void 0))return{colorDepth:u,eotf:l,colorSpace:c}}function Wd(n,e){var p,I,y;let{availabilityTimeOffset:t,manifestBoundsCalculator:r,isDynamic:i,end:o,start:a,receivedTime:s,unsafelyBaseOnPreviousRepresentation:d,inbandEventStreams:u,isLastPeriod:l}=e,f={availabilityTimeComplete:void 0,availabilityTimeOffset:t,unsafelyBaseOnPreviousRepresentation:d,isEMSGWhitelisted:b=>u===void 0?!1:u.some(({schemeIdUri:T})=>T===b.schemeIdUri),isLastPeriod:l,manifestBoundsCalculator:r,isDynamic:i,periodEnd:o,periodStart:a,receivedTime:s,representationBitrate:n.attributes.bitrate,representationId:n.attributes.id},g;if(n.children.segmentBase!==void 0){let{segmentBase:b}=n.children;g=new En(b,f)}else if(n.children.segmentList!==void 0){let{segmentList:b}=n.children;g=new vn(b,f)}else if(n.children.segmentTemplate!==void 0||e.parentSegmentTemplates.length>0){let b=e.parentSegmentTemplates.slice(),T=n.children.segmentTemplate;T!==void 0&&b.push(T);let v=G({},...b);(v.availabilityTimeOffset!==void 0||e.availabilityTimeOffset!==void 0)&&(f.availabilityTimeOffset=((p=v.availabilityTimeOffset)!=null?p:0)+((I=e.availabilityTimeOffset)!=null?I:0)),(v.availabilityTimeComplete!==void 0||e.availabilityTimeComplete!==void 0)&&(f.availabilityTimeComplete=(y=v.availabilityTimeComplete)!=null?y:e.availabilityTimeComplete),g=da.isTimelineIndexArgument(v)?new da(v,f):new Rn(v,f)}else{let b=e.adaptation.children;if(b.segmentBase!==void 0){let{segmentBase:T}=b;g=new En(T,f)}else if(b.segmentList!==void 0){let{segmentList:T}=b;g=new vn(T,f)}else g=new Rn({duration:Number.MAX_VALUE,timescale:1,startNumber:0,media:""},f)}return g}function wt(n,e){var i;if(e.length===0)return n;let t=e.map(o=>({url:o.value}));if(n.length===0)return t;let r=[];for(let o=0;o<n.length;o++){let a=n[o];for(let s=0;s<t.length;s++){let d=t[s],u=cn(a.url,d.url);r.push({url:u,serviceLocation:(i=d.serviceLocation)!=null?i:a.serviceLocation})}}return r}function $h(n,e){let t=[];if(n.children.inbandEventStreams!==void 0&&t.push(...n.children.inbandEventStreams),e.children.inbandEventStreams!==void 0&&t.push(...e.children.inbandEventStreams),t.length!==0)return t}function Qh({adaptationProfiles:n,essentialProperties:e,supplementalProperties:t,manifestProfiles:r,codecs:i}){if(((n!=null?n:"")+(r!=null?r:"")).indexOf("http://dashif.org/guidelines/dash-if-uhd#hevc-hdr-pq10")!==-1&&(i==="hvc1.2.4.L153.B0"||i==="hev1.2.4.L153.B0"))return{colorDepth:10,eotf:"pq",colorSpace:"rec2020"};let a=Z([...e!=null?e:[],...t!=null?t:[]],s=>s.schemeIdUri==="urn:mpeg:mpegB:cicp:TransferCharacteristics");if(a!==void 0)switch(a.value){case"15":return;case"16":return{eotf:"pq"};case"18":return{eotf:"hlg"}}if(i!==void 0&&/^vp(08|09|10)/.exec(i))return xf(i)}function Gd(n,e,t){var i,o,a,s,d,u,l;let r=[];for(let c of n){let f=c.attributes.id!==void 0?c.attributes.id:String(c.attributes.bitrate)+(c.attributes.height!==void 0?`-${c.attributes.height}`:"")+(c.attributes.width!==void 0?`-${c.attributes.width}`:"")+(c.attributes.mimeType!==void 0?`-${c.attributes.mimeType}`:"")+(c.attributes.codecs!==void 0?`-${c.attributes.codecs}`:"");for(;r.some(P=>P.id===f);)f+="-dup";let g=(o=(i=t.unsafelyBaseOnPreviousAdaptation)==null?void 0:i.getRepresentation(f))!=null?o:null,p=$h(c,e),I=(a=c.attributes.availabilityTimeComplete)!=null?a:t.availabilityTimeComplete,y;(c.attributes.availabilityTimeOffset!==void 0||t.availabilityTimeOffset!==void 0)&&(y=((s=c.attributes.availabilityTimeOffset)!=null?s:0)+((d=t.availabilityTimeOffset)!=null?d:0));let b=G({},t,{availabilityTimeOffset:y,availabilityTimeComplete:I,unsafelyBaseOnPreviousRepresentation:g,adaptation:e,inbandEventStreams:p}),T=Wd(c,b),v;c.attributes.bitrate===void 0?(m.warn("DASH: No usable bitrate found in the Representation."),v=0):v=c.attributes.bitrate;let E=wt(t.baseURLs,c.children.baseURLs),R=E.length===0?[{baseUrl:"",id:void 0}]:E.map(P=>({baseUrl:P.url,id:P.serviceLocation})),k={bitrate:v,cdnMetadata:R,index:T,id:f};c.children.supplementalProperties!==void 0&&Z(c.children.supplementalProperties,P=>P.schemeIdUri==="tag:dolby.com,2018:dash:EC3_ExtensionType:2018"&&P.value==="JOC")&&(k.isSpatialAudio=!0);let x;c.attributes.codecs!==void 0?x=c.attributes.codecs:e.attributes.codecs!==void 0&&(x=e.attributes.codecs),x!==void 0&&(x=x==="mp4a.40.02"?"mp4a.40.2":x,k.codecs=x);let M;c.attributes.supplementalCodecs!==void 0?M=c.attributes.supplementalCodecs:e.attributes.supplementalCodecs!==void 0&&(M=e.attributes.supplementalCodecs),M!==void 0&&(k.supplementalCodecs=Af(M)),c.attributes.frameRate!==void 0?k.frameRate=c.attributes.frameRate:e.attributes.frameRate!==void 0&&(k.frameRate=e.attributes.frameRate),c.attributes.height!==void 0?k.height=c.attributes.height:e.attributes.height!==void 0&&(k.height=e.attributes.height),c.attributes.mimeType!==void 0?k.mimeType=c.attributes.mimeType:e.attributes.mimeType!==void 0&&(k.mimeType=e.attributes.mimeType),c.attributes.width!==void 0?k.width=c.attributes.width:e.attributes.width!==void 0&&(k.width=e.attributes.width);{let P=[...(u=e.children.contentProtections)!=null?u:[],...(l=c.children.contentProtections)!=null?l:[]];for(let N of P)t.contentProtectionParser.add(k,N)}k.hdrInfo=Qh({adaptationProfiles:e.attributes.profiles,supplementalProperties:e.children.supplementalProperties,essentialProperties:e.children.essentialProperties,manifestProfiles:t.manifestProfiles,codecs:x}),r.push(k)}return r}function Xh(n){if(n===void 0)return!1;let e=n.schemeIdUri==="urn:tva:metadata:cs:AudioPurposeCS:2007"&&n.value==="1",t=n.schemeIdUri==="urn:mpeg:dash:role:2011"&&n.value==="description";return e||t}function Zh(n,e){return!!(n!==void 0&&n.some(r=>r.schemeIdUri==="urn:tva:metadata:cs:AudioPurposeCS:2007"&&r.value==="2")||e!==void 0&&e.some(r=>r.schemeIdUri==="urn:mpeg:dash:role:2011"&&r.value==="caption"))}function Jh(n){return n===void 0?!1:n.schemeIdUri==="urn:mpeg:dash:role:2011"&&n.value==="sign"}function ey(n,e){if(w(n.attributes.id))return n.attributes.id;let{isClosedCaption:t,isForcedSubtitle:r,isAudioDescription:i,isSignInterpreted:o,isTrickModeTrack:a,type:s}=e,d=s;return w(n.attributes.language)&&(d+=`-${n.attributes.language}`),t===!0&&(d+="-cc"),r===!0&&(d+="-cc"),i===!0&&(d+="-ad"),o===!0&&(d+="-si"),a&&(d+="-trickMode"),w(n.attributes.contentType)&&(d+=`-${n.attributes.contentType}`),w(n.attributes.codecs)&&(d+=`-${n.attributes.codecs}`),w(n.attributes.mimeType)&&(d+=`-${n.attributes.mimeType}`),n.attributes.frameRate!==void 0&&(d+=`-${String(n.attributes.frameRate)}`),d}function ty(n){if(!_(n.children.supplementalProperties)){let{supplementalProperties:e}=n.children;for(let t of e)if(t.schemeIdUri==="urn:mpeg:dash:adaptation-set-switching:2016"&&!_(t.value))return t.value.split(",").map(r=>r.trim()).filter(r=>r)}return[]}function qd(n,e){var s,d,u,l,c,f,g;let t={video:[],audio:[],text:[]},r=[],i={},o=[];for(let p=0;p<n.length;p++){let I=n[p],y=I.children,{essentialProperties:b,roles:T,label:v}=y,E=Array.isArray(T)&&T.some(ye=>ye.value==="main")&&T.some(ye=>ye.schemeIdUri==="urn:mpeg:dash:role:2011"),R=I.children.representations,k=(s=I.attributes.availabilityTimeComplete)!=null?s:e.availabilityTimeComplete,x;(I.attributes.availabilityTimeOffset!==void 0||e.availabilityTimeOffset!==void 0)&&(x=((d=I.attributes.availabilityTimeOffset)!=null?d:0)+((u=e.availabilityTimeOffset)!=null?u:0));let M=I.attributes.mimeType,P=I.attributes.codecs,N=Hd(R,w(M)?M:null,w(P)?P:null,_(y.roles)?null:y.roles);if(N===void 0)continue;let O=(l=I.attributes.selectionPriority)!=null?l:1,K=I.attributes.id,A=ty(I),C=[];e.segmentTemplate!==void 0&&C.push(e.segmentTemplate),I.children.segmentTemplate!==void 0&&C.push(I.children.segmentTemplate);let D={availabilityTimeComplete:k,availabilityTimeOffset:x,baseURLs:wt(e.baseURLs,y.baseURLs),contentProtectionParser:e.contentProtectionParser,manifestBoundsCalculator:e.manifestBoundsCalculator,end:e.end,isDynamic:e.isDynamic,isLastPeriod:e.isLastPeriod,manifestProfiles:e.manifestProfiles,parentSegmentTemplates:C,receivedTime:e.receivedTime,start:e.start,unsafelyBaseOnPreviousAdaptation:null},L=Array.isArray(b)?Z(b,ye=>ye.schemeIdUri==="http://dashif.org/guidelines/trickmode"):void 0,V=(c=L==null?void 0:L.value)==null?void 0:c.split(" "),$=V!==void 0,{accessibilities:j}=y,z;T!==void 0&&T.some(ye=>ye.value==="dub")&&(z=!0);let q;N!=="text"?q=!1:q=Zh(j,T);let W;N==="text"&&T!==void 0&&T.some(ye=>ye.value==="forced-subtitle"||ye.value==="forced_subtitle")&&(W=!0);let se;N!=="audio"?se=!1:j!==void 0&&(se=j.some(Xh));let ae;N!=="video"?ae=!1:j!==void 0&&(ae=j.some(Jh));let de=ey(I,{isAudioDescription:se,isForcedSubtitle:W,isClosedCaption:q,isSignInterpreted:ae,isTrickModeTrack:$,type:N});for(;Q(o,de);)de+="-dup";let Se=de;o.push(de),D.unsafelyBaseOnPreviousAdaptation=(g=(f=e.unsafelyBaseOnPreviousPeriod)==null?void 0:f.getAdaptation(de))!=null?g:null;let Y=Gd(R,I,D),ce={id:de,representations:Y,type:N,isTrickModeTrack:$};if(_(I.attributes.language)||(ce.language=I.attributes.language),_(q)||(ce.closedCaption=q),_(se)||(ce.audioDescription=se),z===!0&&(ce.isDub=!0),W!==void 0&&(ce.forcedSubtitles=W),ae===!0&&(ce.isSignInterpreted=!0),v!==void 0&&(ce.label=v),V!==void 0)r.push({adaptation:ce,trickModeAttachedAdaptationIds:V});else{let ye=-1;for(let Kt of A){let Qe=i[Kt];if(Qe!==void 0&&Qe.newID!==Se&&Q(Qe.adaptationSetSwitchingIDs,K)){ye=he(t[N],_t=>_t[0].id===Kt);let Be=t[N][ye];if(Be!==void 0&&Be[0].audioDescription===ce.audioDescription&&Be[0].closedCaption===ce.closedCaption&&Be[0].language===ce.language){m.info('DASH Parser: merging "switchable" AdaptationSets',K,Kt),Be[0].representations.push(...ce.representations),Be[1]={priority:Math.max(O,Be[1].priority),isMainAdaptation:E||Be[1].isMainAdaptation,indexInMpd:Math.min(p,Be[1].indexInMpd)};break}}}ye<0&&t[N].push([ce,{priority:O,isMainAdaptation:E,indexInMpd:p}])}!_(K)&&_(i[K])&&(i[K]={newID:Se,adaptationSetSwitchingIDs:A})}let a=Qt.reduce((p,I)=>{let y=t[I];return y.length>0&&(y.sort(wf),p[I]=y.map(([b])=>b)),p},{});return t.video.sort(wf),Mf(a,r),a}function wf(n,e){let t=e[1].priority-n[1].priority;return t!==0?t:n[1].isMainAdaptation!==e[1].isMainAdaptation?n[1].isMainAdaptation?-1:1:n[1].indexInMpd-e[1].indexInMpd}var ny=et();function jd(n,e){var a,s,d,u,l;let t=[],r=zd(n,e);if(r.length!==n.length)throw new Error("MPD parsing error: the time information are incoherent.");let{isDynamic:i,manifestBoundsCalculator:o}=e;!i&&!_(e.duration)&&o.setLastPosition(e.duration);for(let c=n.length-1;c>=0;c--){let f=c===n.length-1,g=n[c],p=e.xlinkInfos.get(g),I=wt(e.baseURLs,g.children.baseURLs),{periodStart:y,periodDuration:b,periodEnd:T}=r[c],v;for(_(g.attributes.id)?(m.warn("DASH: No usable id found in the Period. Generating one."),v="gen-dash-period-"+ny()):v=g.attributes.id;t.some(L=>L.id===v);)v+="-dup";let E=p!==void 0?p.receivedTime:e.receivedTime,R=(s=(a=e.unsafelyBaseOnPreviousManifest)==null?void 0:a.getPeriod(v))!=null?s:null,k=g.attributes.availabilityTimeComplete,x=g.attributes.availabilityTimeOffset,{manifestProfiles:M,contentProtectionParser:P}=e,{segmentTemplate:N}=g.children;P.addReferences((d=g.children.contentProtections)!=null?d:[]);let O={availabilityTimeComplete:k,availabilityTimeOffset:x,baseURLs:I,contentProtectionParser:P,manifestBoundsCalculator:o,end:T,isDynamic:i,isLastPeriod:f,manifestProfiles:M,receivedTime:E,segmentTemplate:N,start:y,unsafelyBaseOnPreviousPeriod:R},K=qd(g.children.adaptations,O),A=((u=e.xmlNamespaces)!=null?u:[]).concat((l=g.attributes.namespaces)!=null?l:[]),C=iy(g.children.eventStreams,y,A),D={id:v,start:y,end:T,duration:b,adaptations:K,streamEvents:C};if(t.unshift(D),!o.lastPositionIsKnown()){let L=ry(K);if(!i)typeof L=="number"&&o.setLastPosition(L);else if(typeof L=="number"){let V=F()/1e3;o.setLastPosition(L,V)}else{let V=Of(e,y);if(V!==void 0){let[$,j]=V;o.setLastPosition($,j)}}}}if(e.isDynamic&&!o.lastPositionIsKnown()){let c=Of(e,0);if(c!==void 0){let[f,g]=c;o.setLastPosition(f,g)}}return Vd(t)}function Of(n,e){if(_(n.clockOffset)){let t=Date.now()/1e3;if(t>=e){m.warn("DASH Parser: no clock synchronization mechanism found. Using the system clock instead.");let r=t-n.availabilityStartTime,i=F()/1e3;return[r,i]}}else{let t=n.clockOffset/1e3-n.availabilityStartTime,r=F()/1e3,i=r+t;if(i>=e)return[i,r]}}function ry(n){let e=null,t=!0,r=On(n).filter(o=>!_(o)),i=Nn(r,o=>o);for(let o of i){let a=o.representations;for(let s of a){let d=s.index.getLastAvailablePosition();d!==null&&(t=!1,typeof d=="number"&&(e=_(e)?d:Math.max(e,d)))}}if(_(e)){if(t)return null}else return e}function iy(n,e,t){var i,o;let r=[];for(let a of n){let{schemeIdUri:s="",timescale:d=1}=a.attributes,u=t.concat((i=a.attributes.namespaces)!=null?i:[]);for(let l of a.children.events)if(l.eventStreamData!==void 0){let c=((o=l.presentationTime)!=null?o:0)/d+e,f=l.duration===void 0?void 0:c+l.duration/d,g,p;if(!Vt&&l.eventStreamData instanceof Element)g=l.eventStreamData;else try{p={namespaces:u,data:typeof l.eventStreamData=="string"?l.eventStreamData:Ne(new Uint8Array(l.eventStreamData))}}catch(I){m.error("DASH: Error while parsing event-stream:",I instanceof Error?I.message:"Unknown error")}r.push({start:c,end:f,id:l.id,data:{type:"dash-event-stream",value:{schemeIdUri:s,timescale:d,element:g,xmlData:p}}})}}return r}function Xn(n,e,t,r,i=new WeakMap){let{children:o,attributes:a}=n;if(_(e.externalClockOffset)){let d=a.type==="dynamic",u=Z(o.utcTimings,f=>f.schemeIdUri==="urn:mpeg:dash:utc:direct:2014"&&!_(f.value)),l=!_(u)&&!_(u.value)?ua(u.value):void 0,c=!_(l)&&!isNaN(l)?l:void 0;if(!_(c)&&r!==!0)e.externalClockOffset=c;else if(d&&r!==!0){let f=Nd(n);if(!_(f)&&f.length>0)return{type:"needs-clock",value:{url:f,continue:function(p){return p.success?(e.externalClockOffset=ua(p.data),Xn(n,e,t,!0)):(t.push(p.error),m.warn("DASH Parser: Error on fetching the clock ressource",p.error),Xn(n,e,t,!0))}}}}}let s=[];for(let d=0;d<o.periods.length;d++){let{xlinkHref:u,xlinkActuate:l}=o.periods[d].attributes;!_(u)&&l==="onLoad"&&s.push({index:d,ressource:u})}return s.length===0?oy(n,e,t,i):{type:"needs-xlinks",value:{xlinksUrls:s.map(({ressource:d})=>d),continue:function(u){if(u.length!==s.length)throw new Error("DASH parser: wrong number of loaded ressources.");for(let l=u.length-1;l>=0;l--){let c=s[l].index,{parsed:f,warnings:g,receivedTime:p,sendingTime:I,url:y}=u[l];g.length>0&&t.push(...g);for(let b of f)i.set(b,{receivedTime:p,sendingTime:I,url:y});o.periods.splice(c,1,...f)}return Xn(n,e,t,r,i)}}}}function oy(n,e,t,r){var C,D,L,V,$;let{children:i,attributes:o}=n,a=o.type==="dynamic",s=e.url!==void 0?[{url:e.url.substring(0,_r(e.url))}]:[],d=wt(s,i.baseURLs),u=Kd(o,e.referenceDateTime),l=o.timeShiftBufferDepth,c=o.maxSegmentDuration,{externalClockOffset:f,unsafelyBaseOnPreviousManifest:g}=e,{externalClockOffset:p}=e,I=new Li({availabilityStartTime:u,isDynamic:a,timeShiftBufferDepth:l,serverTimestampOffset:p}),y=new Di;y.addReferences((C=i.contentProtections)!=null?C:[]);let b={availabilityStartTime:u,baseURLs:d,clockOffset:f,contentProtectionParser:y,duration:o.duration,isDynamic:a,manifestBoundsCalculator:I,manifestProfiles:n.attributes.profiles,receivedTime:e.manifestReceivedTime,unsafelyBaseOnPreviousManifest:g,xlinkInfos:r,xmlNamespaces:n.attributes.namespaces},T=jd(i.periods,b);y.finalize();let v=o.duration,E,R,k=null,x;o.minimumUpdatePeriod!==void 0&&o.minimumUpdatePeriod>=0&&(E=o.minimumUpdatePeriod===0?U.getCurrent().DASH_FALLBACK_LIFETIME_WHEN_MINIMUM_UPDATE_PERIOD_EQUAL_0:o.minimumUpdatePeriod);let{minimumSafePosition:M,maximumSafePosition:P,maximumUnsafePosition:N}=Fd(T),O=F();if(a){let j;P!==void 0?j=P:p===void 0?(m.warn("DASH Parser: use system clock to define maximum position"),j=Date.now()/1e3-u):j=(F()+p)/1e3-u;let z=I.getEstimatedLiveEdge();z===void 0&&(N!==void 0?z=N:z=j),x={isLinear:!0,maximumSafePosition:j,livePosition:z,time:O},R=M,k=l!=null?l:null,k!==null&&(k+=c!=null?c:0),k!==null&&R!==void 0&&z-R>k&&(k=z-R)}else{R=M,R===void 0&&(R=(L=(D=T[0])==null?void 0:D.start)!=null?L:0);let j=v!=null?v:1/0;if(T[T.length-1]!==void 0){let z=T[T.length-1],q=(V=z.end)!=null?V:z.duration!==void 0?z.start+z.duration:void 0;q!==void 0&&q<j&&(j=q)}P!==void 0&&P<j&&(j=P),x={isLinear:!1,maximumSafePosition:j,livePosition:void 0,time:O}}let K=!a||n.attributes.minimumUpdatePeriod===void 0&&((($=T[T.length-1])==null?void 0:$.end)!==void 0||n.attributes.duration!==void 0);return{type:"done",value:{parsed:{availabilityStartTime:u,clockOffset:e.externalClockOffset,isDynamic:a,isLive:a,isLastPeriodKnown:K,periods:T,publishTime:o.publishTime,suggestedPresentationDelay:o.suggestedPresentationDelay,transportType:"dash",timeBounds:{minimumSafePosition:R,timeshiftDepth:k,maximumTimeData:x},lifetime:E,uris:_(e.url)?i.locations:[e.url,...i.locations]},warnings:t}}}var Df=Xn;function Ot(n){let e=n.textContent,t=[];return e===null||e.length===0?[void 0,t]:[{value:e},t]}var ay=/^P(([\d.]*)Y)?(([\d.]*)M)?(([\d.]*)D)?T?(([\d.]*)H)?(([\d.]*)M)?(([\d.]*)S)?/,sy=/([0-9]+)-([0-9]+)/;function Ge(n,e){return n==="true"?[!0,null]:n==="false"?[!1,null]:[!1,new tt(`\`${e}\` property is not a boolean value but "${n}"`)]}function be(n,e){let t=parseInt(n,10);return isNaN(t)?[null,new tt(`\`${e}\` property is not an integer value but "${n}"`)]:[t,null]}function Ye(n,e){if(n==="INF")return[1/0,null];let t=parseFloat(n);return isNaN(t)?[null,new tt(`\`${e}\` property is invalid: "${n}"`)]:[t,null]}function Yd(n,e){if(n==="true")return[!0,null];if(n==="false")return[!1,null];let t=parseInt(n,10);return isNaN(t)?[null,new tt(`\`${e}\` property is not a boolean nor an integer but "${n}"`)]:[t,null]}function fa(n,e){let t=Date.parse(n);return isNaN(t)?[null,new tt(`\`${e}\` is in an invalid date format: "${n}"`)]:[new Date(Date.parse(n)).getTime()/1e3,null]}function gt(n,e){if(!w(n))return[0,new tt(`\`${e}\` property is empty`)];let t=ay.exec(n);return t===null?[null,new tt(`\`${e}\` property has an unrecognized format "${n}"`)]:[parseFloat(w(t[2])?t[2]:"0")*365*24*60*60+parseFloat(w(t[4])?t[4]:"0")*30*24*60*60+parseFloat(w(t[6])?t[6]:"0")*24*60*60+parseFloat(w(t[8])?t[8]:"0")*60*60+parseFloat(w(t[10])?t[10]:"0")*60+parseFloat(w(t[12])?t[12]:"0"),null]}function kn(n,e){let t=sy.exec(n);return t===null?[null,new tt(`\`${e}\` property has an unrecognized format "${n}"`)]:[[+t[1],+t[2]],null]}function Lf(n,e){try{return[mt(n),null]}catch(t){return[null,new tt(`\`${e}\` is not a valid base64 string: "${n}"`)]}}function Zn(n,e){let t=/^(\d+)\/(\d+)$/.exec(n);return t!==null?[+t[1]/+t[2],null]:Ye(n,e)}function He(n){let e,t;for(let r=0;r<n.attributes.length;r++){let i=n.attributes[r];switch(i.name){case"schemeIdUri":e=i.value;break;case"value":t=i.value;break}}return{schemeIdUri:e,value:t}}function xe(n,e){return function(t,{asKey:r,parser:i,dashName:o}){let[a,s]=i(t,o);s!==null&&(m.warn(s.message),e.push(s)),a!==null&&(n[r]=a)}}var tt=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype),this.name="MPDError"}};function dy(n){let e=[],t=[];for(let r=0;r<n.length;r++)if(n[r].nodeType===Node.ELEMENT_NODE){let i=n[r];if(i.nodeName==="cenc:pssh"){let o=i.textContent;if(o!==null&&o.length>0){let[a,s]=Lf(o,"cenc:pssh");s!==null&&(m.warn(s.message),e.push(s)),a!==null&&t.push(a)}}}return[{cencPssh:t},e]}function uy(n){let e={};for(let t=0;t<n.attributes.length;t++){let r=n.attributes[t];switch(r.name){case"schemeIdUri":e.schemeIdUri=r.value;break;case"value":e.value=r.value;break;case"cenc:default_KID":e.keyId=je(r.value.replace(/-/g,""));break;case"ref":e.ref=r.value;break;case"refId":e.refId=r.value;break}}return e}function Dt(n){let[e,t]=dy(n.childNodes),r=uy(n);return[{children:e,attributes:r},t]}function $d(n){let e={};for(let t=0;t<n.attributes.length;t++){let r=n.attributes[t];switch(r.name){case"id":e.id=r.value;break;case"lang":e.language=r.value;break;case"contentType":e.contentType=r.value;break;case"par":e.par=r.value;break}}return e}function Qd(n){let e={},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"range":r(o.value,{asKey:"range",parser:kn,dashName:"range"});break;case"sourceURL":e.media=o.value;break}}return[e,t]}function Lt(n){let e={},t=[],r=xe(e,t),i=n.childNodes;for(let o=0;o<i.length;o++)if(i[o].nodeType===Node.ELEMENT_NODE){let a=i[o];if(a.nodeName==="Initialization"){let[s,d]=Qd(a);e.initialization=s,t=t.concat(d)}}for(let o=0;o<n.attributes.length;o++){let a=n.attributes[o];switch(a.name){case"timescale":r(a.value,{asKey:"timescale",parser:be,dashName:"timescale"});break;case"presentationTimeOffset":r(a.value,{asKey:"presentationTimeOffset",parser:Ye,dashName:"presentationTimeOffset"});break;case"indexRange":r(a.value,{asKey:"indexRange",parser:kn,dashName:"indexRange"});break;case"indexRangeExact":r(a.value,{asKey:"indexRangeExact",parser:Ge,dashName:"indexRangeExact"});break;case"availabilityTimeOffset":r(a.value,{asKey:"availabilityTimeOffset",parser:Ye,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(a.value,{asKey:"availabilityTimeComplete",parser:Ge,dashName:"availabilityTimeComplete"});break;case"duration":r(a.value,{asKey:"duration",parser:be,dashName:"duration"});break;case"startNumber":r(a.value,{asKey:"startNumber",parser:be,dashName:"startNumber"});break;case"endNumber":r(a.value,{asKey:"endNumber",parser:be,dashName:"endNumber"});break}}return[e,t]}function Xd(n){let e={},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"media":e.media=o.value;break;case"indexRange":r(o.value,{asKey:"indexRange",parser:kn,dashName:"indexRange"});break;case"index":e.index=o.value;break;case"mediaRange":r(o.value,{asKey:"mediaRange",parser:kn,dashName:"mediaRange"});break}}return[e,t]}function Ni(n){let[e,t]=Lt(n),r=t,i=[],o=n.childNodes;for(let s=0;s<o.length;s++)if(o[s].nodeType===Node.ELEMENT_NODE){let d=o[s];if(d.nodeName==="SegmentURL"){let[u,l]=Xd(d);i.push(u),r=r.concat(l)}}return[G(e,{list:i}),r]}function Zd(n){let e=null;return function(){if(e===null){let t=n.getElementsByTagName("S");return e=t,t}return e}}function Cn(n){let[e,t]=Lt(n),r=t,i;for(let s=0;s<n.childNodes.length;s++)if(n.childNodes[s].nodeType===Node.ELEMENT_NODE){let d=n.childNodes[s];d.nodeName==="SegmentTimeline"&&(i=Zd(d))}let o=G({},e,{duration:e.duration,timelineParser:i}),a=xe(o,r);for(let s=0;s<n.attributes.length;s++){let d=n.attributes[s];switch(d.nodeName){case"initialization":_(o.initialization)&&(o.initialization={media:d.value});break;case"index":o.index=d.value;break;case"availabilityTimeOffset":a(d.value,{asKey:"availabilityTimeOffset",parser:Ye,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":a(d.value,{asKey:"availabilityTimeComplete",parser:Ge,dashName:"availabilityTimeComplete"});break;case"media":o.media=d.value;break;case"bitstreamSwitching":a(d.value,{asKey:"bitstreamSwitching",parser:Ge,dashName:"bitstreamSwitching"});break}}return[o,r]}function ly(n){let e={baseURLs:[]},t=[],r=[];for(let i=0;i<n.length;i++)if(n[i].nodeType===Node.ELEMENT_NODE){let o=n[i];switch(o.nodeName){case"BaseURL":{let[a,s]=Ot(o);a!==void 0&&e.baseURLs.push(a),r=r.concat(s);break}case"InbandEventStream":e.inbandEventStreams===void 0&&(e.inbandEventStreams=[]),e.inbandEventStreams.push(He(o));break;case"SegmentBase":{let[a,s]=Lt(o);e.segmentBase=a,s.length>0&&(r=r.concat(s));break}case"SegmentList":{let[a,s]=Ni(o);r=r.concat(s),e.segmentList=a;break}case"SegmentTemplate":{let[a,s]=Cn(o);r=r.concat(s),e.segmentTemplate=a;break}case"ContentProtection":{let[a,s]=Dt(o);s.length>0&&(r=r.concat(s)),a!==void 0&&t.push(a);break}case"SupplementalProperty":_(e.supplementalProperties)?e.supplementalProperties=[He(o)]:e.supplementalProperties.push(He(o));break}}return t.length>0&&(e.contentProtections=t),[e,r]}function cy(n){let e={},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"audioSamplingRate":e.audioSamplingRate=o.value;break;case"bandwidth":r(o.value,{asKey:"bitrate",parser:be,dashName:"bandwidth"});break;case"codecs":e.codecs=o.value;break;case"codingDependency":r(o.value,{asKey:"codingDependency",parser:Ge,dashName:"codingDependency"});break;case"frameRate":r(o.value,{asKey:"frameRate",parser:Zn,dashName:"frameRate"});break;case"height":r(o.value,{asKey:"height",parser:be,dashName:"height"});break;case"id":e.id=o.value;break;case"maxPlayoutRate":r(o.value,{asKey:"maxPlayoutRate",parser:Ye,dashName:"maxPlayoutRate"});break;case"maximumSAPPeriod":r(o.value,{asKey:"maximumSAPPeriod",parser:Ye,dashName:"maximumSAPPeriod"});break;case"mimeType":e.mimeType=o.value;break;case"profiles":e.profiles=o.value;break;case"qualityRanking":r(o.value,{asKey:"qualityRanking",parser:be,dashName:"qualityRanking"});break;case"scte214:supplementalCodecs":e.supplementalCodecs=o.value;break;case"segmentProfiles":e.segmentProfiles=o.value;break;case"width":r(o.value,{asKey:"width",parser:be,dashName:"width"});break;case"availabilityTimeOffset":r(o.value,{asKey:"availabilityTimeOffset",parser:Ye,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(o.value,{asKey:"availabilityTimeComplete",parser:Ge,dashName:"availabilityTimeComplete"});break}}return e.bitrate===void 0&&t.push(new tt("No bitrate found on a Representation")),[e,t]}function Nf(n){let[e,t]=ly(n.childNodes),[r,i]=cy(n),o=t.concat(i);return[{children:e,attributes:r},o]}function fy(n){let e={baseURLs:[],representations:[]},t=[],r=[];for(let i=0;i<n.length;i++)if(n[i].nodeType===Node.ELEMENT_NODE){let o=n[i];switch(o.nodeName){case"Accessibility":e.accessibilities===void 0?e.accessibilities=[He(o)]:e.accessibilities.push(He(o));break;case"BaseURL":{let[a,s]=Ot(o);a!==void 0&&e.baseURLs.push(a),s.length>0&&(r=r.concat(s));break}case"ContentComponent":e.contentComponent=$d(o);break;case"EssentialProperty":_(e.essentialProperties)?e.essentialProperties=[He(o)]:e.essentialProperties.push(He(o));break;case"InbandEventStream":e.inbandEventStreams===void 0&&(e.inbandEventStreams=[]),e.inbandEventStreams.push(He(o));break;case"Label":{let a=o.textContent;a!=null&&(e.label=a);break}case"Representation":{let[a,s]=Nf(o);e.representations.push(a),s.length>0&&(r=r.concat(s));break}case"Role":_(e.roles)?e.roles=[He(o)]:e.roles.push(He(o));break;case"SupplementalProperty":_(e.supplementalProperties)?e.supplementalProperties=[He(o)]:e.supplementalProperties.push(He(o));break;case"SegmentBase":{let[a,s]=Lt(o);e.segmentBase=a,s.length>0&&(r=r.concat(s));break}case"SegmentList":{let[a,s]=Ni(o);e.segmentList=a,s.length>0&&(r=r.concat(s));break}case"SegmentTemplate":{let[a,s]=Cn(o);e.segmentTemplate=a,s.length>0&&(r=r.concat(s));break}case"ContentProtection":{let[a,s]=Dt(o);s.length>0&&(r=r.concat(s)),a!==void 0&&t.push(a);break}}}return t.length>0&&(e.contentProtections=t),[e,r]}function my(n){let e={},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"id":e.id=o.value;break;case"group":r(o.value,{asKey:"group",parser:be,dashName:"group"});break;case"lang":e.language=o.value;break;case"contentType":e.contentType=o.value;break;case"par":e.par=o.value;break;case"minBandwidth":r(o.value,{asKey:"minBitrate",parser:be,dashName:"minBandwidth"});break;case"maxBandwidth":r(o.value,{asKey:"maxBitrate",parser:be,dashName:"maxBandwidth"});break;case"minWidth":r(o.value,{asKey:"minWidth",parser:be,dashName:"minWidth"});break;case"maxWidth":r(o.value,{asKey:"maxWidth",parser:be,dashName:"maxWidth"});break;case"minHeight":r(o.value,{asKey:"minHeight",parser:be,dashName:"minHeight"});break;case"maxHeight":r(o.value,{asKey:"maxHeight",parser:be,dashName:"maxHeight"});break;case"minFrameRate":r(o.value,{asKey:"minFrameRate",parser:Zn,dashName:"minFrameRate"});break;case"maxFrameRate":r(o.value,{asKey:"maxFrameRate",parser:Zn,dashName:"maxFrameRate"});break;case"selectionPriority":r(o.value,{asKey:"selectionPriority",parser:be,dashName:"selectionPriority"});break;case"segmentAlignment":r(o.value,{asKey:"segmentAlignment",parser:Yd,dashName:"segmentAlignment"});break;case"subsegmentAlignment":r(o.value,{asKey:"subsegmentAlignment",parser:Yd,dashName:"subsegmentAlignment"});break;case"bitstreamSwitching":r(o.value,{asKey:"bitstreamSwitching",parser:Ge,dashName:"bitstreamSwitching"});break;case"audioSamplingRate":e.audioSamplingRate=o.value;break;case"codecs":e.codecs=o.value;break;case"scte214:supplementalCodecs":e.supplementalCodecs=o.value;break;case"codingDependency":r(o.value,{asKey:"codingDependency",parser:Ge,dashName:"codingDependency"});break;case"frameRate":r(o.value,{asKey:"frameRate",parser:Zn,dashName:"frameRate"});break;case"height":r(o.value,{asKey:"height",parser:be,dashName:"height"});break;case"maxPlayoutRate":r(o.value,{asKey:"maxPlayoutRate",parser:Ye,dashName:"maxPlayoutRate"});break;case"maximumSAPPeriod":r(o.value,{asKey:"maximumSAPPeriod",parser:Ye,dashName:"maximumSAPPeriod"});break;case"mimeType":e.mimeType=o.value;break;case"profiles":e.profiles=o.value;break;case"segmentProfiles":e.segmentProfiles=o.value;break;case"width":r(o.value,{asKey:"width",parser:be,dashName:"width"});break;case"availabilityTimeOffset":r(o.value,{asKey:"availabilityTimeOffset",parser:Ye,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(o.value,{asKey:"availabilityTimeComplete",parser:Ge,dashName:"availabilityTimeComplete"});break}}return[e,t]}function Uf(n){let e=n.childNodes,[t,r]=fy(e),[i,o]=my(n),a=r.concat(o);return[{children:t,attributes:i},a]}function Jd(n){let e={children:{events:[]},attributes:{}},t=[],r=xe(e.attributes,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"schemeIdUri":e.attributes.schemeIdUri=o.value;break;case"timescale":r(o.value,{asKey:"timescale",parser:be,dashName:"timescale"});break;case"value":e.attributes.value=o.value;break}}for(let i=0;i<n.childNodes.length;i++)if(n.childNodes[i].nodeType===Node.ELEMENT_NODE){let o=n.childNodes[i];switch(o.nodeName){case"Event":{let[a,s]=py(o);e.children.events.push(a),s.length>0&&(t=t.concat(s));break}}}return[e,t]}function py(n){let e={eventStreamData:n},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"presentationTime":r(o.value,{asKey:"presentationTime",parser:be,dashName:"presentationTime"});break;case"duration":r(o.value,{asKey:"duration",parser:be,dashName:"duration"});break;case"id":e.id=o.value;break}}return[e,t]}function gy(n){let e=[],t=[],r,i=[],o=[],a=[];for(let s=0;s<n.length;s++)if(n[s].nodeType===Node.ELEMENT_NODE){let d=n[s];switch(d.nodeName){case"BaseURL":{let[u,l]=Ot(d);u!==void 0&&e.push(u),o=o.concat(l);break}case"AdaptationSet":{let[u,l]=Uf(d);t.push(u),o=o.concat(l);break}case"EventStream":{let[u,l]=Jd(d);a.push(u),o=o.concat(l);break}case"SegmentTemplate":{let[u,l]=Cn(d);r=u,l.length>0&&(o=o.concat(l));break}case"ContentProtection":{let[u,l]=Dt(d);l.length>0&&(o=o.concat(l)),u!==void 0&&i.push(u);break}}}return[{baseURLs:e,adaptations:t,eventStreams:a,segmentTemplate:r,contentProtections:i},o]}function hy(n){let e={},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"id":e.id=o.value;break;case"start":r(o.value,{asKey:"start",parser:gt,dashName:"start"});break;case"duration":r(o.value,{asKey:"duration",parser:gt,dashName:"duration"});break;case"bitstreamSwitching":r(o.value,{asKey:"bitstreamSwitching",parser:Ge,dashName:"bitstreamSwitching"});break;case"xlink:href":e.xlinkHref=o.value;break;case"xlink:actuate":e.xlinkActuate=o.value;break}}return[e,t]}function ma(n){let[e,t]=gy(n.childNodes),[r,i]=hy(n),o=t.concat(i);return[{children:e,attributes:r},o]}function yy(n){let e=[],t=[],r=[],i=[],o=[],a=[];for(let s=0;s<n.length;s++)if(n[s].nodeType===Node.ELEMENT_NODE){let d=n[s];switch(d.nodeName){case"BaseURL":{let[u,l]=Ot(d);u!==void 0&&e.push(u),a=a.concat(l);break}case"Location":t.push(d.textContent===null?"":d.textContent);break;case"Period":{let[u,l]=ma(d);r.push(u),a=a.concat(l);break}case"UTCTiming":{let u=He(d);i.push(u);break}case"ContentProtection":{let[u,l]=Dt(d);l.length>0&&(a=a.concat(l)),u!==void 0&&o.push(u);break}}}return[{baseURLs:e,locations:t,periods:r,utcTimings:i,contentProtections:o},a]}function Iy(n){let e={},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"id":e.id=o.value;break;case"profiles":e.profiles=o.value;break;case"type":e.type=o.value;break;case"availabilityStartTime":r(o.value,{asKey:"availabilityStartTime",parser:fa,dashName:"availabilityStartTime"});break;case"availabilityEndTime":r(o.value,{asKey:"availabilityEndTime",parser:fa,dashName:"availabilityEndTime"});break;case"publishTime":r(o.value,{asKey:"publishTime",parser:fa,dashName:"publishTime"});break;case"mediaPresentationDuration":r(o.value,{asKey:"duration",parser:gt,dashName:"mediaPresentationDuration"});break;case"minimumUpdatePeriod":r(o.value,{asKey:"minimumUpdatePeriod",parser:gt,dashName:"minimumUpdatePeriod"});break;case"minBufferTime":r(o.value,{asKey:"minBufferTime",parser:gt,dashName:"minBufferTime"});break;case"timeShiftBufferDepth":r(o.value,{asKey:"timeShiftBufferDepth",parser:gt,dashName:"timeShiftBufferDepth"});break;case"suggestedPresentationDelay":r(o.value,{asKey:"suggestedPresentationDelay",parser:gt,dashName:"suggestedPresentationDelay"});break;case"maxSegmentDuration":r(o.value,{asKey:"maxSegmentDuration",parser:gt,dashName:"maxSegmentDuration"});break;case"maxSubsegmentDuration":r(o.value,{asKey:"maxSubsegmentDuration",parser:gt,dashName:"maxSubsegmentDuration"});break}}return[e,t]}function Bf(n){let[e,t]=yy(n.childNodes),[r,i]=Iy(n),o=t.concat(i);return[{children:e,attributes:r},o]}function eu(n,e){let t=n.documentElement;if(_(t)||t.nodeName!=="MPD")throw new Error("DASH Parser: document root should be MPD");let[r,i]=Bf(t),o=Df(r,e,i);return a(o);function a(s){if(s.type==="done")return s;if(s.type==="needs-clock")return{type:"needs-resources",value:{urls:[s.value.url],format:"string",continue(d){if(d.length!==1)throw new Error("DASH parser: wrong number of loaded ressources.");let u=s.value.continue(d[0].responseData);return a(u)}}};if(s.type==="needs-xlinks")return{type:"needs-resources",value:{urls:s.value.xlinksUrls,format:"string",continue(d){let u=[];for(let c=0;c<d.length;c++){let{responseData:f,receivedTime:g,sendingTime:p,url:I}=d[c];if(!f.success)throw f.error;let y="<root>"+f.data+"</root>",b=new DOMParser().parseFromString(y,"text/xml");if(_(b)||b.children.length===0)throw new Error("DASH parser: Invalid external ressources");let T=b.children[0].children,v=[],E=[];for(let R=0;R<T.length;R++)if(T[R].nodeType===Node.ELEMENT_NODE){let[k,x]=ma(T[R]);E.push(...x),v.push(k)}u.push({url:I,receivedTime:g,sendingTime:p,parsed:v,warnings:E})}let l=s.value.continue(u);return a(l)}}};Xe(s)}}var Ff=eu;function $e(n,e){if(e.length===0)return n;let t,r="",i=n.indexOf("#"),o=n;i>=0&&(r=n.substring(i),o=n.substring(0,i));let a=o.indexOf("?");a===-1?t="?":a+1===o.length?t="":t="&";let s=o+t;for(let d=0;d<e.length;d++){let u=e[d];u[1]===null?s+=u[0]:s+=`${u[0]}=${u[1]}`,d<e.length-1&&(s+="&")}return r.length>0&&(s+=r),s}function tu(n,e){return(t,r,i)=>new Promise((o,a)=>{let s=Date.now()-F(),d=!1,f={reject:I=>{var v,E;if(d||i.isCancelled())return;d=!0,i.deregister(p);let y=I,b=(v=y==null?void 0:y.message)!=null?v:"Unknown error when fetching the Manifest through a custom manifestLoader.",T=new rt(b,(E=y==null?void 0:y.canRetry)!=null?E:!1,y==null?void 0:y.xhr);a(T)},resolve:I=>{if(d||i.isCancelled())return;d=!0,i.deregister(p);let y=I.receivingTime!==void 0?I.receivingTime-s:void 0,b=I.sendingTime!==void 0?I.sendingTime-s:void 0;o({responseData:I.data,size:I.size,requestDuration:I.duration,url:I.url,receivedTime:y,sendingTime:b})},fallback:()=>{d||i.isCancelled()||(d=!0,i.deregister(p),e(t,r,i).then(o,a))}},g=n({url:t,timeout:r.timeout,cmcdPayload:r.cmcdPayload},f);i.register(p);function p(I){d||(d=!0,typeof g=="function"&&g(),a(I))}})}function by(n){return function(t,r,i){var s,d;if(t===void 0)throw new Error("Cannot perform HTTP(s) request. URL not known");let o=((s=r.cmcdPayload)==null?void 0:s.type)==="query"?$e(t,r.cmcdPayload.value):t,a=((d=r.cmcdPayload)==null?void 0:d.type)==="headers"?r.cmcdPayload.value:void 0;switch(n){case"arraybuffer":return Te({url:o,headers:a,responseType:"arraybuffer",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});case"text":return Te({url:o,headers:a,responseType:"text",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});case"document":return Te({url:o,headers:a,responseType:"document",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});default:Xe(n)}}}function Ui({customManifestLoader:n},e,t){let r=by(e),i=typeof n!="function"?r:tu(n,r);return t!==null?t(i):i}function en(n,e){if(e){if(It(n,1718909296)<0)throw new Le("INTEGRITY_ERROR","Incomplete `ftyp` box");if(It(n,1836019574)<0)throw new Le("INTEGRITY_ERROR","Incomplete `moov` box")}else{if(It(n,1836019558)<0)throw new Le("INTEGRITY_ERROR","Incomplete `moof` box");if(It(n,1835295092)<0)throw new Le("INTEGRITY_ERROR","Incomplete `mdat` box")}}function ht(n,e){if(n==="audio"||n==="video")return e==="video/mp4"||e==="audio/mp4"?"mp4":e==="video/webm"||e==="audio/webm"?"webm":void 0;if(n==="text")return e==="application/mp4"?"mp4":void 0}function pa(n){return(e,t,r,i,o)=>{return new Promise((s,d)=>{let u=new B,l=u.linkToSignal(i);u.signal.register(d),n(e,t,r,u.signal,ue(oe({},o),{onNewChunk(f){try{a(f),o.onNewChunk(f)}catch(g){c(),u.cancel(),d(g)}}})).then(f=>{if(c(),!u.isUsed()){if(f.resultType==="segment-loaded")try{a(f.resultData.responseData)}catch(g){d(g);return}s(f)}},f=>{c(),d(f)});function c(){u.signal.deregister(d),l()}});function a(s){!(s instanceof ArrayBuffer)&&!(s instanceof Uint8Array)||ht(t.type,t.mimeType)!=="mp4"||en(new Uint8Array(s),t.segment.isInit)}}}function Kf(n){return async(e,t,r)=>{let i=await n(e,t,r);return o(i.responseData),i;function o(a){if(typeof a=="string"){let s=a.length-1,d=["</","MPD",">"];for(let u=d.length-1;u>=0;u--){let l=d[u];for(;Sy(a[s]);)s--;for(let c=l.length-1;c>=0;c--){if(a[s]!==l[c])throw new Error("INTEGRITY_ERROR MPD does not end with </MPD>");s--}}}else if(a instanceof ArrayBuffer){let s=a.byteLength-1,d=new DataView(a),u=[[60,47],[77,80,68],[62]];for(let l=u.length-1;l>=0;l--){let c=u[l];for(;Ty(d.getUint8(s));)s--;for(let f=c.length-1;f>=0;f--){if(d.getUint8(s)!==c[f])throw new Error("INTEGRITY_ERROR MPD does not end with </MPD>");s--}}}else if(!_(J.Document)&&a instanceof J.Document&&a.documentElement.nodeName!=="MPD")throw new Le("INTEGRITY_ERROR","MPD does not end with </MPD>")}}}function Sy(n){return n===" "||n===" "||n==="\r"||n===`
|
|
5
|
-
`}function Ty(n){return n===32||n===9||n===13||n===10}function nu(n){let{referenceDateTime:e}=n,t=n.serverSyncInfos!==void 0?n.serverSyncInfos.serverTimestamp-n.serverSyncInfos.clientTime:void 0;return function(i,o,a,s,d){var T;let{responseData:u}=i,l=o.externalClockOffset,c=(T=i.url)!=null?T:o.originalUrl,f=t!=null?t:l,p={unsafelyBaseOnPreviousManifest:o.unsafeMode?o.previousManifest:null,url:c,referenceDateTime:e,externalClockOffset:f},I=me.dashParsers;if(I.wasm===null||I.wasm.status==="uninitialized"||I.wasm.status==="failure")return m.debug("DASH: WASM MPD Parser not initialized. Running JS one."),y();{let v=ky(u);if(!Cy(v))return m.info("DASH: MPD doesn't seem to be UTF-8-encoded. Running JS parser instead of the WASM one."),y();if(I.wasm.status==="initialized"){m.debug("DASH: Running WASM MPD Parser.");let E=I.wasm.runWasmParser(v,p);return b(E)}else return m.debug("DASH: Awaiting WASM initialization before parsing the MPD."),I.wasm.waitForInitialization().catch(()=>{}).then(()=>{if(I.wasm===null||I.wasm.status!=="initialized")return m.warn("DASH: WASM MPD parser initialization failed. Running JS parser instead"),y();m.debug("DASH: Running WASM MPD Parser.");let R=I.wasm.runWasmParser(v,p);return b(R)})}function y(){if(I.fastJs!==null){let v=vy(u),E=I.fastJs(v,p);return b(E)}else if(I.native!==null){let v=Ry(u),E=I.native(v,p);return b(E)}else throw new Error("No MPD parser is imported")}function b(v){if(v.type==="done"){if(v.value.warnings.length>0&&a(v.value.warnings),s.isCancelled())return Promise.reject(s.cancellationError);let k=[];return{manifest:new zn(v.value.parsed,n,k),url:c,warnings:k}}let{value:E}=v,R=E.urls.map(k=>d(()=>{let x=U.getCurrent().DEFAULT_REQUEST_TIMEOUT,M=U.getCurrent().DEFAULT_CONNECTION_TIMEOUT;return E.format==="string"?Te({url:k,responseType:"text",timeout:x,connectionTimeout:M,cancelSignal:s}):Te({url:k,responseType:"arraybuffer",timeout:x,connectionTimeout:M,cancelSignal:s})}).then(x=>{if(E.format==="string"){if(typeof x.responseData!="string")throw new Error("External DASH resources should have been a string");return G(x,{responseData:{success:!0,data:x.responseData}})}else{if(!(x.responseData instanceof ArrayBuffer))throw new Error("External DASH resources should have been ArrayBuffers");return G(x,{responseData:{success:!0,data:x.responseData}})}},x=>{let M=Oe(x,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"An unknown error occured when parsing ressources."});return G({},{size:void 0,requestDuration:void 0,responseData:{success:!1,error:M}})}));return Promise.all(R).then(k=>E.format==="string"?(_y(k),b(E.continue(k))):(Ey(k),b(E.continue(k))))}}}function _y(n){h.CURRENT_ENV!==h.PRODUCTION&&n.forEach(e=>{let{responseData:t}=e;if(!(t.success&&typeof t.data=="string")&&t.success)throw new Error("Invalid data given to the LoadedRessource")})}function Ey(n){h.CURRENT_ENV!==h.PRODUCTION&&n.forEach(e=>{let{responseData:t}=e;if(!(t.success&&t.data instanceof ArrayBuffer)&&t.success)throw new Error("Invalid data given to the LoadedRessource")})}function vy(n){if(n instanceof ArrayBuffer)return Ne(new Uint8Array(n));if(typeof n=="string")return n;if(n instanceof Document)return n.documentElement.outerHTML;throw new Error("DASH Manifest Parser: Unrecognized Manifest format")}function Ry(n){if(n instanceof ArrayBuffer)return new DOMParser().parseFromString(Ne(new Uint8Array(n)),"text/xml");if(typeof n=="string")return new DOMParser().parseFromString(n,"text/xml");if(n instanceof Document)return n;throw new Error("DASH Manifest Parser: Unrecognized Manifest format")}function ky(n){if(n instanceof ArrayBuffer)return n;if(typeof n=="string")return ve(n).buffer;if(n instanceof Document)return ve(n.documentElement.innerHTML).buffer;throw new Error("DASH Manifest Parser: Unrecognized Manifest format")}function Cy(n){let e=new DataView(n);return e.getUint16(0)===61371&&e.getUint8(2)===191?!0:!(e.getUint16(0)===65279||e.getUint16(0)===65534)}function ut([n,e]){return e===1/0?`bytes=${n}-`:`bytes=${n}-${e}`}function Bi(n,e){return n===null?null:e.url===null?n.baseUrl:cn(n.baseUrl,e.url)}function Fi(n,e,t,r,i){var u,l;let o=n;((u=t.cmcdPayload)==null?void 0:u.type)==="query"&&(o=$e(o,t.cmcdPayload.value));let a=((l=t.cmcdPayload)==null?void 0:l.type)==="headers"?t.cmcdPayload.value:void 0;if(e.range===void 0)return Te({url:o,responseType:"arraybuffer",headers:a,timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(c=>({resultType:"segment-loaded",resultData:c}));if(e.indexRange===void 0)return Te({url:o,headers:ue(oe({},a),{Range:ut(e.range)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(c=>({resultType:"segment-loaded",resultData:c}));if(e.range[1]+1===e.indexRange[0])return Te({url:o,headers:ue(oe({},a),{Range:ut([e.range[0],e.indexRange[1]])}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(c=>({resultType:"segment-loaded",resultData:c}));let s=Te({url:o,headers:ue(oe({},a),{Range:ut(e.range)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}),d=Te({url:o,headers:ue(oe({},a),{Range:ut(e.indexRange)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress});return Promise.all([s,d]).then(([c,f])=>{let g=ie(new Uint8Array(c.responseData),new Uint8Array(f.responseData)),p=Math.min(c.sendingTime,f.sendingTime),I=Math.max(c.receivedTime,f.receivedTime);return{resultType:"segment-loaded",resultData:{url:o,responseData:g,size:c.size+f.size,requestDuration:I-p,sendingTime:p,receivedTime:I}}})}async function Ki(n,e,t,r){let i=null;function o(s){let d=new Uint8Array(s.chunk),u=i!==null?ie(i,d):d,l=Fo(u),c=l[0];i=l[1],!(c!==null&&(c.forEach(f=>{t.onNewChunk(f)}),r.isCancelled()))&&(t.onProgress({duration:s.duration,size:s.size,totalSize:s.totalSize}),r.isCancelled())}return{resultType:"chunk-complete",resultData:await To({url:n,headers:e.headers,onData:o,timeout:e.timeout,connectionTimeout:e.connectionTimeout,cancelSignal:r})}}async function Vf(n,e,t,r,i,o){var f,g;if(e.segment.isInit)return Fi(n,e.segment,r,o,i);let a=((f=r.cmcdPayload)==null?void 0:f.type)==="query"?$e(n,r.cmcdPayload.value):n,s=((g=r.cmcdPayload)==null?void 0:g.type)==="headers"?r.cmcdPayload.value:void 0,{segment:d}=e,u;d.range!==void 0?u=ue(oe({},s),{Range:ut(d.range)}):s!==void 0&&(u=s);let l=ht(e.type,e.mimeType);if(t&&(l==="mp4"||l===void 0)){if(vr())return Ki(a,{headers:u,timeout:r.timeout,connectionTimeout:r.connectionTimeout},i,o);Pt("DASH: Your browser does not have the fetch API. You will have a higher chance of rebuffering when playing close to the live edge")}return{resultType:"segment-loaded",resultData:await Te({url:a,responseType:"arraybuffer",headers:u,timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:o,onProgress:i.onProgress})}}function ru({lowLatencyMode:n,segmentLoader:e,checkMediaSegmentIntegrity:t}){return t!==!0?r:pa(r);function r(i,o,a,s,d){let u=Bi(i,o.segment);return u===null?Promise.resolve({resultType:"segment-created",resultData:null}):n||e===void 0?Vf(u,o,n,a,d,s):new Promise((l,c)=>{let f=!1,b={reject:k=>{var N,O;if(f||s.isCancelled())return;f=!0,s.deregister(R);let x=k,M=(N=x==null?void 0:x.message)!=null?N:"Unknown error when fetching a DASH segment through a custom segmentLoader.",P=new rt(M,(O=x==null?void 0:x.canRetry)!=null?O:!1,x==null?void 0:x.xhr);c(P)},resolve:k=>{f||s.isCancelled()||(f=!0,s.deregister(R),l({resultType:"segment-loaded",resultData:{responseData:k.data,size:k.size,requestDuration:k.duration}}))},progress:k=>{f||s.isCancelled()||d.onProgress({duration:k.duration,size:k.size,totalSize:k.totalSize})},fallback:()=>{f||s.isCancelled()||(f=!0,s.deregister(R),Vf(u,o,n,a,d,s).then(l,c))}},T;o.segment.range!==void 0&&(T=[o.segment.range],o.segment.indexRange!==void 0&&T.push(o.segment.indexRange));let v={isInit:o.segment.isInit,timeout:a.timeout,byteRanges:T,trackType:o.type,url:u,cmcdPayload:a.cmcdPayload},E=e(v,b);s.register(R);function R(k){f||(f=!0,typeof E=="function"&&E(),c(k))}})}}var ou=408125543,zf=357149030,Py=2807729,My=17545,Ay=475249515,xy=187,wy=179,Oy=183,Dy=241;function tn(n,e,t,[r,i]){let o=r;for(;o<i;){let a=Ny(t,o);if(a===null)return null;let{value:s,length:d}=a,u=o+d,l=Uy(t,u);if(l===null)return null;let{length:c,value:f}=l,g=u+c,p=g+f;if(s===n)return[g,p];if(e.length>0){for(let I=0;I<e.length;I++)if(s===e[I]){let y=e.slice(I+1,e.length);return tn(n,y,t,[g,p])}}o=p}return null}function ga(n,e){let t=tn(Py,[ou,zf],n,[e,n.length]);if(t===null)return null;let r=t[1]-t[0];return 1e9/iu(n,t[0],r)}function Ly(n,e){let t=tn(My,[ou,zf],n,[e,n.length]);if(t===null)return null;let r=t[1]-t[0];return r===4?By(n,t[0]):r===8?Fy(n,t[0]):null}function au(n,e){let t=tn(ou,[],n,[e,n.length]);if(t===null)return null;let[r,i]=t,o=ga(n,r);if(o===null)return null;let a=Ly(n,r);if(a===null)return null;let s=tn(Ay,[],n,[r,i]);if(s===null)return null;let d=[],u=s[0];for(;u<s[1];){let c=tn(xy,[],n,[u,s[1]]);if(c===null)break;let f=tn(wy,[],n,[c[0],c[1]]);if(f===null)return null;let g=iu(n,f[0],f[1]-f[0]),p=tn(Dy,[Oy],n,[c[0],c[1]]);if(p===null)return null;let I=iu(n,p[0],p[1]-p[0])+r;d.push({time:g,rangeStart:I}),u=c[1]}let l=[];for(let c=0;c<d.length;c++){let f=d[c];c===d.length-1?l.push({time:f.time,timescale:o,duration:c===0?a:a-f.time,range:[f.rangeStart,1/0]}):l.push({time:f.time,timescale:o,duration:d[c+1].time-f.time,range:[f.rangeStart,d[c+1].rangeStart-1]})}return l}function Hf(n,e){for(let t=1;t<=8;t++)if(n[e]>=Math.pow(2,8-t))return t}function Ny(n,e){let t=Hf(n,e);if(t===void 0)return m.warn("webm: unrepresentable length"),null;if(e+t>n.length)return m.warn("webm: impossible length"),null;let r=0;for(let i=0;i<t;i++)r=n[e+i]*Math.pow(2,(t-i-1)*8)+r;return{length:t,value:r}}function Uy(n,e){let t=Hf(n,e);if(t===void 0)return m.warn("webm: unrepresentable length"),null;if(e+t>n.length)return m.warn("webm: impossible length"),null;let r=(n[e]&(1<<8-t)-1)*Math.pow(2,(t-1)*8);for(let i=1;i<t;i++)r=n[e+i]*Math.pow(2,(t-i-1)*8)+r;return{length:t,value:r}}function By(n,e){return new DataView(n.buffer).getFloat32(e)}function Fy(n,e){return new DataView(n.buffer).getFloat64(e)}function iu(n,e,t){let r=0;for(let i=0;i<t;i++)r=n[e+i]*Math.pow(2,(t-i-1)*8)+r;return r}function Vi(n,e,t,r){let i=Rs(n);if(i===void 0||r===void 0)return null;let o=t.timestampOffset!==void 0?i+t.timestampOffset*r:i,a=Ur(n);if(o<0&&(a!==void 0&&(a+=o),o=0),e||!t.complete)return a===void 0&&m.warn("DASH: Chunked segments should indicate a duration through their trun boxes"),{time:o/r,duration:a!==void 0?a/r:void 0};let s,d=t.duration*r,u=Math.min(r*.9,d/4);return a!==void 0&&Math.abs(a-d)<=u&&(s=a),{time:o/r,duration:s!==void 0?s/r:s}}function Ky(n,e){if(n.length<=0)return!1;let t=n.length;for(let r=0;r<t;r++){let i=n[r],o=e,{messageData:a}=i,s=Ne(a),d=Date.parse(s);if(o===void 0||d===void 0||isNaN(d)||d>=o)return!0}return!1}function su(n,e){if(n.length===0)return;let{manifestRefreshEventsFromEMSGs:t,EMSGs:r}=n.reduce((a,s)=>(s.schemeIdUri==="urn:mpeg:dash:event:2012"&&s.value==="1"?(a.manifestRefreshEventsFromEMSGs===void 0&&(a.manifestRefreshEventsFromEMSGs=[]),a.manifestRefreshEventsFromEMSGs.push(s)):(a.EMSGs===void 0&&(a.EMSGs=[]),a.EMSGs.push(s)),a),{manifestRefreshEventsFromEMSGs:void 0,EMSGs:void 0}),i=r==null?void 0:r.map(a=>({type:"emsg",value:a})),o=e===void 0||t===void 0?!1:Ky(t,e);return{inbandEvents:i,needsManifestRefresh:o}}function du({__priv_patchLastSegmentInSidx:n}){return function(t,r,i){var v,E;let{segment:o,periodStart:a,periodEnd:s}=r,{data:d,isChunked:u}=t,l=[a,s];if(d===null)return o.isInit?{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0}:{segmentType:"media",chunkData:null,chunkSize:0,chunkInfos:null,chunkOffset:0,protectionData:[],appendWindow:l};let c=d instanceof Uint8Array?d:new Uint8Array(d),f=ht(r.type,r.mimeType),g=f==="mp4"||f===void 0,p=[];if(g){let R=Ko(c),k;o.isInit&&(k=(v=Bc(c))!=null?v:void 0),(R.length>0||k!==void 0)&&p.push({initDataType:"cenc",keyId:k,initData:R})}if(!o.isInit){let R=g?Vi(c,u,o,i):null,k=(E=o.timestampOffset)!=null?E:0;if(g){let x=Uc(c);if(x!==void 0){let M=x.filter(N=>o.privateInfos===void 0||o.privateInfos.isEMSGWhitelisted===void 0?!1:o.privateInfos.isEMSGWhitelisted(N)),P=su(M,r.manifestPublishTime);if(P!==void 0){let{needsManifestRefresh:N,inbandEvents:O}=P;return{segmentType:"media",chunkData:c,chunkSize:c.length,chunkInfos:R,chunkOffset:k,appendWindow:l,inbandEvents:O,protectionData:p,needsManifestRefresh:N}}}}return{segmentType:"media",chunkData:c,chunkSize:c.length,chunkInfos:R,chunkOffset:k,protectionData:p,appendWindow:l}}let{indexRange:I}=o,y;if(f==="webm")y=au(c,0);else if(g&&(y=Nr(c,Array.isArray(I)?I[0]:0),n===!0&&y!==null&&y.length>0)){let R=y[y.length-1];Array.isArray(R.range)&&(R.range[1]=1/0)}let b;g?b=Br(c):f==="webm"&&(b=ga(c,0));let T=_(b)?void 0:b;return{segmentType:"init",initializationData:c,initializationDataSize:c.length,protectionData:p,initTimescale:T,segmentList:y!=null?y:void 0}}}function uu({lowLatencyMode:n,checkMediaSegmentIntegrity:e}){return e!==!0?t:pa(t);async function t(r,i,o,a,s){var y,b;let{segment:d}=i,u=Bi(r,d);if(u===null)return Promise.resolve({resultType:"segment-created",resultData:null});if(d.isInit)return Fi(u,d,o,a,s);let l=((y=o.cmcdPayload)==null?void 0:y.type)==="query"?$e(u,o.cmcdPayload.value):u,c=((b=o.cmcdPayload)==null?void 0:b.type)==="headers"?o.cmcdPayload.value:void 0,f;d.range!==void 0?f=ue(oe({},c),{Range:ut(d.range)}):c!==void 0&&(f=c);let g=ht(i.type,i.mimeType),p=g==="mp4"||g===void 0;if(n&&p){if(vr())return Ki(l,{headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout},s,a);Pt("DASH: Your browser does not have the fetch API. You will have a higher chance of rebuffering when playing close to the live edge")}let I;return p?I=await Te({url:l,responseType:"arraybuffer",headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout,onProgress:s.onProgress,cancelSignal:a}):I=await Te({url:l,responseType:"text",headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout,onProgress:s.onProgress,cancelSignal:a}),{resultType:"segment-loaded",resultData:I}}}function Vy(n){let e=Dr(n);return e===null?"":Ne(e)}function zy(n){if(n===void 0)throw new Error("Cannot parse subtitles: unknown format");switch(n.toLowerCase()){case"stpp":case"stpp.ttml":case"stpp.ttml.im1t":return"ttml";case"wvtt":return"vtt"}throw new Error(`The codec used for the subtitles "${n}" is not managed yet.`)}function Hy(n,e){switch(e){case"application/ttml+xml":return"ttml";case"application/x-sami":case"application/smil":return"sami";case"text/vtt":return"vtt"}if(n!==void 0&&n.toLowerCase()==="srt")return"srt";throw new Error(`could not find a text-track parser for the type ${e!=null?e:""}`)}function Wf({segment:n,language:e,codecs:t},r,i,o){if(n.isInit)return null;let a,s;i===null?o?(a=n.time,s=n.end):m.warn("Transport: Unavailable time data for current text track."):(a=i.time,i.duration!==void 0?s=a+i.duration:!o&&n.complete&&(s=a+n.duration));let d=zy(t);return{data:Vy(r),type:d,language:e,start:a,end:s}}function Gf(n,e,t){let{segment:r}=n;if(r.isInit)return null;let i,o;t?m.warn("Transport: Unavailable time data for current text track."):(i=r.time,r.complete&&(o=r.time+r.duration));let a=Hy(n.codecs,n.mimeType);return{data:e,type:a,language:n.language,start:i,end:o}}function Wy(n,e,t,r,i){var f;let{segment:o}=t,{isInit:a,indexRange:s}=o,d;if(typeof n=="string"?d=ve(n):n instanceof Uint8Array?d=n:d=new Uint8Array(n),a){let g=Nr(d,Array.isArray(s)?s[0]:0);if(i===!0&&g!==null&&g.length>0){let I=g[g.length-1];Array.isArray(I.range)&&(I.range[1]=1/0)}let p=Br(d);return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:p,segmentList:g!=null?g:void 0}}let u=Vi(d,e,o,r),l=Wf(t,d,u,e),c=(f=o.timestampOffset)!=null?f:0;return{segmentType:"media",chunkData:l,chunkSize:d.length,chunkInfos:u,chunkOffset:c,protectionData:[],appendWindow:[t.periodStart,t.periodEnd]}}function Gy(n,e,t){let{periodStart:r,periodEnd:i,segment:o}=t,{timestampOffset:a=0}=o;if(o.isInit)return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0};let s,d;if(typeof n!="string"){let l=n instanceof Uint8Array?n:new Uint8Array(n);s=Ne(l),d=l.length}else s=n;return{segmentType:"media",chunkData:Gf(t,s,e),chunkSize:d,chunkInfos:null,chunkOffset:a,protectionData:[],appendWindow:[r,i]}}function lu({__priv_patchLastSegmentInSidx:n}){return function(t,r,i){var c;let{periodStart:o,periodEnd:a,segment:s}=r,{data:d,isChunked:u}=t;if(d===null)return s.isInit?{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0}:{segmentType:"media",chunkData:null,chunkSize:0,chunkInfos:null,chunkOffset:(c=s.timestampOffset)!=null?c:0,protectionData:[],appendWindow:[o,a]};let l=ht(r.type,r.mimeType);if(l==="webm")throw new Error("Text tracks with a WEBM container are not yet handled.");return l==="mp4"?Wy(d,u,r,i,n):Gy(d,u,r)}}function qf(n){let e=Ui({customManifestLoader:n.manifestLoader},qy()?"text":"arraybuffer",n.checkManifestIntegrity===!0?Kf:null),t=nu(n),r=ru(n),i=du(n),o=uu(n),a=lu(n);return{transportName:"dash",manifest:{loadManifest:e,parseManifest:t},audio:{loadSegment:r,parseSegment:i},video:{loadSegment:r,parseSegment:i},text:{loadSegment:o,parseSegment:a}}}function qy(){return me.dashParsers.wasm!==null&&(me.dashParsers.wasm.status==="initialized"||me.dashParsers.wasm.status==="initializing")}var jf=qf;function cu(n){n.transports.dash===void 0&&(n.transports.dash=jf),n.dashParsers.native=Ff,n.mainThreadMediaSourceInit=_n}var jy=typeof MediaSource=="function"&&MediaSource.canConstructInDedicatedWorker===!0,Yf=jy;var zi=class extends qn{constructor(e){super(),this._settings=e,this._initCanceller=new B}prepare(){}start(e,t){let r=this._initCanceller.signal,{keySystems:i,speed:o,url:a}=this._settings;jn(e);let{statusRef:s}=_i(e,i,{onError:u=>this._onFatalError(u),onWarning:u=>this.trigger("warning",u),onBlackListProtectionData:X,onKeyIdsCompatibilityUpdate:X},r);ki(e,u=>this._onFatalError(u),r);let d=new Tn(t,null,o);d.addEventListener("stalled",u=>this.trigger("stalled",u)),d.addEventListener("unstalled",()=>this.trigger("unstalled",null)),d.addEventListener("warning",u=>this.trigger("warning",u)),r.register(()=>{d.destroy()}),d.start(),s.onUpdate((u,l)=>{u.initializationState.type!=="uninitialized"&&(l(),m.info("Setting URL to HTMLMediaElement",a),e.src=a,r.register(()=>{m.info("Init: Removing directfile src from media element",e.src),jn(e)}),u.initializationState.type==="awaiting-media-link"?(u.initializationState.value.isMediaLinked.setValue(!0),s.onUpdate((c,f)=>{c.initializationState.type==="initialized"&&(f(),this._seekAndPlay(e,t))},{emitCurrentValue:!0,clearSignal:r})):(ee(u.initializationState.type==="initialized"),this._seekAndPlay(e,t)))},{emitCurrentValue:!0,clearSignal:r})}updateContentUrls(e,t){throw new Error("Cannot update content URL of directfile contents")}dispose(){this._initCanceller.cancel()}_onFatalError(e){this._initCanceller.cancel(),this.trigger("error",e)}_seekAndPlay(e,t){let r=this._initCanceller.signal,{autoPlay:i,startAt:o}=this._settings;Ti({mediaElement:e,playbackObserver:t,startTime:()=>{m.debug("Init: Calculating initial time");let s=Yy(e,o);return m.debug("Init: Initial time calculated:",s),s},mustAutoPlay:i,onWarning:s=>this.trigger("warning",s),isDirectfile:!0},r).autoPlayResult.then(()=>Si(t,e,!0,r).onUpdate((s,d)=>{s&&(d(),this.trigger("loaded",{getSegmentSinkMetrics:null}))},{emitCurrentValue:!0,clearSignal:r})).catch(s=>{r.isCancelled()||this._onFatalError(s)})}};function Yy(n,e){if(_(e))return 0;if(_(e.position))if(_(e.wallClockTime)){if(!_(e.fromFirstPosition))return e.fromFirstPosition}else return e.wallClockTime;else return e.position;let t=n.duration;if(typeof e.fromLastPosition=="number"){if(!_(t)&&isFinite(t))return Math.max(0,t+e.fromLastPosition);if(n.seekable.length>0){let r=n.seekable.end(n.seekable.length-1);if(isFinite(r))return Math.max(0,r+e.fromLastPosition)}m.warn("Init: startAt.fromLastPosition set but no known duration, it may be too soon to seek");return}else if(typeof e.fromLivePosition=="number"){let r=n.seekable.length>0?n.seekable.end(0):t;return _(r)?(m.warn("Init: startAt.fromLivePosition set but no known live position, beginning at 0."),0):Math.max(0,r+e.fromLivePosition)}else if(!_(e.percentage)){if(_(t)||!isFinite(t))return m.warn("Init: startAt.percentage set but no known duration, beginning at 0."),0;let{percentage:r}=e;if(r>=100)return t;if(r<=0)return 0;let i=+r/100;return t*i}return 0}function fu(n,e){for(let t=0;t<n.length;t++)(!dr||t!==e)&&(n[t].enabled=!1);return e<0||e>=n.length?!1:(n[e].enabled=!0,!0)}function Jn(n,e){var t;if(e.length!==n.length)return!0;for(let r=0;r<e.length;r++)if(e[r].nativeTrack!==((t=n[r])==null?void 0:t.nativeTrack))return!0;return!1}function mu(n){var r;let e=[],t={};for(let i=0;i<n.length;i++){let o=n[i],a=o.language===""?"nolang":o.language,s=(r=t[a])!=null?r:1,d="gen_audio_"+a+"_"+s.toString();t[a]=s+1;let u={language:o.language,id:d,normalized:Rr(o.language),audioDescription:o.kind==="descriptions"||o.kind==="description",representations:[]};e.push({track:u,nativeTrack:o})}return e}function pu(n){var r;let e=[],t={};for(let i=0;i<n.length;i++){let o=n[i],a=o.language===""?"nolang":o.language,s=(r=t[a])!=null?r:1,d="gen_text_"+a+"_"+s.toString();t[a]=s+1;let u=o.kind==="forced"?!0:void 0,l={language:o.language,forced:u,label:o.label,id:d,normalized:Rr(o.language),closedCaption:o.kind==="captions"};e.push({track:l,nativeTrack:o})}return e}function gu(n){var r;let e=[],t={};for(let i=0;i<n.length;i++){let o=n[i],a=o.language===""?"nolang":o.language,s=(r=t[a])!=null?r:1,d="gen_video_"+a+"_"+s.toString();t[a]=s+1,e.push({track:{id:d,representations:[]},nativeTrack:o})}return e}var Hi=class extends re{constructor(e){var t,r,i;super(),this._nativeAudioTracks=e.audioTracks,this._nativeVideoTracks=e.videoTracks,this._nativeTextTracks=e.textTracks,this._audioTracks=this._nativeAudioTracks!==void 0?mu(this._nativeAudioTracks):[],this._videoTracks=this._nativeVideoTracks!==void 0?gu(this._nativeVideoTracks):[],this._textTracks=this._nativeTextTracks!==void 0?pu(this._nativeTextTracks):[],this._lastEmittedNativeAudioTrack=(t=this._getCurrentAudioTrack())==null?void 0:t.nativeTrack,this._lastEmittedNativeVideoTrack=(r=this._getCurrentVideoTrack())==null?void 0:r.nativeTrack,this._lastEmittedNativeTextTrack=(i=this._getCurrentTextTrack())==null?void 0:i.nativeTrack,this._handleNativeTracksCallbacks()}setAudioTrackById(e){for(let t=0;t<this._audioTracks.length;t++){let{track:r,nativeTrack:i}=this._audioTracks[t];if(r.id===e){this._enableAudioTrackFromIndex(t),this._audioTrackLockedOn=i;return}}throw new Error("Audio track not found.")}disableTextTrack(){$f(this._textTracks),this._textTrackLockedOn=null}setTextTrackById(e){let t=!1;for(let r=0;r<this._textTracks.length;r++){let{track:i,nativeTrack:o}=this._textTracks[r];i.id===e?(o.mode="showing",t=!0,this._textTrackLockedOn=o):(o.mode==="showing"||o.mode==="hidden")&&(o.mode="disabled")}if(!t)throw new Error("Text track not found.")}disableVideoTrack(){Qf(this._videoTracks),this._videoTrackLockedOn=null}setVideoTrackById(e){for(let t=0;t<this._videoTracks.length;t++){let{track:r,nativeTrack:i}=this._videoTracks[t];if(r.id===e){i.selected=!0,this._videoTrackLockedOn=i;return}}throw new Error("Video track not found.")}getChosenAudioTrack(){let e=this._getCurrentAudioTrack();return _(e)?e:e.track}getChosenTextTrack(){let e=this._getCurrentTextTrack();return _(e)?e:e.track}getChosenVideoTrack(){let e=this._getCurrentVideoTrack();return _(e)?e:e.track}getAvailableAudioTracks(){return this._audioTracks.map(({track:e,nativeTrack:t})=>({id:e.id,language:e.language,normalized:e.normalized,audioDescription:e.audioDescription,active:t.enabled,representations:e.representations}))}getAvailableTextTracks(){return this._textTracks.map(({track:e,nativeTrack:t})=>({id:e.id,label:e.label,forced:e.forced,language:e.language,normalized:e.normalized,closedCaption:e.closedCaption,active:t.mode==="showing"}))}getAvailableVideoTracks(){return this._videoTracks.map(({track:e,nativeTrack:t})=>({id:e.id,representations:e.representations,active:t.selected}))}dispose(){this._nativeVideoTracks!==void 0&&(this._nativeVideoTracks.onchange=null,this._nativeVideoTracks.onaddtrack=null,this._nativeVideoTracks.onremovetrack=null),this._nativeAudioTracks!==void 0&&(this._nativeAudioTracks.onchange=null,this._nativeAudioTracks.onaddtrack=null,this._nativeAudioTracks.onremovetrack=null),this._nativeTextTracks!==void 0&&(this._nativeTextTracks.onchange=null,this._nativeTextTracks.onaddtrack=null,this._nativeTextTracks.onremovetrack=null),this.removeEventListener()}_getCurrentAudioTrack(){if(this._nativeAudioTracks!==void 0){for(let e=0;e<this._audioTracks.length;e++){let t=this._audioTracks[e];if(t.nativeTrack.enabled)return t}return null}}_getCurrentVideoTrack(){if(this._nativeVideoTracks!==void 0){for(let e=0;e<this._videoTracks.length;e++){let t=this._videoTracks[e];if(t.nativeTrack.selected)return t}return null}}_getCurrentTextTrack(){if(this._nativeTextTracks!==void 0){for(let e=0;e<this._textTracks.length;e++){let t=this._textTracks[e];if(t.nativeTrack.mode==="showing")return t}return null}}_setPreviouslyLockedAudioTrack(){if(this._audioTrackLockedOn!==void 0)if(this._audioTrackLockedOn===null)for(let e=0;e<this._audioTracks.length;e++){let{nativeTrack:t}=this._audioTracks[e];t.enabled=!1}else for(let e=0;e<this._audioTracks.length;e++){let{nativeTrack:t}=this._audioTracks[e];if(t===this._audioTrackLockedOn){this._enableAudioTrackFromIndex(e);return}}}_setPreviouslyLockedTextTrack(){if(this._textTrackLockedOn!==void 0)if(this._textTrackLockedOn===null){$f(this._textTracks);return}else for(let e=0;e<this._textTracks.length;e++){let{nativeTrack:t}=this._textTracks[e];if(t===this._textTrackLockedOn){$y(this._textTracks,t),t.mode!=="showing"&&(t.mode="showing");return}}}_setPreviouslyLockedVideoTrack(){if(this._videoTrackLockedOn!==void 0)if(this._videoTrackLockedOn===null){Qf(this._videoTracks);return}else for(let e=0;e<this._videoTracks.length;e++){let{nativeTrack:t}=this._videoTracks[e];if(t===this._videoTrackLockedOn){t.selected=!0;return}}}_handleNativeTracksCallbacks(){this._nativeAudioTracks!==void 0&&(this._nativeAudioTracks.onaddtrack=()=>{var e,t;if(this._nativeAudioTracks!==void 0){let r=mu(this._nativeAudioTracks);if(Jn(this._audioTracks,r)){this._audioTracks=r,this._setPreviouslyLockedAudioTrack(),this.trigger("availableAudioTracksChange",this.getAvailableAudioTracks());let i=this._getCurrentAudioTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeAudioTrack&&(this.trigger("audioTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeAudioTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeAudioTracks.onremovetrack=()=>{var e,t;if(this._nativeAudioTracks!==void 0){let r=mu(this._nativeAudioTracks);if(Jn(this._audioTracks,r)){this._audioTracks=r,this.trigger("availableAudioTracksChange",this.getAvailableAudioTracks());let i=this._getCurrentAudioTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeAudioTrack&&(this.trigger("audioTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeAudioTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeAudioTracks.onchange=()=>{if(this._audioTracks!==void 0)for(let e=0;e<this._audioTracks.length;e++){let{track:t,nativeTrack:r}=this._audioTracks[e];if(r.enabled){r!==this._lastEmittedNativeAudioTrack&&(this.trigger("audioTrackChange",t),this._lastEmittedNativeAudioTrack=r);return}}this._lastEmittedNativeAudioTrack!==null&&(this.trigger("audioTrackChange",null),this._lastEmittedNativeAudioTrack=null)}),this._nativeTextTracks!==void 0&&(this._nativeTextTracks.onaddtrack=()=>{var e,t;if(this._nativeTextTracks!==void 0){let r=pu(this._nativeTextTracks);if(Jn(this._textTracks,r)){this._textTracks=r,this._setPreviouslyLockedTextTrack(),this.trigger("availableTextTracksChange",this.getAvailableTextTracks());let i=this._getCurrentTextTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeTextTrack&&(this.trigger("textTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeTextTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeTextTracks.onremovetrack=()=>{var e,t;if(this._nativeTextTracks!==void 0){let r=pu(this._nativeTextTracks);if(Jn(this._textTracks,r)){this._textTracks=r,this._setPreviouslyLockedTextTrack(),this.trigger("availableTextTracksChange",this.getAvailableTextTracks());let i=this._getCurrentTextTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeTextTrack&&(this.trigger("textTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeTextTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeTextTracks.onchange=()=>{if(this._textTracks!==void 0)for(let e=0;e<this._textTracks.length;e++){let{track:t,nativeTrack:r}=this._textTracks[e];if(r.mode==="showing"){r!==this._lastEmittedNativeTextTrack&&(this.trigger("textTrackChange",t),this._lastEmittedNativeTextTrack=r);return}}this._lastEmittedNativeTextTrack!==null&&(this.trigger("textTrackChange",null),this._lastEmittedNativeTextTrack=null)}),this._nativeVideoTracks!==void 0&&(this._nativeVideoTracks.onaddtrack=()=>{var e,t;if(this._nativeVideoTracks!==void 0){let r=gu(this._nativeVideoTracks);if(Jn(this._videoTracks,r)){this._videoTracks=r,this._setPreviouslyLockedVideoTrack(),this.trigger("availableVideoTracksChange",this.getAvailableVideoTracks());let i=this._getCurrentVideoTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeVideoTrack&&(this.trigger("videoTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeVideoTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeVideoTracks.onremovetrack=()=>{var e,t;if(this._nativeVideoTracks!==void 0){let r=gu(this._nativeVideoTracks);if(Jn(this._videoTracks,r)){this._videoTracks=r,this._setPreviouslyLockedVideoTrack(),this.trigger("availableVideoTracksChange",this.getAvailableVideoTracks());let i=this._getCurrentVideoTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeVideoTrack&&(this.trigger("videoTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeVideoTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeVideoTracks.onchange=()=>{if(this._videoTracks!==void 0)for(let e=0;e<this._videoTracks.length;e++){let{track:t,nativeTrack:r}=this._videoTracks[e];if(r.selected){r!==this._lastEmittedNativeVideoTrack&&(this.trigger("videoTrackChange",t),this._lastEmittedNativeVideoTrack=r);return}}this._lastEmittedNativeVideoTrack!==null&&(this.trigger("videoTrackChange",null),this._lastEmittedNativeVideoTrack=null)})}_enableAudioTrackFromIndex(e){fu(this._audioTracks.map(({nativeTrack:t})=>t),e)}};function $f(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.mode="disabled"}}function $y(n,e){for(let t=0;t<n.length;t++){let{nativeTrack:r}=n[t];r!==e&&(r.mode==="showing"||r.mode==="hidden")&&(r.mode="disabled")}}function Qf(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.selected=!1}}function hu(n){n.directfile={initDirectFile:zi,mediaElementTracksStore:Hi}}function yu(n){n.decrypt=$c}var Xf=J.ResizeObserver;function Iu(n,e,t){let{height:r,width:i}=n.getBoundingClientRect(),o=new H({height:r,width:i},t),a=r,s=i;if(Xf!==void 0){let d=new Xf(u=>{if(u.length===0){m.error("Compat: Resized but no observed element.");return}let l=u[0],{height:c,width:f}=l.contentRect;(c!==a||f!==s)&&(a=c,s=f,o.setValue({height:c,width:f}))});d.observe(n),t.register(()=>{d.disconnect()})}else{let d=setInterval(()=>{let{height:u,width:l}=n.getBoundingClientRect();(u!==a||l!==s)&&(a=u,s=l,o.setValue({height:u,width:l}))},e);t.register(()=>{clearInterval(d)})}return o}var Pn=class{constructor(){this._ranges=[],this.length=0}insert(e,t){h.CURRENT_ENV===h.DEV&&(ee(e>=0,"invalid start time"),ee(t-e>0,"invalid end time")),Wt(this._ranges,{start:e,end:t}),this.length=this._ranges.length}remove(e,t){h.CURRENT_ENV===h.DEV&&(ee(e>=0,"invalid start time"),ee(t-e>0,"invalid end time"));let r=[];e>0&&r.push({start:0,end:e}),t<1/0&&r.push({start:t,end:1/0}),this._ranges=Jl(this._ranges,r),this.length=this._ranges.length}start(e){if(e>=this._ranges.length)throw new Error("INDEX_SIZE_ERROR");return this._ranges[e].start}end(e){if(e>=this._ranges.length)throw new Error("INDEX_SIZE_ERROR");return this._ranges[e].end}};function bu(n,e,t,r){m.debug("HTSB: Finding parser for html text tracks:",n);let i=me.htmlTextTracksParsers[n];if(typeof i!="function")throw new Error("no parser found for the given text track");m.debug("HTSB: Parser found, parsing...");let o=i(e,t,r);return m.debug("HTTB: Parsed successfully!",o.length),o}function Nt(n,e,t=.2){return Math.abs(n-e)<=Math.min(t,.2)}var Qy=.05;function Zf(n,e){let t=n.end-n.start,r=e.end-e.start,i=Math.abs(n.start-e.start),o=Math.min(t,r,.2);return i/o<=Qy}function Wi(n,e){for(let t=n.length-1;t>=0;t--)if(n[t].start<e)return n.slice(0,t+1);return[]}function er(n,e){for(let t=0;t<n.length;t++)if(n[t].end>e)return n.slice(t,n.length);return[]}function Su(n,e,t){let r=Math.max(n.start,e),i=Wi(n.cues,e),o={start:n.start,end:r,cues:i},a=Math.min(t,n.end),s=er(n.cues,t),d={start:a,end:n.end,cues:s};return[o,d]}var Jf=.001,Xy=5,Gi=class{constructor(){this._cuesBuffer=[]}isEmpty(){return this._cuesBuffer.length===0}get(e){let t=this._cuesBuffer,r=[];for(let i=t.length-1;i>=0;i--){let o=t[i];if(e<o.end&&e>=o.start){let a=o.cues;for(let s of a)e>=s.start&&e<s.end&&r.push(s.element);if(r.length===0&&a.length>0)for(let s of a)(Nt(e,s.start,Jf)||Nt(e,s.end,Jf))&&r.push(s.element);return r}}return[]}remove(e,t){h.CURRENT_ENV===h.DEV&&(ee(e>=0),ee(t>=0),ee(t>e));let r=Math.max(e,t),i=this._cuesBuffer;for(let o=0;o<i.length;o++)if(i[o].end>e){let a=i[o];if(a.start>=r)return;if(a.end>=r){if(e<=a.start)a.cues=er(a.cues,r),a.start=r;else{let[s,d]=Su(a,e,r);this._cuesBuffer[o]=s,i.splice(o+1,0,d)}return}a.start>=e?(i.splice(o,1),o--):(a.cues=Wi(a.cues,e),a.end=Math.max(e,a.start))}}insert(e,t,r){let i=this._cuesBuffer,o={start:t,end:r,cues:e},a=Math.abs(t-r)/Xy;function s(d){let u=i[d];u===void 0||Nt(o.end,u.end,a)?i[d]=o:(u.start>=o.end||(u.cues=er(u.cues,o.end),u.start=o.end),i.splice(d,0,o))}for(let d=0;d<i.length;d++){let u=i[d];if(t<u.end){if(Zf(o,u)){if(Nt(r,u.end,a)){i[d]=o;return}else if(r<u.end){u.cues=er(u.cues,r),u.start=r,i.splice(d,0,o);return}do i.splice(d,1),u=i[d];while(u!==void 0&&r>u.end);s(d);return}else if(t<u.start){if(r<u.start){i.splice(d,0,o);return}else if(Nt(r,u.start,a)){u.start=r,i.splice(d,0,o);return}else if(Nt(r,u.end,a)){i.splice(d,1,o);return}else if(r<u.end){u.cues=er(u.cues,r),u.start=r,i.splice(d,0,o);return}do i.splice(d,1),u=i[d];while(u!==void 0&&r>u.end);s(d);return}if(Nt(u.end,r,a)){u.cues=Wi(u.cues,t),u.end=t,i.splice(d+1,0,o);return}else if(u.end>r){let[l,c]=Su(u,t,r);this._cuesBuffer[d]=l,i.splice(d+1,0,o),i.splice(d+2,0,c);return}else{u.cues=Wi(u.cues,t),u.end=t;let l=d+1;for(u=i[l];u!==void 0&&r>u.end;)i.splice(l,1),u=i[l];s(l);return}}}if(i.length){let d=i[i.length-1];Nt(d.end,t,a)&&(d.end=t)}i.push(o)}};function Tu(n,e,t,r){let i=[e/t.columns,n/t.rows],o=r.getElementsByClassName("proportional-style");for(let a=0;a<o.length;a++){let s=o[a];if(s instanceof HTMLElement){let d=s.getAttribute("data-proportional-font-size");d!==null&&!isNaN(+d)&&(s.style.fontSize=String(+d*i[1])+"px");let u=s.getAttribute("data-proportional-width");u!==null&&!isNaN(+u)&&(s.style.width=String(+u*i[0])+"px");let l=s.getAttribute("data-proportional-height");l!==null&&!isNaN(+l)&&(s.style.height=String(+l*i[1])+"px");let c=s.getAttribute("data-proportional-line-height");c!==null&&!isNaN(+c)&&(s.style.lineHeight=String(+c*i[1])+"px");let f=s.getAttribute("data-proportional-left");f!==null&&!isNaN(+f)&&(s.style.left=String(+f*i[0])+"px");let g=s.getAttribute("data-proportional-top");g!==null&&!isNaN(+g)&&(s.style.top=String(+g*i[1])+"px");let p=s.getAttribute("data-proportional-padding-top");p!==null&&!isNaN(+p)&&(s.style.paddingTop=String(+p*i[1])+"px");let I=s.getAttribute("data-proportional-padding-bottom");I!==null&&!isNaN(+I)&&(s.style.paddingBottom=String(+I*i[1])+"px");let y=s.getAttribute("data-proportional-padding-left");y!==null&&!isNaN(+y)&&(s.style.paddingLeft=String(+y*i[0])+"px");let b=s.getAttribute("data-proportional-padding-right");b!==null&&!isNaN(+b)&&(s.style.paddingRight=String(+b*i[0])+"px")}}return o.length>0}function em(n,e){try{n.removeChild(e)}catch(t){m.warn("HTD: Can't remove text track: not in the element.")}}function Zy(n){let e=n.getAttribute("data-resolution-rows"),t=n.getAttribute("data-resolution-columns");if(e===null||t===null)return null;let r=parseInt(e,10),i=parseInt(t,10);return r===null||i===null?null:{rows:r,columns:i}}var qi=class{constructor(e,t){m.debug("HTD: Creating HTMLTextDisplayer"),this._buffered=new Pn,this._videoElement=e,this._textTrackElement=t,this._sizeUpdateCanceller=new B,this._subtitlesIntervalCanceller=new B,this._buffer=new Gi,this._currentCues=[],this._isAutoRefreshing=!1}pushTextData(e){var I,y;m.debug("HTD: Appending new html text tracks");let{timestampOffset:t,appendWindow:r,chunk:i}=e;if(i===null)return Pe(this._buffered);let{start:o,end:a,data:s,type:d,language:u}=i,l=(I=r[0])!=null?I:0,c=(y=r[1])!=null?y:1/0,f=bu(d,s,t,u);if(l!==0&&c!==1/0){let b=0;for(;b<f.length&&f[b].end<=l;)b++;for(f.splice(0,b),b=0;b<f.length&&f[b].start<l;)f[b].start=l,b++;for(b=f.length-1;b>=0&&f[b].start>=c;)b--;for(f.splice(b,f.length),b=f.length-1;b>=0&&f[b].end>c;)f[b].end=c,b--}let g;if(o!==void 0)g=Math.max(l,o);else{if(f.length<=0)return m.warn("HTD: Current text tracks have no cues nor start time. Aborting"),Pe(this._buffered);m.warn("HTD: No start time given. Guessing from cues."),g=f[0].start}let p;if(a!==void 0)p=Math.min(c,a);else{if(f.length<=0)return m.warn("HTD: Current text tracks have no cues nor end time. Aborting"),Pe(this._buffered);m.warn("HTD: No end time given. Guessing from cues."),p=f[f.length-1].end}return p<=g?(m.warn("HTD: Invalid text track appended: ","the start time is inferior or equal to the end time."),Pe(this._buffered)):(this._buffer.insert(f,g,p),this._buffered.insert(g,p),!this._isAutoRefreshing&&!this._buffer.isEmpty()&&this.autoRefreshSubtitles(this._subtitlesIntervalCanceller.signal),Pe(this._buffered))}removeBuffer(e,t){return m.debug("HTD: Removing html text track data",e,t),this._buffer.remove(e,t),this._buffered.remove(e,t),this._isAutoRefreshing&&this._buffer.isEmpty()&&(this.refreshSubtitles(),this._isAutoRefreshing=!1,this._subtitlesIntervalCanceller.cancel(),this._subtitlesIntervalCanceller=new B),Pe(this._buffered)}getBufferedRanges(){return Pe(this._buffered)}reset(){m.debug("HTD: Resetting HTMLTextDisplayer"),this.stop(),this._subtitlesIntervalCanceller=new B}stop(){this._subtitlesIntervalCanceller.isUsed()||(m.debug("HTD: Stopping HTMLTextDisplayer"),this._disableCurrentCues(),this._buffer.remove(0,1/0),this._buffered.remove(0,1/0),this._isAutoRefreshing=!1,this._subtitlesIntervalCanceller.cancel())}_disableCurrentCues(){if(this._sizeUpdateCanceller.cancel(),this._currentCues.length>0){for(let e of this._currentCues)em(this._textTrackElement,e.element);this._currentCues=[]}}_displayCues(e){if(this._currentCues.length===e.length&&this._currentCues.every((i,o)=>i.element===e[o]))return;this._sizeUpdateCanceller.cancel();for(let i of this._currentCues)em(this._textTrackElement,i.element);this._currentCues=[];for(let i of e){let o=Zy(i);this._currentCues.push({element:i,resolution:o}),this._textTrackElement.appendChild(i)}let r=this._currentCues.filter(i=>i.resolution!==null);if(r.length>0){this._sizeUpdateCanceller=new B,this._sizeUpdateCanceller.linkToSignal(this._subtitlesIntervalCanceller.signal);let{TEXT_TRACK_SIZE_CHECKS_INTERVAL:i}=U.getCurrent();Iu(this._textTrackElement,i,this._sizeUpdateCanceller.signal).onUpdate(({height:a,width:s})=>{for(let d of r){let{resolution:u,element:l}=d;Tu(a,s,u,l)}},{clearSignal:this._sizeUpdateCanceller.signal,emitCurrentValue:!0})}}autoRefreshSubtitles(e){if(this._isAutoRefreshing||e.isCancelled())return;let t=null,{MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:r}=U.getCurrent(),i=()=>{this._isAutoRefreshing=!1,t!==null&&(t.cancel(),t=null)},o=()=>{i(),this._isAutoRefreshing=!0,t=new B,t.linkToSignal(e);let a=setInterval(()=>this.refreshSubtitles(),r);t.signal.register(()=>{clearInterval(a)}),this.refreshSubtitles()};Tc(this._videoElement,()=>{i(),this._disableCurrentCues()},e),_c(this._videoElement,o,e),Ec(this._videoElement,o,e),o()}refreshSubtitles(){let{MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:e}=U.getCurrent(),t;this._videoElement.paused||this._videoElement.playbackRate<=0?t=this._videoElement.currentTime:t=Math.max(this._videoElement.currentTime+e/1e3/2,0);let r=this._buffer.get(t);r.length===0?this._disableCurrentCues():this._displayCues(r)}};h.CURRENT_ENV===h.DEV&&(Jy=function(e){function t(r){}});var Jy;var nn=qi;var eI=/&#([0-9]+);/g,tI=/<br>/gi,nI=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,rI=/\s*<p (?:class=([^>]+))?>(.*)/i,iI=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i;function oI(n){let e=/\.(\S+)\s*{([^}]*)}/gi,t={},r=e.exec(n);for(;r!==null;){let i=r[1],o=sI(r[2],"lang");!_(i)&&!_(o)&&(t[o]=i),r=e.exec(n)}return t}function aI(n){let t=/p\s*{([^}]*)}/gi.exec(n);return t===null?"":t[1]}function sI(n,e){let t=new RegExp("\\s*"+e+":\\s*(\\S+);","i").exec(n);return Array.isArray(t)?t[1]:null}function dI(n){return n.replace(eI,(e,t)=>String.fromCharCode(Number(t)))}function uI(n,e,t){let r=/<sync[ >]/gi,i=/<sync[ >]|<\/body>/gi,o=[],a=nI.exec(n),s=Array.isArray(a)?a[1]:"",d,u;i.exec(n);let l=oI(s),c=aI(s),f;if(w(t)&&(f=l[t],f===void 0))throw new Error(`sami: could not find lang ${t} in CSS`);for(;d=r.exec(n),u=i.exec(n),!(d===null&&u===null);){if(d===null||u===null||d.index>=u.index)throw new Error("parse error");let p=n.slice(d.index,u.index),I=iI.exec(p);if(!Array.isArray(I))throw new Error("parse error (sync time attribute)");let y=+I[1];if(isNaN(y))throw new Error("parse error (sync time attribute NaN)");g(p.split(`
|
|
6
|
-
`),y/1e3)}return o;function g(p,I){let y=p.length;for(;--y>=0;){let b=
|
|
7
|
-
`);for(let u=0;u<d.length;u++)if(u!==0&&o.appendChild(document.createElement("br")),d[u].length>0){let l=document.createTextNode(d[u]);o.appendChild(l)}}else if(s.nodeName==="B"){let d=t(s);d.style.fontWeight="bold",o.appendChild(d)}else if(s.nodeName==="I"){let d=t(s);d.style.fontStyle="italic",o.appendChild(d)}else if(s.nodeName==="U"){let d=t(s);d.style.textDecoration="underline",o.appendChild(d)}else if(fI(s)&&typeof s.color=="string"){let d=t(s);d.style.color=s.color,o.appendChild(d)}else{let d=t(s);o.appendChild(d)}}return o};return t(e)}function fI(n){return n.nodeName==="FONT"&&"color"in n}function Ru(n){n.htmlTextTracksParsers.srt=vu,n.htmlTextDisplayer=nn}var mI=/(\d+) (\d+)/;function ku(n){let e=n.getAttribute("ttp:frameRate"),t=n.getAttribute("ttp:subFramRate"),r=n.getAttribute("ttp:tickRate"),i=n.getAttribute("ttp:frameRateMultiplier"),o=n.getAttribute("xml:space"),a=n.getAttribute("ttp:cellResolution"),s={columns:32,rows:15};if(a!==null){let I=mI.exec(a);if(I===null||I.length<3)m.warn("TTML Parser: Invalid cellResolution");else{let y=parseInt(I[1],10),b=parseInt(I[2],10);isNaN(y)||isNaN(b)?m.warn("TTML Parser: Invalid cellResolution"):s={columns:y,rows:b}}}if(w(o)&&o!=="default"&&o!=="preserve")throw new Error("Invalid spacing style");let d=Number(e);(isNaN(d)||d<=0)&&(d=30);let u=Number(t);(isNaN(u)||u<=0)&&(u=1);let l=Number(r);(isNaN(l)||l<=0)&&(l=void 0);let c=d,f=u!=null?u:1,g=o!=null?o:"default",p=l!=null?l:d*u;if(i!==null){let I=/^(\d+) (\d+)$/g.exec(i);if(I!==null){let y=Number(I[1]),b=Number(I[2]),T=y/b;c=d*T}}return{cellResolution:s,tickRate:p,frameRate:c,subFrameRate:f,spaceStyle:g}}function Mn(n,e,t,r){let i={},o=n.slice();for(let a=0;a<=e.length-1;a++){let s=e[a];if(s!==void 0){let d,u;if(s.nodeType===Node.ELEMENT_NODE){let l=s;for(let c=0;c<=l.attributes.length-1;c++){let f=l.attributes[c],g=f.name;if(g==="style")d=f.value;else if(g==="region")u=f.value;else{let p=g.substring(4);if(Q(o,p)&&(i[p]=f.value,o.splice(c,1),o.length===0))return i}}}if(w(d)){let l=Z(t,c=>c.id===d);if(l!==void 0)for(let c=0;c<=o.length-1;c++){let f=o[c];if(!w(i[f])&&w(l.style[f])){if(i[f]=l.style[f],o.splice(c,1),o.length===0)return i;c--}}}if(w(u)){let l=Z(r,c=>c.id===u);if(l!==void 0)for(let c=0;c<=o.length-1;c++){let f=o[c];if(!w(i[f])&&w(l.style[f])){if(i[f]=l.style[f],o.splice(c,1),o.length===0)return i;c--}}}}}return i}function Cu(n){if(n.nodeType!==Node.ELEMENT_NODE)return{};let e=n,t={};for(let r=0;r<=e.attributes.length-1;r++){let i=e.attributes[r];if(Ze(i.name,"tts")){let o=i.name.substring(4);t[o]=i.value}}return t}function Pu(n){let e=[];function t(r,i){e.push(i);for(let o of r.extendsStyles){let a=he(n,s=>s.id===o);if(a<0)m.warn("TTML Parser: unknown style inheritance: "+o);else{let s=n[a];Q(e,a)?m.warn("TTML Parser: infinite style inheritance loop avoided"):t(s,a),r.style=G({},s.style,r.style)}}r.extendsStyles.length=0}for(let r=0;r<n.length;r++)t(n[r],r),e.length=0}function nm(n,e){if(!(n.parentNode instanceof Element))return[];function t(r){let i=[];r.tagName.toLowerCase()===e.toLowerCase()&&i.push(r);let o=r.parentNode;return o instanceof Element&&i.push(...t(o)),i}return t(n.parentNode)}function ya(n){let e=nm(n,"div");if(e.length===0){let t=nm(n,"tt:div");t.length>0&&(e=t)}return e}function rm(n){let e=n.getElementsByTagName("body");if(e.length>0)return e[0];let t=n.getElementsByTagName("tt:body");return t.length>0?t[0]:null}function im(n){let e=n.getElementsByTagName("style");if(e.length>0)return e;let t=n.getElementsByTagName("tt:style");return t.length>0?t:e}function om(n){let e=n.getElementsByTagName("region");if(e.length>0)return e;let t=n.getElementsByTagName("tt:region");return t.length>0?t:e}function am(n){let e=n.getElementsByTagName("p");if(e.length>0)return e;let t=n.getElementsByTagName("tt:p");return t.length>0?t:e}function Ia(n){return n.nodeName==="br"||n.nodeName==="tt:br"}function ba(n){return n.nodeName==="span"||n.nodeName==="tt:span"}var sm=["align","backgroundColor","color","direction","display","displayAlign","extent","fontFamily","fontSize","fontStyle","fontWeight","lineHeight","opacity","origin","overflow","padding","textAlign","textDecoration","textOutline","unicodeBidi","visibility","wrapOption","writingMode"];function $i(n,e){let t=[],r=new DOMParser().parseFromString(n,"text/xml");if(r!=null){let o=r.getElementsByTagName("tt")[0];if(o===void 0&&(o=r.getElementsByTagNameNS("*","tt")[0],o===void 0))throw new Error("invalid XML");let a=rm(o),s=im(o),d=om(o),u=am(o),l=ku(o),c=[];for(let y=0;y<=s.length-1;y++){let b=s[y];if(b instanceof Element){let T=b.getAttribute("xml:id");if(T!==null){let v=b.getAttribute("style"),E=v===null?[]:v.split(" ");c.push({id:T,style:Cu(b),extendsStyles:E})}}}Pu(c);let f=[];for(let y=0;y<=d.length-1;y++){let b=d[y];if(b instanceof Element){let T=b.getAttribute("xml:id");if(T!==null){let v=Cu(b),E=b.getAttribute("style");if(w(E)){let R=Z(c,k=>k.id===E);R!==void 0&&(v=G({},R.style,v))}f.push({id:T,style:v,extendsStyles:[]})}}}let g=Mn(sm,a!==null?[a]:[],c,f),I=(a!==null?a.getAttribute("xml:space"):void 0)==="default"||l.spaceStyle==="default";for(let y=0;y<u.length;y++){let b=u[y];if(b instanceof Element){let T=ya(b),v=G({},g,Mn(sm,[b,...T],c,f)),E=b.getAttribute("xml:space"),R=w(E)?E==="default":I,k={paragraph:b,timeOffset:e,idStyles:c,regionStyles:f,body:a,paragraphStyle:v,ttParams:l,shouldTrimWhiteSpace:R};k!==null&&t.push(k)}}}return t}function dm(n){return n.extent===void 0&&n.origin===void 0&&n.displayAlign===void 0&&n.display===void 0&&n.textAlign===void 0&&n.fontSize===void 0}function um(n){n.extent="70% 20%",n.fontSize="1c",n.origin="15% 80%",n.displayAlign="before",n.textAlign="center"}var Mu=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Au=/^(?:(\d{2,}):)?(\d{2}):(\d{2})$/,xu=/^(?:(\d{2,}):)?(\d{2}):(\d{2}\.\d{2,})$/,wu=/^(\d*\.?\d*)f$/,Ou=/^(\d*\.?\d*)t$/,Du=/^(?:(\d*\.?\d*)h)?(?:(\d*\.?\d*)m)?(?:(\d*\.?\d*)s)?(?:(\d*\.?\d*)ms)?$/,Lu=/^(\d{1,2}|100)% (\d{1,2}|100)%$/,qe=/^((?:\+|\-)?\d*(?:\.\d+)?)(px|em|c|%|rh|rw)$/,lm=/^#([0-9A-f]{2})([0-9A-f]{2})([0-9A-f]{2})([0-9A-f]{2})$/,cm=/^#([0-9A-f])([0-9A-f])([0-9A-f])([0-9A-f])$/,fm=/^rgb\( *(\d+) *, *(\d+) *, *(\d+) *\)/,mm=/^rgba\( *(\d+) *, *(\d+) *, *(\d+) *, *(\d+) *\)/;function pI(n,e){if(Mu.test(n))return yI(e,n);if(Au.test(n))return Nu(Au,n);if(xu.test(n))return Nu(xu,n);if(wu.test(n))return gI(e,n);if(Ou.test(n))return hI(e,n);if(Du.test(n))return Nu(Du,n)}function gI(n,e){let t=wu.exec(e);return Number(t[1])/n.frameRate}function hI(n,e){let t=Ou.exec(e);return Number(t[1])/n.tickRate}function yI(n,e){let t=Mu.exec(e),r=Number(t[1]),i=Number(t[2]),o=Number(t[3]),a=Number(t[4]),s=Number(t[5]);return isNaN(s)&&(s=0),a+=s/n.subFrameRate,o+=a/n.frameRate,o+i*60+r*3600}function Nu(n,e){let t=n.exec(e);if(t===null||t[0]==="")return null;let r=Number(t[1]);isNaN(r)&&(r=0);let i=Number(t[2]);isNaN(i)&&(i=0);let o=Number(t[3]);isNaN(o)&&(o=0);let a=Number(t[4]);return isNaN(a)&&(a=0),a/1e3+o+i*60+r*3600}var Sa=pI;function Qi(n,e){let t=n.getAttribute("begin"),r=n.getAttribute("dur"),i=n.getAttribute("end"),o=w(t)?Sa(t,e):null,a=w(r)?Sa(r,e):null,s=w(i)?Sa(i,e):null;if(_(o)||_(s)&&_(a))throw new Error("Invalid text cue");let d=_(s)?o+a:s;return{start:o,end:d}}var Uu;function Ce(n,e){Uu===void 0&&(Uu=n.classList!==void 0&&typeof n.classList.add=="function"),Uu?n.classList.add(e):(" "+n.className+" ").indexOf(" "+e+" ")<0&&(n.className+=" "+e)}function Bu(n,e){let t=e.trim();if(t==="auto")return;let r=t.split(" ");if(r.length!==2)return;let i=qe.exec(r[0]),o=qe.exec(r[1]);i!==null&&o!==null&&(i[2]==="px"||i[2]==="%"||i[2]==="em"?n.style.width=i[1]+i[2]:i[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-width",i[1])):m.warn("TTML Parser: unhandled extent unit:",i[2]),o[2]==="px"||o[2]==="%"||o[2]==="em"?n.style.height=o[1]+o[2]:o[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-height",o[1])):m.warn("TTML Parser: unhandled extent unit:",o[2]))}function Fu(n,e){let r=e.trim().split(" ");if(r.length===0)return;let i=qe.exec(r[0]);if(i!==null)if(i[2]==="px"||i[2]==="em")n.style.fontSize=i[1]+i[2];else if(i[2]==="c")n.style.position="relative",Ce(n,"proportional-style"),n.setAttribute("data-proportional-font-size",i[1]);else if(i[2]==="%"){let o=Number(i[1]);isNaN(o)?m.warn('TTML Parser: could not parse fontSize value "'+i[1]+'" into a number'):(n.style.position="relative",Ce(n,"proportional-style"),n.setAttribute("data-proportional-font-size",String(o/100)))}else m.warn("TTML Parser: unhandled fontSize unit:",i[2])}function Ku(n,e){let t=e.trim(),r=t.split(" ");if(t==="auto")return;let i=qe.exec(r[0]);i!==null&&(i[2]==="px"||i[2]==="%"||i[2]==="em"?n.style.lineHeight=i[1]+i[2]:i[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-line-height",i[1])):m.warn("TTML Parser: unhandled lineHeight unit:",i[2]))}function Vu(n,e){let t=e.trim();if(t==="auto")return;let r=t.split(" ");if(r.length!==2)return;let i=qe.exec(r[0]),o=qe.exec(r[1]);i!==null&&o!==null&&(i[2]==="px"||i[2]==="%"||i[2]==="em"?n.style.left=i[1]+i[2]:i[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-left",i[1])):m.warn("TTML Parser: unhandled origin unit:",i[2]),o[2]==="px"||o[2]==="%"||o[2]==="em"?n.style.top=o[1]+o[2]:o[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-top",o[1])):m.warn("TTML Parser: unhandled origin unit:",o[2]))}function zu(n,e){let r=e.trim().split(" ");if(r.length<1)return;let i=qe.exec(r[0]);if(i===null)return;if(i[2]==="px"||i[2]==="%"||i[2]==="em"){let d=i[1]+i[2];r.length===1?n.style.padding=d:r.length===2?(n.style.paddingTop=d,n.style.paddingBottom=d):n.style.paddingTop=d}else i[2]==="c"?(Ce(n,"proportional-style"),r.length===1?(n.setAttribute("data-proportional-padding-top",i[1]),n.setAttribute("data-proportional-padding-bottom",i[1]),n.setAttribute("data-proportional-padding-left",i[1]),n.setAttribute("data-proportional-padding-right",i[1])):r.length===2?(n.setAttribute("data-proportional-padding-top",i[1]),n.setAttribute("data-proportional-padding-bottom",i[1])):n.setAttribute("data-proportional-padding-top",i[1])):m.warn("TTML Parser: unhandled padding unit:",i[2]);if(r.length===1)return;let o=qe.exec(r[1]);if(o===null)return;if(o[2]==="px"||o[2]==="%"||o[2]==="em"){let d=o[1]+o[2];r.length<4&&(n.style.paddingLeft=d),n.style.paddingRight=d}else o[2]==="c"?(Ce(n,"proportional-style"),r.length<4&&n.setAttribute("data-proportional-padding-left",o[1]),n.setAttribute("data-proportional-padding-right",o[1])):m.warn("TTML Parser: unhandled padding unit:",o[2]);if(r.length===2)return;let a=qe.exec(r[2]);if(a===null)return;if(a[2]==="px"||a[2]==="%"||a[2]==="em"){let d=a[1]+a[2];n.style.paddingBottom=d}else a[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-padding-bottom",a[1])):m.warn("TTML Parser: unhandled padding unit:",a[2]);if(r.length===3)return;let s=qe.exec(r[3]);if(s!==null)if(s[2]==="px"||s[2]==="%"||s[2]==="em"){let d=s[1]+s[2];n.style.paddingLeft=d}else s[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-padding-left",s[1])):m.warn("TTML Parser: unhandled padding unit:",s[2])}function tr(n,e){let t=e;return w(e)&&e.trim().endsWith("%")&&(t=e.trim().slice(0,-1),t=(parseInt(t,10)/100).toString()+"em"),`-1px -1px ${t} ${n},1px -1px ${t} ${n},-1px 1px ${t} ${n},1px 1px ${t} ${n}`}function rn(n){let e;return e=lm.exec(n),_(e)?(e=cm.exec(n),_(e)?(e=fm.exec(n),_(e)?(e=mm.exec(n),_(e)?n:"rgba("+String(+e[1])+","+String(+e[2])+","+String(+e[3])+","+String(+e[4]/255)+")"):"rgb("+String(+e[1])+","+String(+e[2])+","+String(+e[3])+")"):"rgba("+String(parseInt(e[1]+e[1],16))+","+String(parseInt(e[2]+e[2],16))+","+String(parseInt(e[3]+e[3],16))+","+String(parseInt(e[4]+e[4],16)/255)+")"):"rgba("+String(parseInt(e[1],16))+","+String(parseInt(e[2],16))+","+String(parseInt(e[3],16))+","+String(parseInt(e[4],16)/255)+")"}var II=["color","direction","display","fontFamily","fontSize","fontStyle","fontWeight","textDecoration","textOutline","unicodeBidi","visibility","wrapOption"];function bI(n,e,t){let r=e.color;w(r)&&(n.style.color=rn(r));let i=e.backgroundColor;w(i)&&(n.style.backgroundColor=rn(i));let o=e.textOutline;if(w(o)){let y=o.trim().replace(/\s+/g," ").split(" "),b=y.length;if(b===3){let T=rn(y[0]),v=y[1];n.style.textShadow=tr(T,v)}else if(w(r)&&b===1){let T=y[0];n.style.textShadow=tr(r,T)}else if(b===2){let T=/^[#A-Z]/i.test(y[0]),v=/^[0-9]/.test(y[0]);if(T!==v){if(T){let E=rn(y[0]),R=y[1];n.style.textShadow=tr(E,R)}else if(w(r)){let E=y[0];n.style.textShadow=tr(r,E)}}}}let a=e.textDecoration;if(w(a))switch(a){case"noUnderline":case"noLineThrough":case"noOverline":n.style.textDecoration="none";break;case"lineThrough":n.style.textDecoration="line-through";break;default:n.style.textDecoration=a;break}let s=e.fontFamily;if(w(s))switch(s){case"proportionalSansSerif":n.style.fontFamily="Arial, Helvetica, Liberation Sans, sans-serif";break;case"monospaceSansSerif":case"sansSerif":n.style.fontFamily="sans-serif";break;case"monospaceSerif":case"default":n.style.fontFamily="Courier New, Liberation Mono, monospace";break;case"proportionalSerif":n.style.fontFamily="serif";break;default:n.style.fontFamily=s}let d=e.fontStyle;w(d)&&(n.style.fontStyle=d);let u=e.fontWeight;w(u)&&(n.style.fontWeight=u);let l=e.fontSize;w(l)?Fu(n,l):(Ce(n,"proportional-style"),n.setAttribute("data-proportional-font-size","1"));let c=e.direction;w(c)&&(n.style.direction=c);let f=e.unicodeBidi;if(w(f))switch(f){case"bidiOverride":n.style.unicodeBidi="bidi-override";break;case"embed":n.style.unicodeBidi="embed";break;default:n.style.unicodeBidi="normal"}let g=e.visibility;w(g)&&(n.style.visibility=g),e.display==="none"&&(n.style.display="none"),e.wrapOption==="noWrap"?t?n.style.whiteSpace="nowrap":n.style.whiteSpace="pre":t?n.style.whiteSpace="normal":n.style.whiteSpace="pre-wrap"}function SI(n,e){n.style.color="white",n.style.position="absolute";let t=e.extent;w(t)&&Bu(n,t);let r=e.writingMode;w(r);let i=e.overflow;n.style.overflow=w(i)?i:"hidden";let o=e.padding;w(o)&&zu(n,o);let a=e.origin;w(a)&&Vu(n,a);let s=e.displayAlign;if(w(s))switch(n.style.display="flex",n.style.flexDirection="column",s){case"before":n.style.justifyContent="flex-start";break;case"center":n.style.justifyContent="center";break;case"after":n.style.justifyContent="flex-end";break}let d=e.opacity;w(d)&&(n.style.opacity=d);let u=e.visibility;w(u)&&(n.style.visibility=u),e.display==="none"&&(n.style.display="none")}function TI(n,e){n.style.margin="0px",Ce(n,"proportional-style"),n.setAttribute("data-proportional-font-size","1");let t=e.backgroundColor;w(t)&&(n.style.backgroundColor=rn(t));let r=e.lineHeight;w(r)&&Ku(n,r);let i=e.textAlign;if(w(i))switch(i){case"center":n.style.textAlign="center";break;case"left":case"start":n.style.textAlign="left";break;case"right":case"end":n.style.textAlign="right";break}}function _I(n,e,t){let r=document.createElement("span"),i=n.textContent===null?"":n.textContent;if(t){let a=i.trim();a=a.replace(/\s+/g," "),i=a}let o=document.createTextNode(i);return r.appendChild(o),r.className="rxp-texttrack-span",bI(r,e,t),r}function EI(n,e,t,r,i){function o(a,s,d,u){let l=a.childNodes,c=[];for(let f=0;f<l.length;f++){let g=l[f];if(g.nodeName==="#text"){let{backgroundColor:p}=Mn(["backgroundColor"],d,t,e);w(p)?s.backgroundColor=p:s.backgroundColor="";let I=_I(g,s,u);c.push(I)}else if(Ia(g)){let p=document.createElement("BR");c.push(p)}else if(ba(g)&&g.nodeType===Node.ELEMENT_NODE&&g.childNodes.length>0){let p=g.getAttribute("xml:space"),I=w(p)?p==="default":u,y=G({},s,Mn(II,[g],t,e));c.push(...o(g,y,[g,...d],I))}}return c}return o(n,G({},r),[],i)}function Hu(n,e,t,r,i,{cellResolution:o,shouldTrimWhiteSpace:a}){let s=ya(n),d=document.createElement("DIV");if(d.className="rxp-texttrack-region",d.setAttribute("data-resolution-columns",String(o.columns)),d.setAttribute("data-resolution-rows",String(o.rows)),SI(d,i),e!==null){let{bodyBackgroundColor:c}=Mn(["backgroundColor"],[...s,e],r,t);w(c)&&(d.style.backgroundColor=rn(c))}let u=document.createElement("p");u.className="rxp-texttrack-p",TI(u,i);let l=EI(n,t,r,i,a);for(let c=0;c<l.length;c++)u.appendChild(l[c]);return d.appendChild(u),d}function Wu(n){let{paragraph:e,ttParams:t,body:r,regionStyles:i,idStyles:o,paragraphStyle:a,timeOffset:s,shouldTrimWhiteSpace:d}=n;if(!e.hasAttribute("begin")&&!e.hasAttribute("end")&&/^\s*$/.test(e.textContent===null?"":e.textContent))return null;let{cellResolution:u}=t,{start:l,end:c}=Qi(e,t),f=Hu(e,r,i,o,a,{cellResolution:u,shouldTrimWhiteSpace:d});return{start:l+s,end:c+s,element:f}}function Gu(n,e){let t=$i(n,e),r=[];for(let i of t){let{paragraphStyle:o}=i;dm(o)&&um(o);let a=Wu(i);a!==null&&r.push(a)}return r}var pm=Gu;function qu(n){n.htmlTextTracksParsers.ttml=pm,n.htmlTextDisplayer=nn}function Ta(n){let e=0;for(;e<n.length;){if(n[e]==="")return e+1;e++}return e}function ju(n,e){return typeof n[e]=="string"&&/^STYLE( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function vI(n,e){return typeof n[e]=="string"&&/^NOTE( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function RI(n,e){return typeof n[e]=="string"&&/^REGION( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function gm(n,e){let t=n[e];if(t===void 0||t===""||ju(n,e)||RI(n,e)||vI(n,e))return!1;if(t.indexOf("-->")>=0)return!0;let r=n[e+1];return r!==void 0&&r.indexOf("-->")>=0}function hm(n,e){let t=e+1;for(;w(n[t]);)t++;return t}function Xi(n,e){let t=[];for(let r=e;r<n.length;r++)if(gm(n,r)){let i=hm(n,r);t.push(n.slice(r,i)),r=i}else if(w(n[r]))for(;w(n[r]);)r++;return t}function Yu(n,e){let t=[];for(let r=e;r<n.length;r++)if(ju(n,r)){let i=r;for(r++;w(n[r]);)r++;let o=n.slice(i,r);t.push(o)}else if(w(n[r]))for(;w(n[r]);)r++;return t}function _a(n){let e=n.split(":").reverse();if(w(e[2])||w(e[1])){let t=w(e[2])?parseInt(e[2],10):0,r=parseInt(e[1],10),i=parseFloat(e[0].replace(",","."));return isNaN(t)||isNaN(r)||isNaN(i)?void 0:t*60*60+r*60+i}}function kI(n){return n.split(/ |\t/).reduce((t,r)=>{let i=r.split(":");return i.length===2&&(t[i[0]]=i[1]),t},{})}function CI(n){let t=/^([\d:.]+)[ |\t]+-->[ |\t]+([\d:.]+)[ |\t]*(.*)$/.exec(n);if(t===null)return null;let r=_a(t[1]),i=_a(t[2]);if(r===void 0||i===void 0)return null;let o=kI(t[3]);return{start:r,end:i,settings:o}}function Zi(n,e){let t=/-->/,r,i,o;if(t.test(n[0]))r=n[0],i=n.slice(1,n.length);else{if(!t.test(n[1]))return null;o=n[0],r=n[1],i=n.slice(2,n.length)}let a=CI(r);if(a===null)return null;let{start:s,end:d,settings:u}=a;return{start:s+e,end:d+e,settings:u,payload:i,header:o}}var $u={white:"#ffffff",lime:"#00ff00",cyan:"#00ffff",red:"#ff0000",yellow:"#ffff00",magenta:"#ff00ff",blue:"#0000ff",black:"#000000"};function Qu(){return Object.keys($u).reduce((n,e)=>(n[e]=`color: ${$u[e]};`,n[`bg_${e}`]=`background-color: ${$u[e]};`,n),{})}function Xu(n){let e=Qu(),t="";return n.forEach(r=>{if(r.length>=2)for(let i=1;i<r.length;i++){let o=r[i];if(Array.isArray(/::cue {/.exec(o)))for(o=r[++i];w(o)&&!(Array.isArray(/}/.exec(o))||o.length===0);)t+=o,o=r[++i];else{let a=[],s=/::cue\(\.?(.*?)\)(?:,| {)/.exec(o);for(;w(o)&&Array.isArray(s);)a.push(s[1]),o=r[++i],s=/::cue\(\.?(.*?)\)(?:,| {)/.exec(o);let d="";for(;w(o)&&!(Array.isArray(/}/.exec(o))||o.length===0);)d+=o,o=r[++i];a.forEach(u=>{e[u]===void 0?e[u]=d:e[u]+=d})}}}),{classes:e,global:t}}function Ji(n,e){let t=["u","i","b"],r=["u","i","b","c","#text"],i=n.nodeName.toLowerCase().split(".")[0],o;if(Q(r,i))if(i==="#text"){let a=n.wholeText.split(`
|
|
8
|
-
`);o=document.createElement("span");for(let s=0;s<a.length;s++)if(s>0&&o.appendChild(document.createElement("br")),a[s].length>0){let d=document.createTextNode(a[s]);o.appendChild(d)}}else{let a=n.nodeName.toLowerCase().split("."),s=[];if(a.forEach(d=>{w(e[d])&&s.push(e[d])}),s.length!==0){let d=document.createAttribute("style");s.forEach(l=>{d.value+=l});let u=Q(t,i)?i:"span";o=document.createElement(u),o.setAttributeNode(d)}else{let d=Q(t,i)?i:"span";o=document.createElement(d)}for(let d=0;d<n.childNodes.length;d++){let u=
|
|
9
|
-
`),p).forEach(b=>{c.appendChild(b)}),s.appendChild(u),u.appendChild(c),{start:t,end:r,element:s}}function rl(n,e){let t=/\r\n|\n|\r/g,r=n.split(t),i=[];if(/^WEBVTT( |\t|\n|\r|$)/.exec(r[0])===null)throw new Error("Can't parse WebVTT: Invalid File.");let o=
|
|
10
|
-
`).replace(
|
|
11
|
-
`),I/1e3)}return
|
|
12
|
-
`);return
|
|
13
|
-
`;else if(
|
|
14
|
-
`);return Ut(e,t,i)}function hl(n,e){let t=n.split(/\r\n|\n|\r/);if(!/^WEBVTT($| |\t)/.test(t[0]))throw new Error("Can't parse WebVTT: Invalid file.");let r=Ta(t),i=Xi(t,r),o=[];for(let a of i){let s=Zi(a,e);if(s!==null){let d=gl(s);d!==null&&(to(d)&&pl(s.settings,d),o.push(d))}}return o}var Sm=hl;function yl(n){n.nativeTextTracksParsers.vtt=Sm,n.nativeTextDisplayer=on}function nr(n){let e=[];n.periods.forEach(t=>{let r=t.id;if(Q(e,r)){m.warn("Two periods with the same ID found. Updating.");let a=r+"-dup";t.id=a,nr(n),e.push(a)}else e.push(r);let{adaptations:i}=t,o=[];Object.keys(i).forEach(a=>{let s=i[a];s!==void 0&&s.forEach(d=>{let u=d.id;if(Q(o,u)){m.warn("Two adaptations with the same ID found. Updating.",u);let c=u+"-dup";d.id=c,nr(n),o.push(c)}else o.push(u);let l=[];d.representations.forEach(c=>{let f=c.id;if(Q(l,f)){m.warn("Two representations with the same ID found. Updating.",f);let g=`${f}-dup`;c.id=g,nr(n),l.push(g)}else l.push(f)})})})})}function Tm(n,e){let t;return e==="AACH"?t=5:t=w(n)?(parseInt(n.substring(0,2),16)&248)>>3:2,t===0?"mp4a.40.2":`mp4a.40.${t}`}function _m(n){let e=/00000001\d7([0-9a-fA-F]{6})/.exec(n);return e===null||!w(e[1])?"avc1.4D401E":"avc1."+e[1]}function Il(n){return n.reduce((e,t,r)=>{let i=t.getAttribute("d"),o=t.getAttribute("t"),a=t.getAttribute("r"),s=a!==null?+a-1:0,d=o!==null?+o:void 0,u=i!==null?+i:void 0;if(r===0)d=d===void 0||isNaN(d)?0:d;else{let l=e[r-1];if(d===void 0||isNaN(d)){if(l.duration===void 0||isNaN(l.duration))throw new Error("Smooth: Invalid CNodes. Missing timestamp.");d=l.start+l.duration*(l.repeatCount+1)}}if(u===void 0||isNaN(u)){let l=n[r+1];if(l!==void 0){let c=l.getAttribute("t"),f=w(c)?+c:null;if(f===null)throw new Error("Can't build index timeline from Smooth Manifest.");u=f-d}else return e}return e.push({duration:u,start:d,repeatCount:s}),e},[])}function eb(n){return[{systemId:"edef8ba9-79d6-4ace-a3c8-27dcd51d21ed",privateData:ie([8,1,18,16],n)}]}function bl(n,e=eb){if(n.firstElementChild===null||n.firstElementChild.nodeName!=="ProtectionHeader")throw new Error("Protection should have ProtectionHeader child");let t=n.firstElementChild,r=mt(t.textContent===null?"":t.textContent),i=Lr(r),o=je(i),a=t.getAttribute("SystemID"),s=(a!==null?a:"").toLowerCase().replace(/\{|\}/g,"");return{keyId:o,keySystems:[{systemId:s,privateData:r}].concat(e(o))}}function Em(n,e,t){return n.replace(/\{bitrate\}/g,String(e)).replace(/{CustomAttributes}/g,t.length>0?t[0]:"")}function vm(n,e){return n.replace(/\{start time\}/g,String(e))}function tb(n,e,t){let r=e-n;return r>0?Math.floor(r/t):0}function nb(n,e,t){let r=n===void 0||n===0?1:n;return{up:e*r,to:(e+t)*r}}function rb(n,e){let t=n.repeatCount;if(n.duration!==void 0&&t<0){let r=e!==void 0?e.start:1/0;t=Math.ceil((r-n.start)/n.duration)-1}return t}var no=class{constructor(e){let{isLive:t,segmentPrivateInfos:r,media:i,sharedSmoothTimeline:o}=e;if(this._sharedSmoothTimeline=o,this._initSegmentInfos={bitsPerSample:r.bitsPerSample,channels:r.channels,codecPrivateData:r.codecPrivateData,packetSize:r.packetSize,samplingRate:r.samplingRate,timescale:o.timescale,height:r.height,width:r.width,protection:r.protection},this._isLive=t,this._media=i,o.timeline.length!==0&&t){let{timeline:a,validityTime:s}=o,d=a[a.length-1],u=ke(d,null),l=s/1e3*o.timescale;this._scaledLiveGap=l-u}}getInitSegment(){return{id:"init",isInit:!0,privateInfos:{smoothInitSegment:this._initSegmentInfos},url:null,time:0,end:0,duration:0,timescale:1,complete:!0}}getSegments(e,t){this._refreshTimeline();let{timescale:r,timeline:i}=this._sharedSmoothTimeline,{up:o,to:a}=nb(r,e,t),s=this._media,d,u=[],l=i.length,c=this._scaledLiveGap===void 0?void 0:F()/1e3*r-this._scaledLiveGap;for(let f=0;f<l;f++){let g=i[f],{duration:p,start:I}=g,y=rb(g,i[f+1]),b=tb(I,o,p),T=I+b*p,v=p;for(;T<a&&b<=y&&(c===void 0||T+v<=c);){let E=T,R=d!==void 0?d+b:void 0,k={id:String(T),isInit:!1,time:E/r,end:(E+p)/r,duration:p/r,timescale:1,number:R,url:vm(s,E),complete:!0,privateInfos:{smoothMediaSegment:{time:E,duration:p}}};u.push(k),b++,T=I+b*p}if(T>=a)return u;d!==void 0&&(d+=y+1)}return u}shouldRefresh(e,t){if(this._refreshTimeline(),!this._isLive)return!1;let{timeline:r,timescale:i}=this._sharedSmoothTimeline,o=r[r.length-1];if(o===void 0)return!1;let a=o.repeatCount,s=o.start+(a+1)*o.duration;if(t*i<s)return!1;if(e*i>=s)return!0;let d=o.start+a*o.duration;return e*i>d}getFirstAvailablePosition(){this._refreshTimeline();let{timeline:e,timescale:t}=this._sharedSmoothTimeline;return e.length===0?null:e[0].start/t}getLastAvailablePosition(){this._refreshTimeline();let{timeline:e,timescale:t}=this._sharedSmoothTimeline;if(this._scaledLiveGap===void 0){let r=e[e.length-1];return ke(r,null)/t}for(let r=e.length-1;r>=0;r--){let i=e[r],o=F()/1e3*t,{start:a,duration:s,repeatCount:d}=i;for(let u=d;u>=0;u--){let l=a+s*(u+1);if(l<=o-this._scaledLiveGap)return l/t}}}getEnd(){if(!this._isLive)return this.getLastAvailablePosition()}awaitSegmentBetween(e,t){var i;if(ee(e<=t),this.isStillAwaitingFutureSegments())return!1;let r=this.getLastAvailablePosition();return r!==void 0&&t<r?!1:t>((i=this.getFirstAvailablePosition())!=null?i:0)?void 0:!1}checkDiscontinuity(e){return this._refreshTimeline(),oa(this._sharedSmoothTimeline,e,void 0)}isSegmentStillAvailable(e){if(e.isInit)return!0;this._refreshTimeline();let{timeline:t,timescale:r}=this._sharedSmoothTimeline;for(let i=0;i<t.length;i++){let o=t[i],a=o.start/r;if(a>e.time)return!1;if(a===e.time)return!0;if(o.repeatCount>=0&&o.duration!==void 0){let d=(a-o.start)/o.duration-1;return d%1===0&&d<=o.repeatCount}}return!1}canBeOutOfSyncError(e){return this._isLive?e instanceof it&&(e.isHttpError(404)||e.isHttpError(412)):!1}_replace(e){this._initialScaledLastPosition=e._initialScaledLastPosition,this._scaledLiveGap=e._scaledLiveGap,this._sharedSmoothTimeline.replace(e._sharedSmoothTimeline)}_update(e){this._scaledLiveGap=e._scaledLiveGap,this._sharedSmoothTimeline.update(e._sharedSmoothTimeline)}isStillAwaitingFutureSegments(){return this._isLive}isInitialized(){return!0}initialize(){m.error("A `SmoothRepresentationIndex` does not need to be initialized")}addPredictedSegments(e,t){this._sharedSmoothTimeline.addPredictedSegments(e,t)}_refreshTimeline(){this._sharedSmoothTimeline.refresh()}};function Sl(n,e,t,r){let i=n.length,o=n[i-1],a=t.timescale===e?{time:t.time,duration:t.duration}:{time:t.time/t.timescale*e,duration:t.duration/t.timescale*e};return r.time===a.time?!1:a.time>=ke(o,null)?(o.duration===a.duration?o.repeatCount++:n.push({duration:a.duration,start:a.time,repeatCount:0}),!0):!1}var ro=class{constructor(e){let{timeline:t,timescale:r,timeShiftBufferDepth:i,manifestReceivedTime:o}=e;this.timeline=t,this.timescale=r;let a=o!=null?o:F();if(this.validityTime=a,this._timeShiftBufferDepth=i,t.length!==0){let s=t[t.length-1],d=ke(s,null);this._initialScaledLastPosition=d}}refresh(){if(this._initialScaledLastPosition===void 0)return;let e=this._timeShiftBufferDepth,r=(F()-this.validityTime)/1e3+this._initialScaledLastPosition/this.timescale;if(e!==void 0){let i=(r-e)*this.timescale;Pi(this.timeline,i)}}replace(e){let t=this.timeline,r=e.timeline,i=this.timescale,o=e.timescale;if(this._initialScaledLastPosition=e._initialScaledLastPosition,this.validityTime=e.validityTime,t.length===0||r.length===0||i!==o)return;let a=t[t.length-1],s=r[r.length-1],d=ke(s,null);if(!(ke(a,null)<=d))for(let u=0;u<t.length;u++){let l=t[u],c=ke(l,null);if(c===d){this.timeline=this.timeline.concat(t.slice(u+1));return}if(c>d){if(l.duration!==s.duration)return;let f=d-l.start;if(f===0){m.warn("Smooth Parser: a discontinuity detected in the previous manifest has been resolved."),this.timeline=this.timeline.concat(t.slice(u));return}if(f<0||f%l.duration!==0)return;let g=f/l.duration-1,p=l.repeatCount-g;if(p<0)return;s.repeatCount+=p;let I=t.slice(u+1);this.timeline=this.timeline.concat(I);return}}}update(e){Mi(this.timeline,e.timeline),this._initialScaledLastPosition=e._initialScaledLastPosition,this.validityTime=e.validityTime}addPredictedSegments(e,t){var r;if(((r=t.privateInfos)==null?void 0:r.smoothMediaSegment)===void 0){m.warn("Smooth Parser: should only encounter SmoothRepresentationIndex");return}this.refresh();for(let i of e)Sl(this.timeline,this.timescale,i,t.privateInfos.smoothMediaSegment)}};function Tl(n){return typeof n=="boolean"?n:typeof n=="string"?n.toUpperCase()==="TRUE":!1}function rr(n,e,t){let r=n.firstElementChild,i=t;for(;r!==null;)i=e(i,r.nodeName,r),r=r.nextElementSibling;return i}var ib={audio:"audio/mp4",video:"video/mp4",text:"application/ttml+xml"},io={AACL:"audio/mp4",AVC1:"video/mp4",H264:"video/mp4",TTML:"application/ttml+xml+mp4",DFXP:"application/ttml+xml+mp4"};function ob(n={}){let e=n.referenceDateTime===void 0?Date.UTC(1970,0,1,0,0,0,0)/1e3:n.referenceDateTime,t=n.minRepresentationBitrate===void 0?0:n.minRepresentationBitrate,{serverSyncInfos:r}=n,i=r!==void 0?r.serverTimestamp-r.clientTime:void 0;function o(d,u){let l=rr(d,(f,g,p)=>(g==="CustomAttributes"&&f.push(...rr(p,(I,y,b)=>{if(y==="Attribute"){let T=b.getAttribute("Name"),v=b.getAttribute("Value");T!==null&&v!==null&&I.push(T+"="+v)}return I},[])),f),[]);function c(f){let g=d.getAttribute(f);return g===null?void 0:g}switch(u){case"audio":{let f=c("AudioTag"),g=c("BitsPerSample"),p=c("Channels"),I=c("CodecPrivateData"),y=c("FourCC"),b=c("PacketSize"),T=c("SamplingRate"),v=c("Bitrate"),E=v===void 0?0:parseInt(v,10);if(E=isNaN(E)?0:E,y!==void 0&&io[y]===void 0||I===void 0)return m.warn("Smooth parser: Unsupported audio codec. Ignoring quality level."),null;let R=Tm(I,y);return{audiotag:f!==void 0?parseInt(f,10):f,bitrate:E,bitsPerSample:g!==void 0?parseInt(g,10):g,channels:p!==void 0?parseInt(p,10):p,codecPrivateData:I,codecs:R,customAttributes:l,mimeType:y!==void 0?io[y]:y,packetSize:b!==void 0?parseInt(b,10):b,samplingRate:T!==void 0?parseInt(T,10):T}}case"video":{let f=c("CodecPrivateData"),g=c("FourCC"),p=c("MaxWidth"),I=c("MaxHeight"),y=c("Bitrate"),b=y===void 0?0:parseInt(y,10);if(b=isNaN(b)?0:b,g!==void 0&&io[g]===void 0||f===void 0)return m.warn("Smooth parser: Unsupported video codec. Ignoring quality level."),null;let T=_m(f);return{bitrate:b,customAttributes:l,mimeType:g!==void 0?io[g]:g,codecPrivateData:f,codecs:T,width:p!==void 0?parseInt(p,10):void 0,height:I!==void 0?parseInt(I,10):void 0}}case"text":{let f=c("CodecPrivateData"),g=c("FourCC"),p=c("Bitrate"),I=p===void 0?0:parseInt(p,10);return I=isNaN(I)?0:I,{bitrate:I,customAttributes:l,mimeType:g!==void 0?io[g]:g,codecPrivateData:f!=null?f:""}}default:return m.error("Smooth Parser: Unrecognized StreamIndex type: "+u),null}}function a(d){let{root:u,timescale:l,baseUrl:c,protections:f,timeShiftBufferDepth:g,manifestReceivedTime:p,isLive:I}=d,y=u.getAttribute("Timescale"),b=y===null?l:+y;isNaN(b)&&(b=l);let T=u.getAttribute("Type");if(T===null)throw new Error("StreamIndex without type.");Q(Qt,T)||m.warn("Smooth Parser: Unrecognized adaptation type:",T);let v=T,E=u.getAttribute("Subtype"),R=u.getAttribute("Language"),k=u.getAttribute("Url"),x=k===null?"":k;h.CURRENT_ENV===h.DEV&&ee(x!=="");let{qualityLevels:M,cNodes:P}=rr(u,(C,D,L)=>{switch(D){case"QualityLevel":{let V=o(L,v);if(V===null)return C;(v!=="video"||V.bitrate>t)&&C.qualityLevels.push(V);break}case"c":C.cNodes.push(L);break}return C},{qualityLevels:[],cNodes:[]}),N=new ro({timeline:Il(P),timescale:b,timeShiftBufferDepth:g,manifestReceivedTime:p});ee(M.length!==0,"Adaptation should have at least one playable representation.");let O=v+(w(R)?"_"+R:""),K=M.map(C=>{let D=Em(x,C.bitrate,C.customAttributes),L=w(C.mimeType)?C.mimeType:ib[v],V=C.codecs,$=O+"_"+(_(v)?"":v+"-")+(_(L)?"":L+"-")+(_(V)?"":V+"-")+String(C.bitrate),j=[],z;f.length>0&&(z=f[0],f.forEach(ae=>{j.push(ae.keyId)}));let q={bitsPerSample:C.bitsPerSample,channels:C.channels,codecPrivateData:C.codecPrivateData,packetSize:C.packetSize,samplingRate:C.samplingRate,height:C.height,width:C.width,protection:_(z)?void 0:{keyId:z.keyId}},W=new no({isLive:I,sharedSmoothTimeline:N,media:D,segmentPrivateInfos:q}),se=G({},C,{index:W,cdnMetadata:[{baseUrl:c}],mimeType:L,codecs:V,id:$});if(j.length>0||z!==void 0){let ae=z===void 0?[]:z.keySystems.map(de=>{let{systemId:Se,privateData:Y}=de,ce=Se.replace(/-/g,""),ye=ab(ce,Y);return{systemId:ce,data:ye}});if(ae.length>0){let de=[{type:"cenc",values:ae}];se.contentProtections={keyIds:j,initData:de}}else se.contentProtections={keyIds:j,initData:[]}}return se});if(E==="ADVT")return null;let A={id:O,type:v,representations:K,language:R===null?void 0:R};return v==="text"&&E==="DESC"&&(A.closedCaption=!0),A}function s(d,u,l){let c="";if(u!==void 0){let W=_r(u);c=u.substring(0,W)}let f=d.documentElement;if(_(f)||f.nodeName!=="SmoothStreamingMedia")throw new Error("document root should be SmoothStreamingMedia");let g=f.getAttribute("MajorVersion"),p=f.getAttribute("MinorVersion");if(g===null||p===null||!/^[2]-[0-2]$/.test(g+"-"+p))throw new Error("Version should be 2.0, 2.1 or 2.2");let I=f.getAttribute("Timescale"),y=w(I)?+I:1e7;isNaN(y)&&(y=1e7);let{protections:b,adaptationNodes:T}=rr(f,(W,se,ae)=>{switch(se){case"Protection":{W.protections.push(bl(ae,n.keySystems));break}case"StreamIndex":W.adaptationNodes.push(ae);break}return W},{adaptationNodes:[],protections:[]}),v={},E=Tl(f.getAttribute("IsLive")),R;if(E){let W=f.getAttribute("DVRWindowLength");W!==null&&!isNaN(+W)&&+W!=0&&(R=+W/y)}let k=T.reduce((W,se)=>{let ae=a({root:se,baseUrl:c,timescale:y,protections:b,isLive:E,timeShiftBufferDepth:R,manifestReceivedTime:l});if(ae===null)return W;let de=ae.type,Se=W[de];return Se===void 0?W[de]=[ae]:Se.push(ae),W},v),x,M,P,N=null,O,K=k.video!==void 0?k.video[0]:void 0,A=k.audio!==void 0?k.audio[0]:void 0,C,D,L;if(K!==void 0||A!==void 0){let W=[],se=[];if(K!==void 0){let ae=K.representations[0];if(ae!==void 0){let de=ae.index.getFirstAvailablePosition(),Se=ae.index.getLastAvailablePosition();_(de)||W.push(de),_(Se)||se.push(Se)}}if(A!==void 0){let ae=A.representations[0];if(ae!==void 0){let de=ae.index.getFirstAvailablePosition(),Se=ae.index.getLastAvailablePosition();_(de)||W.push(de),_(Se)||se.push(Se)}}W.length>0&&(C=Math.max(...W)),se.length>0&&(D=Math.min(...se),L=Math.max(...se))}let V=f.getAttribute("Duration"),$=V!==null&&+V!=0?+V/y:void 0;if(E){x=n.suggestedPresentationDelay,M=e,P=C!=null?C:M;let W=L;W===void 0&&(W=Date.now()/1e3-M);let se=D;se===void 0&&(se=W),O={isLinear:!0,maximumSafePosition:se,livePosition:W,time:F()},N=R!=null?R:null}else{P=C!=null?C:0;let W=D;W===void 0&&(W=$!==void 0?P+$:1/0),O={isLinear:!1,maximumSafePosition:W,livePosition:void 0,time:F()}}let j=E?0:P,z=E?void 0:O.maximumSafePosition,q={availabilityStartTime:M===void 0?0:M,clockOffset:i,isLive:E,isDynamic:E,isLastPeriodKnown:!0,timeBounds:{minimumSafePosition:P,timeshiftDepth:N,maximumTimeData:O},periods:[{adaptations:k,duration:z!==void 0?z-j:$,end:z,id:"gen-smooth-period-0",start:j}],suggestedPresentationDelay:x,transportType:"smooth",uris:_(u)?[]:[u]};return nr(q),q}return s}function ab(n,e){if(n.length!==32)throw new Error("HSS: wrong system id length");return le("pssh",ie([0,0,0,0],je(n),Ie(e.length),e))}var Rm=ob;var km=Rm;function Cm(n,e,t,r,i,o,a){return le("avc1",ie(6,fe(1),16,fe(n),fe(e),fe(t),2,fe(r),6,[0,1,i.length],ve(i),31-i.length,fe(o),[255,255],a))}function Pm(n,e,t,r,i,o,a,s){return le("encv",ie(6,fe(1),16,fe(n),fe(e),fe(t),2,fe(r),6,[0,1,i.length],ve(i),31-i.length,fe(o),[255,255],a,s))}function Mm(n,e,t,r,i,o){return le("mp4a",ie(6,fe(n),8,fe(e),fe(t),2,fe(r),fe(i),2,o))}function Am(n,e,t,r,i,o,a){return le("enca",ie(6,fe(n),8,fe(e),fe(t),2,fe(r),fe(i),2,o,a))}function xm(n){return le("dref",ie(7,[1],n))}function wm(n,e){let t=ie(...[ve(n),[0,0,0,1]].concat(e.map(ve)));return le("ftyp",t)}function Ea(n,e){return le("schm",ie(4,ve(n),Ie(e)))}function Om(n){return le("tfdt",ie([1,0,0,0],Yt(n)))}function Dm(){let n=new Uint8Array(12);return n[3]=1,le("vmhd",n)}function Lm(n){return le("trex",ie(4,Ie(n),[0,0,0,1],12))}function Nm(n){return le("free",new Uint8Array(n-8))}function Um(n,e){return le("esds",ie(4,[3,25],fe(n),[0,4,17,64,21],11,[5,2],je(e),[6,1,2]))}function va(n){return le("frma",ve(n))}function Bm(n,e,t){let r;t===2?r=1:t===4?r=3:r=0;let i=n[1],o=n[2],a=n[3];return le("avcC",ie([1,i,o,a,252|r,225],fe(n.length),n,[1],fe(e.length),e))}function Fm(n){let e,t;switch(n){case"video":e="vide",t="VideoHandler";break;case"audio":e="soun",t="SoundHandler";break;default:e="hint",t="";break}return le("hdlr",ie(8,ve(e),12,ve(t),1))}function Km(n){return le("mdhd",ie(12,Ie(n),8))}function Vm(n,e){return le("mvhd",ie(12,Ie(n),4,[0,1],2,[1,0],10,[0,1],14,[0,1],14,[64,0,0,0],26,fe(e+1)))}function zm(n,e,t,r){return le("saio",ie(4,[0,0,0,1],Ie(n.length+e.length+t.length+r.length+8+8+8+8)))}function Hm(n){if(n.length===0)return le("saiz",new Uint8Array(0));let e=ne(n,0),t=ne(n,4),r=new Uint8Array(t+9);r.set(Ie(t),5);let i=9,o=8,a,s;for(;o<n.length;)o+=8,(e&2)===2?(s=2,a=No(n,o),o+=a*6+2):(a=0,s=0),r[i]=a*6+8+s,i++;return le("saiz",r)}function Wm(){return le("smhd",new Uint8Array(8))}function ir(n){let e=[7,[n.length]];return le("stsd",ie(...e.concat(n)))}function Gm(n,e,t){return le("tkhd",ie(Ie(7),8,Ie(t),20,[1,0,0,0],[0,1,0,0],12,[0,1,0,0],12,[64,0,0,0],fe(n),2,fe(e),2))}function Ra(n,e,t){return le("tenc",ie(6,[n,e],t))}function sb(n,e,t){return Ae("moov",[n,e,t])}function oo(n,e,t,r,i,o){let a=Ae("stbl",[t,le("stts",new Uint8Array(8)),le("stsc",new Uint8Array(8)),le("stsz",new Uint8Array(12)),le("stco",new Uint8Array(8))]),s=le("url ",new Uint8Array([0,0,0,1])),d=xm(s),u=Ae("dinf",[d]),l=Ae("minf",[r,u,a]),c=Fm(e),f=Km(n),g=Ae("mdia",[f,c,l]),p=Gm(i,o,1),I=Ae("trak",[p,g]),y=Lm(1),b=Ae("mvex",[y]),T=Vm(n,1),v=sb(T,b,I),E=wm("isom",["isom","iso2","iso6","avc1","dash"]);return ie(E,v)}var db=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];function _l(n,e,t){let r=db.indexOf(e),i;return i=(n&63)<<4,i=(i|r&31)<<4,i=(i|t&31)<<3,Ue(fe(i))}function ka(n,e,t,r,i,o,a){let s=o.length===0?_l(2,i,e):o,d=Um(1,s),u=(()=>{if(a===void 0){let y=Mm(1,e,t,r,i,d);return ir([y])}let l=Ra(1,8,a),c=Ae("schi",[l]),f=Ea("cenc",65536),g=va("mp4a"),p=Ae("sinf",[g,f,c]),I=Am(1,e,t,r,i,d,p);return ir([I])})();return oo(n,"audio",u,Wm(),0,0)}function Ca(n,e,t,r,i,o,a,s){let[,d,u]=a.split("00000001");if(d===void 0||u===void 0)throw new Error("Smooth: unsupported codec private data.");let l=je(d),c=je(u),f=Bm(l,c,o),g;if(s===void 0){let p=Cm(e,t,r,i,"AVC Coding",24,f);g=ir([p])}else{let p=Ra(1,8,s),I=Ae("schi",[p]),y=Ea("cenc",65536),b=va("avc1"),T=Ae("sinf",[b,y,I]),v=Pm(e,t,r,i,"AVC Coding",24,f,T);g=ir([v])}return oo(n,"video",g,Dm(),e,t)}function Pa(n){let e=gn(n,3565190898,3392751253,2387879627,2655430559);if(e===void 0)return[];let t=[],r=e[0],i=e[4];for(let o=0;o<i;o++){let a,s;r===1?(s=Ve(e,o*16+5),a=Ve(e,o*16+5+8)):(s=ne(e,o*8+5),a=ne(e,o*8+5+4)),t.push({time:s,duration:a})}return t}function Ma(n){let e=gn(n,1830656773,1121273062,2162299933,2952222642);if(e!==void 0)return{duration:Ve(e,12),time:Ve(e,4)}}function El(){return!Ht}function vl(n,e,t,r,i){let o=[n,e,t];return i!==void 0&&o.push(le("senc",i),Hm(i),zm(r,n,e,t)),Ae("traf",o)}function Aa(n,e){let t=ze(n,1836019558);if(t===null)throw new Error("Smooth: Invalid ISOBMFF given");let r=n.subarray(t[1],t[2]),i=Ts(r,1835427940),o=Re(r,1953653094);if(o===null||i===null)throw new Error("Smooth: Invalid ISOBMFF given");let a=ze(o,1952868452),s=ze(o,1953658222);if(a===null||s===null)throw new Error("Smooth: Invalid ISOBMFF given");let d=o.subarray(a[0],a[2]),u=o.subarray(s[0],s[2]);d.set([0,0,0,1],a[1]-a[0]+4);let l=Om(e),c=ub(u,s[1]-s[0]),f=gn(o,2721664850,1520127764,2722393154,2086964724),g=vl(d,l,c,i,f),p=Ae("moof",[i,g]),I=ze(p,1836019558),y=ze(g,1953653094),b=ze(c,1953658222);if(I===null||y===null||b===null)throw new Error("Smooth: Invalid moof, trun or traf generation");let T=I[1]-I[0]+i.length+(y[1]-y[0])+d.length+l.length+(b[1]-b[0])+8,v=t[2]-t[0],E=p.length-v,R=ze(n,1835295092);if(R===null)throw new Error("Smooth: Invalid ISOBMFF given");if(El()&&(E===0||E<=-8)){let k=R[1];return p.set(Ie(k),T),n.set(p,t[0]),E<=-8&&n.set(Nm(-E),p.length),n}else{let k=R[1]+E;p.set(Ie(k),T);let x=new Uint8Array(n.length+E),M=n.subarray(0,t[0]),P=n.subarray(t[2],n.length);return x.set(M,0),x.set(p,M.length),x.set(P,M.length+p.length),x}}function ub(n,e){if((n[e+3]&1)>0)return n;let r=new Uint8Array(n.length+4);return r.set(n.subarray(0,e+8),0),r[e+3]=r[e+3]|1,r.set([0,0,0,0],e+8),r.set(n.subarray(e+8,n.length),e+12),ks(r)}function xa(n,e,t,r,i){var g;let o=[],a,s,d;if(i){let p=Or(n);p!==null?(d=Pa(p),s=Ma(p)):m.warn("smooth: could not find traf atom")}if(d!==void 0)for(let p of d)o.push({time:p.time,duration:p.duration,timescale:t});if(s!==void 0)return a={time:s.time/t,duration:s.duration/t},{nextSegments:o,chunkInfos:a,scaledSegmentTime:s.time};if(e||!r.complete)return{nextSegments:o,chunkInfos:null,scaledSegmentTime:void 0};let u=r.duration*t,l=Math.min(t*.9,u/4),c=Ur(n),f=((g=r.privateInfos)==null?void 0:g.smoothMediaSegment)!==void 0?r.privateInfos.smoothMediaSegment.time:Math.round(r.time*t);return c!==void 0&&Math.abs(c-u)<=l?a={time:r.time,duration:c/t}:a={time:r.time,duration:r.duration},{nextSegments:o,chunkInfos:a,scaledSegmentTime:f}}function An(n){return typeof n=="string"&&n.indexOf("mp4")>=0}async function qm(n,e,t,r,i,o){var g,p;let a=((g=r.cmcdPayload)==null?void 0:g.type)==="headers"?r.cmcdPayload.value:void 0,s=e.segment.range,d;Array.isArray(s)?d=ue(oe({},a),{Range:ut(s)}):a!==void 0&&(d=a);let u=((p=r.cmcdPayload)==null?void 0:p.type)==="query"?$e(n,r.cmcdPayload.value):n,l=await Te({url:u,responseType:"arraybuffer",headers:d,timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i,onProgress:t.onProgress});if(!An(e.mimeType)||o!==!0)return{resultType:"segment-loaded",resultData:l};let f=new Uint8Array(l.responseData);return en(f,e.segment.isInit),{resultType:"segment-loaded",resultData:ue(oe({},l),{responseData:f})}}var lb=({checkMediaSegmentIntegrity:n,segmentLoader:e})=>(t,r,i,o,a)=>{let{segment:s}=r;if(s.isInit){if(s.privateInfos===void 0||s.privateInfos.smoothInitSegment===void 0)throw new Error("Smooth: Invalid segment format");let d=s.privateInfos.smoothInitSegment,u,{codecPrivateData:l,timescale:c,height:f,width:g,protection:p={keyId:void 0,keySystems:void 0}}=d;if(l===void 0)throw new Error("Smooth: no codec private data.");switch(r.type){case"video":{u=Ca(c,g!=null?g:0,f!=null?f:0,72,72,4,l,p.keyId);break}case"audio":{let{channels:I=0,bitsPerSample:y=0,packetSize:b=0,samplingRate:T=0}=d;u=ka(c,I,y,b,T,l,p.keyId);break}default:h.CURRENT_ENV===h.DEV&&ee(!1,"responseData should have been set"),u=new Uint8Array(0)}return Promise.resolve({resultType:"segment-created",resultData:u})}else return t===null?Promise.resolve({resultType:"segment-created",resultData:null}):typeof e!="function"?qm(t,r,a,i,o,n):new Promise((d,u)=>{let l=!1,I={reject:E=>{var M,P;if(l||o.isCancelled())return;l=!0,o.deregister(v);let R=E,k=(M=R==null?void 0:R.message)!=null?M:"Unknown error when fetching a Smooth segment through a custom segmentLoader.",x=new rt(k,(P=R==null?void 0:R.canRetry)!=null?P:!1,R==null?void 0:R.xhr);u(x)},resolve:E=>{if(l||o.isCancelled())return;l=!0,o.deregister(v),(!An(r.mimeType)||n!==!0)&&d({resultType:"segment-loaded",resultData:{responseData:E.data,size:E.size,requestDuration:E.duration}});let k=E.data instanceof Uint8Array?E.data:new Uint8Array(E.data);en(k,r.segment.isInit),d({resultType:"segment-loaded",resultData:{responseData:k,size:E.size,requestDuration:E.duration}})},fallback:()=>{l||o.isCancelled()||(l=!0,o.deregister(v),qm(t,r,a,i,o,n).then(d,u))},progress:E=>{l||o.isCancelled()||a.onProgress({duration:E.duration,size:E.size,totalSize:E.totalSize})}},y;r.segment.range!==void 0&&(y=[r.segment.range],r.segment.indexRange!==void 0&&y.push(r.segment.indexRange));let b={isInit:r.segment.isInit,timeout:i.timeout,byteRanges:y,trackType:r.type,url:t,cmcdPayload:i.cmcdPayload},T=e(b,I);o.register(v);function v(E){l||(l=!0,!l&&typeof T=="function"&&T(),u(E))}})},jm=lb;function Rl(n,e){return n===null?null:e.url===null?n.baseUrl:cn(n.baseUrl,e.url)}function Ym(n){let e=km(n),t=jm(n),r={customManifestLoader:n.manifestLoader},o={loadManifest:Ui(r,"text",null),parseManifest(d,u){var b;let l=(b=d.url)!=null?b:u.originalUrl,{receivedTime:c,responseData:f}=d,g=typeof f=="string"?new DOMParser().parseFromString(f,"text/xml"):f,p=e(g,l,c),I=[];return{manifest:new zn(p,{representationFilter:n.representationFilter},I),url:l,warnings:I}}},a={loadSegment(d,u,l,c,f){let g=Rl(d,u.segment);return t(g,u,l,c,f)},parseSegment(d,u,l){var R,k;let{segment:c}=u,{data:f,isChunked:g}=d;if(f===null)return c.isInit?{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0}:{segmentType:"media",chunkData:null,chunkInfos:null,chunkOffset:0,chunkSize:0,protectionData:[],appendWindow:[void 0,void 0]};let p=f instanceof Uint8Array?f:new Uint8Array(f);if(c.isInit){let x=(k=(R=c.privateInfos)==null?void 0:R.smoothInitSegment)==null?void 0:k.timescale;return{segmentType:"init",initializationData:f,initializationDataSize:f.byteLength,initTimescale:x,protectionData:[]}}let I=l!==void 0?xa(p,g,l,c,u.isLive):null;if(I===null||I.chunkInfos===null||I.scaledSegmentTime===void 0)throw new Error("Smooth Segment without time information");let{nextSegments:y,chunkInfos:b,scaledSegmentTime:T}=I,v=Aa(p,T),E=y.length>0?y:void 0;return{segmentType:"media",chunkData:v,chunkInfos:b,chunkOffset:0,chunkSize:v.length,protectionData:[],predictedSegments:E,appendWindow:[void 0,void 0]}}};return{transportName:"smooth",manifest:o,audio:a,video:a,text:{loadSegment(d,u,l,c,f){var y,b,T,v;let{segment:g}=u,p=Rl(d,g);return g.isInit||p===null?Promise.resolve({resultType:"segment-created",resultData:null}):An(u.mimeType)?Te({url:((T=l.cmcdPayload)==null?void 0:T.type)==="query"?$e(p,l.cmcdPayload.value):p,headers:((v=l.cmcdPayload)==null?void 0:v.type)==="headers"?l.cmcdPayload.value:void 0,responseType:"arraybuffer",timeout:l.timeout,connectionTimeout:l.connectionTimeout,cancelSignal:c,onProgress:f.onProgress}).then(E=>{if(n.checkMediaSegmentIntegrity!==!0)return{resultType:"segment-loaded",resultData:E};let R=new Uint8Array(E.responseData);return en(R,u.segment.isInit),{resultType:"segment-loaded",resultData:ue(oe({},E),{responseData:R})}}):Te({url:((y=l.cmcdPayload)==null?void 0:y.type)==="query"?$e(p,l.cmcdPayload.value):p,headers:((b=l.cmcdPayload)==null?void 0:b.type)==="headers"?l.cmcdPayload.value:void 0,responseType:"text",timeout:l.timeout,connectionTimeout:l.connectionTimeout,cancelSignal:c,onProgress:f.onProgress}).then(E=>({resultType:"segment-loaded",resultData:E}))},parseSegment(d,u,l){var O;let{segment:c,language:f,mimeType:g="",codecs:p=""}=u,I=An(u.mimeType),{data:y,isChunked:b}=d,T;if(c.isInit)return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0};if(y===null)return{segmentType:"media",chunkData:null,chunkInfos:null,chunkOffset:0,chunkSize:0,protectionData:[],appendWindow:[void 0,void 0]};let v,E=null,R,k,x,M;if(I){let K;typeof y=="string"?K=ve(y):K=y instanceof Uint8Array?y:new Uint8Array(y),T=K.length;let A=l!==void 0?xa(K,b,l,c,u.isLive):null;v=A==null?void 0:A.nextSegments,E=(O=A==null?void 0:A.chunkInfos)!=null?O:null,E===null?b?m.warn("Smooth: Unavailable time data for current text track."):(R=c.time,k=c.end):(R=E.time,k=E.duration!==void 0?E.time+E.duration:c.end);let C=p.toLowerCase();if(g==="application/ttml+xml+mp4"||C==="stpp"||C==="stpp.ttml"||C==="stpp.ttml.im1t")M="ttml";else if(C==="wvtt")M="vtt";else throw new Error(`could not find a text-track parser for the type ${g}`);let D=Dr(K);x=D===null?"":Ne(D)}else{R=c.time,k=c.end;let K;if(typeof y!="string"){let A=y instanceof Uint8Array?y:new Uint8Array(y);T=A.length,K=Ne(A)}else K=y;switch(g){case"application/x-sami":case"application/smil":M="sami";break;case"application/ttml+xml":M="ttml";break;case"text/vtt":M="vtt";break}if(M===void 0)if(p.toLowerCase()==="srt")M="srt";else throw new Error(`could not find a text-track parser for the type ${g}`);x=K}let P=Array.isArray(v)&&v.length>0?v:void 0,N=R!=null?R:0;return{segmentType:"media",chunkData:{type:M,data:x,start:R,end:k,language:f},chunkSize:T,chunkInfos:E,chunkOffset:N,protectionData:[],predictedSegments:P,appendWindow:[void 0,void 0]}}}}}var $m=Ym;function kl(n){n.transports.smooth===void 0&&(n.transports.smooth=$m),n.mainThreadMediaSourceInit=_n}function Qm(){if(!dn)return m.warn("Compat: Can't access Firefox version on no firefox browser."),null;let n=navigator.userAgent,e=/Firefox\/([0-9]+)\./.exec(n);if(e===null)return-1;let t=parseInt(e[1],10);return isNaN(t)?-1:t}function Cl(){if(!dn)return!0;let n=Qm();if(n===null||n<67)return!0;let e=HTMLVideoElement==null?void 0:HTMLVideoElement.prototype;return(e==null?void 0:e.requirePictureInPicture)!==void 0}function ao(n){let e=n;if(typeof e.getStartDate=="function"){let t=e.getStartDate();if(typeof t=="object"&&t!==null){let r=+t;if(!isNaN(r))return r/1e3}else if(typeof t=="number"&&!isNaN(t))return t}}function Pl(){return za&&typeof Worker=="object"||typeof Worker=="function"}var xn=class n extends Error{constructor(e,t){super(ct(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="WorkerInitializationError",this.type="WORKER_INITIALIZATION_ERROR",this.code=e}};function wa(n,e,t){let r=e(n.getReference(),t);return{getCurrentTime(){return n.getCurrentTime()},getReadyState(){return n.getReadyState()},getPlaybackRate(){return n.getPlaybackRate()},getIsPaused(){return n.getIsPaused()},getReference(){return r},listen(i,o){t.isCancelled()||o.clearSignal.isCancelled()||r.onUpdate(i,{clearSignal:o.clearSignal,emitCurrentValue:o.includeLastObservation})},deriveReadOnlyObserver(i){return wa(this,i,t)}}}var cb=["canplay","ended","play","pause","seeking","seeked","loadedmetadata","ratechange"],so=class{constructor(e,t){this._internalSeeksIncoming=[],this._mediaElement=e,this._withMediaSource=t.withMediaSource,this._lowLatencyMode=t.lowLatencyMode,this._canceller=new B,this._observationRef=this._createSharedReference(),this._expectedSeekingPosition=null,this._pendingSeek=null;let r=()=>{if(this._pendingSeek!==null){let i=this._pendingSeek;this._pendingSeek=null,this._actuallySetCurrentTime(i)}};e.addEventListener("loadedmetadata",r),this._canceller.signal.register(()=>{e.removeEventListener("loadedmetadata",r)})}stop(){this._canceller.cancel()}getCurrentTime(){return this._mediaElement.currentTime}getPlaybackRate(){return this._mediaElement.playbackRate}getIsPaused(){return this._mediaElement.paused}setCurrentTime(e){this._mediaElement.readyState>=1?this._actuallySetCurrentTime(e):(this._internalSeeksIncoming=[],this._pendingSeek=e,this._generateObservationForEvent("manual"))}setPlaybackRate(e){this._mediaElement.playbackRate=e}getReadyState(){return this._mediaElement.readyState}getReference(){return this._observationRef}listen(e,t){if(this._canceller.isUsed()||t.clearSignal.isCancelled())return X;this._observationRef.onUpdate(e,{clearSignal:t.clearSignal,emitCurrentValue:t.includeLastObservation})}deriveReadOnlyObserver(e){return wa(this,e,this._canceller.signal)}_actuallySetCurrentTime(e){m.info("API: Seeking internally",e),this._internalSeeksIncoming.push(e),this._mediaElement.currentTime=e}_createSharedReference(){if(this._observationRef!==void 0)return this._observationRef;let{SAMPLING_INTERVAL_MEDIASOURCE:e,SAMPLING_INTERVAL_LOW_LATENCY:t,SAMPLING_INTERVAL_NO_MEDIASOURCE:r}=U.getCurrent(),i=new H(this._getCurrentObservation("init"),this._canceller.signal),o;this._lowLatencyMode?o=t:this._withMediaSource?o=e:o=r;let a=()=>{this._generateObservationForEvent("timeupdate")},s=setInterval(a,o);return cb.map(u=>{let l=()=>{d(),this._generateObservationForEvent(u)};this._mediaElement.addEventListener(u,l),this._canceller.signal.register(()=>{this._mediaElement.removeEventListener(u,l)})}),this._canceller.signal.register(()=>{clearInterval(s),i.finish()}),i;function d(){clearInterval(s),s=setInterval(a,o)}}_getCurrentObservation(e){var T,v;let t=e,r=this._observationRef===void 0?hb(this._mediaElement):this._observationRef.getValue(),i=!1,o=this._pendingSeek,a=Zm(this._mediaElement),{buffered:s,readyState:d,position:u,seeking:l}=a;if(t==="seeking")if(this._internalSeeksIncoming.length>0){i=!0,t="internal-seeking";let E=this._internalSeeksIncoming.shift();this._expectedSeekingPosition=$n?Math.max(u,E!=null?E:0):u}else this._expectedSeekingPosition=u;else l?this._expectedSeekingPosition=Math.max(u,(T=this._expectedSeekingPosition)!=null?T:0):$n&&this._expectedSeekingPosition!==null&&u<this._expectedSeekingPosition?o=this._expectedSeekingPosition:this._expectedSeekingPosition=null;l&&r.seeking===1&&e!=="seeking"&&(i=!0);let c=(v=this._expectedSeekingPosition)!=null?v:u,f,g;!this._withMediaSource&&s.length===0&&d>=3?(f=void 0,g=void 0):(f=Ya(s,c),g=f!==null?f.end-c:1/0);let p=mb({previousObservation:r,currentObservation:a,basePosition:c,observationEvent:t,lowLatencyMode:this._lowLatencyMode,withMediaSource:this._withMediaSource,bufferGap:g,currentRange:f}),I=pb(r,a,t,g),y;i?y=1:l?y=2:y=0;let b=G({},a,{position:new Yn(a.position,o),event:t,seeking:y,rebuffering:p,freezing:I,bufferGap:g,currentRange:f});return m.hasLevel("DEBUG")&&m.debug("API: current media element state tick","event",b.event,"position",b.position.getPolled(),"seeking",b.seeking,"internalSeek",i,"rebuffering",b.rebuffering!==null,"freezing",b.freezing!==null,"ended",b.ended,"paused",b.paused,"playbackRate",b.playbackRate,"readyState",b.readyState,"pendingPosition",o),b}_generateObservationForEvent(e){let t=this._getCurrentObservation(e);m.hasLevel("DEBUG")&&m.debug(`API: current playback timeline:
|
|
15
|
-
`+
|
|
16
|
-
${e}`),this._observationRef.setValue(t)}};function
|
|
17
|
-
`+r}function hb(n){let e=Zm(n);return G(e,{rebuffering:null,event:"init",seeking:0,position:new Yn(e.position,null),freezing:null,bufferGap:0,currentRange:null})}var uo=class extends re{constructor(e){super(),this._canceller=new B,this._adaptationRef=e,this._updateToken=!1,this._lastEmitted=void 0,this.refresh=X}hasSetTrack(){return this._adaptationRef.getValue()!==void 0}updateTrack(e){if(this._updateToken=!0,e===null){if(this._lastEmitted===null)return;this._updateToken=!1,this._canceller.cancel(),this._canceller=new B,this._lastEmitted=null,this._adaptationRef.setValue(null);return}let{adaptation:t,switchingMode:r,relativeResumingPosition:i}=e;this._canceller.cancel(),this._canceller=new B;let o=this._constructLockedRepresentationsReference(e);this._updateToken&&(this._lastEmitted={adaptation:t,switchingMode:r,lockedRepresentations:null},this._updateToken=!1,this._adaptationRef.setValue({adaptationId:t.id,switchingMode:r,representations:o,relativeResumingPosition:i}))}_constructLockedRepresentationsReference(e){let t=new H({representationIds:[],switchingMode:"lazy"}),r=this;return this.refresh=i,this._canceller.signal.register(o),e.lockedRepresentations.onUpdate(i,{clearSignal:this._canceller.signal,emitCurrentValue:!1}),i(),t;function i(){let a=e.lockedRepresentations.getValue(),s,d;if(a===null)d=e.adaptation.representations.filter(c=>c.isSupported===!0&&c.decipherable!==!1),s="lazy";else{let{representationIds:c}=a;if(s=a.switchingMode,d=e.adaptation.representations.filter(g=>Q(c,g.id)).filter(g=>g.isSupported===!0&&g.decipherable!==!1),d.length===0){r.trigger("noPlayableLockedRepresentation",null);return}}if(d.length<=0){r.trigger("noPlayableRepresentation",null);return}let u=t.getValue(),l=d.map(c=>c.id).slice().sort();if(l.length!==u.representationIds.length){t.setValue({representationIds:l,switchingMode:s});return}for(let c=0;c<l.length;c++)if(u.representationIds[c]!==l[c]){t.setValue({representationIds:l,switchingMode:s});return}}function o(){r.refresh=X}}dispose(){this.removeEventListener(),this._canceller.cancel(),this._adaptationRef.finish()}};var lo=class extends re{constructor(e){var t;super(),this._storedPeriodInfo=[],this._isDisposed=!1,this._cachedPeriodInfo=new WeakMap,this._isTrickModeTrackEnabled=e.preferTrickModeTracks,this._defaultAudioTrackSwitchingMode=(t=e.defaultAudioTrackSwitchingMode)!=null?t:U.getCurrent().DEFAULT_AUDIO_TRACK_SWITCHING_MODE}getAvailablePeriods(){return this._storedPeriodInfo.reduce((e,t)=>(t.isPeriodAdvertised&&e.push(Bt(t.period)),e),[])}onManifestCodecSupportUpdate(){this._selectInitialTrackIfNeeded()}onManifestUpdate(e){var a,s,d,u,l,c;let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:t}=U.getCurrent(),{periods:r}=e;if(h.CURRENT_ENV===h.DEV)for(let f=1;f<r.length;f++)ee(r[f-1].start<=r[f].start);let i=[],o=0;for(let f=0;f<this._storedPeriodInfo.length;f++){let g=this._storedPeriodInfo[f].period,p=r[o];if(p===void 0)for(let I=this._storedPeriodInfo.length-1;I>=f;I--)this._storedPeriodInfo[I].inManifest=!1,Ml(this._storedPeriodInfo[I])&&this._removePeriodObject(I);else if(g===p){o++;let I=this._storedPeriodInfo[f].text.storedSettings;if(!_(I)&&!pt(p,"text").some(E=>E.id===I.adaptation.id)){m.warn("TS: Chosen text Adaptation not available anymore");let E=this._storedPeriodInfo[f];if(E.text.storedSettings=null,this.trigger("trackUpdate",{period:Bt(p),trackType:"text",reason:"missing"}),this._isDisposed)return;let R=lt(this._storedPeriodInfo,E.period.id);R!==void 0&&R.isPeriodAdvertised&&R.text.storedSettings===null&&((a=R.text.dispatcher)==null||a.updateTrack(null))}let y=this._storedPeriodInfo[f].video.storedSettings;if(!_(y)){let T=pt(p,"video");if(!T.some(E=>E.id===y.adaptation.id)){m.warn("TS: Chosen video Adaptation not available anymore");let E=this._storedPeriodInfo[f],R;if(T.length===0)R=null;else{let x=T[0],M=Oa(x,this._isTrickModeTrackEnabled),P=new H(null);R={adaptationBase:x,adaptation:M,switchingMode:t,lockedRepresentations:P}}if(E.video.storedSettings=R,this.trigger("trackUpdate",{period:Bt(p),trackType:"video",reason:"missing"}),this._isDisposed)return;let k=lt(this._storedPeriodInfo,E.period.id);k!==void 0&&k.isPeriodAdvertised&&k.video.storedSettings===R&&((s=k.video.dispatcher)==null||s.updateTrack(R))}}let b=this._storedPeriodInfo[f].audio.storedSettings;if(!_(b)){let T=pt(p,"audio");if(!T.some(E=>E.id===b.adaptation.id)){m.warn("TS: Chosen audio Adaptation not available anymore");let E=this._storedPeriodInfo[f],R=T.length===0?null:{adaptation:T[0],switchingMode:this._defaultAudioTrackSwitchingMode,lockedRepresentations:new H(null)};if(E.audio.storedSettings=R,this.trigger("trackUpdate",{period:Bt(p),trackType:"audio",reason:"missing"}),this._isDisposed)return;let k=lt(this._storedPeriodInfo,E.period.id);k!==void 0&&k.isPeriodAdvertised&&k.audio.storedSettings===R&&((d=k.audio.dispatcher)==null||d.updateTrack(R))}}}else if(g.start<=p.start)this._storedPeriodInfo[f].inManifest=!1,Ml(this._storedPeriodInfo[f])&&(this._removePeriodObject(f),f--);else{let I=Al(p,!0);this._storedPeriodInfo.splice(f,0,I),i.push(I),o++}}if(o<r.length){let f=r.slice(o).map(g=>Al(g,!0));this._storedPeriodInfo.push(...f),i.push(...f)}for(let f of this._storedPeriodInfo)(u=f.audio.dispatcher)==null||u.refresh(),(l=f.video.dispatcher)==null||l.refresh(),(c=f.text.dispatcher)==null||c.refresh()}onDecipherabilityUpdates(){var e,t,r;for(let i of this._storedPeriodInfo)(e=i.audio.dispatcher)==null||e.refresh(),(t=i.video.dispatcher)==null||t.refresh(),(r=i.text.dispatcher)==null||r.refresh()}addTrackReference(e,t,r){let i=lt(this._storedPeriodInfo,t.id);if(i===void 0){i=Al(t,!1);let s=!1;for(let d=0;d<this._storedPeriodInfo.length;d++)this._storedPeriodInfo[d].period.start>t.start&&(this._storedPeriodInfo.splice(d,0,i),s=!0);s||this._storedPeriodInfo.push(i)}if(i[e].dispatcher!==null){m.error(`TS: Subject already added for ${e} and Period ${t.start}`);return}let o=new uo(r);if(i[e].dispatcher=o,o.addEventListener("noPlayableRepresentation",()=>{var c,f,g,p;let s=Z((c=t.adaptations[e])!=null?c:[],I=>I.supportStatus.hasSupportedCodec===!1||I.supportStatus.isDecipherable===!1?!1:I.representations.filter(b=>b.isSupported===!0&&b.decipherable!==!1).length>0);if(s===void 0){let I=new te("NO_PLAYABLE_REPRESENTATION",`No ${e} Representation can be played`,{tracks:void 0});this.trigger("error",I),this.dispose();return}let d=(f=lt(this._storedPeriodInfo,t.id))==null?void 0:f[e];if(_(d))return;let u=e==="audio"?this._defaultAudioTrackSwitchingMode:"reload",l={adaptation:s,switchingMode:u,lockedRepresentations:new H(null)};d.storedSettings=l,this.trigger("trackUpdate",{period:Bt(t),trackType:e,reason:"no-playable-representation"}),!this._isDisposed&&(d=(g=lt(this._storedPeriodInfo,t.id))==null?void 0:g[e],!(_(d)||d.storedSettings!==l)&&((p=d.dispatcher)==null||p.updateTrack(l)))}),o.addEventListener("noPlayableLockedRepresentation",()=>{i!==void 0&&(this.unlockVideoRepresentations(i),this.trigger("brokenRepresentationsLock",{period:{id:t.id,start:t.start,end:t.end},trackType:e}))}),this._selectInitialTrackIfNeeded(),this._shouldAdvertisePeriod(i)&&(i.isPeriodAdvertised=!0,this.trigger("newAvailablePeriods",[{id:t.id,start:t.start,end:t.end}]),this._isDisposed))return;let a=["audio","video","text"];for(let s of a){let d=i[s];if(i.isPeriodAdvertised&&d.dispatcher!==null&&!d.dispatcher.hasSetTrack()&&d.storedSettings!==void 0&&d.dispatcher.updateTrack(d.storedSettings),this._isDisposed)return}}removeTrackReference(e,t){let r=yb(this._storedPeriodInfo,t);if(r===void 0){m.warn(`TS: ${e} not found for period`,t.start);return}let i=this._storedPeriodInfo[r],o=i[e];if((o==null?void 0:o.dispatcher)===null){m.warn(`TS: TrackDispatcher already removed for ${e} and Period ${t.start}`);return}o.dispatcher.dispose(),o.dispatcher=null,Ml(i)&&this._removePeriodObject(r)}getPeriodObjectFromPeriod(e){let t=lt(this._storedPeriodInfo,e.id);return t===void 0&&e!==void 0?this._cachedPeriodInfo.get(e):t}getPeriodObjectFromId(e){return lt(this._storedPeriodInfo,e)}disableVideoTrickModeTracks(){this._isTrickModeTrackEnabled&&(this._isTrickModeTrackEnabled=!1,this._resetVideoTrackChoices("trickmode-disabled"))}enableVideoTrickModeTracks(){this._isTrickModeTrackEnabled||(this._isTrickModeTrackEnabled=!0,this._resetVideoTrackChoices("trickmode-enabled"))}resetPeriodObjects(){var e,t,r;for(let i=this._storedPeriodInfo.length-1;i>=0;i--){let o=this._storedPeriodInfo[i];(e=o.audio.dispatcher)==null||e.dispose(),o.audio.dispatcher=null,(t=o.video.dispatcher)==null||t.dispose(),o.video.dispatcher=null,(r=o.text.dispatcher)==null||r.dispose(),o.text.dispatcher=null,o.inManifest||this._removePeriodObject(i)}}isTrickModeEnabled(){return this._isTrickModeTrackEnabled}setAudioTrack(e){let{periodRef:t,trackId:r,switchingMode:i,lockedRepresentations:o,relativeResumingPosition:a}=e;return this._setAudioOrTextTrack({bufferType:"audio",periodRef:t,trackId:r,switchingMode:i!=null?i:this._defaultAudioTrackSwitchingMode,lockedRepresentations:o,relativeResumingPosition:a})}setTextTrack(e,t){return this._setAudioOrTextTrack({bufferType:"text",periodRef:e,trackId:t,switchingMode:"direct",lockedRepresentations:null,relativeResumingPosition:void 0})}_setAudioOrTextTrack({bufferType:e,periodRef:t,trackId:r,switchingMode:i,lockedRepresentations:o,relativeResumingPosition:a}){var g,p;if(!t.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let s=t.period,d=Z((g=s.adaptations[e])!=null?g:[],({id:I,supportStatus:y})=>y.hasSupportedCodec!==!1&&y.isDecipherable!==!1&&I===r);if(d===void 0)throw new Error(`Wanted ${e} track not found.`);let u=t[e],l;if(o===null)l=new H(null);else{let I=this._getRepresentationsToLock(d,o),y=e==="audio"?this._defaultAudioTrackSwitchingMode:"direct";l=new H({representationIds:I,switchingMode:y})}let c={adaptation:d,switchingMode:i,lockedRepresentations:l,relativeResumingPosition:a};if(u.storedSettings=c,this.trigger("trackUpdate",{period:Bt(s),trackType:e,reason:"manual"}),this._isDisposed)return;let f=lt(this._storedPeriodInfo,s.id);f!==void 0&&f[e].storedSettings===c&&((p=f[e].dispatcher)==null||p.updateTrack(c))}setVideoTrack(e){var I,y;let{periodRef:t,trackId:r,switchingMode:i,lockedRepresentations:o,relativeResumingPosition:a}=e;if(!t.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let s=t.period,d=Z((I=s.adaptations.video)!=null?I:[],({id:b,supportStatus:T})=>T.isDecipherable!==!1&&T.hasSupportedCodec!==!1&&b===r);if(d===void 0)throw new Error("Wanted video track not found.");let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:u}=U.getCurrent(),l=t.video,c=Oa(d,this._isTrickModeTrackEnabled),f;if(o===null)f=new H(null);else{let b=this._getRepresentationsToLock(d,o),T=u;f=new H({representationIds:b,switchingMode:T})}let g={adaptationBase:d,switchingMode:i!=null?i:u,adaptation:c,relativeResumingPosition:a,lockedRepresentations:f};if(l.storedSettings=g,this.trigger("trackUpdate",{period:Bt(s),trackType:"video",reason:"manual"}),this._isDisposed)return;let p=lt(this._storedPeriodInfo,s.id);p!==void 0&&p.video.storedSettings===g&&((y=p.video.dispatcher)==null||y.updateTrack(g))}disableTrack(e,t){var o,a;if(!e.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let r=e[t];if(r.storedSettings===null||(t!=="text"&&((o=e[t].storedSettings)==null||o.lockedRepresentations.finish()),r.storedSettings=null,this.trigger("trackUpdate",{period:Bt(e.period),trackType:t,reason:"manual"}),this._isDisposed))return;let i=lt(this._storedPeriodInfo,e.period.id);i!==void 0&&i[t].storedSettings===null&&((a=i[t].dispatcher)==null||a.updateTrack(null))}getChosenAudioTrack(e,t){return _(e.audio.storedSettings)?null:Yo(e.audio.storedSettings.adaptation,t)}getChosenTextTrack(e){return _(e.text.storedSettings)?null:$o(e.text.storedSettings.adaptation)}getChosenVideoTrack(e,t){return _(e.video.storedSettings)?null:Qo(e.video.storedSettings.adaptation,t)}getAvailableAudioTracks(e,t){let r=e.audio.storedSettings,i=_(r)?null:r.adaptation.id;return pt(e.period,"audio").map(a=>{let s=i===null?!1:i===a.id;return G(Yo(a,t),{active:s})})}getAvailableTextTracks(e){let t=e.text.storedSettings,r=_(t)?null:t.adaptation.id;return pt(e.period,"text").map(o=>{let a=r===null?!1:r===o.id;return G($o(o),{active:a})})}getAvailableVideoTracks(e,t){let r=e.video.storedSettings,i=_(r)?void 0:r.adaptation.id;return pt(e.period,"video").map(a=>{let s=i===null?!1:i===a.id,d=Qo(a,t),u=d.trickModeTracks!==void 0?d.trickModeTracks.map(c=>{let f=i===null?!1:i===c.id;return G(c,{active:f})}):[],l=G(d,{active:s});return u!==void 0&&(l.trickModeTracks=u),l})}getLockedAudioRepresentations(e){let{storedSettings:t}=e.audio;if(_(t))return null;let r=t.lockedRepresentations.getValue();return r===null?null:r.representationIds}getLockedVideoRepresentations(e){let{storedSettings:t}=e.video;if(_(t))return null;let r=t.lockedRepresentations.getValue();return r===null?null:r.representationIds}lockAudioRepresentations(e,t){var s;let{storedSettings:r}=e.audio;if(_(r))return;let{DEFAULT_AUDIO_REPRESENTATIONS_SWITCHING_MODE:i}=U.getCurrent(),o=this._getRepresentationsToLock(r.adaptation,t.representations),a=(s=t.switchingMode)!=null?s:i;r.lockedRepresentations.setValue({representationIds:o,switchingMode:a})}lockVideoRepresentations(e,t){var s;let{storedSettings:r}=e.video;if(_(r))return;let{DEFAULT_VIDEO_REPRESENTATIONS_SWITCHING_MODE:i}=U.getCurrent(),o=this._getRepresentationsToLock(r.adaptation,t.representations),a=(s=t.switchingMode)!=null?s:i;r.lockedRepresentations.setValue({representationIds:o,switchingMode:a})}unlockAudioRepresentations(e){let{storedSettings:t}=e.audio;_(t)||t.lockedRepresentations.getValue()===null||t.lockedRepresentations.setValue(null)}unlockVideoRepresentations(e){let{storedSettings:t}=e.video;_(t)||t.lockedRepresentations.getValue()===null||t.lockedRepresentations.setValue(null)}dispose(){for(this._isDisposed=!0;;){let e=this._storedPeriodInfo.pop();if(e===void 0)return;e.isRemoved=!0}}_resetVideoTrackChoices(e){var r;for(let i=0;i<this._storedPeriodInfo.length;i++){let o=this._storedPeriodInfo[i];if(!_(o.video.storedSettings)){let a=o.video.storedSettings.adaptationBase;if(a!==null){let s=Oa(a,this._isTrickModeTrackEnabled);o.video.storedSettings.adaptationBase=a,o.video.storedSettings.adaptation=s}}}let t=this._storedPeriodInfo.slice();for(let i=0;i<t.length;i++){let o=t[i].period,s=t[i].video.storedSettings;if(s!==void 0){if(this.trigger("trackUpdate",{period:Bt(o),trackType:"video",reason:e}),this._isDisposed)return;let d=lt(this._storedPeriodInfo,o.id);d!==void 0&&d.isPeriodAdvertised&&d.video.storedSettings===s&&((r=d.video.dispatcher)==null||r.updateTrack(s))}}}_removePeriodObject(e){h.CURRENT_ENV===h.DEV&&ee(e<this._storedPeriodInfo.length,"Invalid index for Period removal");let t=this._storedPeriodInfo[e];this._storedPeriodInfo[e].isRemoved=!0,this._storedPeriodInfo.splice(e,1),this._cachedPeriodInfo.set(t.period,t)}_getRepresentationsToLock(e,t){let r=t.reduce((i,o)=>{let a=Z(e.representations,s=>s.id===o);return a===void 0?m.warn("API: Wanted locked Representation not found."):i.push(a.id),i},[]);if(r.length===0)throw new Error("Cannot lock Representations: None of the given Representation id are found");return r}_selectInitialTrackIfNeeded(){var i,o,a,s;let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:e}=U.getCurrent(),t=[],r=[];for(let d of this._storedPeriodInfo){let{period:u}=d;if(d.audio.storedSettings!==void 0&&d.video.storedSettings!==void 0&&d.text.storedSettings!==void 0)continue;let l=[...(i=u.adaptations.audio)!=null?i:[],...(o=u.adaptations.video)!=null?o:[]],c=l.every(b=>b.supportStatus.hasCodecWithUndefinedSupport);if(l.length>0&&c)continue;let f=pt(u,"audio")[0];d.audio.storedSettings=f===void 0?null:{adaptation:f,switchingMode:this._defaultAudioTrackSwitchingMode,lockedRepresentations:new H(null)};let g=pt(u,"video")[0],p=Oa(g,this._isTrickModeTrackEnabled);d.video.storedSettings=p===void 0?null:{adaptation:p,adaptationBase:g,switchingMode:e,lockedRepresentations:new H(null)};let I=null,y=((a=u.adaptations.text)!=null?a:[]).filter(b=>b.isForcedSubtitles===!0);if(y.length>0){if(f!=null){let b=Z(y,T=>T.normalizedLanguage===f.normalizedLanguage);b!==void 0&&(I=b)}I===null&&(I=(s=Z(y,b=>b.normalizedLanguage===void 0))!=null?s:null)}d.text.storedSettings=I===null?null:{adaptation:I,switchingMode:"direct",lockedRepresentations:new H(null)},r.push(d),this._shouldAdvertisePeriod(d)&&(d.isPeriodAdvertised=!0,t.push({id:u.id,start:u.start,end:u.end}))}if(!(t.length>0&&(this.trigger("newAvailablePeriods",t),this._isDisposed)))for(let d of r){if(!d.isPeriodAdvertised)continue;let u=["audio","video","text"];for(let l of u){let c=d[l];if(c.dispatcher!==null&&c.storedSettings!==void 0&&!c.dispatcher.hasSetTrack()&&(c.dispatcher.updateTrack(c.storedSettings),this._isDisposed))return}}}_shouldAdvertisePeriod(e){return!e.isPeriodAdvertised&&e.text.dispatcher!==null&&e.video.dispatcher!==null&&e.audio.dispatcher!==null}};function yb(n,e){for(let t=0;t<n.length;t++)if(n[t].period.id===e.id)return t}function lt(n,e){for(let t=0;t<n.length;t++){let r=n[t];if(r.period.id===e)return r}}function Ml(n){var e,t,r;return!n.inManifest&&((e=n.text)==null?void 0:e.dispatcher)===null&&((t=n.audio)==null?void 0:t.dispatcher)===null&&((r=n.video)==null?void 0:r.dispatcher)===null}function Oa(n,e){var t;return e&&((t=n.trickModeTracks)==null?void 0:t[0])!==void 0?n.trickModeTracks[0]:n}function Al(n,e){return{period:n,inManifest:e,isPeriodAdvertised:!1,isRemoved:!1,audio:{storedSettings:void 0,dispatcher:null},video:{storedSettings:void 0,dispatcher:null},text:{storedSettings:void 0,dispatcher:null}}}function Bt(n){return{start:n.start,end:n.end,id:n.id}}var Jm=lo;function ep(n){let e,t,r,i,o,a,{DEFAULT_BASE_BANDWIDTH:s,DEFAULT_VIDEO_RESOLUTION_LIMIT:d,DEFAULT_MAX_BUFFER_AHEAD:u,DEFAULT_MAX_BUFFER_BEHIND:l,DEFAULT_MAX_VIDEO_BUFFER_SIZE:c,DEFAULT_THROTTLE_VIDEO_BITRATE_WHEN_HIDDEN:f,DEFAULT_WANTED_BUFFER_AHEAD:g}=U.getCurrent();if(_(n.maxBufferAhead))e=u;else if(e=Number(n.maxBufferAhead),isNaN(e))throw new Error("Invalid maxBufferAhead parameter. Should be a number.");if(_(n.maxBufferBehind))t=l;else if(t=Number(n.maxBufferBehind),isNaN(t))throw new Error("Invalid maxBufferBehind parameter. Should be a number.");if(_(n.wantedBufferAhead))r=g;else if(r=Number(n.wantedBufferAhead),isNaN(r))throw new Error("Invalid wantedBufferAhead parameter. Should be a number.");if(_(n.maxVideoBufferSize))i=c;else if(i=Number(n.maxVideoBufferSize),isNaN(i))throw new Error("Invalid maxVideoBufferSize parameter. Should be a number.");let p=_(n.videoResolutionLimit)?d:n.videoResolutionLimit,I=_(n.throttleVideoBitrateWhenHidden)?f:!!n.throttleVideoBitrateWhenHidden;if(_(n.videoElement))o=document.createElement("video");else if(n.videoElement.nodeName.toLowerCase()==="video"||n.videoElement.nodeName.toLowerCase()==="audio")o=n.videoElement;else throw new Error("Invalid videoElement parameter. Should be a HTMLMediaElement.");if(_(n.baseBandwidth))a=s;else if(a=Number(n.baseBandwidth),isNaN(a))throw new Error("Invalid baseBandwidth parameter. Should be a number.");return{maxBufferAhead:e,maxBufferBehind:t,videoResolutionLimit:p,videoElement:o,wantedBufferAhead:r,maxVideoBufferSize:i,throttleVideoBitrateWhenHidden:I,baseBandwidth:a}}function tp(n){var e,t,r,i;if(n===null||typeof n!="object"&&n!==void 0)throw new Error("API: reload - Invalid options format.");if((n==null?void 0:n.reloadAt)===null||typeof(n==null?void 0:n.reloadAt)!="object"&&(n==null?void 0:n.reloadAt)!==void 0)throw new Error("API: reload - Invalid 'reloadAt' option format.");if(typeof((e=n==null?void 0:n.reloadAt)==null?void 0:e.position)!="number"&&((t=n==null?void 0:n.reloadAt)==null?void 0:t.position)!==void 0)throw new Error("API: reload - Invalid 'reloadAt.position' option format.");if(typeof((r=n==null?void 0:n.reloadAt)==null?void 0:r.relative)!="number"&&((i=n==null?void 0:n.reloadAt)==null?void 0:i.relative)!==void 0)throw new Error("API: reload - Invalid 'reloadAt.relative' option format.");if(!Array.isArray(n==null?void 0:n.keySystems)&&(n==null?void 0:n.keySystems)!==void 0)throw new Error("API: reload - Invalid 'keySystems' option format.");if((n==null?void 0:n.autoPlay)!==void 0&&typeof n.autoPlay!="boolean")throw new Error("API: reload - Invalid 'autoPlay' option format.")}function np(n){var E,R,k;let e,t,r,i,o,a,s,{DEFAULT_AUTO_PLAY:d,DEFAULT_CODEC_SWITCHING_BEHAVIOR:u,DEFAULT_ENABLE_FAST_SWITCHING:l,DEFAULT_TEXT_TRACK_MODE:c}=U.getCurrent();if(_(n))throw new Error("No option set on loadVideo");if(!_(n.url))e=String(n.url);else if(_(n.initialManifest)&&_(n.manifestLoader))throw new Error("Unable to load a content: no url set on loadVideo.\nPlease provide at least either an `url` argument, a `initialManifest` option or a `manifestLoader` option so the RxPlayer can load the content.");if(_(n.transport))throw new Error("No transport set on loadVideo");t=String(n.transport);let f=_(n.autoPlay)?d:!!n.autoPlay;if(_(n.keySystems))r=[];else{r=Array.isArray(n.keySystems)?n.keySystems:[n.keySystems];for(let x of r)if(typeof x.type!="string"||typeof x.getLicense!="function")throw new Error("Invalid key system given: Missing type string or getLicense callback")}let g=n.lowLatencyMode===void 0?!1:!!n.lowLatencyMode,p=n.initialManifest,I=(E=n.minimumManifestUpdateInterval)!=null?E:0,y=(R=n.defaultAudioTrackSwitchingMode)!=null?R:void 0;y!==void 0&&!Q(["seamless","direct","reload"],y)&&(m.warn("The `defaultAudioTrackSwitchingMode` loadVideo option must match one of the following strategy name:\n- `seamless`\n- `direct`\n- `reload`"),y=void 0);let b=_(n.onCodecSwitch)?u:n.onCodecSwitch;if(Q(["continue","reload"],b)||(m.warn("The `onCodecSwitch` loadVideo option must match one of the following string:\n- `continue`\n- `reload`\nIf badly set, "+u+" will be used as default"),b=u),_(n.textTrackMode))i=c;else{if(n.textTrackMode!=="native"&&n.textTrackMode!=="html")throw new Error("Invalid textTrackMode.");i=n.textTrackMode}if(i==="html"){if(_(n.textTrackElement))throw new Error('You have to provide a textTrackElement in "html" textTrackMode.');if(n.textTrackElement instanceof HTMLElement)a=n.textTrackElement;else throw new Error("textTrackElement should be an HTMLElement.")}else _(n.textTrackElement)||m.warn('API: You have set a textTrackElement without being in an "html" textTrackMode. It will be ignored.');if(_(n.mode))o="auto";else{if(!Q(["auto","multithread","main"],n.mode))throw new Error("Invalid `mode` option.");o=n.mode}let T=_(n.enableFastSwitching)?l:n.enableFastSwitching;if(!_(n.startAt))if("wallClockTime"in n.startAt&&n.startAt.wallClockTime instanceof Date){let x=n.startAt.wallClockTime.getTime()/1e3;s=G({},n.startAt,{wallClockTime:x})}else s=n.startAt;let v=(k=n.requestConfig)!=null?k:{};return{__priv_patchLastSegmentInSidx:n.__priv_patchLastSegmentInSidx,__priv_manifestUpdateUrl:n.__priv_manifestUpdateUrl,checkMediaSegmentIntegrity:n.checkMediaSegmentIntegrity,checkManifestIntegrity:n.checkManifestIntegrity,autoPlay:f,defaultAudioTrackSwitchingMode:y,enableFastSwitching:T,initialManifest:p,keySystems:r,lowLatencyMode:g,manifestLoader:n.manifestLoader,minimumManifestUpdateInterval:I,requestConfig:v,onCodecSwitch:b,referenceDateTime:n.referenceDateTime,representationFilter:n.representationFilter,segmentLoader:n.segmentLoader,serverSyncInfos:n.serverSyncInfos,startAt:s,textTrackElement:a,textTrackMode:i,transport:t,mode:o,url:e,cmcd:n.cmcd}}function rp(n,e,t,r,i){if(i.isCancelled()||n===null)return;let o=e.getReference().getValue().seeking===2;o&&(t(),i.isCancelled())||e.listen(a=>{a.event==="seeking"?(o=!0,t()):o&&a.event==="seeked"&&(o=!1,r())},{includeLastObservation:!0,clearSignal:i})}function ip(n,e,t,r){r.isCancelled()||n===null||(n.addEventListener("play",e),n.addEventListener("pause",t),r.register(()=>{n.removeEventListener("play",e),n.removeEventListener("pause",t)}))}function op(n,e,t,r){let i=new H("LOADING",r);n.addEventListener("loaded",()=>{if(i.getValue()==="LOADING"){if(i.setValue("LOADED"),!r.isCancelled()){let s=xl(e,null);s!=="PAUSED"&&i.setValue(s)}}else i.getValue()==="RELOADING"?i.setValue(xl(e,null)):a(null)},r),n.addEventListener("reloadingMediaSource",()=>{or(i.getValue())&&i.setValueIfChanged("RELOADING")},r);let o=null;return n.addEventListener("stalled",s=>{s!==o&&(a(s),o=s)},r),n.addEventListener("unstalled",()=>{o!==null&&(a(null),o=null)},r),t.listen(s=>{Q(["seeking","ended","play","pause"],s.event)&&a(o)},{clearSignal:r}),i;function a(s){if(!or(i.getValue()))return;let d=xl(e,s);i.getValue()==="LOADED"&&d==="PAUSED"||i.setValueIfChanged(d)}}function xl(n,e){let{FORCED_ENDED_THRESHOLD:t}=U.getCurrent();if(n.ended)return"ENDED";if(e!==null){let r=Math.abs(n.duration-n.currentTime);return!_(t)&&r<t?"ENDED":e==="seeking"?"SEEKING":e==="freezing"?"FREEZING":"BUFFERING"}return n.paused?"PAUSED":"PLAYING"}function or(n){return n!=="LOADING"&&n!=="RELOADING"&&n!=="STOPPED"}var Ib=et(),bb=["manifestLoader","segmentLoader"],Ft=class Ft extends re{static get ErrorTypes(){return Je}static get ErrorCodes(){return rs}static get LogLevel(){return m.getLevel()}static set LogLevel(e){m.setLevel(e,m.getFormat())}static get LogFormat(){return m.getFormat()}static set LogFormat(e){m.setLevel(m.getLevel(),e)}static addFeatures(e){ra(e)}static _priv_registerVideoElement(e){Ft._priv_currentlyUsedVideoElements.has(e)&&console.warn(`The video element is already attached to another RxPlayer instance.
|
|
18
|
-
Make sure to dispose the previous instance with player.dispose() before creating a new player instance attaching that video element.`),Ft._priv_currentlyUsedVideoElements.add(e)}static _priv_deregisterVideoElement(e){Ft._priv_currentlyUsedVideoElements.has(e)&&Ft._priv_currentlyUsedVideoElements.delete(e)}constructor(e={}){super();let{baseBandwidth:t,videoResolutionLimit:r,maxBufferAhead:i,maxBufferBehind:o,throttleVideoBitrateWhenHidden:a,videoElement:s,wantedBufferAhead:d,maxVideoBufferSize:u}=ep(e);s.preload="auto",this.version="4.3.0-dev.2024112900",this.log=m,this.state="STOPPED",this.videoElement=s,Ft._priv_registerVideoElement(this.videoElement);let l=new B;this._destroyCanceller=l,this._priv_pictureInPictureRef=mc(s,l.signal),this._priv_speed=new H(s.playbackRate,this._destroyCanceller.signal),this._priv_preferTrickModeTracks=!1,this._priv_contentLock=new H(!1,this._destroyCanceller.signal),this._priv_bufferOptions={wantedBufferAhead:new H(d,this._destroyCanceller.signal),maxBufferAhead:new H(i,this._destroyCanceller.signal),maxBufferBehind:new H(o,this._destroyCanceller.signal),maxVideoBufferSize:new H(u,this._destroyCanceller.signal)},this._priv_bitrateInfos={lastBitrates:{audio:t,video:t}},this._priv_throttleVideoBitrateWhenHidden=a,this._priv_videoResolutionLimit=r,this._priv_currentError=null,this._priv_contentInfos=null,this._priv_contentEventsMemory={},this._priv_reloadingMetadata={},this._priv_lastAutoPlay=!1,this._priv_worker=null,this._priv_segmentSinkMetricsCallback=null;let c=()=>{this.trigger("volumeChange",{volume:s.volume,muted:s.muted})};s.addEventListener("volumechange",c),l.signal.register(()=>{s.removeEventListener("volumechange",c)})}attachWorker(e){return new Promise((t,r)=>{var a;if(!Pl())return m.warn("API: Cannot rely on a WebWorker: Worker API unavailable"),r(new xn("INCOMPATIBLE_ERROR","Worker unavailable"));if(typeof e.workerUrl=="string")this._priv_worker=new Worker(e.workerUrl);else{let s=URL.createObjectURL(e.workerUrl);this._priv_worker=new Worker(s),URL.revokeObjectURL(s)}this._priv_worker.onerror=s=>{this._priv_worker!==null&&(this._priv_worker.terminate(),this._priv_worker=null),m.error("API: Unexpected worker error",s.error instanceof Error?s.error:void 0),r(new xn("UNKNOWN_ERROR",'Unexpected Worker "error" event'))};let i=s=>{let d=s.data;d.type==="init-error"?(m.warn("API: Processing InitError worker message: detaching worker"),this._priv_worker!==null&&(this._priv_worker.removeEventListener("message",i),this._priv_worker.terminate(),this._priv_worker=null),r(new xn("SETUP_ERROR","Worker parser initialization failed: "+d.value.errorMessage))):d.type==="init-success"&&(m.info("API: InitSuccess received from worker."),this._priv_worker!==null&&this._priv_worker.removeEventListener("message",i),t())};this._priv_worker.addEventListener("message",i),m.debug("---> Sending To Worker:","init"),this._priv_worker.postMessage({type:"init",value:{dashWasmUrl:e.dashWasmUrl,logLevel:m.getLevel(),logFormat:m.getFormat(),sendBackLogs:wn(),date:Date.now(),timestamp:F(),hasVideo:((a=this.videoElement)==null?void 0:a.nodeName.toLowerCase())==="video",hasMseInWorker:Yf}}),m.addEventListener("onLogLevelChange",s=>{this._priv_worker!==null&&(m.debug("---> Sending To Worker:","log-level-update"),this._priv_worker.postMessage({type:"log-level-update",value:{logLevel:s.level,logFormat:s.format,sendBackLogs:wn()}}))},this._destroyCanceller.signal);let o=s=>{this._priv_worker!==null&&(m.debug("---> Sending To Worker:","config-update"),this._priv_worker.postMessage({type:"config-update",value:s}))};U.updated&&o(U.getCurrent()),U.addEventListener("update",o,this._destroyCanceller.signal)})}getCurrentModeInformation(){return this._priv_contentInfos===null?null:{isDirectFile:this._priv_contentInfos.isDirectFile,useWorker:this._priv_contentInfos.useWorker}}addEventListener(e,t){return super.addEventListener(e,t)}stop(){this._priv_contentInfos!==null&&this._priv_contentInfos.currentContentCanceller.cancel(),this._priv_cleanUpCurrentContentState(),this.state!=="STOPPED"&&this._priv_setPlayerState("STOPPED")}dispose(){this.stop(),this.videoElement!==null&&(Ft._priv_deregisterVideoElement(this.videoElement),Dn(this.videoElement).catch(e=>{let t=e instanceof Error?e.message:"Unknown error";m.error("API: Could not dispose decryption resources: "+t)})),this._destroyCanceller.cancel(),this._priv_reloadingMetadata={},this.videoElement=null,this._priv_worker!==null&&(this._priv_worker.terminate(),this._priv_worker=null)}loadVideo(e){let t=np(e);m.info("API: Calling loadvideo",t.url,t.transport),this._priv_reloadingMetadata={options:t},this._priv_initializeContentPlayback(t),this._priv_lastAutoPlay=t.autoPlay}reload(e){var l,c,f;let{options:t,manifest:r,reloadPosition:i,reloadInPause:o}=this._priv_reloadingMetadata;if(t===void 0)throw new Error("API: Can't reload without having previously loaded a content.");tp(e);let a;if(((l=e==null?void 0:e.reloadAt)==null?void 0:l.position)!==void 0)a={position:e.reloadAt.position};else if(((c=e==null?void 0:e.reloadAt)==null?void 0:c.relative)!==void 0){if(i===void 0)throw new Error("Can't reload to a relative position when previous content was not loaded.");a={position:e.reloadAt.relative+i}}else i!==void 0&&(a={position:i});let s;(e==null?void 0:e.autoPlay)!==void 0?s=e.autoPlay:o!==void 0&&(s=!o);let d;(e==null?void 0:e.keySystems)!==void 0?d=e.keySystems:((f=this._priv_reloadingMetadata.options)==null?void 0:f.keySystems)!==void 0&&(d=this._priv_reloadingMetadata.options.keySystems);let u=ue(oe({},t),{initialManifest:r});a!==void 0&&(u.startAt=a),s!==void 0&&(u.autoPlay=s),d!==void 0&&(u.keySystems=d),this._priv_initializeContentPlayback(u)}createDebugElement(e){if(me.createDebugElement===null)throw new Error("Feature `DEBUG_ELEMENT` not added to the RxPlayer");let t=new B;return me.createDebugElement(e,this,t.signal),{dispose(){t.cancel()}}}_priv_initializeContentPlayback(e){var q,W,se,ae,de,Se;let{autoPlay:t,cmcd:r,defaultAudioTrackSwitchingMode:i,enableFastSwitching:o,initialManifest:a,keySystems:s,lowLatencyMode:d,minimumManifestUpdateInterval:u,requestConfig:l,onCodecSwitch:c,startAt:f,transport:g,checkMediaSegmentIntegrity:p,checkManifestIntegrity:I,manifestLoader:y,referenceDateTime:b,segmentLoader:T,serverSyncInfos:v,mode:E,__priv_manifestUpdateUrl:R,__priv_patchLastSegmentInSidx:k,url:x}=e;if(this.videoElement===null)throw new Error("the attached video element is disposed");let M=g==="directfile",P=new B,N=this.videoElement,O,K=!1,A=null;if(M){if(me.directfile===null)throw this.stop(),this._priv_currentError=null,new Error("DirectFile feature not activated in your build.");if(_(x))throw new Error("No URL for a DirectFile content");if(m.info("API: Initializing DirectFile mode in the main thread"),A=this._priv_initializeMediaElementTracksStore(P.signal),P.isUsed())return;O=new me.directfile.initDirectFile({autoPlay:t,keySystems:s,speed:this._priv_speed,startAt:f,url:x})}else{let Y={lowLatencyMode:d,maxRetry:(q=l.manifest)==null?void 0:q.maxRetry,requestTimeout:(W=l.manifest)==null?void 0:W.timeout,connectionTimeout:(se=l.manifest)==null?void 0:se.connectionTimeout,minimumManifestUpdateInterval:u,initialManifest:a},ce=Cl(),ye={throttleBitrate:{},limitResolution:{}};this._priv_throttleVideoBitrateWhenHidden&&(ce?ye.throttleBitrate={video:an(pc(this._priv_pictureInPictureRef,P.signal),De=>De?1/0:0,P.signal)}:m.warn("API: Can't apply throttleVideoBitrateWhenHidden because browser can't be trusted for visibility.")),this._priv_videoResolutionLimit==="videoElement"?ce?ye.limitResolution={video:hc(N,this._priv_pictureInPictureRef,P.signal)}:m.warn("API: Can't apply videoResolutionLimit because browser can't be trusted for video size."):this._priv_videoResolutionLimit==="screen"&&(ye.limitResolution={video:gc(P.signal)});let Kt={initialBitrates:this._priv_bitrateInfos.lastBitrates,lowLatencyMode:d,throttlers:ye},Qe=e.textTrackMode==="native"?{textTrackMode:"native"}:{textTrackMode:"html",textTrackElement:e.textTrackElement},Be=G({enableFastSwitching:o,onCodecSwitch:c},this._priv_bufferOptions),_t={lowLatencyMode:d,maxRetry:(ae=l.segment)==null?void 0:ae.maxRetry,requestTimeout:(de=l.segment)==null?void 0:de.timeout,connectionTimeout:(Se=l.segment)==null?void 0:Se.connectionTimeout},yt=me.multithread!==null&&this._priv_worker!==null&&g==="dash"&&bb.every(De=>_(e[De]))&&typeof e.representationFilter!="function";if(E==="main"||E==="auto"&&!yt){if(me.mainThreadMediaSourceInit===null)throw new Error("Cannot load video, neither in a WebWorker nor with the `MEDIA_SOURCE_MAIN` feature");let De=me.transports[g];if(typeof De!="function")throw this.stop(),this._priv_currentError=null,new Error(`transport "${g}" not supported`);let sp=typeof e.representationFilter=="string"?ef(e.representationFilter):e.representationFilter;m.info("API: Initializing MediaSource mode in the main thread");let dp=De({lowLatencyMode:d,checkMediaSegmentIntegrity:p,checkManifestIntegrity:I,manifestLoader:y,referenceDateTime:b,representationFilter:sp,segmentLoader:T,serverSyncInfos:v,__priv_manifestUpdateUrl:R,__priv_patchLastSegmentInSidx:k});O=new me.mainThreadMediaSourceInit({adaptiveOptions:Kt,autoPlay:t,bufferOptions:Be,cmcd:r,keySystems:s,lowLatencyMode:d,transport:dp,manifestRequestSettings:Y,segmentRequestOptions:_t,speed:this._priv_speed,startAt:f,textTrackOptions:Qe,url:x})}else{if(me.multithread===null)throw new Error("Cannot load video in multithread mode: `MULTI_THREAD` feature not imported.");if(this._priv_worker===null)throw new Error("Cannot load video in multithread mode: `attachWorker` method not called.");ee(typeof e.representationFilter!="function"),K=!0,m.info("API: Initializing MediaSource mode in a WebWorker");let De={lowLatencyMode:d,checkMediaSegmentIntegrity:p,checkManifestIntegrity:I,referenceDateTime:b,serverSyncInfos:v,manifestLoader:void 0,segmentLoader:void 0,representationFilter:e.representationFilter,__priv_manifestUpdateUrl:R,__priv_patchLastSegmentInSidx:k};O=new me.multithread.init({adaptiveOptions:Kt,autoPlay:t,bufferOptions:Be,cmcd:r,keySystems:s,lowLatencyMode:d,transportOptions:De,manifestRequestSettings:Y,segmentRequestOptions:_t,speed:this._priv_speed,startAt:f,textTrackOptions:Qe,worker:this._priv_worker,url:x})}}let C={contentId:Ib(),originalUrl:x,currentContentCanceller:P,defaultAudioTrackSwitchingMode:i,initializer:O,isDirectFile:M,manifest:null,currentPeriod:null,activeAdaptations:null,activeRepresentations:null,tracksStore:null,mediaElementTracksStore:A,useWorker:K};O.addEventListener("error",Y=>{this._priv_onFatalError(Y,C)}),O.addEventListener("warning",Y=>{let ce=Oe(Y,{defaultCode:"NONE",defaultReason:"An unknown error happened."});m.warn("API: Sending warning:",ce),this.trigger("warning",ce)}),O.addEventListener("reloadingMediaSource",Y=>{C.tracksStore!==null&&C.tracksStore.resetPeriodObjects(),this._priv_segmentSinkMetricsCallback=null,this._priv_lastAutoPlay=Y.autoPlay}),O.addEventListener("inbandEvents",Y=>this.trigger("inbandEvents",Y)),O.addEventListener("streamEvent",Y=>this.trigger("streamEvent",Y)),O.addEventListener("streamEventSkip",Y=>this.trigger("streamEventSkip",Y)),O.addEventListener("activePeriodChanged",Y=>this._priv_onActivePeriodChanged(C,Y)),O.addEventListener("periodStreamReady",Y=>this._priv_onPeriodStreamReady(C,Y)),O.addEventListener("periodStreamCleared",Y=>this._priv_onPeriodStreamCleared(C,Y)),O.addEventListener("representationChange",Y=>this._priv_onRepresentationChange(C,Y)),O.addEventListener("adaptationChange",Y=>this._priv_onAdaptationChange(C,Y)),O.addEventListener("bitrateEstimateChange",Y=>this._priv_onBitrateEstimateChange(Y)),O.addEventListener("manifestReady",Y=>this._priv_onManifestReady(C,Y)),O.addEventListener("manifestUpdate",Y=>this._priv_onManifestUpdate(C,Y)),O.addEventListener("codecSupportUpdate",()=>this._priv_onCodecSupportUpdate(C)),O.addEventListener("decipherabilityUpdate",Y=>this._priv_onDecipherabilityUpdate(C,Y)),O.addEventListener("loaded",Y=>{this._priv_segmentSinkMetricsCallback=Y.getSegmentSinkMetrics}),O.prepare(),this.stop();let D=new so(N,{withMediaSource:!M,lowLatencyMode:d});P.signal.register(()=>{D.stop()});let L=op(O,N,D,P.signal);P.signal.register(()=>{O.dispose()});let V=Y=>{switch(Y){case"STOPPED":case"RELOADING":case"LOADING":break;case"ENDED":this._priv_reloadingMetadata.reloadInPause=!0,this._priv_reloadingMetadata.reloadPosition=D.getReference().getValue().position.getPolled();break;default:{let ce=D.getReference().getValue();this._priv_reloadingMetadata.reloadInPause=ce.paused,this._priv_reloadingMetadata.reloadPosition=ce.position.getWanted();break}}},$=null,j=Y=>{$!==null&&($.cancel(),$=null),L.onUpdate((ce,ye)=>{or(ce)&&(ye(),$!==null&&$.cancel(),$=new B,$.linkToSignal(P.signal),Y!==!N.paused&&(N.paused?this.trigger("pause",null):this.trigger("play",null)),ip(N,()=>this.trigger("play",null),()=>this.trigger("pause",null),P.signal))},{emitCurrentValue:!1,clearSignal:P.signal})};j(t),O.addEventListener("reloadingMediaSource",Y=>{j(Y.autoPlay)}),this._priv_currentError=null,this._priv_contentInfos=C;let z=null;L.onUpdate(Y=>{V(Y),this._priv_setPlayerState(Y),!P.isUsed()&&(z!==null?or(this.state)||(z.cancel(),z=null):or(this.state)&&(z=new B,z.linkToSignal(P.signal),rp(N,D,()=>this.trigger("seeking",null),()=>this.trigger("seeked",null),z.signal)))},{emitCurrentValue:!0,clearSignal:P.signal}),D.listen(Y=>{V(this.state),this._priv_triggerPositionUpdate(C,Y)},{clearSignal:P.signal}),P.signal.register(()=>{O.removeEventListener()}),this._priv_contentLock.onUpdate((Y,ce)=>{Y||(ce(),O.start(N,D))},{emitCurrentValue:!0,clearSignal:P.signal})}getError(){return this._priv_currentError}getVideoElement(){return this.videoElement}getPlayerState(){return this.state}isContentLoaded(){return!Q(["LOADING","RELOADING","STOPPED"],this.state)}isBuffering(){return Q(["BUFFERING","SEEKING","LOADING","RELOADING"],this.state)}isPaused(){return this.videoElement?Q(["LOADING","RELOADING"],this.state)?!this._priv_lastAutoPlay:this.videoElement.paused:!0}isLive(){if(this._priv_contentInfos===null)return!1;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;return e||t===null?!1:t.isLive}areTrickModeTracksEnabled(){return this._priv_preferTrickModeTracks}getContentUrls(){if(this._priv_contentInfos===null)return;let{isDirectFile:e,manifest:t,originalUrl:r}=this._priv_contentInfos;if(e)return r===void 0?void 0:[r];if(t!==null)return t.uris}updateContentUrls(e,t){if(this._priv_contentInfos===null)throw new Error("No content loaded");let r=(t==null?void 0:t.refresh)===!0;this._priv_contentInfos.initializer.updateContentUrls(e,r)}getMediaDuration(){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.duration}getCurrentBufferGap(){if(this.videoElement===null)throw new Error("Disposed player");let e=this.videoElement,t=Xl(e.buffered,e.currentTime);return t===1/0?0:t}getWallClockTime(){var r;if(this.videoElement===null)throw new Error("Disposed player");if(this._priv_contentInfos===null)return this.videoElement.currentTime;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;if(e){let i=ao(this.videoElement);return(i!=null?i:0)+this.videoElement.currentTime}if(t!==null){let i=this.videoElement.currentTime,o=(r=t.availabilityStartTime)!=null?r:0;return i+o}return 0}getPosition(){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.currentTime}getLastStoredContentPosition(){return this._priv_reloadingMetadata.reloadPosition}getPlaybackRate(){return this._priv_speed.getValue()}setPlaybackRate(e,t){var o;e!==this._priv_speed.getValue()&&this._priv_speed.setValue(e);let r=t==null?void 0:t.preferTrickModeTracks;if(typeof r!="boolean")return;this._priv_preferTrickModeTracks=r;let i=(o=this._priv_contentInfos)==null?void 0:o.tracksStore;_(i)||(r&&!i.isTrickModeEnabled()?i.enableVideoTrickModeTracks():!r&&i.isTrickModeEnabled()&&i.disableVideoTrickModeTracks())}getVideoRepresentation(){let e=this.__priv_getCurrentRepresentations();if(e!==null)return e.video}getAudioRepresentation(){let e=this.__priv_getCurrentRepresentations();if(e!==null)return e.audio}play(){if(this.videoElement===null)throw new Error("Disposed player");let e=this.videoElement.play();return _(e)||typeof e.catch!="function"?Promise.resolve():e.catch(t=>{if(t.name==="NotAllowedError"){let r=new te("MEDIA_ERR_PLAY_NOT_ALLOWED",t.toString());this.trigger("warning",r)}throw t})}pause(){if(this.videoElement===null)throw new Error("Disposed player");this.videoElement.pause()}seekTo(e){var o;if(this.videoElement===null)throw new Error("Disposed player");if(this._priv_contentInfos===null)throw new Error("player: no content loaded");let{isDirectFile:t,manifest:r}=this._priv_contentInfos;if(!t&&r===null)throw new Error("player: the content did not load yet");let i;if(typeof e=="number")i=e;else if(typeof e=="object"){let a=e,s=this.videoElement.currentTime;if(!_(a.relative))i=s+a.relative;else if(!_(a.position))i=a.position;else{if(_(a.wallClockTime))throw new Error('invalid time object. You must set one of the following properties: "relative", "position" or "wallClockTime"');if(r!==null)i=a.wallClockTime-((o=r.availabilityStartTime)!=null?o:0);else if(t&&this.videoElement!==null){let d=ao(this.videoElement);d!==void 0&&(i=a.wallClockTime-d)}i===void 0&&(i=a.wallClockTime)}}if(i===void 0)throw new Error("invalid time given");return m.info("API: API Seek to",i),this.videoElement.currentTime=i,i}getVolume(){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.volume}setVolume(e){if(this.videoElement===null)throw new Error("Disposed player");let t=this.videoElement;e!==t.volume&&(t.volume=e)}isMute(){var e;return((e=this.videoElement)==null?void 0:e.muted)===!0}mute(){if(this.videoElement===null)throw new Error("Disposed player");this.videoElement.muted||(this.videoElement.muted=!0)}unMute(){if(this.videoElement===null)throw new Error("Disposed player");this.videoElement.muted&&(this.videoElement.muted=!1)}setMaxBufferBehind(e){this._priv_bufferOptions.maxBufferBehind.setValue(e)}setMaxBufferAhead(e){this._priv_bufferOptions.maxBufferAhead.setValue(e)}setWantedBufferAhead(e){this._priv_bufferOptions.wantedBufferAhead.setValue(e)}setMaxVideoBufferSize(e){this._priv_bufferOptions.maxVideoBufferSize.setValue(e)}getMaxBufferBehind(){return this._priv_bufferOptions.maxBufferBehind.getValue()}getMaxBufferAhead(){return this._priv_bufferOptions.maxBufferAhead.getValue()}getWantedBufferAhead(){return this._priv_bufferOptions.wantedBufferAhead.getValue()}getMaxVideoBufferSize(){return this._priv_bufferOptions.maxVideoBufferSize.getValue()}getCurrentPeriod(){var t;let e=(t=this._priv_contentInfos)==null?void 0:t.currentPeriod;return _(e)?null:{id:e.id,start:e.start,end:e.end}}getKeySystemConfiguration(){if(this.videoElement===null)throw new Error("Disposed player");let e=Vn(this.videoElement);return e===null?null:{keySystem:e[0],configuration:e[1]}}getAvailablePeriods(){if(this._priv_contentInfos===null)return[];let{isDirectFile:e,tracksStore:t}=this._priv_contentInfos;return e?[]:t===null?[]:t.getAvailablePeriods().slice()}getAvailableAudioTracks(e){var a,s;if(this._priv_contentInfos===null)return[];let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return(a=r==null?void 0:r.getAvailableAudioTracks())!=null?a:[];let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(s=e==null?void 0:e.filterPlayableRepresentations)!=null?s:!0),this._priv_callTracksStoreGetterSetter(i,[],(d,u)=>{var l;return(l=d.getAvailableAudioTracks(u,o))!=null?l:[]})}getAvailableTextTracks(e){var i;if(this._priv_contentInfos===null)return[];let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t?(i=r==null?void 0:r.getAvailableTextTracks())!=null?i:[]:this._priv_callTracksStoreGetterSetter(e,[],(o,a)=>{var s;return(s=o.getAvailableTextTracks(a))!=null?s:[]})}getAvailableVideoTracks(e){var a,s;if(this._priv_contentInfos===null)return[];let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return(a=r==null?void 0:r.getAvailableVideoTracks())!=null?a:[];let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(s=e==null?void 0:e.filterPlayableRepresentations)!=null?s:!0),this._priv_callTracksStoreGetterSetter(i,[],(d,u)=>{var l;return(l=d.getAvailableVideoTracks(u,o))!=null?l:[]})}getAudioTrack(e){var a;if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return r===null?void 0:r.getChosenAudioTrack();let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(a=e==null?void 0:e.filterPlayableRepresentations)!=null?a:!0),this._priv_callTracksStoreGetterSetter(i,void 0,(s,d)=>s.getChosenAudioTrack(d,o))}getTextTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t?r===null?void 0:r.getChosenTextTrack():this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.getChosenTextTrack(o))}getVideoTrack(e){var a;if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return r===null?void 0:r.getChosenVideoTrack();let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(a=e==null?void 0:e.filterPlayableRepresentations)!=null?a:!0),this._priv_callTracksStoreGetterSetter(i,void 0,(s,d)=>s.getChosenVideoTrack(d,o))}setAudioTrack(e){var u;if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)try{let l=typeof e=="string"?e:e.trackId;r==null||r.setAudioTrackById(l);return}catch(l){throw new Error("player: unknown audio track")}let i,o,a,s=null,d;return typeof e=="string"?o=e:(o=e.trackId,i=e.periodId,a=e.switchingMode,s=(u=e.lockedRepresentations)!=null?u:null,d=e.relativeResumingPosition),this._priv_callTracksStoreGetterSetter(i,void 0,(l,c)=>l.setAudioTrack({periodRef:c,trackId:o,switchingMode:a,lockedRepresentations:s,relativeResumingPosition:d}))}setTextTrack(e){if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)try{let a=typeof e=="string"?e:e.trackId;r==null||r.setTextTrackById(a);return}catch(a){throw new Error("player: unknown text track")}let i,o;return typeof e=="string"?o=e:(o=e.trackId,i=e.periodId),this._priv_callTracksStoreGetterSetter(i,void 0,(a,s)=>a.setTextTrack(s,o))}disableTextTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t){r==null||r.disableTextTrack();return}return this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.disableTrack(o,"text"))}setVideoTrack(e){var u;if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)try{let l=typeof e=="string"?e:e.trackId;r==null||r.setVideoTrackById(l);return}catch(l){throw new Error("player: unknown video track")}let i,o,a,s=null,d;return typeof e=="string"?o=e:(o=e.trackId,i=e.periodId,a=e.switchingMode,s=(u=e.lockedRepresentations)!=null?u:null,d=e.relativeResumingPosition),this._priv_callTracksStoreGetterSetter(i,void 0,(l,c)=>l.setVideoTrack({periodRef:c,trackId:o,switchingMode:a,lockedRepresentations:s,relativeResumingPosition:d}))}disableVideoTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t&&r!==null?r.disableVideoTrack():this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.disableTrack(o,"video"))}lockVideoRepresentations(e){if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t}=this._priv_contentInfos;if(t)throw new Error("Cannot lock video Representations in directfile mode.");let r,i,o;return Array.isArray(e)?(r=e,i=void 0):(r=e.representations,i=e.periodId,o=e.switchingMode),this._priv_callTracksStoreGetterSetter(i,void 0,(a,s)=>a.lockVideoRepresentations(s,{representations:r,switchingMode:o}))}lockAudioRepresentations(e){if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t}=this._priv_contentInfos;if(t)throw new Error("Cannot lock audio Representations in directfile mode.");let r,i,o;return Array.isArray(e)?(r=e,i=void 0):(r=e.representations,i=e.periodId,o=e.switchingMode),this._priv_callTracksStoreGetterSetter(i,void 0,(a,s)=>a.lockAudioRepresentations(s,{representations:r,switchingMode:o}))}getLockedVideoRepresentations(e){if(this._priv_contentInfos===null)return null;let{isDirectFile:t}=this._priv_contentInfos;return t?null:this._priv_callTracksStoreGetterSetter(e,null,(r,i)=>r.getLockedVideoRepresentations(i))}getLockedAudioRepresentations(e){if(this._priv_contentInfos===null)return null;let{isDirectFile:t}=this._priv_contentInfos;return t?null:this._priv_callTracksStoreGetterSetter(e,null,(r,i)=>r.getLockedAudioRepresentations(i))}unlockVideoRepresentations(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t}=this._priv_contentInfos;if(!t)return this._priv_callTracksStoreGetterSetter(e,void 0,(r,i)=>r.unlockVideoRepresentations(i))}unlockAudioRepresentations(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t}=this._priv_contentInfos;if(!t)return this._priv_callTracksStoreGetterSetter(e,void 0,(r,i)=>r.unlockAudioRepresentations(i))}getMinimumPosition(){if(this._priv_contentInfos===null)return null;if(this._priv_contentInfos.isDirectFile)return 0;let{manifest:e}=this._priv_contentInfos;return e!==null?yn(e):null}getLivePosition(){if(this._priv_contentInfos===null)return null;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;if(!e)return(t==null?void 0:t.isLive)!==!0?null:In(t)}getMaximumPosition(){if(this._priv_contentInfos===null)return null;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;if(e){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.duration}return t!==null?!t.isDynamic&&this.videoElement!==null?this.videoElement.duration:St(t):null}async __priv_getSegmentSinkMetrics(){if(this._priv_segmentSinkMetricsCallback!==null)return this._priv_segmentSinkMetricsCallback()}__priv_getManifest(){return this._priv_contentInfos===null?null:this._priv_contentInfos.manifest}__priv_getCurrentAdaptation(){if(this._priv_contentInfos===null)return null;let{currentPeriod:e,activeAdaptations:t}=this._priv_contentInfos;return e===null||t===null||_(t[e.id])?null:t[e.id]}__priv_getCurrentRepresentations(){if(this._priv_contentInfos===null)return null;let{currentPeriod:e,activeRepresentations:t}=this._priv_contentInfos;return e===null||t===null||_(t[e.id])?null:t[e.id]}_priv_cleanUpCurrentContentState(){var t,r,i,o;m.debug("Locking `contentLock` to clean-up the current content."),this._priv_contentLock.setValue(!0),(r=(t=this._priv_contentInfos)==null?void 0:t.tracksStore)==null||r.dispose(),(o=(i=this._priv_contentInfos)==null?void 0:i.mediaElementTracksStore)==null||o.dispose(),this._priv_contentInfos=null,this._priv_segmentSinkMetricsCallback=null,this._priv_contentEventsMemory={};let e=()=>{this.videoElement!==null&&(m.debug("Unlocking `contentLock`. Next content can begin."),this._priv_contentLock.setValue(!1))};_(this.videoElement)?e():_o(this.videoElement).then(()=>{m.debug("API: DRM session cleaned-up with success!"),e()},a=>{m.error("API: An error arised when trying to clean-up the DRM session:"+(a instanceof Error?a.toString():"Unknown Error")),e()})}_priv_onManifestReady(e,t){var i;if(e.contentId!==((i=this._priv_contentInfos)==null?void 0:i.contentId))return;e.manifest=t,t.manifestFormat===0&&(this._priv_reloadingMetadata.manifest=t);let r=new Jm({preferTrickModeTracks:this._priv_preferTrickModeTracks,defaultAudioTrackSwitchingMode:e.defaultAudioTrackSwitchingMode});e.tracksStore=r,r.addEventListener("newAvailablePeriods",o=>{this.trigger("newAvailablePeriods",o)}),r.addEventListener("brokenRepresentationsLock",o=>{this.trigger("brokenRepresentationsLock",o)}),r.addEventListener("trackUpdate",o=>{var s,d;this.trigger("trackUpdate",o);let a=(d=(s=this._priv_contentInfos)==null?void 0:s.currentPeriod)!=null?d:void 0;o.reason==="no-playable-representation"&&o.period.id===(a==null?void 0:a.id)&&this._priv_onAvailableTracksMayHaveChanged(o.trackType)}),e.tracksStore.addEventListener("warning",o=>{this.trigger("warning",o)}),e.tracksStore.addEventListener("error",o=>{this._priv_onFatalError(o,e)}),e.tracksStore.onManifestUpdate(t)}_priv_onManifestUpdate(e,t){var o,a,s;if(this._priv_contentInfos===null||this._priv_contentInfos.manifest===null)return;_(e==null?void 0:e.tracksStore)||e.tracksStore.onManifestUpdate(this._priv_contentInfos.manifest);let r=(a=(o=this._priv_contentInfos)==null?void 0:o.currentPeriod)!=null?a:void 0,i=(s=this._priv_contentInfos)==null?void 0:s.tracksStore;if(!(r===void 0||_(i))){for(let d of t.updatedPeriods)if(d.period.id===r.id&&(d.result.addedAdaptations.length>0||d.result.removedAdaptations.length>0)){if(i.getPeriodObjectFromPeriod(r)===void 0)return;this._priv_onAvailableTracksMayHaveChanged("audio"),this._priv_onAvailableTracksMayHaveChanged("text"),this._priv_onAvailableTracksMayHaveChanged("video")}}}_priv_onCodecSupportUpdate(e){let t=e==null?void 0:e.tracksStore;_(t)||t.onManifestCodecSupportUpdate()}_priv_onDecipherabilityUpdate(e,t){if(e===null||e.manifest===null)return;_(e==null?void 0:e.tracksStore)||e.tracksStore.onDecipherabilityUpdates();let r=t.reduce((i,o)=>{var s,d,u;if(!(Z(i,l=>l[0].id===o.period.id&&l[1]===o.adaptation.type)!==void 0)){let l=e.tracksStore;if(l===null)return i;let c=!1,f=l.getPeriodObjectFromPeriod(o.period);if(f===void 0)return i;switch(o.adaptation.type){case"audio":c=((s=l.getChosenAudioTrack(f,!1))==null?void 0:s.id)===o.adaptation.id;break;case"video":c=((d=l.getChosenVideoTrack(f,!1))==null?void 0:d.id)===o.adaptation.id;break;case"text":c=((u=l.getChosenTextTrack(f))==null?void 0:u.id)===o.adaptation.id;break}c&&i.push([o.period,o.adaptation.type])}return i},[]);for(let[i,o]of r)this._priv_triggerEventIfNotStopped("representationListUpdate",{period:{start:i.start,end:i.end,id:i.id},trackType:o,reason:"decipherability-update"},e.currentContentCanceller.signal)}_priv_onActivePeriodChanged(e,{period:t}){var s,d,u,l,c,f;if(e.contentId!==((s=this._priv_contentInfos)==null?void 0:s.contentId))return;e.currentPeriod=t;let r=e.currentContentCanceller.signal;this._priv_contentEventsMemory.periodChange!==t&&(this._priv_contentEventsMemory.periodChange=t,this._priv_triggerEventIfNotStopped("periodChange",{start:t.start,end:t.end,id:t.id},r)),this._priv_triggerEventIfNotStopped("availableAudioTracksChange",this.getAvailableAudioTracks(),r),this._priv_triggerEventIfNotStopped("availableTextTracksChange",this.getAvailableTextTracks(),r),this._priv_triggerEventIfNotStopped("availableVideoTracksChange",this.getAvailableVideoTracks(),r);let i=(d=this._priv_contentInfos)==null?void 0:d.tracksStore;if(_(i))this._priv_triggerEventIfNotStopped("audioTrackChange",null,r),this._priv_triggerEventIfNotStopped("textTrackChange",null,r),this._priv_triggerEventIfNotStopped("videoTrackChange",null,r);else{let g=i.getPeriodObjectFromPeriod(t);if(g){let p=i.getChosenAudioTrack(g,!0);this._priv_triggerEventIfNotStopped("audioTrackChange",p,r);let I=i.getChosenTextTrack(g);this._priv_triggerEventIfNotStopped("textTrackChange",I,r);let y=i.getChosenVideoTrack(g,!0);this._priv_triggerEventIfNotStopped("videoTrackChange",y,r)}}let o=(l=(u=this.__priv_getCurrentRepresentations())==null?void 0:u.audio)!=null?l:null;this._priv_triggerEventIfNotStopped("audioRepresentationChange",o,r);let a=(f=(c=this.__priv_getCurrentRepresentations())==null?void 0:c.video)!=null?f:null;this._priv_triggerEventIfNotStopped("videoRepresentationChange",a,r)}_priv_onPeriodStreamReady(e,t){var s;if(e.contentId!==((s=this._priv_contentInfos)==null?void 0:s.contentId))return;let{type:r,period:i,adaptationRef:o}=t,a=e.tracksStore;switch(r){case"video":case"audio":case"text":_(a)?(m.error(`API: TracksStore not instanciated for a new ${r} period`),o.setValue(null)):a.addTrackReference(r,i,o);break;default:Xe(r)}}_priv_onPeriodStreamCleared(e,t){var d;if(e.contentId!==((d=this._priv_contentInfos)==null?void 0:d.contentId))return;let{type:r,period:i}=t,o=e.tracksStore;switch(r){case"audio":case"text":case"video":_(o)||o.removeTrackReference(r,i);break}let{activeAdaptations:a,activeRepresentations:s}=e;if(!_(a)&&!_(a[i.id])){let u=a[i.id];delete u[r],Object.keys(u).length===0&&delete a[i.id]}if(!_(s)&&!_(s[i.id])){let u=s[i.id];delete u[r],Object.keys(u).length===0&&delete s[i.id]}}_priv_onAdaptationChange(e,{type:t,adaptation:r,period:i}){var l;if(e.contentId!==((l=this._priv_contentInfos)==null?void 0:l.contentId))return;e.activeAdaptations===null&&(e.activeAdaptations={});let{activeAdaptations:o,currentPeriod:a}=e,s=o[i.id];_(s)?o[i.id]={[t]:r}:s[t]=r;let{tracksStore:d}=e,u=e.currentContentCanceller.signal;if(d!==null&&a!==null&&!_(i)&&i.id===a.id){let c=d.getPeriodObjectFromPeriod(i);if(c===void 0)return;switch(t){case"audio":{let f=d.getChosenAudioTrack(c,!0);this._priv_triggerEventIfNotStopped("audioTrackChange",f,u);break}case"text":{let f=d.getChosenTextTrack(c);this._priv_triggerEventIfNotStopped("textTrackChange",f,u);break}case"video":{let f=d.getChosenVideoTrack(c,!0);this._priv_triggerEventIfNotStopped("videoTrackChange",f,u);break}}}}_priv_onRepresentationChange(e,{type:t,period:r,representation:i}){var d;if(e.contentId!==((d=this._priv_contentInfos)==null?void 0:d.contentId))return;e.activeRepresentations===null&&(e.activeRepresentations={});let{activeRepresentations:o,currentPeriod:a}=e,s=o[r.id];if(_(s)?o[r.id]={[t]:i}:s[t]=i,!_(r)&&a!==null&&a.id===r.id){let u=this._priv_contentInfos.currentContentCanceller.signal;t==="video"?this._priv_triggerEventIfNotStopped("videoRepresentationChange",i,u):t==="audio"&&this._priv_triggerEventIfNotStopped("audioRepresentationChange",i,u)}}_priv_onBitrateEstimateChange({type:e,bitrate:t}){t!==void 0&&(this._priv_bitrateInfos.lastBitrates[e]=t),this.trigger("__priv_bitrateEstimateChange",{type:e,bitrate:t})}_priv_setPlayerState(e){this.state!==e&&(this.state=e,m.info("API: playerStateChange event",e),this.trigger("playerStateChange",e))}_priv_triggerPositionUpdate(e,t){var s,d;if(e.contentId!==((s=this._priv_contentInfos)==null?void 0:s.contentId))return;let{isDirectFile:r,manifest:i}=e;if(!r&&i===null||_(t))return;let o=i!==null?St(i):void 0,a={position:t.position.getPolled(),duration:t.duration,playbackRate:t.playbackRate,maximumPosition:o,bufferGap:t.bufferGap===void 0||!isFinite(t.bufferGap)?0:t.bufferGap};if(i!==null&&i.isLive&&t.position.getPolled()>0){let u=(d=i.availabilityStartTime)!=null?d:0;a.wallClockTime=t.position.getPolled()+u;let l=In(i);l!==void 0&&(a.liveGap=l-t.position.getPolled())}else if(r&&this.videoElement!==null){let u=ao(this.videoElement);u!==void 0&&(a.wallClockTime=u+t.position.getPolled())}this.trigger("positionUpdate",a)}_priv_triggerEventIfNotStopped(e,t,r){r.isCancelled()||this.trigger(e,t)}_priv_initializeMediaElementTracksStore(e){var r,i,o;ee(me.directfile!==null,"Initializing `MediaElementTracksStore` without Directfile feature"),ee(this.videoElement!==null,"Initializing `MediaElementTracksStore` on a disposed RxPlayer");let t=new me.directfile.mediaElementTracksStore(this.videoElement);return this._priv_triggerEventIfNotStopped("availableAudioTracksChange",t.getAvailableAudioTracks(),e),this._priv_triggerEventIfNotStopped("availableVideoTracksChange",t.getAvailableVideoTracks(),e),this._priv_triggerEventIfNotStopped("availableTextTracksChange",t.getAvailableTextTracks(),e),this._priv_triggerEventIfNotStopped("audioTrackChange",(r=t.getChosenAudioTrack())!=null?r:null,e),this._priv_triggerEventIfNotStopped("textTrackChange",(i=t.getChosenTextTrack())!=null?i:null,e),this._priv_triggerEventIfNotStopped("videoTrackChange",(o=t.getChosenVideoTrack())!=null?o:null,e),t.addEventListener("availableVideoTracksChange",a=>this.trigger("availableVideoTracksChange",a)),t.addEventListener("availableAudioTracksChange",a=>this.trigger("availableAudioTracksChange",a)),t.addEventListener("availableTextTracksChange",a=>this.trigger("availableTextTracksChange",a)),t.addEventListener("audioTrackChange",a=>this.trigger("audioTrackChange",a)),t.addEventListener("videoTrackChange",a=>this.trigger("videoTrackChange",a)),t.addEventListener("textTrackChange",a=>this.trigger("textTrackChange",a)),t}_priv_callTracksStoreGetterSetter(e,t,r){var d,u;if(this._priv_contentInfos===null||this._priv_contentInfos.tracksStore===null)return m.warn("API: Trying to call track API too soon"),t;let{tracksStore:i}=this._priv_contentInfos,o=(u=(d=this._priv_contentInfos)==null?void 0:d.currentPeriod)!=null?u:void 0,a=e!=null?e:o==null?void 0:o.id;if(a===void 0)return t;let s=a===(o==null?void 0:o.id)?i.getPeriodObjectFromPeriod(o):i.getPeriodObjectFromId(a);return s===void 0?t:r(i,s)}_priv_onAvailableTracksMayHaveChanged(e,t){let r=this._priv_contentInfos;if(r===null)return;let{currentPeriod:i,tracksStore:o,currentContentCanceller:a}=r,s=a.signal;if(_(i)||o===null)return;let d=t!=null?t:o.getPeriodObjectFromPeriod(i);if(d!==void 0)switch(e){case"video":{let u=o.getAvailableVideoTracks(d,!0);this._priv_triggerEventIfNotStopped("availableVideoTracksChange",u!=null?u:[],s);break}case"audio":{let u=o.getAvailableAudioTracks(d,!0);this._priv_triggerEventIfNotStopped("availableAudioTracksChange",u!=null?u:[],s);break}case"text":{let u=o.getAvailableTextTracks(d);this._priv_triggerEventIfNotStopped("availableTextTracksChange",u!=null?u:[],s);break}default:Xe(e)}}_priv_onFatalError(e,t){let r=Oe(e,{defaultCode:"NONE",defaultReason:"An unknown error stopped content playback."});r.fatal=!0,t.currentContentCanceller.cancel(),this._priv_cleanUpCurrentContentState(),this._priv_currentError=r,m.error("API: The player stopped because of an error",r),this._priv_setPlayerState("STOPPED"),this._priv_currentError===r&&this.trigger("error",r)}};Ft._priv_currentlyUsedVideoElements=new WeakSet;var Da=Ft;Da.version="4.3.0-dev.2024112900";var ap=Da;var La=ap;Na();La.addFeatures([kl,cu,hu,yu,ml,dl,yl,ll,qu,_u,il,Ru]);wn()?m.setLevel("DEBUG","standard"):h.CURRENT_ENV===h.DEV&&m.setLevel(S.CURRENT_LEVEL,"standard");var Woe=La;J.RxPlayer=La;})();
|
|
1
|
+
"use strict";(()=>{var lp=Object.defineProperty,cp=Object.defineProperties;var fp=Object.getOwnPropertyDescriptors;var wl=Object.getOwnPropertySymbols;var mp=Object.prototype.hasOwnProperty,pp=Object.prototype.propertyIsEnumerable;var Ol=(n,e,t)=>e in n?lp(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,oe=(n,e)=>{for(var t in e||(e={}))mp.call(e,t)&&Ol(n,t,e[t]);if(wl)for(var t of wl(e))pp.call(e,t)&&Ol(n,t,e[t]);return n},ue=(n,e)=>cp(n,fp(e));var h={PRODUCTION:0,DEV:1,CURRENT_ENV:0};var S={CURRENT_LEVEL:"NONE"};function Dn(){return typeof __RX_PLAYER_DEBUG_MODE__=="boolean"&&__RX_PLAYER_DEBUG_MODE__}function E(n){return n==null}var re=class{constructor(){this._listeners={}}addEventListener(e,t,r){let i=this._listeners[e];Array.isArray(i)?i.push(t):this._listeners[e]=[t],r!==void 0&&r.register(()=>{this.removeEventListener(e,t)})}removeEventListener(e,t){if(E(e)){this._listeners={};return}let r=this._listeners[e];if(!Array.isArray(r))return;if(E(t)){delete this._listeners[e];return}let i=r.indexOf(t);i!==-1&&r.splice(i,1),r.length===0&&delete this._listeners[e]}trigger(e,t){let r=this._listeners[e];Array.isArray(r)&&r.slice().forEach(i=>{try{i(t)}catch(o){if(h.CURRENT_ENV===h.DEV)throw o instanceof Error?o:new Error("EventEmitter: listener error");console.error("RxPlayer: EventEmitter error",o instanceof Error?o:null)}})}};var zt=typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope;var yp=typeof window=="undefined"&&!zt,Ht=yp;var fo;zt?fo=self:Ht?fo=global:fo=window;var J=fo;var vt=typeof queueMicrotask=="function"?queueMicrotask:function(e){Promise.resolve().then(e,()=>e())};function Ua(){if(!Ht&&!E(J.WebKitSourceBuffer)&&J.WebKitSourceBuffer.prototype.addEventListener===void 0){let e=J.WebKitSourceBuffer.prototype;for(let t in re.prototype)re.prototype.hasOwnProperty(t)&&(e[t]=re.prototype[t]);e._listeners=[],e._emitUpdate=function(t,r){vt(()=>{this.trigger(t,r),this.updating=!1,this.trigger("updateend",new Event("updateend"))})},e.appendBuffer=function(t){var r,i;if(this.updating)throw new Error("updating");this.trigger("updatestart",new Event("updatestart")),this.updating=!0;try{this.append(t)}catch(o){(r=this._emitUpdate)==null||r.call(this,"error",o);return}(i=this._emitUpdate)==null||i.call(this,"update",new Event("update"))}}}function he(n,e,t){if(typeof Array.prototype.findIndex=="function")return n.findIndex(e,t);let r=n.length>>>0;for(let i=0;i<r;i++)if(e.call(t,n[i],i,n))return i;return-1}function X(){}var mo=class{constructor(e,t){this._value=e,this._listeners=[],this._isFinished=!1,this._onFinishCbs=[],t!==void 0&&(this._deregisterCancellation=t.register(()=>this.finish()))}getValue(){return this._value}setValue(e){if(this._isFinished){h.CURRENT_ENV===h.DEV&&console.error("Finished shared references cannot be updated");return}if(this._value=e,this._listeners.length===0)return;let t=this._listeners.slice();for(let r of t)try{r.hasBeenCleared||r.trigger(e,r.complete)}catch(i){}}setValueIfChanged(e){e!==this._value&&this.setValue(e)}onUpdate(e,t){let r=()=>{if(t.clearSignal!==void 0&&t.clearSignal.deregister(r),i.hasBeenCleared)return;i.hasBeenCleared=!0;let o=this._listeners.indexOf(i);o>=0&&this._listeners.splice(o,1)},i={trigger:e,complete:r,hasBeenCleared:!1};if(this._listeners.push(i),t.emitCurrentValue===!0&&e(this._value,r),this._isFinished||i.hasBeenCleared){r();return}t.clearSignal.register(r)}waitUntilDefined(e,t){this.onUpdate((r,i)=>{r!==void 0&&(i(),e(this._value))},{clearSignal:t.clearSignal,emitCurrentValue:!0})}_onFinished(e,t){if(t.isCancelled())return X;let r=()=>{let a=he(this._onFinishCbs,s=>s.trigger===i);a>=0&&(this._onFinishCbs[a].hasBeenCleared=!0,this._onFinishCbs.splice(a,1))},i=()=>{r(),e()},o=t.register(r);return this._onFinishCbs.push({trigger:i,hasBeenCleared:!1}),o}finish(){this._deregisterCancellation!==void 0&&this._deregisterCancellation(),this._isFinished=!0;let e=this._listeners.slice();for(let t of e)try{t.hasBeenCleared||(t.complete(),t.hasBeenCleared=!0)}catch(r){}if(this._listeners.length=0,this._onFinishCbs.length>0){let t=this._onFinishCbs.slice();for(let r of t)try{r.hasBeenCleared||(r.trigger(),r.hasBeenCleared=!0)}catch(i){}this._onFinishCbs.length=0}}};function dn(n,e,t){let r=new mo(e(n.getValue()),t);return n.onUpdate(function(o){r.setValue(e(o))},{clearSignal:t}),n._onFinished(()=>{r.finish()},t),r}var H=mo;var Dl=new H(0);var Ip=typeof performance!="undefined"?()=>performance.now()+Dl.getValue():()=>Date.now()+Dl.getValue(),K=Ip;var bp="NONE",dr=class extends re{constructor(){super(),this.error=X,this.warn=X,this.info=X,this.debug=X,this._levels={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4},this._currentFormat="standard",this._currentLevel=bp}setLevel(e,t,r){let i,o=this._levels[e];typeof o=="number"?(i=o,this._currentLevel=e):(i=0,this._currentLevel="NONE");let a;if(t==="standard"||t==="full"?a=t:a="standard",a==="full"&&a!==this._currentFormat){let d=K();console.log(String(d.toFixed(2)),"[Init]",`Local-Date: ${Date.now()}`)}this._currentFormat=a;let s=this._currentFormat==="full"?(d,u)=>(...l)=>{let c=K();return u(String(c.toFixed(2)),`[${d}]`,...l)}:(d,u)=>u;if(r===void 0)this.error=i>=this._levels.ERROR?s("error",console.error.bind(console)):X,this.warn=i>=this._levels.WARNING?s("warn",console.warn.bind(console)):X,this.info=i>=this._levels.INFO?s("info",console.info.bind(console)):X,this.debug=i>=this._levels.DEBUG?s("log",console.log.bind(console)):X;else{let d=u=>i>=this._levels[u]?(...l)=>r(u,l):X;this.error=d("ERROR"),this.warn=d("WARNING"),this.info=d("INFO"),this.debug=d("DEBUG")}this.trigger("onLogLevelChange",{level:this._currentLevel,format:this._currentFormat})}getLevel(){return this._currentLevel}getFormat(){return this._currentFormat}hasLevel(e){return this._levels[e]>=this._levels[this._currentLevel]}};var Sp=new dr,m=Sp;var we=J,Ll,Nl,Ul,Bl,Fl,Rt=(Fl=(Bl=(Ul=(Nl=(Ll=we==null?void 0:we.MediaSource)!=null?Ll:we==null?void 0:we.MozMediaSource)!=null?Nl:we==null?void 0:we.WebKitMediaSource)!=null?Ul:we==null?void 0:we.MSMediaSource)!=null?Bl:we==null?void 0:we.ManagedMediaSource)!=null?Fl:void 0,Kl=Rt!==void 0&&Rt===(we==null?void 0:we.ManagedMediaSource);var Tp=200,po=new Map;function Ba(n){if(E(Rt))return zt&&m.error("Compat: Cannot request codec support in a worker without MSE."),!1;if(typeof Rt.isTypeSupported=="function"){let e=po.get(n);if(e!==void 0)return e;{let t=Rt.isTypeSupported(n);return po.size>=Tp&&po.clear(),po.set(n,t),t}}return!0}var ur=!1,un=!1,Wt=!1,ln=!1,Fa=!1,cn=!1,Ka=!1,lr=!1,cr=!1,_p=!1,Ep=!1,Va=!1,za=!1,Ha=!1,fn=!1,vp=!1,Wa=!1;(function(){var e,t,r;Ht||(typeof J.MSInputMethodContext!="undefined"&&typeof document.documentMode!="undefined"?(un=!0,Wt=!0):navigator.appName==="Microsoft Internet Explorer"||navigator.appName==="Netscape"&&/(Trident|Edge)\//.test(navigator.userAgent)?Wt=!0:navigator.userAgent.toLowerCase().indexOf("edg/")!==-1?ur=!0:navigator.userAgent.toLowerCase().indexOf("firefox")!==-1?ln=!0:typeof navigator.platform=="string"&&/iPad|iPhone|iPod/.test(navigator.platform)?cn=!0:(Object.prototype.toString.call(J.HTMLElement).indexOf("Constructor")>=0||((t=(e=J.safari)==null?void 0:e.pushNotification)==null?void 0:t.toString())==="[object SafariRemoteNotification]"||/Safari\/(\d+)/.test(navigator.userAgent)&&/Version\/(\d+)/.test(navigator.userAgent)&&((r=navigator.vendor)==null?void 0:r.indexOf("Apple"))!==-1&&!/Chrome\/(\d+)/.test(navigator.userAgent)&&!/Chromium\/(\d+)/.test(navigator.userAgent))&&(Fa=!0),/SamsungBrowser/.test(navigator.userAgent)&&(Ka=!0),navigator.userAgent.indexOf("PlayStation 4")!==-1?Ha=!0:navigator.userAgent.indexOf("PlayStation 5")!==-1?fn=!0:/Tizen/.test(navigator.userAgent)?lr=!0:/[Ww]eb[O0]S/.test(navigator.userAgent)?(cr=!0,/[Ww]eb[O0]S.TV-2022/.test(navigator.userAgent)||/[Cc]hr[o0]me\/87/.test(navigator.userAgent)?Ep=!0:(/[Ww]eb[O0]S.TV-2021/.test(navigator.userAgent)||/[Cc]hr[o0]me\/79/.test(navigator.userAgent))&&(_p=!0)):navigator.userAgent.indexOf("NETTV")!==-1&&navigator.userAgent.indexOf("Philips")!==-1?za=!0:/[Pp]anasonic/.test(navigator.userAgent)?Va=!0:navigator.userAgent.indexOf("Xbox")!==-1?vp=!0:navigator.userAgent.indexOf("Model/a1-kstb40xx")!==-1&&(Wa=!0))})();var Rp=fn,Vl=Rp;function Ga(n){return n===void 0||n.indexOf("widevine")<0}var zl={DEFAULT_REQUEST_TIMEOUT:3e4,DEFAULT_CONNECTION_TIMEOUT:15e3,DEFAULT_TEXT_TRACK_MODE:"native",DEFAULT_ENABLE_FAST_SWITCHING:!0,DELTA_POSITION_AFTER_RELOAD:{bitrateSwitch:-.1,trackSwitch:{audio:0,video:0,other:0}},DEFAULT_CODEC_SWITCHING_BEHAVIOR:"continue",DEFAULT_AUTO_PLAY:!1,DEFAULT_WANTED_BUFFER_AHEAD:30,DEFAULT_MAX_BUFFER_AHEAD:1/0,DEFAULT_MAX_BUFFER_BEHIND:1/0,DEFAULT_MAX_VIDEO_BUFFER_SIZE:1/0,MAXIMUM_MAX_BUFFER_AHEAD:{text:18e3},MINIMUM_MAX_BUFFER_AHEAD:{text:120},MAXIMUM_MAX_BUFFER_BEHIND:{text:18e3},DEFAULT_BASE_BANDWIDTH:0,INACTIVITY_DELAY:6e4,DEFAULT_THROTTLE_VIDEO_BITRATE_WHEN_HIDDEN:!1,DEFAULT_VIDEO_RESOLUTION_LIMIT:"none",DEFAULT_LIVE_GAP:{DEFAULT:10,LOW_LATENCY:3.5},BUFFER_DISCONTINUITY_THRESHOLD:.2,BITRATE_REBUFFERING_RATIO:1.5,DEFAULT_MAX_MANIFEST_REQUEST_RETRY:4,DEFAULT_CDN_DOWNGRADE_TIME:60,DEFAULT_MAX_REQUESTS_RETRY_ON_ERROR:4,INITIAL_BACKOFF_DELAY_BASE:{REGULAR:200,LOW_LATENCY:50},MAX_BACKOFF_DELAY_BASE:{REGULAR:3e3,LOW_LATENCY:1e3},SAMPLING_INTERVAL_MEDIASOURCE:1e3,SAMPLING_INTERVAL_LOW_LATENCY:500,SAMPLING_INTERVAL_NO_MEDIASOURCE:500,ABR_ENTER_BUFFER_BASED_ALGO:10,ABR_EXIT_BUFFER_BASED_ALGO:5,ABR_MINIMUM_TOTAL_BYTES:15e4,ABR_MINIMUM_CHUNK_SIZE:16e3,ABR_STARVATION_FACTOR:{DEFAULT:.72,LOW_LATENCY:.72},ABR_REGULAR_FACTOR:{DEFAULT:.72,LOW_LATENCY:.72},ABR_STARVATION_GAP:{DEFAULT:5,LOW_LATENCY:5},OUT_OF_STARVATION_GAP:{DEFAULT:7,LOW_LATENCY:7},ABR_STARVATION_DURATION_DELTA:.1,ABR_FAST_EMA:2,ABR_SLOW_EMA:10,RESUME_GAP_AFTER_SEEKING:{DEFAULT:1.5,LOW_LATENCY:.5},RESUME_GAP_AFTER_NOT_ENOUGH_DATA:{DEFAULT:.5,LOW_LATENCY:.5},RESUME_GAP_AFTER_BUFFERING:{DEFAULT:5,LOW_LATENCY:.5},REBUFFERING_GAP:{DEFAULT:.5,LOW_LATENCY:.2},MINIMUM_BUFFER_AMOUNT_BEFORE_FREEZING:2,UNFREEZING_SEEK_DELAY:6e3,FREEZING_STALLED_DELAY:600,UNFREEZING_DELTA_POSITION:.001,SEGMENT_SYNCHRONIZATION_DELAY:1500,MISSING_DATA_TRIGGER_SYNC_DELAY:.1,MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:.15,MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:.4,MAX_MANIFEST_BUFFERED_DURATION_DIFFERENCE:.3,MINIMUM_SEGMENT_SIZE:.001,APPEND_WINDOW_SECURITIES:{START:.2,END:.1},MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:50,TEXT_TRACK_SIZE_CHECKS_INTERVAL:250,BUFFER_PADDING:{audio:1,video:3,other:1},SEGMENT_PRIORITIES_STEPS:[2,4,8,12,18,25],MAX_HIGH_PRIORITY_LEVEL:1,MIN_CANCELABLE_PRIORITY:3,EME_DEFAULT_VIDEO_CODECS:['video/mp4;codecs="avc1.4d401e"','video/mp4;codecs="avc1.42e01e"','video/mp4;codecs="hvc1.1.6.L93.B0"','video/webm;codecs="vp8"'],EME_DEFAULT_AUDIO_CODECS:['audio/mp4;codecs="mp4a.40.2"',"audio/webm;codecs=opus"],EME_DEFAULT_WIDEVINE_ROBUSTNESSES:["HW_SECURE_ALL","HW_SECURE_DECODE","HW_SECURE_CRYPTO","SW_SECURE_DECODE","SW_SECURE_CRYPTO"],EME_DEFAULT_PLAYREADY_RECOMMENDATION_ROBUSTNESSES:["3000","2000"],EME_KEY_SYSTEMS:{clearkey:["webkit-org.w3.clearkey","org.w3.clearkey"],widevine:["com.widevine.alpha"],playready:["com.microsoft.playready.recommendation","com.microsoft.playready","com.chromecast.playready","com.youtube.playready"],fairplay:["com.apple.fps.1_0"]},MAX_CONSECUTIVE_MANIFEST_PARSING_IN_UNSAFE_MODE:10,MIN_MANIFEST_PARSING_TIME_TO_ENTER_UNSAFE_MODE:200,MIN_DASH_S_ELEMENTS_TO_PARSE_UNSAFELY:300,OUT_OF_SYNC_MANIFEST_REFRESH_DELAY:3e3,FAILED_PARTIAL_UPDATE_MANIFEST_REFRESH_DELAY:3e3,DASH_FALLBACK_LIFETIME_WHEN_MINIMUM_UPDATE_PERIOD_EQUAL_0:3,EME_DEFAULT_MAX_SIMULTANEOUS_MEDIA_KEY_SESSIONS:15,EME_MAX_STORED_PERSISTENT_SESSION_INFORMATION:1e3,EME_WAITING_DELAY_LOADED_SESSION_EMPTY_KEYSTATUSES:100,FORCED_ENDED_THRESHOLD:8e-4,ADAP_REP_SWITCH_BUFFER_PADDINGS:{video:{before:5,after:5},audio:{before:2,after:2.5},text:{before:0,after:0}},SOURCE_BUFFER_FLUSHING_INTERVAL:500,CONTENT_REPLACEMENT_PADDING:1.2,CACHE_LOAD_DURATION_THRESHOLDS:{video:50,audio:10},STREAM_EVENT_EMITTER_POLL_INTERVAL:250,DEFAULT_MAXIMUM_TIME_ROUNDING_ERROR:.001,BUFFERED_HISTORY_RETENTION_TIME:6e4,BUFFERED_HISTORY_MAXIMUM_ENTRIES:200,MIN_BUFFER_AHEAD:5,UPTO_CURRENT_POSITION_CLEANUP:5,DEFAULT_VIDEO_REPRESENTATIONS_SWITCHING_MODE:"seamless",DEFAULT_AUDIO_REPRESENTATIONS_SWITCHING_MODE:"seamless",DEFAULT_VIDEO_TRACK_SWITCHING_MODE:"reload",DEFAULT_AUDIO_TRACK_SWITCHING_MODE:"seamless"},Hl=zl;function kp(n,...e){if(n==null)throw new TypeError("Cannot convert undefined or null to object");let t=Object(n);for(let r of e)for(let i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i]);return t}var G=typeof Object.assign=="function"?Object.assign:kp;function qa(n){return n!=null&&!Array.isArray(n)&&typeof n=="object"}function fr(n,...e){if(e.length===0)return n;let t=e.shift();if(qa(n)&&qa(t))for(let r in t)if(qa(t[r])){let i=n[r];i===void 0&&(i={},n[r]=i),fr(i,t[r])}else G(n,{[r]:t[r]});return fr(n,...e)}var ja=class extends re{constructor(){super(...arguments);this.updated=!1;this._config=Hl}update(t){let r=fr(this._config,t);this._config=r,this.updated=!0,this.trigger("update",t)}getCurrent(){return this._config}},Cp=new ja,U=Cp;var Pp=.016666666666666666;function Wl(n,e){return Math.abs(n-e)<Pp}function ql(n,e){let t=Math.min(n.start,e.start),r=Math.max(n.end,e.end);return{start:t,end:r}}function Mp(n){for(let e=0;e<n.length;e++){let t=n[e];t.start===t.end&&n.splice(e--,1)}return n}function Ap(n){for(let e=1;e<n.length;e++){let t=n[e-1],r=n[e];if(Yl(t,r)){let i=ql(t,r);n.splice(--e,2,i)}}return n}function Ya(n,e){return n.end<=e.start}function Gl({start:n,end:e},t){return n<=t&&t<e}function jl(n,e){return Gl(n,e.start)||n.start<e.end&&e.end<n.end||Gl(e,n.start)}function Yl(n,e){return Wl(e.start,n.end)||Wl(e.end,n.start)}function Pe(n){let e=[];for(let t=0;t<n.length;t++)e.push({start:n.start(t),end:n.end(t)});return e}function $a(n,e){for(let t=n.length-1;t>=0;t--){let r=n.start(t);if(e>=r){let i=n.end(t);if(e<i)return{start:r,end:i}}}return null}function xp(n,e){for(let t=n.length-1;t>=0;t--){let r=n[t].start;if(e>=r){let i=n[t].end;if(e<i)return n[t]}}return null}function $l(n,e){let t=n.length;for(let r=0;r<t;r++){let i=n.start(r);if(e<i)return i-e}return 1/0}function Ql(n,e){let t=null,r=[];for(let i=0;i<n.length;i++){let o=n[i].start,a=n[i].end;e<o||e>=a?r.push({start:o,end:a}):t={start:o,end:a}}return{outerRanges:r,innerRange:t}}function Xl(n,e){let t=$a(n,e);return t!==null?t.end-e:1/0}function go(n,e){let t=xp(n,e);return t!==null?t.end-e:1/0}function Gt(n,e){if(e.start===e.end)return n;let t=e,r=0;for(;r<n.length;r++){let i=n[r],o=jl(t,i),a=Yl(t,i);if(o||a)t=ql(t,i),n.splice(r--,1);else if(r===0){if(Ya(t,n[0]))break}else if(Ya(n[r-1],t)&&Ya(t,i))break}return n.splice(r,0,t),Ap(Mp(n))}function Zl(n,e){let t=[];for(let r=0;r<e.length;r++)jl(n,e[r])&&t.push(e[r]);return t}function Jl(n,e){let t=[];for(let r=0;r<n.length;r++){let i=n[r],o=Zl(i,e);if(o.length>0)for(let a=0;a<o.length;a++){let s=o[a];t.push({start:Math.max(i.start,s.start),end:Math.min(i.end,s.end)})}}return t}function ho(n,e){let t=[];for(let r=0;r<n.length;r++){let i=n[r],o=[],a=Zl(i,e);if(a.length>0)for(let s=0;s<a.length;s++){let d=a[s];o.push({start:Math.max(i.start,d.start),end:Math.min(i.end,d.end)})}if(o.length===0)t.push(i);else{let s=i.start;for(let d=0;d<o.length;d++)o[d].start>s&&t.push({start:s,end:o[d].start}),s=o[d].end;s<i.end&&t.push({start:s,end:i.end})}}return t}var yo=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype),this.name="AssertionError"}};function ee(n,e){if(h.DEV===h.CURRENT_ENV&&!n)throw new yo(e===void 0?"invalid assertion":e)}function ec(n,e,t="object"){ee(!E(n),`${t} should be an object`);for(let r in e)e.hasOwnProperty(r)&&ee(typeof n[r]===e[r],`${t} should have property ${r} as a ${e[r]}`)}function Xe(n){throw new yo("Unreachable path taken")}var B=class{constructor(){let[e,t]=wp();this._isUsed=!1,this._trigger=e,this.signal=new mr(t)}isUsed(){return this._isUsed}linkToSignal(e){let t=e.register(()=>{this.cancel()});return this.signal.register(t),t}cancel(e){if(this._isUsed)return;this._isUsed=!0;let t=e!=null?e:new Me;this._trigger(t)}static isCancellationError(e){return e instanceof Me}},mr=class{constructor(e){this._isCancelled=!1,this.cancellationError=null,this._listeners=[],e(t=>{for(this.cancellationError=t,this._isCancelled=!0;this._listeners.length>0;)try{let r=this._listeners.pop();r==null||r(t)}catch(r){m.error("Error while calling clean up listener",r instanceof Error?r.toString():"Unknown error")}})}isCancelled(){return this._isCancelled}register(e){return this._isCancelled?(ee(this.cancellationError!==null),e(this.cancellationError),X):(this._listeners.push(e),()=>this.deregister(e))}deregister(e){for(let t=this._listeners.length-1;t>=0;t--)this._listeners[t]===e&&this._listeners.splice(t,1)}},Me=class n extends Error{constructor(){super("This task was cancelled."),Object.setPrototypeOf(this,n.prototype),this.name="CancellationError"}};function wp(){let n=X;return[function(t){n(t)},function(t){n=t}]}function Qa(n){let e=n.map(a=>Math.log(a/n[0])),t=e.map(a=>a-e[0]+1),r=(t[t.length-1]-1)/(n.length*2+10),i=1/r;return n.map((a,s)=>o(s));function o(a){if(a===0)return 0;let s=Math.min(Math.max(1,a),n.length-1);return n[s]===n[s-1]?o(a-1):i*(r+(n[s]*t[s-1]-n[s-1]*t[s])/(n[s]-n[s-1]))+4}}var nt=class{constructor(e){this._alpha=Math.exp(Math.log(.5)/e),this._lastEstimate=0,this._totalWeight=0}addSample(e,t){let r=Math.pow(this._alpha,e),i=t*(1-r)+r*this._lastEstimate;isNaN(i)||(this._lastEstimate=i,this._totalWeight+=e)}getEstimate(){let e=1-Math.pow(this._alpha,this._totalWeight);return this._lastEstimate/e}};var pr=class{constructor(){this._currentRepresentationData=null,this._lastRepresentationWithGoodScore=null}addSample(e,t,r){let i=r/t,o=this._currentRepresentationData,a;o!==null&&o.representation.id===e.id?(a=o.ewma,o.ewma.addSample(t,i),o.loadedDuration+=r,o.loadedSegments++):(a=new nt(5),a.addSample(t,i),this._currentRepresentationData={representation:e,ewma:a,loadedDuration:r,loadedSegments:0}),a.getEstimate()>1&&this._lastRepresentationWithGoodScore!==e&&(m.debug("ABR: New last stable representation",e.bitrate),this._lastRepresentationWithGoodScore=e)}getEstimate(e){if(this._currentRepresentationData===null||this._currentRepresentationData.representation.id!==e.id)return;let{ewma:t,loadedSegments:r,loadedDuration:i}=this._currentRepresentationData,o=t.getEstimate(),a=r>=5&&i>=10?1:0;return{score:o,confidenceLevel:a}}getLastStableRepresentation(){return this._lastRepresentationWithGoodScore}};var tc=6e3,Op=15e3,Dp=3e3,Lp=1e3,Np=9e3,gr=class{constructor(e){this._levelsMap=Qa(e).map(t=>t+4),this._bitrates=e,this._lastUnsuitableQualityTimestamp=void 0,this._blockRaiseDelay=tc,m.debug("ABR: Steps for buffer based chooser.",this._levelsMap.map((t,r)=>`bufferLevel: ${t}, bitrate: ${e[r]}`).join(" ,"))}onAddedSegment(e){let t=this._levelsMap,r=this._bitrates,{bufferGap:i,currentBitrate:o,currentScore:a,speed:s}=e;if(E(o)){this._currentEstimate=r[0];return}let d=-1;for(let p=0;p<r.length;p++){let I=r[p];if(I===o)d=p;else if(I>o)break}if(d<0||r.length!==t.length){m.info("ABR: Current Bitrate not found in the calculated levels"),this._currentEstimate=r[0];return}let u;a!==void 0&&(u=s===0?a.score:a.score/s);let l=isFinite(i)?i:0,c=K();if(l<t[d]||u!==void 0&&u<1&&(a==null?void 0:a.confidenceLevel)===1){if((this._lastUnsuitableQualityTimestamp===void 0?-1:c-this._lastUnsuitableQualityTimestamp)<this._blockRaiseDelay+Np){let y=this._blockRaiseDelay+Dp;this._blockRaiseDelay=Math.min(y,Op),m.debug("ABR: Incrementing blocking raise in BufferBasedChooser due to unstable quality",this._blockRaiseDelay)}else{let y=this._blockRaiseDelay-Lp;this._blockRaiseDelay=Math.max(tc,y),m.debug("ABR: Lowering quality in BufferBasedChooser",this._blockRaiseDelay)}this._lastUnsuitableQualityTimestamp=c;let I=he(r,y=>y===o);for(let y=I-1;y>=0;y--)if(l>=t[y]){this._currentEstimate=r[y];return}this._currentEstimate=r[0];return}if(this._lastUnsuitableQualityTimestamp!==void 0&&c-this._lastUnsuitableQualityTimestamp<this._blockRaiseDelay||u===void 0||u<1.15||(a==null?void 0:a.confidenceLevel)!==1){this._currentEstimate=o;return}let f=t[d],g=(()=>{for(let p=d+1;p<t.length;p++)if(t[p]>f)return p})();if(g!==void 0){let p=t[g];if(i>=p){m.debug("ABR: Raising quality in BufferBasedChooser",r[g]),this._currentEstimate=r[g];return}}this._currentEstimate=o}getLastEstimate(){return this._currentEstimate}};function Z(n,e,t){if(typeof Array.prototype.find=="function")return n.find(e,t);let r=n.length>>>0;for(let i=0;i<r;i++){let o=n[i];if(e.call(t,o,i,n))return o}}function Up(n,e){let t=-1;for(let a=0;a<n.length;a++){let{segment:s}=n[a].content;if(s.duration<=0)continue;let d=s.time+s.duration;if(!s.complete&&a===n.length-1&&e-s.time>-1.2){t=a;break}if(d>e&&e-s.time>-1.2){t=a;break}}if(t<0)return[];let r=n[t],i=r.content.segment.time,o=[r];for(let a=t+1;a<n.length&&n[a].content.segment.time===i;a++)o.push(n[a]);return o}function Io(n){if(n.progress.length<5)return;let e=new nt(2),{progress:t}=n;for(let r=1;r<t.length;r++){let i=t[r].size-t[r-1].size,o=t[r].timestamp-t[r-1].timestamp,a=i*8/(o/1e3);e.addSample(o/1e3,a)}return e.getEstimate()}function nc(n,e){let t=(n.totalSize-n.size)*8;return Math.max(t/e,0)}function Bp(n,e,t,r,i){if(r)return;let{bufferGap:o,speed:a,position:s}=e,d=isFinite(o)?o:0,u=s.getWanted()+d,l=Up(n,u);if(l.length!==1)return;let c=l[0],f=K(),g=c.content.segment.duration*1.5;if(g=Math.min(g,3e3),g=Math.max(g,12e3),f-c.requestTimestamp<g)return;let p=c.progress.length>0?c.progress[c.progress.length-1]:void 0,I=Io(c);if(p!==void 0&&I!==void 0){let R=nc(p,I);if((f-p.timestamp)/1e3<=R&&R-d/a>2500)return I}if(!c.content.segment.complete)return;let y=c.content.segment.duration,b=(f-c.requestTimestamp)/1e3,T=b<=(y*1.5+2)/a;if(E(t)||T)return;let v=y/b,_=t.bitrate*Math.min(.7,v);if(i===void 0||_<i)return _}function Fp(n,e,t){if(t)return!0;let r=isFinite(n.bufferGap)?n.bufferGap:0,i=n.position.getWanted()+r,o=Z(e,({content:c})=>c.segment.duration>0&&c.segment.time+c.segment.duration>i);if(o===void 0)return!0;let a=K(),s=o.progress.length>0?o.progress[o.progress.length-1]:void 0,d=Io(o);if(s===void 0||d===void 0)return!0;let u=nc(s,d);return(a-s.timestamp)/1e3>u*1.2?!0:u-r/n.speed>-1.5}var hr=class{constructor(e,t){let{ABR_STARVATION_GAP:r,OUT_OF_STARVATION_GAP:i,ABR_STARVATION_FACTOR:o,ABR_REGULAR_FACTOR:a}=U.getCurrent();this._initialBitrate=e,this._inStarvationMode=!1,this._lowLatencyMode=t,t?this._config={starvationGap:r.LOW_LATENCY,outOfStarvationGap:i.LOW_LATENCY,starvationBitrateFactor:o.LOW_LATENCY,regularBitrateFactor:a.LOW_LATENCY}:this._config={starvationGap:r.DEFAULT,outOfStarvationGap:i.DEFAULT,starvationBitrateFactor:o.DEFAULT,regularBitrateFactor:a.DEFAULT}}getBandwidthEstimate(e,t,r,i,o){let a,s,d=this._config,{bufferGap:u,position:l,duration:c}=e,f=isFinite(u)?u:0,{ABR_STARVATION_DURATION_DELTA:g}=U.getCurrent();return isNaN(c)||f+l.getWanted()<c-g?!this._inStarvationMode&&f<=d.starvationGap?(m.info("ABR: enter starvation mode."),this._inStarvationMode=!0):this._inStarvationMode&&f>=d.outOfStarvationGap&&(m.info("ABR: exit starvation mode."),this._inStarvationMode=!1):this._inStarvationMode&&(m.info("ABR: exit starvation mode."),this._inStarvationMode=!1),this._inStarvationMode&&(s=Bp(i,e,r,this._lowLatencyMode,o),s!==void 0&&(m.info("ABR: starvation mode emergency estimate:",s),t.reset(),a=E(r)?s:Math.min(s,r.bitrate))),E(a)&&(s=t.getEstimate(),s!==void 0?a=s*(this._inStarvationMode?d.starvationBitrateFactor:d.regularBitrateFactor):o!==void 0?a=o*(this._inStarvationMode?d.starvationBitrateFactor:d.regularBitrateFactor):a=this._initialBitrate),e.speed>1&&(a/=e.speed),{bandwidthEstimate:s,bitrateChosen:a}}isUrgent(e,t,r,i){return t===null?!0:e>=t.bitrate?!1:Fp(i,r,this._lowLatencyMode)}};var yr=class{constructor(){this.bandwidth=void 0,this.representation=null,this.algorithmType=3}update(e,t,r){this.representation=e,this.bandwidth=t,this.algorithmType=r}};var Ir=class{constructor(e,t){this._scoreCalculator=e,this._lastAbrEstimate=t,this._consecutiveWrongGuesses=0,this._blockGuessesUntil=0,this._lastMaintanableBitrate=null}getGuess(e,t,r,i,o){let{bufferGap:a,speed:s}=t,d=this._lastAbrEstimate.representation;if(d===null)return null;if(i>d.bitrate)return this._lastAbrEstimate.algorithmType===2&&(this._lastAbrEstimate.representation!==null&&(this._lastMaintanableBitrate=this._lastAbrEstimate.representation.bitrate),this._consecutiveWrongGuesses=0),null;let u=this._scoreCalculator.getEstimate(r);if(this._lastAbrEstimate.algorithmType!==2){if(u===void 0)return null;if(this._canGuessHigher(a,s,u)){let c=rc(e,r);if(c!==null)return c}return null}if(this._isLastGuessValidated(d,i,u)&&(m.debug("ABR: Guessed Representation validated",d.bitrate),this._lastMaintanableBitrate=d.bitrate,this._consecutiveWrongGuesses=0),r.id!==d.id)return d;if(this._shouldStopGuess(r,u,a,o))return this._consecutiveWrongGuesses++,this._blockGuessesUntil=K()+Math.min(this._consecutiveWrongGuesses*15e3,12e4),Kp(e,r);if(u===void 0)return r;if(this._canGuessHigher(a,s,u)){let c=rc(e,r);if(c!==null)return c}return r}_canGuessHigher(e,t,{score:r,confidenceLevel:i}){return isFinite(e)&&e>=2.5&&K()>this._blockGuessesUntil&&i===1&&r/t>1.01}_shouldStopGuess(e,t,r,i){if(t!==void 0&&t.score<1.01)return!0;if((t===void 0||t.score<1.2)&&r<.6)return!0;let o=i.filter(s=>s.content.representation.id===e.id),a=K();for(let s of o){let d=a-s.requestTimestamp;if(s.content.segment.isInit){if(d>1e3)return!0}else{if(d>s.content.segment.duration*1e3+200)return!0;{let u=Io(s);if(u!==void 0&&u<e.bitrate*.8)return!0}}}return!1}_isLastGuessValidated(e,t,r){return r!==void 0&&r.confidenceLevel===1&&r.score>1.5?!0:t>=e.bitrate&&(this._lastMaintanableBitrate===null||this._lastMaintanableBitrate<e.bitrate)}};function rc(n,e){let t=n.length,r=he(n,({id:i})=>i===e.id);if(r<0)return m.error("ABR: Current Representation not found."),null;for(;++r<t;)if(n[r].bitrate>e.bitrate)return n[r];return null}function Kp(n,e){let t=he(n,({id:r})=>r===e.id);if(t<0)return m.error("ABR: Current Representation not found."),null;for(;--t>=0;)if(n[t].bitrate<e.bitrate)return n[t];return null}var br=class{constructor(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=U.getCurrent();this._fastEWMA=new nt(e),this._slowEWMA=new nt(t),this._bytesSampled=0}addSample(e,t){let{ABR_MINIMUM_CHUNK_SIZE:r}=U.getCurrent();if(t<r)return;let i=t*8e3/e,o=e/1e3;this._bytesSampled+=t,this._fastEWMA.addSample(o,i),this._slowEWMA.addSample(o,i)}getEstimate(){let{ABR_MINIMUM_TOTAL_BYTES:e}=U.getCurrent();if(!(this._bytesSampled<e))return Math.min(this._fastEWMA.getEstimate(),this._slowEWMA.getEstimate())}reset(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=U.getCurrent();this._fastEWMA=new nt(e),this._slowEWMA=new nt(t),this._bytesSampled=0}};function Xa(n,e){if(n.length===0)return[];n.sort((o,a)=>o.bitrate-a.bitrate);let t=n[0].bitrate,r=Math.max(e,t),i=he(n,o=>o.bitrate>r);return i===-1?n:n.slice(0,i)}function Za(n,e){if(e.width===void 0||e.height===void 0)return n;let t=e.width*e.pixelRatio,r=e.height*e.pixelRatio,i=n.slice().sort((s,d)=>{var u,l;return((u=s.width)!=null?u:0)-((l=d.width)!=null?l:0)}),o=Z(i,s=>typeof s.width=="number"&&s.width>=t&&typeof s.height=="number"&&s.height>=r);if(o===void 0)return n;let a=typeof o.width=="number"?o.width:0;return n.filter(s=>typeof s.width=="number"?s.width<=a:!0)}function Sr(n){return Object.keys(n).map(e=>n[e])}var Ln=typeof Object.values=="function"?Object.values:Sr;var Tr=class{constructor(){this._currentRequests={}}add(e){let{id:t,requestTimestamp:r,content:i}=e;this._currentRequests[t]={requestTimestamp:r,progress:[],content:i}}addProgress(e){let t=this._currentRequests[e.id];if(E(t)){if(h.CURRENT_ENV===h.DEV)throw new Error("ABR: progress for a request not added");m.warn("ABR: progress for a request not added");return}t.progress.push(e)}remove(e){if(E(this._currentRequests[e])){if(h.CURRENT_ENV===h.DEV)throw new Error("ABR: can't remove unknown request");m.warn("ABR: can't remove unknown request")}delete this._currentRequests[e]}getRequests(){return Ln(this._currentRequests).filter(e=>!E(e)).sort((e,t)=>e.content.segment.time-t.content.segment.time)}};function bo(n,e){let t=he(n,r=>r.bitrate>e);return t===-1?n[n.length-1]:t===0?n[0]:n[t-1]}var ic=new H(void 0);ic.finish();var oc=new H(1/0);oc.finish();function Ja(n){let e={},{initialBitrates:t,throttlers:r,lowLatencyMode:i}=n;return function(s,d,u,l,c){var y,b,T;let{type:f}=s.adaptation,g=o(f),p=(y=t[f])!=null?y:0,I={limitResolution:(b=r.limitResolution[f])!=null?b:ic,throttleBitrate:(T=r.throttleBitrate[f])!=null?T:oc};return Vp({bandwidthEstimator:g,context:s,currentRepresentation:d,filters:I,initialBitrate:p,playbackObserver:l,representations:u,lowLatencyMode:i},c)};function o(a){let s=e[a];if(E(s)){m.debug("ABR: Creating new BandwidthEstimator for ",a);let d=new br;return e[a]=d,d}return s}}function Vp({bandwidthEstimator:n,context:e,currentRepresentation:t,filters:r,initialBitrate:i,lowLatencyMode:o,playbackObserver:a,representations:s},d){let u=new pr,l=new hr(i!=null?i:0,o),c=new Tr,f=X,g={metrics:T,requestBegin:v,requestProgress:_,requestEnd:R,addedSegment(k){f(k)}},p=new B;p.linkToSignal(d);let I=y(s.getValue(),p.signal);return s.onUpdate(b,{clearSignal:d}),{estimates:I,callbacks:g};function y(k,x){if(k.length<=1)return new H({bitrate:void 0,representation:k[0],urgent:!0,knownStableBitrate:void 0});let M=!1,P=k.sort((V,$)=>V.bitrate-$.bitrate),N=new gr(P.map(V=>V.bitrate)),O=new yr,F=new Ir(u,O),A=a.getReference().getValue(),C=new H(L());return a.listen(V=>{A=V,D()},{includeLastObservation:!1,clearSignal:x}),f=function(V){if(A===null)return;let{position:$,speed:j}=A,z=V.buffered,q=go(z,$.getWanted()),{representation:W}=V.content,se=u.getEstimate(W),ae=W.bitrate,de={bufferGap:q,currentBitrate:ae,currentScore:se,speed:j};N.onAddedSegment(de),D()},x.register(()=>{f=X}),r.throttleBitrate.onUpdate(D,{clearSignal:x}),r.limitResolution.onUpdate(D,{clearSignal:x}),C;function D(){C.setValue(L())}function L(){let{bufferGap:V,position:$,maximumPosition:j}=A,z=r.limitResolution.getValue(),q=r.throttleBitrate.getValue(),W=t.getValue(),se=zp(P,z,q),ae=c.getRequests(),{bandwidthEstimate:de,bitrateChosen:Se}=l.getBandwidthEstimate(A,n,W,ae,O.bandwidth),Y=u.getLastStableRepresentation(),ce=Y===null?void 0:Y.bitrate/(A.speed>0?A.speed:1),{ABR_ENTER_BUFFER_BASED_ALGO:ye,ABR_EXIT_BUFFER_BASED_ALGO:Vt}=U.getCurrent();M&&V<=Vt?M=!1:!M&&isFinite(V)&&V>=ye&&(M=!0);let Qe=bo(se,Se),Be=N.getLastEstimate(),Et=Qe.bitrate,yt=null;M&&Be!==void 0&&Be>Et&&(yt=bo(se,Be),Et=yt.bitrate);let De=null;return o&&W!==null&&e.manifest.isDynamic&&j-$.getWanted()<40&&(De=F.getGuess(P,A,W,Et,ae)),De!==null&&De.bitrate>Et?(m.debug("ABR: Choosing representation with guess-based estimation.",De.bitrate,De.id),O.update(De,de,2),{bitrate:de,representation:De,urgent:W===null||De.bitrate<W.bitrate,knownStableBitrate:ce}):yt!==null?(m.debug("ABR: Choosing representation with buffer-based estimation.",yt.bitrate,yt.id),O.update(yt,de,0),{bitrate:de,representation:yt,urgent:l.isUrgent(yt.bitrate,W,ae,A),knownStableBitrate:ce}):(m.debug("ABR: Choosing representation with bandwidth estimation.",Qe.bitrate,Qe.id),O.update(Qe,de,1),{bitrate:de,representation:Qe,urgent:l.isUrgent(Qe.bitrate,W,ae,A),knownStableBitrate:ce})}}function b(){let k=s.getValue();p.cancel(),p=new B,p.linkToSignal(d),y(k,p.signal).onUpdate(function(P){I.setValue(P)},{clearSignal:p.signal,emitCurrentValue:!0})}function T(k){let{requestDuration:x,segmentDuration:M,size:P,content:N}=k;if(n.addSample(x,P),!N.segment.isInit){let{segment:O,representation:F}=N;if(M===void 0&&!O.complete)return;let A=M!=null?M:O.duration;u.addSample(F,x/1e3,A)}}function v(k){c.add(k)}function _(k){c.addProgress(k)}function R(k){c.remove(k.id)}}function zp(n,e,t){let r=n;return t!==void 0&&t<1/0&&(r=Xa(r,t)),e!==void 0&&(r=Za(r,e)),r}var ac=Ja;function So(){var t;if(typeof((t=J.crypto)==null?void 0:t.randomUUID)=="function")return J.crypto.randomUUID();let n=new Date().getTime(),e=K();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let i=Math.random()*16;return n>0?(i=(n+i)%16|0,n=Math.floor(n/16)):(i=(e+i)%16|0,e=Math.floor(e/16)),(r==="x"?i:i&3|8).toString(16)})}function w(n){return typeof n=="string"&&n.length>0}function Ze(n,e,t){if(typeof String.prototype.startsWith=="function")return n.startsWith(e,t);let r=typeof t=="number"?Math.max(t,0):0;return n.substring(r,r+e.length)===e}var Hp=/^(?:[a-z]+:)?\/\//i,Wp=/^(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/;function vr(n){let e=n.lastIndexOf("/");if(e<0)return n.length;if(Hp.test(n)){let r=n.indexOf("/");if(r>=0&&e===r+1)return n.length}let t=n.indexOf("?");return t>=0&&t<e?vr(n.substring(0,t)):e+1}function sc(n,e){let t=To(n),r=To(e);if(t.scheme!==r.scheme||t.authority!==r.authority||t.path[0]!==void 0&&t.path[0]!=="/"&&r.path[0]==="/"||r.path[0]!==void 0&&r.path[0]!=="/"&&t.path[0]==="/")return null;let i=Er(t.path),o=Er(r.path),a;if(i===o)a="";else{let d=i.split("/");d.pop();let u=o.split("/");for(;d.length>0&&u.length>0&&d[0]===u[0];)d.shift(),u.shift();for(;d.length>0;)d.shift(),u.unshift("..");let l=u.join("/");(l.endsWith("../")||l.endsWith("./"))&&(l=l.slice(0,l.length-1)),a=l===""?".":l}let s=a;return a===""&&r.query===t.query||w(r.query)&&(s+="?",s+=r.query),w(r.fragment)&&(s+="#",s+=r.fragment),s}function Gp(n,e){let t=To(n),r=To(e);if(w(r.scheme))return es(r);let i={scheme:t.scheme,authority:t.authority,path:"",query:r.query,fragment:r.fragment};return w(r.authority)?(i.authority=r.authority,i.path=Er(r.path),es(i)):(r.path===""?(i.path=t.path,w(r.query)||(i.query=t.query)):Ze(r.path,"/")?i.path=Er(r.path):i.path=Er(jp(t,r.path)),es(i))}var _r=new Map,qp=200;function To(n){var r,i,o,a,s;if(_r.has(n))return _r.get(n);let e=n.match(Wp),t;return e===null?t={scheme:"",authority:"",path:"",query:"",fragment:""}:t={scheme:(r=e[1])!=null?r:"",authority:(i=e[2])!=null?i:"",path:(o=e[3])!=null?o:"",query:(a=e[4])!=null?a:"",fragment:(s=e[5])!=null?s:""},_r.size>=qp&&_r.clear(),_r.set(n,t),t}function es(n){let e="";return w(n.scheme)&&(e+=n.scheme+":"),w(n.authority)&&(e+="//"+n.authority),e+=n.path,w(n.query)&&(e+="?"+n.query),w(n.fragment)&&(e+="#"+n.fragment),e}function Er(n){let e=n.split(/(?=\/)/),t=[];for(let r=0;r<e.length;r++){let i=e[r];if(!(i===".."||i==="."||i==="")){if(i==="/.."){t.pop(),r===e.length-1&&t.push("/");continue}if(i==="/."){r===e.length-1&&t.push("/");continue}t.push(i)}}return t.join("")}function jp(n,e){if(w(n.authority)&&n.path==="")return"/"+e;let t=n.path;return t.substring(0,t.lastIndexOf("/")+1)+e}function mn(...n){var r,i,o;let e=n.filter(a=>a!==""),t=e.length;if(t===0)return"";if(t===1)return(r=e[0])!=null?r:"";{let a=(i=e[0])!=null?i:"",s=(o=e[1])!=null?o:"",d=Gp(a,s),u=e.slice(2);return mn(d,...u)}}var Yp=4,Rr=class{constructor(e){var t,r;this._sessionId=(t=e.sessionId)!=null?t:So(),this._contentId=(r=e.contentId)!=null?r:So(),this._typePreference=e.communicationType==="headers"?0:1,this._bufferStarvationToggle=!1,this._playbackObserver=null,this._lastThroughput={},this._canceller=null}startMonitoringPlayback(e){var t;(t=this._canceller)==null||t.cancel(),this._canceller=new B,this._playbackObserver=e,e.listen(r=>{r.rebuffering!==null&&(this._bufferStarvationToggle=!0)},{includeLastObservation:!0,clearSignal:this._canceller.signal})}stopMonitoringPlayback(){var e;(e=this._canceller)==null||e.cancel(),this._canceller=null,this._playbackObserver=null}updateThroughput(e,t){this._lastThroughput[e]=t}_getCommonCmcdData(e){var i;let t={};t.bs=this._bufferStarvationToggle,this._bufferStarvationToggle=!1,t.cid=this._contentId,t.mtp=e!==void 0?Math.floor(Math.round(e/1e3/100)*100):void 0,t.sid=this._sessionId;let r=(i=this._playbackObserver)==null?void 0:i.getReference().getValue();return t.pr=r===void 0||r.speed===1?void 0:r.speed,r!==void 0&&(t.su=r.rebuffering!==null),t}getCmcdDataForManifest(e){var r;let t=this._getCommonCmcdData((r=this._lastThroughput.video)!=null?r:this._lastThroughput.audio);switch(t.ot="m",e){case"dash":t.sf="d";break;case"smooth":t.sf="s";break;default:t.sf="o";break}return this._producePayload(t)}getCmcdDataForSegmentRequest(e){var a,s,d,u;let t=(a=this._playbackObserver)==null?void 0:a.getReference().getValue(),r=this._getCommonCmcdData(this._lastThroughput[e.adaptation.type]);switch(r.br=Math.round(e.representation.bitrate/1e3),r.d=Math.round(e.segment.duration*1e3),e.adaptation.type){case"video":r.ot="v";break;case"audio":r.ot="a";break;case"text":r.ot="c";break}if(e.segment.isInit&&(r.ot="i"),!E(e.nextSegment)&&e.segment.url!==null&&e.nextSegment.url!==null&&(!e.nextSegment.isInit||e.nextSegment.indexRange===void 0)){let l=e.segment.url,c=e.nextSegment.url,f=sc(l,c);f!==null&&(f!=="."&&(r.nor=encodeURIComponent(f)),e.nextSegment.range!==void 0&&(r.nrr=String(e.nextSegment.range[0])+"-",isFinite(e.nextSegment.range[1])&&(r.nrr+=String(e.nextSegment.range[1]))))}let i;if(t!==void 0&&(r.ot==="v"||r.ot==="a"||r.ot==="av")){let l=t.buffered[e.adaptation.type];if(!E(l)){let c=(u=(d=(s=this._playbackObserver)==null?void 0:s.getCurrentTime())!=null?d:t.position.getWanted())!=null?u:t.position.getPolled();for(let f of l)if(c>=f.start&&c<f.end){i=(f.end-c)*1e3,r.bl=Math.floor(Math.round(i/100)*100);break}}}let o=i===void 0||t===void 0?void 0:i/t.speed;if(r.dl=o===void 0?void 0:Math.floor(Math.round(o/100)*100),o!==void 0){let c=e.representation.bitrate*e.segment.duration/1e3/(o/1e3);r.rtp=Math.floor(Math.round(c*Yp/100)*100)}switch(e.manifest.transport){case"dash":r.sf="d";break;case"smooth":r.sf="s";break;default:r.sf="o";break}return r.st=e.manifest.isDynamic?"l":"v",r.tb=e.adaptation.representations.reduce((l,c)=>c.isPlayable()!==!0?l:l===void 0?Math.round(c.bitrate/1e3):Math.max(l,Math.round(c.bitrate/1e3)),void 0),this._producePayload(r)}_producePayload(e){let t={object:"",request:"",session:"",status:""},r="",i=(u,l)=>{this._typePreference===0?t[l]+=u:r+=u},o=(u,l)=>{let c=e[u];if(c!==void 0){let f=`${u}=${String(c)},`;i(f,l)}},a=(u,l)=>{if(e[u]===!0){let c=`${u},`;i(c,l)}},s=(u,l)=>{let c=e[u];if(c!==void 0){let g=`prop=${`"${c.replace("\\","\\\\").replace('"','\\"')}"`},`;i(g,l)}},d=(u,l)=>{let c=e[u];if(c!==void 0){let f=`prop=${c},`;i(f,l)}};return o("bl","request"),o("br","object"),a("bs","status"),s("cid","session"),o("d","object"),o("dl","request"),o("mtp","request"),s("nor","request"),s("nrr","request"),d("ot","object"),o("pr","session"),o("rtp","status"),d("sf","session"),s("sid","session"),d("st","session"),a("su","request"),o("tb","object"),this._typePreference===0?(t.object[t.object.length-1]===","&&(t.object=t.object.substring(0,t.object.length-1)),t.request[t.request.length-1]===","&&(t.request=t.request.substring(0,t.request.length-1)),t.session[t.session.length-1]===","&&(t.session=t.session.substring(0,t.session.length-1)),t.status[t.status.length-1]===","&&(t.status=t.status.substring(0,t.status.length-1)),m.debug("CMCD: proposing headers payload"),{type:"headers",value:{"CMCD-Object":t.object,"CMCD-Request":t.request,"CMCD-Session":t.session,"CMCD-Status":t.status}}):(r[r.length-1]===","&&(r=r.substring(0,r.length-1)),r=encodeURIComponent(r),m.debug("CMCD: proposing query string payload",r),{type:"query",value:[["CMCD",r]]})}};var dc=Rr;var rt=class n extends Error{constructor(e,t,r){super(e),Object.setPrototypeOf(this,n.prototype),this.name="CustomLoaderError",this.canRetry=t,this.xhr=r}};var Ee=class n extends Error{constructor(e,t,r){let i;switch(r){case"TIMEOUT":i="The request timed out";break;case"ERROR_EVENT":i="An error prevented the request to be performed successfully";break;case"PARSE_ERROR":i="An error happened while formatting the response data";break;case"ERROR_HTTP_CODE":i="An HTTP status code indicating failure was received: "+String(t);break}super(i),Object.setPrototypeOf(this,n.prototype),this.name="RequestError",this.url=e,this.status=t,this.type=r}serialize(){return{url:this.url,status:this.status,type:this.type}}},Fe={TIMEOUT:"TIMEOUT",ERROR_EVENT:"ERROR_EVENT",ERROR_HTTP_CODE:"ERROR_HTTP_CODE",PARSE_ERROR:"PARSE_ERROR"};var ts=typeof Headers=="function"?Headers:null,ns=typeof AbortController=="function"?AbortController:null;function _o(n){var f,g;let e;if(!E(n.headers))if(E(ts))e=n.headers;else{e=new ts;let p=Object.keys(n.headers);for(let I=0;I<p.length;I++){let y=p[I];e.append(y,n.headers[y])}}m.debug("Fetch: Called with URL",n.url);let t=null,r=!1,i=!1,o=K(),a=E(ns)?null:new ns;function s(){if(E(a)){m.warn("Fetch: AbortController API not available.");return}a.abort()}let d;n.timeout!==void 0&&(d=setTimeout(()=>{r=!0,u!==void 0&&clearTimeout(u),s()},n.timeout));let u;n.connectionTimeout!==void 0&&(u=setTimeout(()=>{i=!0,d!==void 0&&clearTimeout(d),s()},n.connectionTimeout));let l=n.cancelSignal.register(function(I){t=I,s()}),c={method:"GET"};if(e!==void 0&&(c.headers=e),c.signal=E(a)?null:a.signal,m.hasLevel("DEBUG")){let p="FETCH: Sending GET "+n.url;n.timeout!==void 0&&(p+=" to="+String(n.timeout/1e3)),n.connectionTimeout!==void 0&&(p+=" cto="+String(n.connectionTimeout/1e3)),((f=n.headers)==null?void 0:f.Range)!==void 0&&(p+=" Range="+((g=n.headers)==null?void 0:g.Range)),m.debug(p)}return fetch(n.url,c).then(p=>{if(u!==void 0&&clearTimeout(u),p.status>=300)throw m.warn("Fetch: Request HTTP Error",p.status,p.url),new Ee(p.url,p.status,Fe.ERROR_HTTP_CODE);if(E(p.body))throw new Ee(p.url,p.status,Fe.PARSE_ERROR);let I=p.headers.get("Content-Length"),y=!E(I)&&!isNaN(+I)?+I:void 0,b=p.body.getReader(),T=0;return v();async function v(){let _=await b.read();if(!_.done&&!E(_.value)){T+=_.value.byteLength;let R=K(),k={url:p.url,currentTime:R,duration:R-o,sendingTime:o,chunkSize:_.value.byteLength,chunk:_.value.buffer,size:T,totalSize:y};return n.onData(k),v()}else if(_.done){d!==void 0&&clearTimeout(d),l();let R=K();return{requestDuration:R-o,receivedTime:R,sendingTime:o,size:T,status:p.status,url:p.url}}return v()}}).catch(p=>{throw t!==null?t:(l(),r?(m.warn("Fetch: Request timed out."),new Ee(n.url,0,Fe.TIMEOUT)):i?(m.warn("Fetch: Request connection timed out."),new Ee(n.url,0,Fe.TIMEOUT)):p instanceof Ee?p:(m.warn("Fetch: Request Error",p instanceof Error?p.toString():""),new Ee(n.url,0,Fe.ERROR_EVENT)))})}function kr(){return typeof J.fetch=="function"&&!E(ns)&&!E(ts)}var $p="json";function rs(n){let e={url:n.url,headers:n.headers,responseType:E(n.responseType)?$p:n.responseType,timeout:n.timeout,connectionTimeout:n.connectionTimeout};return new Promise((t,r)=>{let{onProgress:i,cancelSignal:o}=n,{url:a,headers:s,responseType:d,timeout:u,connectionTimeout:l}=e,c=new XMLHttpRequest;c.open("GET",a,!0);let f;u!==void 0&&(c.timeout=u,f=setTimeout(()=>{y(),r(new Ee(a,c.status,Fe.TIMEOUT))},u+3e3));let g;if(l!==void 0&&(g=setTimeout(()=>{y(),c.readyState!==XMLHttpRequest.DONE&&c.abort(),r(new Ee(a,c.status,Fe.TIMEOUT))},l)),c.responseType=d,c.responseType==="document"&&c.overrideMimeType("text/xml"),!E(s)){let b=s;for(let T in b)b.hasOwnProperty(T)&&c.setRequestHeader(T,b[T])}let p=K(),I=null;if(o!==void 0&&(I=o.register(function(T){y(),c.readyState!==XMLHttpRequest.DONE&&c.abort(),r(T)}),o.isCancelled()))return;if(c.onerror=function(){y(),r(new Ee(a,c.status,Fe.ERROR_EVENT))},c.ontimeout=function(){y(),r(new Ee(a,c.status,Fe.TIMEOUT))},l!==void 0&&(c.onreadystatechange=function(){c.readyState>=XMLHttpRequest.HEADERS_RECEIVED&&clearTimeout(g)}),i!==void 0&&(c.onprogress=function(T){let v=K();i({url:a,duration:v-p,sendingTime:p,currentTime:v,size:T.loaded,totalSize:T.total})}),c.onload=function(T){if(c.readyState===XMLHttpRequest.DONE)if(y(),c.status>=200&&c.status<300){let v=K(),_=c.response instanceof ArrayBuffer?c.response.byteLength:T.total,R=c.status,k=c.responseType,x=w(c.responseURL)?c.responseURL:a,M;if(k==="json"?M=typeof c.response=="object"?c.response:Qp(c.responseText):M=c.response,E(M)){r(new Ee(a,c.status,Fe.PARSE_ERROR));return}t({status:R,url:x,responseType:k,sendingTime:p,receivedTime:v,requestDuration:v-p,size:_,responseData:M})}else r(new Ee(a,c.status,Fe.ERROR_HTTP_CODE))},m.hasLevel("DEBUG")){let b="XHR: Sending GET "+a;n.responseType!==void 0&&(b+=" type="+n.responseType),u!==void 0&&(b+=" to="+String(u/1e3)),l!==void 0&&(b+=" cto="+String(l/1e3)),(s==null?void 0:s.Range)!==void 0&&(b+=" Range="+(s==null?void 0:s.Range)),m.debug(b)}c.send();function y(){f!==void 0&&clearTimeout(f),g!==void 0&&clearTimeout(g),I!==null&&I()}})}function Qp(n){try{return JSON.parse(n)}catch(e){return null}}var Te=rs;var pn=Fe,Je={NETWORK_ERROR:"NETWORK_ERROR",MEDIA_ERROR:"MEDIA_ERROR",ENCRYPTED_MEDIA_ERROR:"ENCRYPTED_MEDIA_ERROR",OTHER_ERROR:"OTHER_ERROR"},is={PIPELINE_LOAD_ERROR:"PIPELINE_LOAD_ERROR",PIPELINE_PARSE_ERROR:"PIPELINE_PARSE_ERROR",INTEGRITY_ERROR:"INTEGRITY_ERROR",MANIFEST_PARSE_ERROR:"MANIFEST_PARSE_ERROR",MANIFEST_INCOMPATIBLE_CODECS_ERROR:"MANIFEST_INCOMPATIBLE_CODECS_ERROR",MANIFEST_UPDATE_ERROR:"MANIFEST_UPDATE_ERROR",MANIFEST_UNSUPPORTED_ADAPTATION_TYPE:"MANIFEST_UNSUPPORTED_ADAPTATION_TYPE",MEDIA_STARTING_TIME_NOT_FOUND:"MEDIA_STARTING_TIME_NOT_FOUND",MEDIA_TIME_BEFORE_MANIFEST:"MEDIA_TIME_BEFORE_MANIFEST",MEDIA_TIME_AFTER_MANIFEST:"MEDIA_TIME_AFTER_MANIFEST",MEDIA_TIME_NOT_FOUND:"MEDIA_TIME_NOT_FOUND",NO_PLAYABLE_REPRESENTATION:"NO_PLAYABLE_REPRESENTATION",MEDIA_IS_ENCRYPTED_ERROR:"MEDIA_IS_ENCRYPTED_ERROR",CREATE_MEDIA_KEYS_ERROR:"CREATE_MEDIA_KEYS_ERROR",MEDIA_KEYS_ATTACHMENT_ERROR:"MEDIA_KEYS_ATTACHMENT_ERROR",KEY_ERROR:"KEY_ERROR",KEY_STATUS_CHANGE_ERROR:"KEY_STATUS_CHANGE_ERROR",KEY_UPDATE_ERROR:"KEY_UPDATE_ERROR",KEY_LOAD_ERROR:"KEY_LOAD_ERROR",KEY_LOAD_TIMEOUT:"KEY_LOAD_TIMEOUT",KEY_GENERATE_REQUEST_ERROR:"KEY_GENERATE_REQUEST_ERROR",INCOMPATIBLE_KEYSYSTEMS:"INCOMPATIBLE_KEYSYSTEMS",INVALID_ENCRYPTED_EVENT:"INVALID_ENCRYPTED_EVENT",INVALID_KEY_SYSTEM:"INVALID_KEY_SYSTEM",LICENSE_SERVER_CERTIFICATE_ERROR:"LICENSE_SERVER_CERTIFICATE_ERROR",MULTIPLE_SESSIONS_SAME_INIT_DATA:"MULTIPLE_SESSIONS_SAME_INIT_DATA",BUFFER_APPEND_ERROR:"BUFFER_APPEND_ERROR",BUFFER_FULL_ERROR:"BUFFER_FULL_ERROR",BUFFER_TYPE_UNKNOWN:"BUFFER_TYPE_UNKNOWN",MEDIA_ERR_BLOCKED_AUTOPLAY:"MEDIA_ERR_BLOCKED_AUTOPLAY",MEDIA_ERR_PLAY_NOT_ALLOWED:"MEDIA_ERR_PLAY_NOT_ALLOWED",MEDIA_ERR_NOT_LOADED_METADATA:"MEDIA_ERR_NOT_LOADED_METADATA",MEDIA_ERR_ABORTED:"MEDIA_ERR_ABORTED",MEDIA_ERR_NETWORK:"MEDIA_ERR_NETWORK",MEDIA_ERR_DECODE:"MEDIA_ERR_DECODE",MEDIA_ERR_SRC_NOT_SUPPORTED:"MEDIA_ERR_SRC_NOT_SUPPORTED",MEDIA_ERR_UNKNOWN:"MEDIA_ERR_UNKNOWN",MEDIA_SOURCE_NOT_SUPPORTED:"MEDIA_SOURCE_NOT_SUPPORTED",MEDIA_KEYS_NOT_SUPPORTED:"MEDIA_KEYS_NOT_SUPPORTED",DISCONTINUITY_ENCOUNTERED:"DISCONTINUITY_ENCOUNTERED",NONE:"NONE"};function ct(n,e){return`${n}: ${e}`}var pe=class n extends Error{constructor(e,t,r){super(ct(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="EncryptedMediaError",this.type=Je.ENCRYPTED_MEDIA_ERROR,this.code=e,this._originalMessage=t,this.fatal=!1,typeof(r==null?void 0:r.keyStatuses)=="string"&&(this.keyStatuses=r.keyStatuses)}serialize(){return{name:this.name,code:this.code,reason:this._originalMessage,keyStatuses:this.keyStatuses}}};var te=class n extends Error{constructor(e,t,r){super(ct(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="MediaError",this.type=Je.MEDIA_ERROR,this._originalMessage=t,this.code=e,this.fatal=!1,(r==null?void 0:r.tracks)!==void 0&&(r==null?void 0:r.tracks.length)>0&&(this.tracksInfo=r.tracks)}serialize(){return{name:this.name,code:this.code,reason:this._originalMessage,tracks:this.tracksInfo}}};var it=class n extends Error{constructor(e,t){super(ct(e,t.message)),Object.setPrototypeOf(this,n.prototype),this.name="NetworkError",this.type=Je.NETWORK_ERROR,this.url=t.url,this.status=t.status,this.errorType=t.type,this._baseError=t,this.code=e,this.fatal=!1}isHttpError(e){return this.errorType===pn.ERROR_HTTP_CODE&&this.status===e}serialize(){return{name:this.name,code:this.code,baseError:this._baseError.serialize()}}};var Le=class n extends Error{constructor(e,t){super(ct(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="OtherError",this.type=Je.OTHER_ERROR,this.code=e,this.fatal=!1,this._originalMessage=t}serialize(){return{name:this.name,code:this.code,reason:this._originalMessage}}};function qt(n){return(n instanceof pe||n instanceof te||n instanceof Le||n instanceof it)&&Object.keys(Je).indexOf(n.type)>=0}function Oe(n,{defaultCode:e,defaultReason:t}){if(qt(n))return n;let r=n instanceof Error?n.toString():t;return new Le(e,r)}var ot=class n extends Error{constructor(e,t,r){super(t),Object.setPrototypeOf(this,n.prototype),this.name="SourceBufferError",this.errorName=e,this.isBufferFull=r}serialize(){return{errorName:this.name,message:this.message,isBufferFull:this.isBufferFull}}toString(){return`${this.errorName}: ${this.message}`}};var Xp={aa:"aar",ab:"abk",ae:"ave",af:"afr",ak:"aka",am:"amh",an:"arg",ar:"ara",as:"asm",av:"ava",ay:"aym",az:"aze",ba:"bak",be:"bel",bg:"bul",bi:"bis",bm:"bam",bn:"ben",bo:"bod",br:"bre",bs:"bos",ca:"cat",ce:"che",ch:"cha",co:"cos",cr:"cre",cs:"ces",cu:"chu",cv:"chv",cy:"cym",da:"dan",de:"deu",dv:"div",dz:"dzo",ee:"ewe",el:"ell",en:"eng",eo:"epo",es:"spa",et:"est",eu:"eus",fa:"fas",ff:"ful",fi:"fin",fj:"fij",fo:"fao",fr:"fra",fy:"fry",ga:"gle",gd:"gla",gl:"glg",gn:"grn",gu:"guj",gv:"glv",ha:"hau",he:"heb",hi:"hin",ho:"hmo",hr:"hrv",ht:"hat",hu:"hun",hy:"hye",hz:"her",ia:"ina",id:"ind",ie:"ile",ig:"ibo",ii:"iii",ik:"ipk",io:"ido",is:"isl",it:"ita",iu:"iku",ja:"jpn",jv:"jav",ka:"kat",kg:"kon",ki:"kik",kj:"kua",kk:"kaz",kl:"kal",km:"khm",kn:"kan",ko:"kor",kr:"kau",ks:"kas",ku:"kur",kv:"kom",kw:"cor",ky:"kir",la:"lat",lb:"ltz",lg:"lug",li:"lim",ln:"lin",lo:"lao",lt:"lit",lu:"lub",lv:"lav",mg:"mlg",mh:"mah",mi:"mri",mk:"mkd",ml:"mal",mn:"mon",mr:"mar",ms:"msa",mt:"mlt",my:"mya",na:"nau",nb:"nob",nd:"nde",ne:"nep",ng:"ndo",nl:"nld",nn:"nno",no:"nor",nr:"nbl",nv:"nav",ny:"nya",oc:"oci",oj:"oji",om:"orm",or:"ori",os:"oss",pa:"pan",pi:"pli",pl:"pol",ps:"pus",pt:"por",qu:"que",rm:"roh",rn:"run",ro:"ron",ru:"rus",rw:"kin",sa:"san",sc:"srd",sd:"snd",se:"sme",sg:"sag",si:"sin",sk:"slk",sl:"slv",sm:"smo",sn:"sna",so:"som",sq:"sqi",sr:"srp",ss:"ssw",st:"sot",su:"sun",sv:"swe",sw:"swa",ta:"tam",te:"tel",tg:"tgk",th:"tha",ti:"tir",tk:"tuk",tl:"tgl",tn:"tsn",to:"ton",tr:"tur",ts:"tso",tt:"tat",tw:"twi",ty:"tah",ug:"uig",uk:"ukr",ur:"urd",uz:"uzb",ve:"ven",vi:"vie",vo:"vol",wa:"wln",wo:"wol",xh:"xho",yi:"yid",yo:"yor",za:"zha",zh:"zho",zu:"zul"},uc=Xp;var Zp={alb:"sqi",arm:"hye",baq:"eus",bur:"mya",chi:"zho",cze:"ces",dut:"nld",fre:"fra",geo:"kat",ger:"deu",gre:"ell",ice:"isl",mac:"mkd",mao:"mri",may:"msa",per:"fas",slo:"slk",rum:"ron",tib:"bod",wel:"cym"},lc=Zp;function Jp(n){if(E(n)||n==="")return"und";let t=(""+n).toLowerCase().split("-")[0],r=eg(t);return w(r)?r:n}function eg(n){let e;switch(n.length){case 2:e=uc[n];break;case 3:e=lc[n];break}return e}var cc=Jp;var Cr=cc;function ge(n,e){if(n.length!==e.length)return!1;if(n===e)return!0;for(let t=n.length-1;t>=0;t--)if(n[t]!==e[t])return!1;return!0}var jt=["audio","video","text"];function gn(n){var o,a;let e=n.timeBounds;if(e.timeshiftDepth===null)return(o=e.minimumSafePosition)!=null?o:0;let{maximumTimeData:t}=e,r;if(!e.maximumTimeData.isLinear)r=t.maximumSafePosition;else{let s=K()-t.time;r=t.maximumSafePosition+s/1e3}let i=r-e.timeshiftDepth;return Math.max((a=e.minimumSafePosition)!=null?a:0,i)}function hn(n){let{maximumTimeData:e}=n.timeBounds;if(!n.isLive||e.livePosition===void 0)return;if(!e.isLinear)return e.livePosition;let t=K()-e.time;return e.livePosition+t/1e3}function bt(n){let{maximumTimeData:e}=n.timeBounds;if(!e.isLinear)return e.maximumSafePosition;let t=K()-e.time;return e.maximumSafePosition+t/1e3}function ft(n,e){if(e===void 0)return as(n).filter(r=>r.supportStatus.hasSupportedCodec!==!1&&r.supportStatus.isDecipherable!==!1);let t=n.adaptations[e];return t===void 0?[]:t.filter(r=>r.supportStatus.hasSupportedCodec!==!1&&r.supportStatus.isDecipherable!==!1)}function mc(n,e){let t=null;for(let r of n.periods){if(os(r,e,t))return r;t=r}}function Eo(n,e){let t=e.end;if(t===void 0)return null;let r=Z(n.periods,i=>i.end===void 0||t<i.end);return r===void 0?null:r}function os(n,e,t){return e>=n.start&&(n.end===void 0||e<n.end)?!0:e===n.end&&(t===null||t.start>n.end)}function as(n){let e=n.adaptations;return Sr(e).reduce((t,r)=>E(r)?t:t.concat(r),[])}function vo(n,e){var r,i;let t={language:(r=n.language)!=null?r:"",normalized:(i=n.normalizedLanguage)!=null?i:"",audioDescription:n.isAudioDescription===!0,id:n.id,representations:(e?n.representations.filter(o=>It(o)):n.representations).map(tg),label:n.label};return n.isDub===!0&&(t.dub=!0),t}function Ro(n){var e,t;return{language:(e=n.language)!=null?e:"",normalized:(t=n.normalizedLanguage)!=null?t:"",closedCaption:n.isClosedCaption===!0,id:n.id,label:n.label,forced:n.isForcedSubtitles}}function ko(n,e){let t=n.trickModeTracks!==void 0?n.trickModeTracks.map(i=>{let o=(e?i.representations.filter(s=>It(s)===!0):i.representations).map(fc),a={id:i.id,representations:o,isTrickModeTrack:!0};return i.isSignInterpreted===!0&&(a.signInterpreted=!0),a}):void 0,r={id:n.id,representations:(e?n.representations.filter(i=>It(i)===!0):n.representations).map(fc),label:n.label};return n.isSignInterpreted===!0&&(r.signInterpreted=!0),n.isTrickModeTrack===!0&&(r.isTrickModeTrack=!0),t!==void 0&&(r.trickModeTracks=t),r}function tg(n){let{id:e,bitrate:t,codecs:r,isSpatialAudio:i,isSupported:o,decipherable:a}=n;return{id:e,bitrate:t,codec:r==null?void 0:r[0],isSpatialAudio:i,isCodecSupported:o,decipherable:a}}function fc(n){let{id:e,bitrate:t,frameRate:r,width:i,height:o,codecs:a,hdrInfo:s,isSupported:d,decipherable:u,contentProtections:l}=n;return{id:e,bitrate:t,frameRate:r,width:i,height:o,codec:a==null?void 0:a[0],hdrInfo:s,isCodecSupported:d,decipherable:u,contentProtections:l!==void 0?{keyIds:l.keyIds}:void 0}}function Yt(n){switch(n.type){case"audio":return{type:"audio",track:vo(n,!1)};case"video":return{type:"video",track:ko(n,!1)};case"text":return{type:"text",track:Ro(n)}}}function It(n){return n.decipherable===!1?!1:n.isSupported}function pc(n){return new Function(`return (${n}(arguments[0], arguments[1]))`)}function et(){let n="",e=-1;return function(){return e++,e>=Number.MAX_SAFE_INTEGER&&(n+="0",e=0),n+String(e)}}var ng=et(),ss=class{constructor(e,t,r){var o,a,s,d,u;this.id=e.id,this.uniqueId=ng(),this.bitrate=e.bitrate,this.codecs=[],this.trackType=t,e.isSpatialAudio!==void 0&&(this.isSpatialAudio=e.isSpatialAudio),e.height!==void 0&&(this.height=e.height),e.width!==void 0&&(this.width=e.width),e.mimeType!==void 0&&(this.mimeType=e.mimeType),e.contentProtections!==void 0&&(this.contentProtections=e.contentProtections),e.frameRate!==void 0&&(this.frameRate=e.frameRate),e.hdrInfo!==void 0&&(this.hdrInfo=e.hdrInfo),this.cdnMetadata=e.cdnMetadata,this.index=e.index;let i=this.contentProtections!==void 0;if(t==="audio"||t==="video"){if(e.supplementalCodecs!==void 0){let l=r.isSupported((o=this.mimeType)!=null?o:"",(a=e.supplementalCodecs)!=null?a:"",i);l!==!1&&(this.codecs=[e.supplementalCodecs],this.isSupported=l)}this.isSupported!==!0&&(this.codecs.length>0?this.codecs.push((s=e.codecs)!=null?s:""):(this.codecs=e.codecs===void 0?[]:[e.codecs],this.isSupported=r.isSupported((d=this.mimeType)!=null?d:"",(u=e.codecs)!=null?u:"",i)))}else e.codecs!==void 0&&this.codecs.push(e.codecs),this.isSupported=!0}refreshCodecSupport(e){var s,d;if(this.isSupported!==void 0)return;let t=this.contentProtections!==void 0,r=!1,i=(s=this.mimeType)!=null?s:"",o=(d=this.codecs)!=null?d:[];o.length===0&&(o=[""]);let a=!1;for(let u of o){if(r=e.isSupported(i,u,t),r===!0){this.codecs=[u];break}r===void 0&&(a=!0)}r===!0?this.isSupported=!0:a?this.isSupported=void 0:this.isSupported=!1}getMimeTypeString(){var e,t,r;return`${(e=this.mimeType)!=null?e:""};codecs="${(r=(t=this.codecs)==null?void 0:t[0])!=null?r:""}"`}getEncryptionData(e){var i;let t=this.getAllEncryptionData(),r=[];for(let o=0;o<t.length;o++){let a=!1,s=t[o];for(let d=0;d<s.values.length;d++)if(s.values[d].systemId.toLowerCase()===e.toLowerCase())if(a)r[r.length-1].values.push(s.values[d]);else{let u=(i=this.contentProtections)==null?void 0:i.keyIds;r.push({type:s.type,keyIds:u,values:[s.values[d]]}),a=!0}}return r}getAllEncryptionData(){var t;if(this.contentProtections===void 0||this.contentProtections.initData.length===0)return[];let e=(t=this.contentProtections)==null?void 0:t.keyIds;return this.contentProtections.initData.map(r=>({type:r.type,keyIds:e,values:r.values}))}addProtectionData(e,t,r){let i=!1;if(this.contentProtections===void 0)return this.contentProtections={keyIds:t!==void 0?[t]:[],initData:[{type:e,values:r}]},!0;if(t!==void 0){let a=this.contentProtections.keyIds;if(a===void 0)this.contentProtections.keyIds=[t];else{let s=!1;for(let d of a)ge(d,t)&&(s=!0);s||(m.warn("Manifest: found unanounced key id."),a.push(t))}}let o=this.contentProtections.initData;for(let a=0;a<o.length;a++)if(o[a].type===e){let s=o[a].values;for(let d=0;d<r.length;d++){let u=r[d],l;for(l=0;l<s.length;l++)if(u.systemId===s[l].systemId){if(ge(u.data,s[l].data))break;m.warn("Manifest: different init data for the same system ID")}l===s.length&&(s.push(u),i=!0)}return i}return this.contentProtections.initData.push({type:e,values:r}),!0}isPlayable(){return It(this)}getMetadataSnapshot(){return{id:this.id,uniqueId:this.uniqueId,bitrate:this.bitrate,codecs:this.codecs,mimeType:this.mimeType,width:this.width,height:this.height,frameRate:this.frameRate,isSupported:this.isSupported,hdrInfo:this.hdrInfo,contentProtections:this.contentProtections,decipherable:this.decipherable}}},gc=ss;var Pr=class n{constructor(e,t,r={}){let{trickModeTracks:i}=e,{representationFilter:o,isManuallyAdded:a}=r;this.id=e.id,this.type=e.type,e.isTrickModeTrack!==void 0&&(this.isTrickModeTrack=e.isTrickModeTrack),e.language!==void 0&&(this.language=e.language,this.normalizedLanguage=Cr(e.language)),e.closedCaption!==void 0&&(this.isClosedCaption=e.closedCaption),e.audioDescription!==void 0&&(this.isAudioDescription=e.audioDescription),e.isDub!==void 0&&(this.isDub=e.isDub),e.forcedSubtitles!==void 0&&(this.isForcedSubtitles=e.forcedSubtitles),e.isSignInterpreted!==void 0&&(this.isSignInterpreted=e.isSignInterpreted),e.label!==void 0&&(this.label=e.label),i!==void 0&&i.length>0&&(this.trickModeTracks=i.map(u=>new n(u,t)));let s=e.representations,d=[];this.supportStatus={hasSupportedCodec:!1,hasCodecWithUndefinedSupport:!1,isDecipherable:!1};for(let u=0;u<s.length;u++){let l=new gc(s[u],this.type,t),c=!0;if(!E(o)){let f={id:l.id,bitrate:l.bitrate,codecs:l.codecs,height:l.height,width:l.width,frameRate:l.frameRate,hdrInfo:l.hdrInfo};if(l.contentProtections!==void 0&&(f.contentProtections={},l.contentProtections.keyIds!==void 0)){let g=l.contentProtections.keyIds;f.contentProtections.keyIds=g}c=o(f,{trackType:this.type,language:this.language,normalizedLanguage:this.normalizedLanguage,isClosedCaption:this.isClosedCaption,isDub:this.isDub,isAudioDescription:this.isAudioDescription,isSignInterpreted:this.isSignInterpreted})}c?(d.push(l),l.isSupported===void 0?(this.supportStatus.hasCodecWithUndefinedSupport=!0,this.supportStatus.hasSupportedCodec===!1&&(this.supportStatus.hasSupportedCodec=void 0)):l.isSupported&&(this.supportStatus.hasSupportedCodec=!0),l.decipherable===void 0?this.supportStatus.isDecipherable===!1&&(this.supportStatus.isDecipherable=void 0):l.decipherable&&(this.supportStatus.isDecipherable=!0)):m.debug("Filtering Representation due to representationFilter",this.type,`Adaptation: ${this.id}`,`Representation: ${l.id}`,`(${l.bitrate})`)}d.sort((u,l)=>u.bitrate-l.bitrate),this.representations=d,this.manuallyAdded=a===!0}refreshCodecSupport(e){let t=!1,r=!1;for(let i of this.representations)i.refreshCodecSupport(e),i.isSupported===void 0?t=!0:i.isSupported&&(r=!0);r?this.supportStatus.hasSupportedCodec=!0:t?this.supportStatus.hasSupportedCodec=void 0:this.supportStatus.hasSupportedCodec=!1,this.supportStatus.hasCodecWithUndefinedSupport=t}getRepresentation(e){return Z(this.representations,({id:t})=>e===t)}getMetadataSnapshot(){let e=[],t=this.representations;for(let r of t)e.push(r.getMetadataSnapshot());return{id:this.id,type:this.type,supportStatus:this.supportStatus,language:this.language,isForcedSubtitles:this.isForcedSubtitles,isClosedCaption:this.isClosedCaption,isAudioDescription:this.isAudioDescription,isSignInterpreted:this.isSignInterpreted,normalizedLanguage:this.normalizedLanguage,representations:e,label:this.label,isDub:this.isDub}}};function ds(){return un}function In(n){return new Promise(e=>{setTimeout(e,n)})}function us(){return cr}function ls(n,e,t){let r=n.setMediaKeys(e,t).then(()=>{m.info("Compat: MediaKeys updated with success")}).catch(i=>{if(t===null){m.error("Compat: Could not reset MediaKeys",i instanceof Error?i:"Unknown Error");return}throw m.error("Compat: Could not update MediaKeys",i instanceof Error?i:"Unknown Error"),i});return us()?r:Promise.race([r,In(1e3)])}var St=new WeakMap,qe={async attach(n,e){let t=St.get(n),r=rg(n,t,e).then(()=>{St.set(n,{pendingTask:null,mediaKeysState:e})},()=>{St.set(n,{pendingTask:null,mediaKeysState:null})});return St.set(n,{pendingTask:r,mediaKeysState:e}),r},getAwaitedState(n){var t;let e=St.get(n);return(t=e==null?void 0:e.mediaKeysState)!=null?t:null},async getAttachedMediaKeysState(n){let e=St.get(n);return e===void 0?null:e.pendingTask!==null?(await e.pendingTask,this.getAttachedMediaKeysState(n)):e.mediaKeysState},clearMediaKeys(n){let e=St.get(n),t=ig(n,e).then(()=>{St.set(n,{pendingTask:null,mediaKeysState:null})},()=>{St.set(n,{pendingTask:null,mediaKeysState:null})});return St.set(n,{pendingTask:t,mediaKeysState:null}),t}};async function hc(n){let e=n.pendingTask;if(!E(e)){m.info("DRM: Awaiting previous MediaKeys attachment operation");try{await n.pendingTask}catch(t){m.info("DRM: previous MediaKeys attachment operation failed",t instanceof Error?t:"Unknown error")}}}async function rg(n,e,t){if(e!==void 0&&(e.pendingTask!==null&&await hc(e),await(!E(e.mediaKeysState)&&e.mediaKeysState.loadedSessionsStore!==t.loadedSessionsStore?e.mediaKeysState.loadedSessionsStore.closeAllSessions():Promise.resolve()),n.mediaKeys===t.mediaKeys)){m.debug("DRM: Right MediaKeys already set");return}m.info("DRM: Attaching MediaKeys to the media element");try{await ls(t.emeImplementation,n,t.mediaKeys),m.info("DRM: MediaKeys attached with success")}catch(r){let i=r instanceof Error?r.toString():"Unknown Error";throw new pe("MEDIA_KEYS_ATTACHMENT_ERROR","Could not attach the MediaKeys to the media element: "+i)}}async function ig(n,e){if(e===void 0||(e.pendingTask!==null&&await hc(e),e.mediaKeysState===null))return;m.info("DRM: Disposing of the current MediaKeys");let{loadedSessionsStore:t}=e.mediaKeysState;return await t.closeAllSessions(),ls(e.mediaKeysState.emeImplementation,n,null)}async function Nn(n){return qe.clearMediaKeys(n)}async function Co(n){if(m.info("DRM: Clearing-up DRM session."),ds())return m.info("DRM: disposing current MediaKeys."),Nn(n);let e=await qe.getAttachedMediaKeysState(n);return e!==null&&e.keySystemOptions.closeSessionsOnStop===!0?(m.info("DRM: closing all current sessions."),e.loadedSessionsStore.closeAllSessions()):(m.info("DRM: Nothing to clear. Returning right away. No state =",e===null),Promise.resolve())}function at(n,e){let t;return new Promise((r,i)=>{if(n.cancellationError!==null)return i(n.cancellationError);let o=!1;t=e(function(d){n.deregister(a),o=!0,r(d)},function(d){n.deregister(a),o=!0,i(d)}),o||n.register(a);function a(s){t!==void 0&&t(),i(s)}})}function $t(n,e){return at(e,t=>{let r=setTimeout(()=>t(),n);return()=>clearTimeout(r)})}function Po(n){let e=new B;return Promise.race([n.close().then(()=>{e.cancel()}),n.closed.then(()=>{e.cancel()}),t()]);async function t(){try{await $t(1e3,e.signal),await r()}catch(i){if(i instanceof Me)return;let o=i instanceof Error?i.message:"Unknown error made it impossible to close the session";m.error(`DRM: ${o}`)}}async function r(){try{await n.update(new Uint8Array(1))}catch(i){if(e.isUsed()||i instanceof Error&&i.message==="The session is already closed.")return;await $t(1e3,e.signal)}if(!e.isUsed())throw new Error("Compat: Couldn't know if session is closed")}}var og=["","webkit","moz","ms"];function ag(n,e){let t=document.createElement(n.tagName),r="on"+e;return r in t?!0:(t.setAttribute(r,"return;"),typeof t[r]=="function")}function sg(n,e){return e.filter(t=>ag(n,t))[0]}function dg(n,e){return n.reduce((t,r)=>t.concat((e===void 0?og:e).map(i=>i+r)),[])}function _e(n,e){let t,r=dg(n,e);return(i,o,a)=>{if(!a.isCancelled()){if(typeof HTMLElement!="undefined"&&i instanceof HTMLElement)if(typeof t=="undefined"&&(t=sg(i,r)),w(t))i.addEventListener(t,o),a.register(()=>{t!==void 0&&i.removeEventListener(t,o)});else{h.CURRENT_ENV===h.DEV&&m.warn(`compat: element ${i.tagName} does not support any of these events: `+r.join(", "));return}r.forEach(s=>{let d=!1;typeof i.addEventListener=="function"?i.addEventListener(s,o):(d=!0,i["on"+s]=o),a.register(()=>{typeof i.removeEventListener=="function"&&i.removeEventListener(s,o),d&&delete i["on"+s]})})}}}function ug(n){let e,t=document;E(t.hidden)?E(t.mozHidden)?E(t.msHidden)?E(t.webkitHidden)||(e="webkit"):e="ms":e="moz":e="";let r=w(e)?e+"Hidden":"hidden",i=w(e)?e+"visibilitychange":"visibilitychange",o=document[r],a=new H(!o,n);return bn(document,i,()=>{let s=!document[r];a.setValueIfChanged(s)},n),a}function yc(n,e){if(n.webkitSupportsPresentationMode===!0&&typeof n.webkitSetPresentationMode=="function"){let i=n.webkitPresentationMode==="picture-in-picture",o=new H({isEnabled:i,pipWindow:null},e);return bn(n,"webkitpresentationmodechanged",()=>{let a=n.webkitPresentationMode==="picture-in-picture";o.setValue({isEnabled:a,pipWindow:null})},e),o}let t=document.pictureInPictureElement===n,r=new H({isEnabled:t,pipWindow:null},e);return bn(n,"enterpictureinpicture",i=>{var o;r.setValue({isEnabled:!0,pipWindow:(o=i.pictureInPictureWindow)!=null?o:null})},e),bn(n,"leavepictureinpicture",()=>{r.setValue({isEnabled:!1,pipWindow:null})},e),r}function Ic(n,e){let t=ug(e),r,i=new H(!0,e);return e.register(()=>{clearTimeout(r),r=void 0}),t.onUpdate(o,{clearSignal:e}),n.onUpdate(o,{clearSignal:e}),o(),i;function o(){if(clearTimeout(r),r=void 0,n.getValue().isEnabled||t.getValue())i.setValueIfChanged(!0);else{let{INACTIVITY_DELAY:a}=U.getCurrent();r=setTimeout(()=>{i.setValueIfChanged(!1)},a)}}}function bc(n){var o,a;let e=E(J.devicePixelRatio)||J.devicePixelRatio===0?1:J.devicePixelRatio,t=new H({width:(o=J.screen)==null?void 0:o.width,height:(a=J.screen)==null?void 0:a.height,pixelRatio:e},n),r=setInterval(i,2e4);return n.register(function(){clearInterval(r)}),t;function i(){let s=t.getValue();(s.width!==screen.width||s.height!==screen.height||s.pixelRatio!==e)&&t.setValue({width:screen.width,height:screen.height,pixelRatio:e})}}function Sc(n,e,t){let r=E(J.devicePixelRatio)||J.devicePixelRatio===0?1:J.devicePixelRatio,i=new H({width:n.clientWidth,height:n.clientHeight,pixelRatio:r},t),o=X;e.onUpdate(s,{clearSignal:t}),bn(J,"resize",s,t),bn(n,"enterpictureinpicture",s,t),bn(n,"leavepictureinpicture",s,t);let a=setInterval(s,2e4);return s(),t.register(function(){o(),clearInterval(a)}),i;function s(){o();let d=e.getValue(),{pipWindow:u}=d;if(d.isEnabled)if(E(u)){let c=i.getValue();(c.width!==void 0||c.height!==void 0||c.pixelRatio!==r)&&i.setValue({width:void 0,height:void 0,pixelRatio:r})}else{let c=()=>{l()};u.addEventListener("resize",c),o=()=>{u.removeEventListener("resize",c),o=X},l()}else{let c=i.getValue();(c.width!==n.clientWidth||c.height!==n.clientHeight||c.pixelRatio!==r)&&i.setValue({width:n.clientWidth,height:n.clientHeight,pixelRatio:r})}function l(){let c=i.getValue();(c.width!==(u==null?void 0:u.width)||c.height!==(u==null?void 0:u.height)||c.pixelRatio!==r)&&i.setValue({width:u==null?void 0:u.width,height:u==null?void 0:u.height,pixelRatio:r})}}}var gC=_e(["loadedmetadata"]),hC=_e(["timeupdate"]),yC=_e(["addtrack"]),IC=_e(["removetrack"]),Un=_e(["sourceopen","webkitsourceopen"]),Mo=_e(["sourceclose","webkitsourceclose"]),Ao=_e(["sourceended","webkitsourceended"]),Tc=_e(["update"]),_c=_e(["removesourcebuffer"]),xo=_e(["keymessage","message"]),Ec=_e(["keyadded","ready"]),wo=_e(["keyerror","error"]),vc=_e(["keystatuseschange"]),Rc=_e(["seeking"]),kc=_e(["seeked"]),Cc=_e(["ended"]);function bn(n,e,t,r){n.addEventListener(e,t),r.register(()=>{n.removeEventListener(e,t)})}var mt,{WebKitMediaKeys:Oo}=J;Oo!==void 0&&typeof Oo.isTypeSupported=="function"&&typeof Oo.prototype.createSession=="function"&&typeof HTMLMediaElement.prototype.webkitSetMediaKeys=="function"&&(mt=Oo);function cs(){return(Fa||cn)&&mt!==void 0}var Mr=class{constructor(e,t,r){this._keyType=e;this._mediaKeys=t;this._configuration=r}get keySystem(){return this._keyType}createMediaKeys(){return new Promise(e=>e(this._mediaKeys))}getConfiguration(){return this._configuration}};function Ct(n){try{let e=n();return typeof e=="object"&&e!==null&&typeof e.then=="function"?e:Promise.resolve(e)}catch(e){return Promise.reject(e)}}var Pt,{MSMediaKeys:Ar}=J;Ar!==void 0&&Ar.prototype!==void 0&&typeof Ar.isTypeSupported=="function"&&typeof Ar.prototype.createSession=="function"&&(Pt=Ar);var fs=class extends re{constructor(e){super(),this.expiration=NaN,this.keyStatuses=new Map,this._mk=e,this._sessionClosingCanceller=new B,this.closed=new Promise(t=>{this._sessionClosingCanceller.signal.register(()=>t())}),this.update=t=>new Promise((r,i)=>{if(this._ss===void 0)return i("MediaKeySession not set.");try{r(this._ss.update(t,""))}catch(o){i(o)}})}generateRequest(e,t){return new Promise(r=>{let i;t instanceof Uint8Array?i=t:t instanceof ArrayBuffer?i=new Uint8Array(t):i=new Uint8Array(t.buffer),this._ss=this._mk.createSession("video/mp4",i),xo(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"message",o)},this._sessionClosingCanceller.signal),Ec(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"keyadded",o)},this._sessionClosingCanceller.signal),wo(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"keyerror",o)},this._sessionClosingCanceller.signal),r()})}close(){return new Promise(e=>{E(this._ss)||(this._ss.close(),this._ss=void 0),this._sessionClosingCanceller.cancel(),e()})}load(){return Promise.resolve(!1)}remove(){return Promise.resolve()}get sessionId(){var e,t;return(t=(e=this._ss)==null?void 0:e.sessionId)!=null?t:""}},Do=class{constructor(e){if(Pt===void 0)throw new Error("No MSMediaKeys API.");this._mediaKeys=new Pt(e)}_setVideo(e){return Ct(()=>{this._videoElement=e,this._videoElement.msSetMediaKeys!==void 0&&this._videoElement.msSetMediaKeys(this._mediaKeys)})}createSession(){if(this._videoElement===void 0||this._mediaKeys===void 0)throw new Error("Video not attached to the MediaKeys");return new fs(this._mediaKeys)}setServerCertificate(){throw new Error("Server certificate is not implemented in your browser")}};function ms(){return{isTypeSupported:(r,i)=>{if(Pt===void 0)throw new Error("No MSMediaKeys API.");return i!==void 0?Pt.isTypeSupported(r,i):Pt.isTypeSupported(r)},createCustomMediaKeys:r=>new Do(r),setMediaKeys:(r,i)=>{if(i===null)return Promise.resolve(void 0);if(!(i instanceof Do))throw new Error("Custom setMediaKeys is supposed to be called with IE11 custom MediaKeys.");return i._setVideo(r)}}}var Qt,{MozMediaKeys:xr}=J;xr!==void 0&&xr.prototype!==void 0&&typeof xr.isTypeSupported=="function"&&typeof xr.prototype.createSession=="function"&&(Qt=xr);function ps(){return{isTypeSupported:(r,i)=>{if(Qt===void 0)throw new Error("No MozMediaKeys API.");return i!==void 0?Qt.isTypeSupported(r,i):Qt.isTypeSupported(r)},createCustomMediaKeys:r=>{if(Qt===void 0)throw new Error("No MozMediaKeys API.");return new Qt(r)},setMediaKeys:(r,i)=>Ct(()=>{if(r.mozSetMediaKeys===void 0||typeof r.mozSetMediaKeys!="function")throw new Error("Can't set video on MozMediaKeys.");return r.mozSetMediaKeys(i)})}}var Mt=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"],Pc=[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,62,255,255,255,63,52,53,54,55,56,57,58,59,60,61,255,255,255,0,255,255,255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,255,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51];function Lo(n){if(n>=Pc.length)throw new Error("Unable to parse base64 string.");let e=Pc[n];if(e===255)throw new Error("Unable to parse base64 string.");return e}function No(n){let e="",t,r=n.length;for(t=2;t<r;t+=3)e+=Mt[n[t-2]>>2],e+=Mt[(n[t-2]&3)<<4|n[t-1]>>4],e+=Mt[(n[t-1]&15)<<2|n[t]>>6],e+=Mt[n[t]&63];return t===r+1&&(e+=Mt[n[t-2]>>2],e+=Mt[(n[t-2]&3)<<4],e+="=="),t===r&&(e+=Mt[n[t-2]>>2],e+=Mt[(n[t-2]&3)<<4|n[t-1]>>4],e+=Mt[(n[t-1]&15)<<2],e+="="),e}function pt(n){let e=n.length%4,t=n;e!==0&&(m.warn("base64ToBytes: base64 given miss padding"),t+=e===3?"=":e===2?"==":"===");let r=t.indexOf("=");if(r!==-1&&r<t.length-2)throw new Error("Unable to parse base64 string.");let i=t.endsWith("==")?2:t.endsWith("=")?1:0,o=t.length,a=new Uint8Array(o/4*3),s;for(let d=0,u=0;d<o;d+=4,u+=3)s=Lo(t.charCodeAt(d))<<18|Lo(t.charCodeAt(d+1))<<12|Lo(t.charCodeAt(d+2))<<6|Lo(t.charCodeAt(d+3)),a[u]=s>>16,a[u+1]=s>>8&255,a[u+2]=s&255;return a.subarray(0,a.length-i)}var Ac=typeof J=="object"&&typeof J.TextDecoder=="function",cg=typeof J=="object"&&typeof J.TextEncoder=="function";function Uo(n){let e=new ArrayBuffer(n.length*2),t=new Uint8Array(e);for(let r=0;r<t.length;r+=2){let i=n.charCodeAt(r/2);t[r]=i&255,t[r+1]=i>>8&255}return t}function Bo(n){if(Ac)try{return new TextDecoder("utf-16le").decode(n)}catch(t){let r=t instanceof Error?t:"";m.warn("Utils: could not use TextDecoder to parse UTF-16LE, fallbacking to another implementation",r)}let e="";for(let t=0;t<n.length;t+=2)e+=String.fromCharCode((n[t+1]<<8)+n[t]);return e}function ve(n){if(cg)try{return new TextEncoder().encode(n)}catch(i){let o=i instanceof Error?i:"";m.warn("Utils: could not use TextEncoder to encode string into UTF-8, fallbacking to another implementation",o)}let e,t=encodeURIComponent(n);if(typeof unescape=="function")e=unescape(t);else{let i=/[0-9a-fA-F]/,o=t.length;e="";for(let a=0;a<t.length;a++){let s=!1;if(t[a]==="%"){if(a<=o-6&&t[a+1]==="u"&&i.test(t[a+2])&&i.test(t[a+3])&&i.test(t[a+4])&&i.test(t[a+5])){let d=parseInt(t.substring(a+1,a+6),16);e+=String.fromCharCode(d),s=!0,a+=5}else if(a<=o-3&&i.test(t[a+1])&&i.test(t[a+2])){let d=parseInt(t.substring(a+1,a+3),16);e+=String.fromCharCode(d),s=!0,a+=2}}s||(e+=t[a])}}let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i)&255;return r}function fg(n){let t="";for(let r=0;r<n.length;r+=16e3){let i=n.subarray(r,r+16e3);t+=String.fromCharCode.apply(null,i)}return t}function Mc(n,e){let t=n.toString(16);return t.length>=e?t:new Array(e-t.length+1).join("0")+t}function Ne(n){if(Ac)try{return new TextDecoder().decode(n)}catch(i){let o=i instanceof Error?i:"";m.warn("Utils: could not use TextDecoder to parse UTF-8, fallbacking to another implementation",o)}let e=n;e[0]===239&&e[1]===187&&e[2]===191&&(e=e.subarray(3));let t=fg(e),r;if(typeof escape=="function")r=escape(t);else{let i=/[A-Za-z0-9*_\+-\.\/]/;r="";for(let o=0;o<t.length;o++)if(i.test(t[o]))r+=t[o];else{let a=t.charCodeAt(o);r+=a>=256?"%u"+Mc(a,4):"%"+Mc(a,2)}}return decodeURIComponent(r)}function je(n){let e=n.length,t=new Uint8Array(e/2);for(let r=0,i=0;r<e;r+=2,i++)t[i]=parseInt(n.substring(r,r+2),16)&255;return t}function Ue(n,e=""){let t="";for(let r=0;r<n.byteLength;r++)t+=(n[r]>>>4).toString(16),t+=(n[r]&15).toString(16),e.length>0&&r<n.byteLength-1&&(t+=e);return t}function Fo(n){ee(n.length===16,"GUID length should be 16");let e=n[0],t=n[1],r=n[2],i=n[3],o=n[4],a=n[5],s=n[6],d=n[7],u=new Uint8Array(16);return u[0]=i,u[1]=r,u[2]=t,u[3]=e,u[4]=a,u[5]=o,u[6]=d,u[7]=s,u.set(n.subarray(8,16),8),u}function gs(n,e){let t=e;for(;t<n.length&&n[t]!==0;)t+=1;let r=n.subarray(e,t);return{end:t+1,string:Ne(r)}}function ys(n){return typeof(n==null?void 0:n.webkitGenerateKeyRequest)=="function"}var hs=class extends re{constructor(e,t){super(),this._vid=e,this._key=t,this.sessionId="",this._closeSession=X,this.keyStatuses=new Map,this.expiration=NaN;let r=i=>{this.trigger(i.type,i)};this.closed=new Promise(i=>{this._closeSession=()=>{["keymessage","message","keyadded","ready","keyerror","error"].forEach(o=>{e.removeEventListener(o,r),e.removeEventListener(`webkit${o}`,r)}),i()}}),["keymessage","message","keyadded","ready","keyerror","error"].forEach(i=>{e.addEventListener(i,r),e.addEventListener(`webkit${i}`,r)})}update(e){return new Promise((t,r)=>{try{if(this._key.indexOf("clearkey")>=0){let i=e instanceof ArrayBuffer?new Uint8Array(e):e,o=JSON.parse(Ne(i)),a=pt(o.keys[0].k),s=pt(o.keys[0].kid);t(this._vid.webkitAddKey(this._key,a,s,""))}else t(this._vid.webkitAddKey(this._key,e,null,""))}catch(i){r(i)}})}generateRequest(e,t){return new Promise(r=>{this._vid.webkitGenerateKeyRequest(this._key,t),r()})}close(){return new Promise(e=>{this._closeSession(),e()})}load(){return Promise.resolve(!1)}remove(){return Promise.resolve()}},Ko=class{constructor(e){this._keySystem=e}_setVideo(e){return Ct(()=>{if(!ys(e))throw new Error("Video not attached to the MediaKeys");this._videoElement=e})}createSession(){if(E(this._videoElement))throw new Error("Video not attached to the MediaKeys");return new hs(this._videoElement,this._keySystem)}setServerCertificate(){throw new Error("Server certificate is not implemented in your browser")}};function Is(){return{isTypeSupported:function(r){let i=document.querySelector("video");return E(i)&&(i=document.createElement("video")),!E(i)&&typeof i.canPlayType=="function"?!!i.canPlayType("video/mp4",r):!1},createCustomMediaKeys:r=>new Ko(r),setMediaKeys:(r,i)=>{if(i===null)return Promise.resolve(void 0);if(!(i instanceof Ko))throw new Error("Custom setMediaKeys is supposed to be called with old webkit custom MediaKeys.");return i._setVideo(r)}}}function ie(...n){let e=n.length,t=-1,r=0,i;for(;++t<e;)i=n[t],r+=typeof i=="number"?i:i.length;let o=new Uint8Array(r),a=0;for(t=-1;++t<e;)i=n[t],typeof i=="number"?a+=i:i.length>0&&(o.set(i,a),a+=i.length);return o}function Vo(n,e){return(n[e+0]<<8)+(n[e+1]<<0)}function bs(n,e){return n[e+0]*65536+n[e+1]*256+n[e+2]}function ne(n,e){return n[e+0]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3]}function Ke(n,e){return(n[e+0]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3])*4294967296+n[e+4]*16777216+n[e+5]*65536+n[e+6]*256+n[e+7]}function fe(n){return new Uint8Array([n>>>8&255,n&255])}function Ie(n){return new Uint8Array([n>>>24&255,n>>>16&255,n>>>8&255,n&255])}function Xt(n){let e=n%4294967296,t=(n-e)/4294967296;return new Uint8Array([t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255])}function xc(n,e){return(n[e+0]<<0)+(n[e+1]<<8)}function wc(n,e){return n[e+0]+n[e+1]*256+n[e+2]*65536+n[e+3]*16777216}function Oc(n){return new Uint8Array([n&255,n>>>8&255])}function wr(n){return new Uint8Array([n&255,n>>>8&255,n>>>16&255,n>>>24&255])}function Ss(n,e){let t=n instanceof Uint8Array?n:new Uint8Array(n),r=e instanceof Uint8Array?e:new Uint8Array(e);if(wc(t,0)+4!==t.length)throw new Error("Unsupported WebKit initData.");let o=Bo(t),a=o.indexOf("skd://"),s=a>-1?o.substring(a+6):o,d=Uo(s),u=0,l=new Uint8Array(t.byteLength+4+d.byteLength+4+r.byteLength);return l.set(t),u+=t.length,l.set(wr(d.byteLength),u),u+=4,l.set(d,u),u+=d.byteLength,l.set(wr(r.byteLength),u),u+=4,l.set(r,u),l}function mg(n){return Ze(n,"com.apple.fps")}function Dc(n,e){return Ct(()=>{if(n.webkitSetMediaKeys===void 0)throw new Error("No webKitMediaKeys API.");n.webkitSetMediaKeys(e)})}var Ts=class extends re{constructor(e,t,r){super(),this._serverCertificate=r,this._videoElement=e,this._keyType=t,this._unbindSession=X,this._closeSession=X,this.closed=new Promise(i=>{this._closeSession=i}),this.keyStatuses=new Map,this.expiration=NaN}update(e){return new Promise((t,r)=>{if(this._nativeSession===void 0||this._nativeSession.update===void 0||typeof this._nativeSession.update!="function")return r("Unavailable WebKit key session.");try{let i;e instanceof ArrayBuffer?i=new Uint8Array(e):e instanceof Uint8Array?i=e:i=new Uint8Array(e.buffer),t(this._nativeSession.update(i))}catch(i){r(i)}})}generateRequest(e,t){return new Promise(r=>{var s;let i=this._videoElement;if(((s=i.webkitKeys)==null?void 0:s.createSession)===void 0)throw new Error("No WebKitMediaKeys API.");let o;if(mg(this._keyType)){if(this._serverCertificate===void 0)throw new Error("A server certificate is needed for creating fairplay session.");o=Ss(t,this._serverCertificate)}else o=t;let a=i.webkitKeys.createSession("video/mp4",o);if(a==null)throw new Error("Impossible to get the key sessions");this._listenEvent(a),this._nativeSession=a,r()})}close(){return new Promise((e,t)=>{if(this._unbindSession(),this._closeSession(),this._nativeSession===void 0){t("No session to close.");return}this._nativeSession.close(),e()})}load(){return Promise.resolve(!1)}remove(){return Promise.resolve()}get sessionId(){var e,t;return(t=(e=this._nativeSession)==null?void 0:e.sessionId)!=null?t:""}_listenEvent(e){this._unbindSession();let t=r=>{this.trigger(r.type,r)};["keymessage","message","keyadded","ready","keyerror","error"].forEach(r=>{e.addEventListener(r,t),e.addEventListener(`webkit${r}`,t)}),this._unbindSession=()=>{["keymessage","message","keyadded","ready","keyerror","error"].forEach(r=>{e.removeEventListener(r,t),e.removeEventListener(`webkit${r}`,t)})}}},zo=class{constructor(e){if(mt===void 0)throw new Error("No WebKitMediaKeys API.");this._keyType=e,this._mediaKeys=new mt(e)}_setVideo(e){if(this._videoElement=e,this._videoElement===void 0)throw new Error("Video not attached to the MediaKeys");return Dc(this._videoElement,this._mediaKeys)}createSession(){if(this._videoElement===void 0||this._mediaKeys===void 0)throw new Error("Video not attached to the MediaKeys");return new Ts(this._videoElement,this._keyType,this._serverCertificate)}setServerCertificate(e){return this._serverCertificate=e,Promise.resolve()}};function Ho(){if(mt===void 0)throw new Error("No WebKitMediaKeys API.");return{isTypeSupported:mt.isTypeSupported,createCustomMediaKeys:r=>new zo(r),setMediaKeys:(r,i)=>{if(i===null)return Dc(r,i);if(!(i instanceof zo))throw new Error("Custom setMediaKeys is supposed to be called with webkit custom MediaKeys.");return i._setVideo(r)}}}var pg=gg("auto"),Nc=pg;function gg(n){var o;let e,t,r=hg,i;if((n==="standard"||n==="auto"&&!cs())&&(Ht||!E(navigator.requestMediaKeySystemAccess)))e=(...a)=>navigator.requestMediaKeySystemAccess(...a),t=_e(["encrypted"]),i="standard";else{let a,s;if(n==="webkit"&&mt!==void 0){let d=Ho();t=Lc(),a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="webkit"}else if(ys((o=J.HTMLVideoElement)==null?void 0:o.prototype)){t=_e(["needkey"]);let d=Is();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="older-webkit"}else if(mt!==void 0){t=Lc();let d=Ho();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="webkit"}else if(un&&Pt!==void 0){t=_e(["encrypted","needkey"]);let d=ms();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="ms"}else if(Qt!==void 0){t=_e(["encrypted","needkey"]);let d=ps();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="moz"}else{t=_e(["encrypted","needkey"]);let d=J.MediaKeys,u=()=>{if(d===void 0)throw new te("MEDIA_KEYS_NOT_SUPPORTED","No `MediaKeys` implementation found in the current browser.");if(typeof d.isTypeSupported=="undefined"){let l="This browser seems to be unable to play encrypted contents currently.Note: Some browsers do not allow decryption in some situations, like when not using HTTPS.";throw new Error(l)}};a=l=>(u(),ee(typeof d.isTypeSupported=="function"),d.isTypeSupported(l)),s=l=>(u(),new d(l)),i="unknown"}e=function(d,u){if(!a(d))return Promise.reject(new Error("Unsupported key type"));for(let l=0;l<u.length;l++){let c=u[l],{videoCapabilities:f,audioCapabilities:g,initDataTypes:p,distinctiveIdentifier:I}=c,y=!0;if(y=y&&(E(p)||p.some(b=>b==="cenc")),y=y&&I!=="required",y){let b={initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",persistentState:"required",sessionTypes:["temporary","persistent-license"]};f!==void 0&&(b.videoCapabilities=f),g!==void 0&&(b.audioCapabilities=g);let T=s(d);return Promise.resolve(new Mr(d,T,b))}}return Promise.reject(new Error("Unsupported configuration"))}}return{requestMediaKeySystemAccess:e,onEncrypted:t,setMediaKeys:r,implementation:i}}function Lc(){let n=_e(["needkey"],void 0);return(t,r,i)=>{n(t,o=>{let a=G(o,{forceSessionRecreation:!0});r(a)},i)}}function hg(n,e){try{let t;return typeof n.setMediaKeys=="function"?t=n.setMediaKeys(e):typeof n.webkitSetMediaKeys=="function"?t=n.webkitSetMediaKeys(e):typeof n.mozSetMediaKeys=="function"?t=n.mozSetMediaKeys(e):typeof n.msSetMediaKeys=="function"&&e!==null&&(t=n.msSetMediaKeys(e)),typeof t=="object"&&t!==null&&typeof t.then=="function"?t:Promise.resolve(t)}catch(t){return Promise.reject(t)}}function Tt(n,e){let t=n.length,r=0;for(;r+8<=t;){let i=ne(n,r);if(i===0)i=t-r;else if(i===1){if(r+16>t)return-1;i=Ke(n,r+8)}if(isNaN(i)||i<=0)return-1;if(ne(n,r+4)===e)return r+i<=t?r:-1;r+=i}return-1}function Wo(n){let e=0,t=[],r=null;for(;e<=n.length;){if(e===n.length){r=null;break}r=n.subarray(e,1/0);let i=Tt(r,1836019558);if(i<0)break;let o=ne(n,i+e),a=e+i+o;if(a>n.length)break;let s=Tt(r,1835295092);if(s<0)break;let d=ne(n,s+e),u=e+s+d;if(u>n.length)break;let l=Math.max(a,u),c=n.subarray(e,l);t.push(c),e=l}return t.length===0?[null,r]:[t,r]}function yg(n,e,t){return new Uint8Array(Array.prototype.slice.call(n,e,t))}function Ig(n,e,t){return n.slice(e,t)}var _s=typeof Uint8Array.prototype.slice=="function"?Ig:yg;function Es(n,e){let t=n;for(let r of e){let i=Re(t,r);if(i===null)return null;t=i}return t}function Re(n,e){let t=Ve(n,e);return t!==null?n.subarray(t[1],t[2]):null}function Uc(n,e){let t=[],r=n;for(;;){let i=Ve(r,e);if(i===null)return t;ee(i[2]!==0&&r.length!==0),t.push(r.subarray(i[1],i[2])),r=r.subarray(i[2])}}function vs(n,e){let t=Ve(n,e);return t!==null?n.subarray(t[0],t[2]):null}function Ve(n,e){let t=n.length,r=0,i,o=0,a;for(;r+8<=t;){if(a=r,o=ne(n,a),a+=4,i=ne(n,a),a+=4,o===0)o=t-r;else if(o===1){if(a+8>t)return null;o=Ke(n,a),a+=8}if(o<0)throw new Error("ISOBMFF: Size out of range");if(i===e)return e===1970628964&&(a+=16),[r,a,r+o];r+=o}return null}function Sn(n,e,t,r,i){let o=n.length,a;for(let s=0;s<o;s+=a){let d=s;a=ne(n,d),d+=4;let u=ne(n,d);if(d+=4,a===0)a=o-s;else if(a===1){if(d+8>o)return;a=Ke(n,d),d+=8}if(u===1970628964&&d+16<=o&&ne(n,d)===e&&ne(n,d+4)===t&&ne(n,d+8)===r&&ne(n,d+12)===i)return d+=16,n.subarray(d,s+a)}}function Rs(n){let e=n.length;if(e<8)return m.warn("ISOBMFF: box inferior to 8 bytes, cannot find offsets"),null;let t=0,r=ne(n,t);t+=4;let i=ne(n,t);if(t+=4,r===0)r=e;else if(r===1){if(t+8>e)return m.warn("ISOBMFF: box too short, cannot find offsets"),null;r=Ke(n,t),t+=8}if(r<0)throw new Error("ISOBMFF: Size out of range");return i===1970628964&&(t+=16),[0,t,r]}function Go(n){let e=0,t=Re(n,1836019574);if(t===null)return[];let r=[];for(;e<t.length;){let i;try{i=Ve(t,1886614376)}catch(s){let d=s instanceof Error?s:"";return m.warn("Error while removing PSSH from ISOBMFF",d),r}if(i===null)return r;let o=_s(t,i[0],i[2]),a=qo(o,i[1]-i[0]);a!==void 0&&r.push({systemId:a,data:o}),t[i[0]+4]=102,t[i[0]+5]=114,t[i[0]+6]=101,t[i[0]+7]=101,e=i[2]}return r}function qo(n,e){if(n[e]>1){m.warn("ISOBMFF: un-handled PSSH version");return}let t=e+4;if(t+16>n.length)return;let r=_s(n,t,t+16);return Ue(r)}var Or=Math.pow(2,32)-1;var ks={};function Bc(n){if(ks[n]!==void 0)return ks[n];let e=ve(n);return ks[n]=e,e}function le(n,e){let t=e.length+8;return t<=Or?ie(Ie(t),Bc(n),e):ie(Ie(1),Bc(n),Xt(t+8),e)}function Ae(n,e){return le(n,ie(...e))}function Dr(n){let e=Re(n,1836019558);return e===null?null:Re(e,1953653094)}function Fc(n){return Uc(n,1836019558).reduce((t,r)=>{let i=Re(r,1953653094);return i!==null&&t.push(i),t},[])}function Lr(n){return Re(n,1835295092)}function Cs(n){let e=Re(n,1836019574);if(e===null)return null;let t=Re(e,1953653099);return t===null?null:Re(t,1835297121)}function Kc(n,e=0){return Re(n.subarray(e),1701671783)}function Nr(n){let e=xc(n,8),t=Bo(n.subarray(10,e+10)),i=new DOMParser().parseFromString(t,"application/xml").querySelector("KID");if(i===null)throw new Error("Cannot parse PlayReady private data: invalid XML");let o=i.textContent===null?"":i.textContent,a=Fo(pt(o));return Ue(a).toLowerCase()}function Ur(n,e){let t=Ve(n,1936286840);if(t===null)return null;let r=e,i=t[2]-t[0],o=t[1],a=n[o];o+=8;let s=ne(n,o);o+=4;let d;if(a===0)d=ne(n,o),o+=4,r+=ne(n,o)+i,o+=4;else if(a===1)d=Ke(n,o),o+=8,r+=Ke(n,o)+i,o+=8;else return null;let u=[];o+=2;let l=Vo(n,o);for(o+=2;--l>=0;){let c=ne(n,o);o+=4;let f=(c&2147483648)>>>31,g=c&2147483647;if(f===1)throw new Error("sidx with reference_type `1` not yet implemented");let p=ne(n,o);o+=4,o+=4,u.push({time:d,duration:p,timescale:s,range:[r,r+g-1]}),d+=p,r+=g}return u}function Ps(n){let e=Dr(n);if(e===null)return;let t=Re(e,1952867444);if(t===null)return;let r=t[0];if(r===1)return Ke(t,4);if(r===0)return ne(t,4)}function bg(n){let e=Re(n,1952868452);if(e===null)return;let t=1,r=bs(e,t);t+=3;let i=(r&1)>0,o=(r&2)>0;return(r&8)>0?(t+=4,i&&(t+=8),o&&(t+=4),ne(e,t)):void 0}function Br(n){let e=Fc(n);if(e.length===0)return;let t=0;for(let r of e){let i=Re(r,1953658222);if(i===null)return;let o=0,a=i[o];if(o+=1,a>1)return;let s=bs(i,o);o+=3;let d=(s&256)>0,u=0;if(!d&&(u=bg(r),u===void 0))return;let l=(s&1)>0,c=(s&4)>0,f=(s&512)>0,g=(s&1024)>0,p=(s&2048)>0,I=ne(i,o);o+=4,l&&(o+=4),c&&(o+=4);let y=I,b=0;for(;y-- >0;)d?(b+=ne(i,o),o+=4):b+=u,f&&(o+=4),g&&(o+=4),p&&(o+=4);t+=b}return t}function Fr(n){let e=Cs(n);if(e===null)return;let t=Re(e,1835296868);if(t===null)return;let r=0,i=t[r];if(r+=4,i===1)return ne(t,r+16);if(i===0)return ne(t,r+8)}function Ms(n){let e=n.length;if(e<4)throw new Error("Cannot update box length: box too short");let t=ne(n,0);if(t===0)if(e>Or){let r=new Uint8Array(e+8);return r.set(Ie(1),0),r.set(n.subarray(4,8),4),r.set(Xt(e+8),8),r.set(n.subarray(8,e),16),r}else return n.set(Ie(e),0),n;else if(t===1){if(e<16)throw new Error("Cannot update box length: box too short");return n.set(Xt(e),8),n}else{if(e<=Or)return n.set(Ie(e),0),n;{let r=new Uint8Array(e+8);return r.set(Ie(1),0),r.set(n.subarray(4,8),4),r.set(Xt(e+8),8),r.set(n.subarray(8,e),16),r}}}function Vc(n){let e=[],t=0;for(;t<n.length;){let r=Kc(n,t);if(r===null)break;let i=r.length;t+=i;let o=r[0];if(o!==0)m.warn("ISOBMFF: EMSG version "+o.toString()+" not supported.");else{let a=4,{end:s,string:d}=gs(r,a);a=s;let{end:u,string:l}=gs(r,a);a=u;let c=ne(r,a);a+=4;let f=ne(r,a);a+=4;let g=ne(r,a);a+=4;let p=ne(r,a);a+=4;let I=r.subarray(a,i),y={schemeIdUri:d,value:l,timescale:c,presentationTimeDelta:f,eventDuration:g,id:p,messageData:I};e.push(y)}}if(e.length!==0)return e}function zc(n){let e=Es(n,[1836019574,1953653099,1835297121,1835626086,1937007212,1937011556]);if(e===null)return null;let t=e.subarray(8),r=Re(t,1701733238),i=0;if(r===null?(i=28,r=Re(t,1701733217)):i=78,r===null)return null;let o=Es(r.subarray(i),[1936289382,1935894633,1952804451]);if(o===null||o.byteLength<24)return null;let a=o.subarray(8,24);return a.every(s=>s===0)?null:a}var jo=ne(ve("pssh"),0);function Sg(n){m.info("Compat: Trying to move CENC PSSH from init data at the end of it.");let e=!1,t=new Uint8Array,r=new Uint8Array,i=0;for(;i<n.length;){if(n.length<i+8||ne(n,i+4)!==jo)throw m.warn("Compat: unrecognized initialization data. Cannot patch it."),new Error("Compat: unrecognized initialization data. Cannot patch it.");let o=ne(new Uint8Array(n),i);if(i+o>n.length)throw m.warn("Compat: unrecognized initialization data. Cannot patch it."),new Error("Compat: unrecognized initialization data. Cannot patch it.");let a=n.subarray(i,i+o);if(n[i+12]===16&&n[i+13]===119&&n[i+14]===239&&n[i+15]===236&&n[i+16]===192&&n[i+17]===178&&n[i+18]===77&&n[i+19]===2&&n[i+20]===172&&n[i+21]===227&&n[i+22]===60&&n[i+23]===30&&n[i+24]===82&&n[i+25]===226&&n[i+26]===251&&n[i+27]===75){let s=Rs(a),d=s===null?void 0:a[s[1]];m.info("Compat: CENC PSSH found with version",d),d===void 0?m.warn("Compat: could not read version of CENC PSSH"):e===(d===1)?t=ie(t,a):d===1?(m.warn("Compat: cenc version 1 encountered, removing every other cenc pssh box."),t=a,e=!0):m.warn("Compat: filtering out cenc pssh box with wrong version",d)}else r=ie(r,a);i+=o}if(i!==n.length)throw m.warn("Compat: unrecognized initialization data. Cannot patch it."),new Error("Compat: unrecognized initialization data. Cannot patch it.");return ie(r,t)}function Kr(n,e,t){m.debug("Compat: Calling generateRequest on the MediaKeySession");let r;try{r=Sg(t)}catch(o){r=t}let i=e!=null?e:"";return n.generateRequest(i,r).catch(o=>{if(i!==""||!(o instanceof TypeError))throw o;return m.warn('Compat: error while calling `generateRequest` with an empty initialization data type. Retrying with a default "cenc" value.',o),n.generateRequest("cenc",r)})}function Tg(n){let e=[],t=0;for(;t<n.length;){if(n.length<t+8||ne(n,t+4)!==jo)return m.warn("Compat: Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}];let r=ne(new Uint8Array(n),t);if(t+r>n.length)return m.warn("Compat: Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}];let i=n.subarray(t,t+r),a={systemId:qo(i,8),data:i};_g(e,a)?m.warn("Compat: Duplicated PSSH found in initialization data, removing it."):e.push(a),t+=r}return t!==n.length?(m.warn("Compat: Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}]):e}function _g(n,e){for(let t=0;t<n.length;t++){let r=n[t];if((e.systemId===void 0||r.systemId===void 0||e.systemId===r.systemId)&&ge(e.data,r.data))return!0}return!1}function Yo(n){let{initData:e,initDataType:t,forceSessionRecreation:r}=n;if(E(e))return m.warn("Compat: No init data found on media encrypted event."),null;let i=new Uint8Array(e),o=Tg(i);return{type:t,values:o,forceSessionRecreation:r}}var Eg=100;async function Vr(n,e){m.info("DRM: Load persisted session",e);let t=await n.load(e);return!t||n.keyStatuses.size>0?t:new Promise(r=>{n.addEventListener("keystatuseschange",o);let i=setTimeout(o,Eg);function o(){a(),r(t)}function a(){clearTimeout(i),n.removeEventListener("keystatuseschange",o)}})}var Zt=Nc;function Q(n,e,t){if(typeof Array.prototype.includes=="function")return n.includes(e,t);let r=n.length>>>0;if(r===0)return!1;let i=t|0,o=i>=0?Math.min(i,r-1):Math.max(r+i,0),a=(s,d)=>s===d||typeof s=="number"&&typeof d=="number"&&isNaN(s)&&isNaN(d);for(;o<r;){if(a(n[o],e))return!0;o++}return!1}function zr(n){if(n.sessionId==="")return!1;let e=n.keyStatuses,t=[];return e.forEach(r=>{t.push(r)}),t.length<=0?(m.debug("DRM: isSessionUsable: MediaKeySession given has an empty keyStatuses",n.sessionId),!1):Q(t,"expired")?(m.debug("DRM: isSessionUsable: MediaKeySession given has an expired key",n.sessionId),!1):Q(t,"internal-error")?(m.debug("DRM: isSessionUsable: MediaKeySession given has a key with an internal-error",n.sessionId),!1):(m.debug("DRM: isSessionUsable: MediaKeySession is usable",n.sessionId),!0)}function As(n,e,t,r){let{loadedSessionsStore:i,persistentSessionsStore:o}=n;return t==="temporary"?Hc(i,e):o===null?(m.warn("DRM: Cannot create persistent MediaKeySession, PersistentSessionsStore not created."),Hc(i,e)):vg(i,o,e,r)}function Hc(n,e){m.info("DRM: Creating a new temporary session");let t=n.createSession(e,"temporary");return Promise.resolve({type:"created-session",value:t})}async function vg(n,e,t,r){if(r.cancellationError!==null)throw r.cancellationError;m.info("DRM: Creating persistent MediaKeySession");let i=n.createSession(t,"persistent-license"),o=e.getAndReuse(t);if(o===null)return{type:"created-session",value:i};try{let s=await n.loadPersistentSession(i.mediaKeySession,o.sessionId);if(!s){m.warn("DRM: No data stored for the loaded session"),e.delete(o.sessionId),n.removeSessionWithoutClosingIt(i.mediaKeySession);let d=n.createSession(t,"persistent-license");return{type:"created-session",value:d}}return s&&zr(i.mediaKeySession)?(e.add(t,t.keyIds,i.mediaKeySession),m.info("DRM: Succeeded to load persistent session."),{type:"loaded-persistent-session",value:i}):(m.warn("DRM: Previous persistent session not usable anymore."),a())}catch(s){return m.warn("DRM: Unable to load persistent session: "+(s instanceof Error?s.toString():"Unknown Error")),a()}async function a(){if(r.cancellationError!==null)throw r.cancellationError;m.info("DRM: Removing previous persistent session.");let s=e.get(t);s!==null&&e.delete(s.sessionId);try{await n.closeSession(i.mediaKeySession)}catch(u){if(i.mediaKeySession.sessionId!=="")throw u;n.removeSessionWithoutClosingIt(i.mediaKeySession)}if(r.cancellationError!==null)throw r.cancellationError;let d=n.createSession(t,"persistent-license");return{type:"created-session",value:d}}}async function xs(n,e){if(e<0||e>=n.getLength())return;m.info("DRM: LSS cache limit exceeded",e,n.getLength());let t=[],r=n.getAll().slice(),i=r.length-e;for(let o=0;o<i;o++){let a=r[o];t.push(n.closeSession(a.mediaKeySession))}await Promise.all(t)}async function ws(n,e,t,r,i){let o=null,{loadedSessionsStore:a,persistentSessionsStore:s}=e,d=a.reuse(n);if(d!==null){if(o=d.mediaKeySession,zr(o))return m.info("DRM: Reuse loaded session",o.sessionId),{type:"loaded-open-session",value:{mediaKeySession:o,sessionType:d.sessionType,keySessionRecord:d.keySessionRecord}};s!==null&&d.mediaKeySession.sessionId!==""&&s.delete(d.mediaKeySession.sessionId)}if(o!==null&&(await a.closeSession(o),i.cancellationError!==null)||(await xs(a,r<=0?r:r-1),i.cancellationError!==null))throw i.cancellationError;let u=await As(e,n,t,i);return{type:u.type,value:{mediaKeySession:u.value.mediaKeySession,sessionType:u.value.sessionType,keySessionRecord:u.value.keySessionRecord}}}function Os(){return!cr&&!za&&!Va&&!Wa}function Wc(n){return!(ur&&n.indexOf("playready")!==-1)}var Gc='<WRMHEADER xmlns="http://schemas.microsoft.com/DRM/2007/03/PlayReadyHeader" version="4.0.0.0"><DATA><PROTECTINFO><KEYLEN>16</KEYLEN><ALGID>AESCTR</ALGID></PROTECTINFO><KID>ckB07BNLskeUq0qd83fTbA==</KID><DS_ID>yYIPDBca1kmMfL60IsfgAQ==</DS_ID><CUSTOMATTRIBUTES xmlns=""><encryptionref>312_4024_2018127108</encryptionref></CUSTOMATTRIBUTES><CHECKSUM>U/tsUYRgMzw=</CHECKSUM></DATA></WRMHEADER>';function qc(n){let e=Uo(n),t=Oc(e.length),r=new Uint8Array([1,0]),i=new Uint8Array([1,0]),o=wr(e.length+6),a=ie(o,i,r,t,e),s=je("9a04f07998404286ab92e65be0885f95");return Rg(a,s)}function Rg(n,e){let t=ve("pssh"),r=new Uint8Array([0,0,0,0]),i=Ie(n.length),o=Ie(32+n.length);return ie(o,t,r,e,i,n)}function Ds(){return un}function kg(n,e){let{mimeType:t,codecs:r}=$o(n),{mimeType:i,codecs:o}=$o(e);if(t!==i||r===""||o==="")return!1;let a=r.split(".")[0];a=a==="hev1"?"hvc1":a;let s=o.split(".")[0];return s=s==="hev1"?"hvc1":s,a===s}var Cg=7;function $o(n){var i;let[e,...t]=n.split(";"),r=(i=Z(t,o=>Ze(o,"codecs=")))!=null?i:"";return r=r.substring(Cg),r[0]==='"'&&(r=r.substring(1,r.length-2)),{mimeType:e,codecs:r}}var Qo=kg;function Bn(n,e){return typeof Array.prototype.flatMap=="function"?n.flatMap(e):n.reduce((t,r)=>{let i=e(r);return Array.isArray(i)?(t.push(...i),t):(t.push(i),t)},[])}function Pg(n,e){var l,c,f,g,p,I,y,b,T,v;if(n.label!==e.label)return!1;let t=(l=e.distinctiveIdentifier)!=null?l:"optional",r=(c=n.distinctiveIdentifier)!=null?c:"optional";if(t!==r)return!1;let i=(f=e.persistentState)!=null?f:"optional",o=(g=n.persistentState)!=null?g:"optional";if(i!==o)return!1;let a=(p=e.initDataTypes)!=null?p:[],s=(I=n.initDataTypes)!=null?I:[];if(!Yc(s,a))return!1;let d=(y=e.sessionTypes)!=null?y:[],u=(b=n.sessionTypes)!=null?b:[];if(!Yc(u,d))return!1;for(let _ of["audioCapabilities","videoCapabilities"]){let R=(T=n[_])!=null?T:[],k=(v=e[_])!=null?v:[];if(!R.every(M=>{var P,N,O,F,A,C;for(let D=0;D<k.length;D++){let L=k[D];if(((P=L.robustness)!=null?P:"")===((N=M.robustness)!=null?N:"")||((O=L.encryptionScheme)!=null?O:null)===((F=M.encryptionScheme)!=null?F:null)||((A=L.robustness)!=null?A:"")===((C=M.robustness)!=null?C:""))return!0}return!1}))return!1}return!0}function Mg(n){let{EME_KEY_SYSTEMS:e}=U.getCurrent();for(let t of Object.keys(e))if(Q(e[t],n))return t}function Ag(n){let{keyName:e,keyType:t,keySystemOptions:r}=n,i,o="optional",a="optional";Array.isArray(r.wantedSessionTypes)?(i=r.wantedSessionTypes,Q(r.wantedSessionTypes,"persistent-license")&&!E(r.persistentLicenseConfig)&&(o="required")):E(r.persistentLicenseConfig)?i=["temporary"]:(o="required",i=["persistent-license"]),E(r.persistentState)||(o=r.persistentState),E(r.distinctiveIdentifier)||(a=r.distinctiveIdentifier);let{EME_DEFAULT_AUDIO_CODECS:s,EME_DEFAULT_VIDEO_CODECS:d,EME_DEFAULT_WIDEVINE_ROBUSTNESSES:u,EME_DEFAULT_PLAYREADY_RECOMMENDATION_ROBUSTNESSES:l}=U.getCurrent(),c,f,{audioCapabilitiesConfig:g,videoCapabilitiesConfig:p}=r;if((g==null?void 0:g.type)==="full")c=g.value;else{let y;(g==null?void 0:g.type)==="robustness"?y=g.value:e==="widevine"?y=u:t==="com.microsoft.playready.recommendation"?y=l:y=[],y.length===0&&y.push(void 0);let b=(g==null?void 0:g.type)==="contentType"?g.value:s;c=Bn(y,T=>b.map(v=>T!==void 0?{contentType:v,robustness:T}:{contentType:v}))}if((p==null?void 0:p.type)==="full")f=p.value;else{let y;(p==null?void 0:p.type)==="robustness"?y=p.value:e==="widevine"?y=u:t==="com.microsoft.playready.recommendation"?y=l:y=[],y.length===0&&y.push(void 0);let b=(p==null?void 0:p.type)==="contentType"?p.value:d;f=Bn(y,T=>b.map(v=>T!==void 0?{contentType:v,robustness:T}:{contentType:v}))}let I={initDataTypes:["cenc"],videoCapabilities:f,audioCapabilities:c,distinctiveIdentifier:a,persistentState:o,sessionTypes:i};return g!==void 0?p!==void 0?[I]:[I,ue(oe({},I),{videoCapabilities:void 0})]:p!==void 0?[I,ue(oe({},I),{audioCapabilities:void 0})]:[I,ue(oe({},I),{audioCapabilities:void 0,videoCapabilities:void 0})]}function jc(n,e){var u,l,c,f,g,p;let t=(l=(u=n.audioCapabilities)==null?void 0:u.map(I=>I.contentType))!=null?l:[],r=(f=(c=n.videoCapabilities)==null?void 0:c.map(I=>I.contentType))!=null?f:[],i=t.concat(r).filter(I=>I!==void 0),o=(g=e.videoCapabilities)==null?void 0:g.map(I=>I.contentType),a=(p=e.audioCapabilities)==null?void 0:p.map(I=>I.contentType),s=[...o!=null?o:[],...a!=null?a:[]].filter(I=>I!==void 0);return s.length===0?[]:i.map(I=>{let{codecs:y,mimeType:b}=$o(I),T=Q(s,I);return{codec:y,mimeType:b,result:T}})}function Ls(n,e,t){m.info("DRM: Searching for compatible MediaKeySystemAccess");let r=e.reduce((o,a)=>{let{EME_KEY_SYSTEMS:s}=U.getCurrent(),d=s[a.type],u;if(!E(d))u=d.map(l=>({keyName:a.type,keyType:l,keySystemOptions:a}));else{let l=Mg(a.type),c=a.type;u=[{keyName:l,keyType:c,keySystemOptions:a}]}return o.concat(u)},[]);return i(0);async function i(o){if(o>=r.length)throw new pe("INCOMPATIBLE_KEYSYSTEMS","No key system compatible with your wanted configuration has been found in the current browser.");if(E(Zt.requestMediaKeySystemAccess))throw new Error("requestMediaKeySystemAccess is not implemented in your browser.");let a=r[o],{keyType:s,keySystemOptions:d}=a,u=Ag(a);m.debug(`DRM: Request keysystem access ${s},${o+1} of ${r.length}`);let l,c=await qe.getAttachedMediaKeysState(n);for(let f=0;f<u.length;f++){let g=u[f];if(c!==null&&!Ds()&&s===c.mediaKeySystemAccess.keySystem&&Zt.implementation===c.emeImplementation.implementation&&Pg(g,c.askedConfiguration))return m.info("DRM: Found cached compatible keySystem"),Promise.resolve({type:"reuse-media-key-system-access",value:{mediaKeySystemAccess:c.mediaKeySystemAccess,askedConfiguration:c.askedConfiguration,options:d,codecSupport:jc(c.askedConfiguration,c.mediaKeySystemAccess.getConfiguration())}});try{return l=await xg(s,[g]),m.info("DRM: Found compatible keysystem",s,o+1),{type:"create-media-key-system-access",value:{options:d,mediaKeySystemAccess:l,askedConfiguration:g,codecSupport:jc(g,l.getConfiguration())}}}catch(p){if(m.debug("DRM: Rejected access to keysystem",s,o+1,f),t.cancellationError!==null)throw t.cancellationError}}return i(o+1)}}async function xg(n,e){let t=await Zt.requestMediaKeySystemAccess(n,e);if(!Wc(n))try{let i=(await t.createMediaKeys()).createSession(),o=qc(Gc);await i.generateRequest("cenc",o),i.close().catch(()=>{m.warn("DRM: Failed to close the dummy session")})}catch(r){throw m.debug("DRM: KeySystemAccess was granted but it is not usable"),r}return t}function Yc(n,e){for(let t=0;t<n.length;t++)if(!Q(e,n[t]))return!1;return!0}function Fn(n,e){for(let t of n)if(!e.some(i=>ge(i,t)))return!1;return!0}function $c(n,e){for(let t of n)if(e.some(i=>ge(i,t)))return!0;return!1}var Hr=class{constructor(e){this._initializationData=e,this._keyIds=null}associateKeyIds(e){this._keyIds===null&&(this._keyIds=[]);let t=Array.from(e);for(let r of t)this.isAssociatedWithKeyId(r)||this._keyIds.push(r)}isAssociatedWithKeyId(e){if(this._keyIds===null)return!1;for(let t of this._keyIds)if(ge(t,e))return!0;return!1}getAssociatedKeyIds(){return this._keyIds===null?[]:this._keyIds}isCompatibleWith(e){let{keyIds:t}=e;if(t!==void 0&&t.length>0){if(this._keyIds!==null&&Fn(t,this._keyIds))return!0;if(this._initializationData.keyIds!==void 0)return Fn(t,this._initializationData.keyIds)}return this._checkInitializationDataCompatibility(e)}_checkInitializationDataCompatibility(e){return e.keyIds!==void 0&&e.keyIds.length>0&&this._initializationData.keyIds!==void 0?Fn(e.keyIds,this._initializationData.keyIds):this._initializationData.type!==e.type?!1:this._initializationData.values.isCompatibleWith(e.values)}};var Wr=class{constructor(e){this._mediaKeys=e,this._storage=[]}createSession(e,t){let r=new Hr(e);m.debug("DRM-LSS: calling `createSession`",t);let i=this._mediaKeys.createSession(t),o={mediaKeySession:i,sessionType:t,keySessionRecord:r,isGeneratingRequest:!1,isLoadingPersistentSession:!1,closingStatus:{type:"none"}};return E(i.closed)||i.closed.then(()=>{m.info("DRM-LSS: session was closed, removing it.",i.sessionId);let a=this.getIndex(r);a>=0&&this._storage[a].mediaKeySession===i&&this._storage.splice(a,1)}).catch(a=>{m.warn(`DRM-LSS: MediaKeySession.closed rejected: ${a}`)}),this._storage.push(oe({},o)),m.debug("DRM-LSS: MediaKeySession added",o.sessionType,this._storage.length),o}reuse(e){for(let t=this._storage.length-1;t>=0;t--){let r=this._storage[t];if(r.keySessionRecord.isCompatibleWith(e))return this._storage.splice(t,1),this._storage.push(r),m.debug("DRM-LSS: Reusing session:",r.mediaKeySession.sessionId,r.sessionType),oe({},r)}return null}getEntryForSession(e){for(let t=this._storage.length-1;t>=0;t--){let r=this._storage[t];if(r.mediaKeySession===e)return oe({},r)}return null}async generateLicenseRequest(e,t,r){let i;for(let o of this._storage)if(o.mediaKeySession===e){i=o;break}if(i===void 0)return m.error("DRM-LSS: generateRequest error. No MediaKeySession found with the given initData and initDataType"),Kr(e,t,r);if(i.isGeneratingRequest=!0,i.closingStatus.type!=="none")throw new Error("The `MediaKeySession` is being closed.");try{await Kr(e,t,r)}catch(o){throw i===void 0||(i.isGeneratingRequest=!1,i.closingStatus.type==="awaiting"&&i.closingStatus.start()),o}i!==void 0&&(i.isGeneratingRequest=!1,i.closingStatus.type==="awaiting"&&i.closingStatus.start())}async loadPersistentSession(e,t){let r;for(let o of this._storage)if(o.mediaKeySession===e){r=o;break}if(r===void 0)return m.error("DRM-LSS: loadPersistentSession error. No MediaKeySession found with the given initData and initDataType"),Vr(e,t);if(r.isLoadingPersistentSession=!0,r.closingStatus.type!=="none")throw new Error("The `MediaKeySession` is being closed.");let i;try{i=await Vr(e,t)}catch(o){throw r===void 0||(r.isLoadingPersistentSession=!1,r.closingStatus.type==="awaiting"&&r.closingStatus.start()),o}return r===void 0||(r.isLoadingPersistentSession=!1,r.closingStatus.type==="awaiting"&&r.closingStatus.start()),i}async closeSession(e){let t;for(let r of this._storage)if(r.mediaKeySession===e){t=r;break}return t===void 0?(m.warn("DRM-LSS: No MediaKeySession found with the given initData and initDataType"),Promise.resolve(!1)):this._closeEntry(t)}getLength(){return this._storage.length}getAll(){return this._storage}async closeAllSessions(){let e=this._storage;m.debug("DRM-LSS: Closing all current MediaKeySessions",e.length),this._storage=[];let t=e.map(r=>this._closeEntry(r));await Promise.all(t)}removeSessionWithoutClosingIt(e){ee(e.sessionId==="","Initialized `MediaKeySession`s should always be properly closed");for(let t=this._storage.length-1;t>=0;t--)if(this._storage[t].mediaKeySession===e)return m.debug("DRM-LSS: Removing session without closing it",e.sessionId),this._storage.splice(t,1),!0;return!1}getIndex(e){for(let t=0;t<this._storage.length;t++)if(this._storage[t].keySessionRecord===e)return t;return-1}async _closeEntry(e){let{mediaKeySession:t}=e;return new Promise((r,i)=>{e!==void 0&&(e.isLoadingPersistentSession||e.isGeneratingRequest)?e.closingStatus={type:"awaiting",start:o}:o();function o(){e!==void 0&&(e.closingStatus={type:"pending"}),wg(t).then(()=>{e!==void 0&&(e.closingStatus={type:"done"}),r(!0)}).catch(a=>{e!==void 0&&(e.closingStatus={type:"failed"}),i(a)})}})}};async function wg(n){m.debug("DRM: Trying to close a MediaKeySession",n.sessionId);try{await Po(n),m.debug("DRM: Succeeded to close MediaKeySession");return}catch(e){m.error("DRM: Could not close MediaKeySession: "+(e instanceof Error?e.toString():"Unknown error"));return}}function Jt(n){let e=0,t;for(let r=0;r<n.length;r++)t=n[r],e=(e<<5)-e+t,e=e&e;return e}var st=class{constructor(e){this.initData=e}toJSON(){return No(this.initData)}static decode(e){return pt(e)}};function Kn(n,e){var t,r;return(r=(t=Qc(n,e))!=null?t:Qc(e,n))!=null?r:!1}function Qc(n,e){if(n.length===0)return!1;if(e.length<n.length)return null;let t=n[0],r=0,i=0;for(;i<e.length;i++){let o=e[i];if(o.systemId!==t.systemId)continue;if(o.hash!==t.hash)return!1;let a;t.data instanceof Uint8Array?a=t.data:typeof t.data=="string"?a=st.decode(t.data):a=t.data.initData;let s;if(o.data instanceof Uint8Array?s=o.data:typeof o.data=="string"?s=st.decode(o.data):s=o.data.initData,!ge(a,s))return!1;if(e.length-i<n.length)return null;for(r=1;r<n.length;r++){let d=n[r];for(i+=1;i<e.length;i++){let u=e[i];if(d.systemId!==u.systemId)continue;if(d.hash!==u.hash)return!1;let l;d.data instanceof Uint8Array?l=d.data:typeof d.data=="string"?l=st.decode(d.data):l=d.data.initData;let c;if(u.data instanceof Uint8Array?c=u.data:typeof u.data=="string"?c=st.decode(u.data):c=u.data.initData,!ge(l,c))return!1;break}if(r===e.length)return null}return!0}return null}function Og(n){ec(n,{save:"function",load:"function"},"persistentLicenseConfig")}var Gr=class{constructor(e){Og(e),this._entries=[],this._storage=e;try{let t=this._storage.load();Array.isArray(t)||(t=[]),this._entries=t}catch(t){m.warn("DRM-PSS: Could not get entries from license storage",t instanceof Error?t:""),this.dispose()}}getLength(){return this._entries.length}getAll(){return this._entries}get(e){let t=this._getIndex(e);return t===-1?null:this._entries[t]}getAndReuse(e){let t=this._getIndex(e);if(t===-1)return null;let r=this._entries.splice(t,1)[0];return this._entries.push(r),r}add(e,t,r){var s;if(E(r)||!w(r.sessionId)){m.warn("DRM-PSS: Invalid Persisten Session given.");return}let{sessionId:i}=r,o=this._getIndex(e);if(o>=0){let d=t===void 0?3:4,u=this._entries[o];if(((s=u.version)!=null?s:-1)>=d&&i===u.sessionId)return;m.info("DRM-PSS: Updating session info.",i),this._entries.splice(o,1)}else m.info("DRM-PSS: Add new session",i);let a=Dg(e.values.getFormattedValues());t===void 0?this._entries.push({version:3,sessionId:i,values:a,initDataType:e.type}):this._entries.push({version:4,sessionId:i,keyIds:t.map(d=>new st(d)),values:a,initDataType:e.type}),this._save()}delete(e){let t=-1;for(let i=0;i<this._entries.length;i++)if(this._entries[i].sessionId===e){t=i;break}if(t===-1){m.warn("DRM-PSS: initData to delete not found.");return}let r=this._entries[t];m.warn("DRM-PSS: Delete session from store",r.sessionId),this._entries.splice(t,1),this._save()}deleteOldSessions(e){m.info(`DRM-PSS: Deleting last ${e} sessions.`),!(e<=0)&&(e<=this._entries.length?this._entries.splice(0,e):(m.warn("DRM-PSS: Asked to remove more information that it contains",e,this._entries.length),this._entries=[]),this._save())}dispose(){this._entries=[],this._save()}_getIndex(e){let t=null;function r(){if(t===null){let i=e.values.constructRequestData();t={initData:i,initDataHash:Jt(i)}}return t}for(let i=0;i<this._entries.length;i++){let o=this._entries[i];if(o.initDataType===e.type)switch(o.version){case 4:if(e.keyIds!==void 0){if(e.keyIds.every(s=>{let d=No(s);for(let u of o.keyIds)if(typeof u=="string"){if(d===u)return!0}else if(ge(u.initData,s))return!0;return!1}))return i}else{let a=e.values.getFormattedValues();if(Kn(a,o.values))return i}break;case 3:{let a=e.values.getFormattedValues();if(Kn(a,o.values))return i;break}case 2:{let{initData:a,initDataHash:s}=r();if(o.initDataHash===s)try{let d=typeof o.initData=="string"?st.decode(o.initData):o.initData.initData;if(ge(d,a))return i}catch(d){m.warn("DRM-PSS: Could not decode initialization data.",d instanceof Error?d:"")}break}case 1:{let{initData:a,initDataHash:s}=r();if(o.initDataHash===s){if(typeof o.initData.length=="undefined")return i;if(ge(o.initData,a))return i}break}default:{let{initDataHash:a}=r();if(o.initData===a)return i}}}return-1}_save(){try{this._storage.save(this._entries)}catch(e){let t=e instanceof Error?e:void 0;m.warn("DRM-PSS: Could not save MediaKeySession information",t)}}};function Dg(n){return n.map(({systemId:e,data:t,hash:r})=>({systemId:e,hash:r,data:new st(t)}))}var Xo=new WeakMap,Tn={prepare(n){Xo.set(n,null)},set(n,e){let t=e instanceof Uint8Array?e:new Uint8Array(e instanceof ArrayBuffer?e:e.buffer),r=Jt(t);Xo.set(n,{hash:r,serverCertificate:t})},hasOne(n){let e=Xo.get(n);if(e===void 0)return!1;if(e!==null)return!0},has(n,e){let t=Xo.get(n);if(t==null)return!1;let{hash:r,serverCertificate:i}=t,o=e instanceof Uint8Array?e:new Uint8Array(e instanceof ArrayBuffer?e:e.buffer);if(Jt(o)!==r||i.length!==o.length)return!1;for(let s=0;s<i.length;s++)if(i[s]!==o[s])return!1;return!0}};function Lg(n){let{persistentLicenseConfig:e}=n;return E(e)?null:(m.debug("DRM: Set the given license storage"),new Gr(e))}async function Ns(n,e,t){let r=await Ls(n,e,t);if(t.cancellationError!==null)throw t.cancellationError;let{options:i,mediaKeySystemAccess:o,askedConfiguration:a,codecSupport:s}=r.value,d=await qe.getAttachedMediaKeysState(n),u=Lg(i);if(r.value.options.reuseMediaKeys!==!1&&Os()&&d!==null&&r.type==="reuse-media-key-system-access"){m.debug("DRM: Reusing already created MediaKeys");let{mediaKeys:f,loadedSessionsStore:g}=d;if(Tn.hasOne(f)===!1||!E(i.serverCertificate)&&Tn.has(f,i.serverCertificate))return{mediaKeys:f,mediaKeySystemAccess:o,askedConfiguration:a,stores:{loadedSessionsStore:g,persistentSessionsStore:u},options:i,codecSupport:s}}let l=await Ng(o);m.info("DRM: MediaKeys created with success");let c=new Wr(l);return{mediaKeys:l,mediaKeySystemAccess:o,askedConfiguration:a,stores:{loadedSessionsStore:c,persistentSessionsStore:u},options:i,codecSupport:s}}async function Ng(n){m.info("DRM: Calling createMediaKeys on the MediaKeySystemAccess");try{return await n.createMediaKeys()}catch(e){let t=e instanceof Error?e.message:"Unknown error when creating MediaKeys.";throw new pe("CREATE_MEDIA_KEYS_ERROR",t)}}async function Us(n,e,t){let r=await Ns(n,e,t),{mediaKeys:i}=r;return n.mediaKeys!==null&&n.mediaKeys!==void 0&&i!==n.mediaKeys&&(m.debug("DRM: Disabling old MediaKeys"),await qe.clearMediaKeys(n)),r}function qr(n){let e=(Math.random()*2-1)*.3;return n*(e+1)}function Bs(n,e,t){let{baseDelay:r,maxDelay:i,totalRetry:o,shouldRetry:a,onRetry:s}=e,d=0;return u();async function u(){if(t.cancellationError!==null)throw t.cancellationError;try{return await n()}catch(l){if(t.cancellationError!==null)throw t.cancellationError;if(!E(a)&&!a(l)||d++>=o)throw l;typeof s=="function"&&s(l,d);let c=Ug(r,d,i);return await In(c),u()}}}function Ug(n,e,t){let r=n*Math.pow(2,e-1),i=qr(r);return Math.min(i,t)}function Fs(n,e){return n.indexOf("playready")!==-1&&(Wt||ur)?Fo(e):e}var Vn=class n extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,n.prototype),this.reason=e}},Ks={EXPIRED:"expired",INTERNAL_ERROR:"internal-error",OUTPUT_RESTRICTED:"output-restricted"};function Vs(n,e,t){let{onKeyInternalError:r,onKeyOutputRestricted:i,onKeyExpiration:o}=e,a=[],s=[],d=[];n.keyStatuses.forEach((l,c)=>{let[f,g]=typeof l=="string"?[l,c]:[c,l],p=Fs(t,new Uint8Array(g)),I={keyId:p.buffer,keyStatus:f};switch(m.hasLevel("DEBUG")&&m.debug(`DRM: key status update (${Ue(p)}): ${f}`),f){case Ks.EXPIRED:{let y=new pe("KEY_STATUS_CHANGE_ERROR",`A decryption key expired (${Ue(p)})`,{keyStatuses:[I,...d]});if(o==="error"||o===void 0)throw y;switch(o){case"close-session":throw new Vn(y);case"fallback":a.push(p);break;default:o==="continue"||o===void 0?s.push(p):Xe(o);break}d.push(I);break}case Ks.INTERNAL_ERROR:{let y=new pe("KEY_STATUS_CHANGE_ERROR",`A "${f}" status has been encountered (${Ue(p)})`,{keyStatuses:[I,...d]});switch(r){case void 0:case"error":throw y;case"close-session":throw new Vn(y);case"fallback":a.push(p);break;case"continue":s.push(p);break;default:if(r!==void 0)Xe(r);else throw y}d.push(I);break}case Ks.OUTPUT_RESTRICTED:{let y=new pe("KEY_STATUS_CHANGE_ERROR",`A "${f}" status has been encountered (${Ue(p)})`,{keyStatuses:[I,...d]});switch(i){case void 0:case"error":throw y;case"fallback":a.push(p);break;case"continue":s.push(p);break;default:if(i!==void 0)Xe(i);else throw y}d.push(I);break}default:s.push(p);break}});let u;return d.length>0&&(u=new pe("KEY_STATUS_CHANGE_ERROR","One or several problematic key statuses have been encountered",{keyStatuses:d})),{warning:u,blacklistedKeyIds:a,whitelistedKeyIds:s}}function zs(n,e,t,r,i){m.info("DRM: Binding session events",n.sessionId);let{getLicenseConfig:o={}}=e,a=new B;a.linkToSignal(i),E(n.closed)||n.closed.then(()=>a.cancel()).catch(l=>{i.isCancelled()||(a.cancel(),r.onError(l))}),wo(n,l=>{a.cancel(),r.onError(new pe("KEY_ERROR",l.type))},a.signal),vc(n,()=>{m.info("DRM: keystatuseschange event received",n.sessionId);try{s()}catch(l){if(i.isCancelled()||a.isUsed()&&l instanceof mr)return;a.cancel(),r.onError(l)}},a.signal),xo(n,l=>{let c=l,f=new Uint8Array(c.message),g=w(c.messageType)?c.messageType:"license-request";m.info(`DRM: Received message event, type ${g}`,n.sessionId);let p=u(o.retry);Bs(()=>d(f,g),p,a.signal).then(I=>{if(a.isUsed())return Promise.resolve();if(E(I))m.info("DRM: No license given, skipping session.update");else try{return Bg(n,I)}catch(y){a.cancel(),r.onError(y)}}).catch(I=>{if(a.isUsed())return;a.cancel();let y=Xc(I);if(!E(I)){let{fallbackOnLastTry:b}=I;if(b===!0){m.warn("DRM: Last `getLicense` attempt failed. Blacklisting the current session."),r.onError(new zn(y));return}}r.onError(y)})},a.signal),m.info("DRM: transmitting current keystatuses",n.sessionId),s();return;function s(){if(a.isUsed()||n.keyStatuses.size===0)return;let{warning:l,blacklistedKeyIds:c,whitelistedKeyIds:f}=Vs(n,e,t);l!==void 0&&(r.onWarning(l),a.isUsed())||r.onKeyUpdate({whitelistedKeyIds:f,blacklistedKeyIds:c})}function d(l,c){let f;return new Promise((g,p)=>{try{m.debug("DRM: Calling `getLicense`",c);let b=e.getLicense(l,c),T=E(o.timeout)?10*1e3:o.timeout;T>=0&&(f=setTimeout(()=>{p(new jr(`"getLicense" timeout exceeded (${T} ms)`))},T)),Promise.resolve(b).then(I,y)}catch(b){y(b)}function I(b){f!==void 0&&clearTimeout(f),g(b)}function y(b){f!==void 0&&clearTimeout(f),p(b)}})}function u(l){return{totalRetry:l!=null?l:2,baseDelay:200,maxDelay:3e3,shouldRetry:c=>c instanceof jr||E(c)||c.noRetry!==!0,onRetry:c=>r.onWarning(Xc(c))}}}function Xc(n){if(n instanceof jr)return new pe("KEY_LOAD_TIMEOUT","The license server took too much time to respond.");let e=new pe("KEY_LOAD_ERROR","An error occured when calling `getLicense`.");return!E(n)&&w(n.message)&&(e.message=n.message),e}async function Bg(n,e){m.info("DRM: Updating MediaKeySession with message");try{await n.update(e)}catch(t){let r=t instanceof Error?t.toString():"`session.update` failed";throw new pe("KEY_UPDATE_ERROR",r)}m.info("DRM: MediaKeySession update succeeded.")}var zn=class n extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,n.prototype),this.sessionError=e}},jr=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,zn.prototype),this.message=e}};async function Fg(n,e){try{return await n.setServerCertificate(e)}catch(t){m.warn("DRM: mediaKeys.setServerCertificate returned an error",t instanceof Error?t:"");let r=t instanceof Error?t.toString():"`setServerCertificate` error";throw new pe("LICENSE_SERVER_CERTIFICATE_ERROR",r)}}async function Hs(n,e){if(Tn.hasOne(n)===!0)return m.info("DRM: The MediaKeys already has a server certificate, skipping..."),{type:"already-has-one"};if(typeof n.setServerCertificate!="function")return m.warn("DRM: Could not set the server certificate. mediaKeys.setServerCertificate is not a function"),{type:"method-not-implemented"};m.info("DRM: Setting server certificate on the MediaKeys"),Tn.prepare(n);try{let t=await Fg(n,e);return Tn.set(n,e),{type:"success",value:t}}catch(t){return{type:"error",value:qt(t)?t:new pe("LICENSE_SERVER_CERTIFICATE_ERROR","Unknown error when setting the server certificate.")}}}function Ws(n,e){if(isNaN(e)||e<0||e>=n.getLength())return;let t=n.getLength(),r=t-e;m.info("DRM: Too many stored persistent sessions, removing some.",t,r),n.deleteOldSessions(r)}function Gs(n){if(Ze(n,"com.microsoft.playready")||n==="com.chromecast.playready"||n==="com.youtube.playready")return"9a04f07998404286ab92e65be0885f95";if(n==="com.widevine.alpha")return"edef8ba979d64acea3c827dcd51d21ed";if(Ze(n,"com.apple.fps"))return"94ce86fb07ff4f43adb893d2fa968ca2";if(Ze(n,"com.nagra."))return"adb41c242dbf4a6d958b4457c0d27b95"}var Yr=class n{constructor(e){this._innerValues=e,this._lazyFormattedValues=null}constructRequestData(){return ie(...this._innerValues.map(e=>e.data))}isCompatibleWith(e){let t=e instanceof n?e.getFormattedValues():e;return Kn(this.getFormattedValues(),t)}getFormattedValues(){return this._lazyFormattedValues===null&&(this._lazyFormattedValues=Kg(this._innerValues)),this._lazyFormattedValues}};function Kg(n){return n.slice().sort((e,t)=>e.systemId===t.systemId?0:e.systemId===void 0?1:t.systemId===void 0||e.systemId<t.systemId?-1:1).map(({systemId:e,data:t})=>({systemId:e,data:t,hash:Jt(t)}))}function qs(n,e,t){let r=`${n};codecs="${e}"`,i=t.filter(o=>o.mimeType===n);if(i.length!==0)for(let{codec:o,mimeType:a,result:s}of i){let d=`${a};codecs="${o}"`;if(Qo(r,d))return s}}var $r=class extends re{static hasEmeApis(){return!E(Zt.requestMediaKeySystemAccess)}constructor(e,t){super(),m.debug("DRM: Starting ContentDecryptor logic.");let r=new B;this._currentSessions=[],this._canceller=r,this._initDataQueue=[],this._stateData={state:0,isMediaKeysAttached:0,isInitDataQueueLocked:!0,data:null},this._supportedCodecWhenEncrypted=[],this.error=null,Zt.onEncrypted(e,i=>{m.debug("DRM: Encrypted event received from media element.");let o=Yo(i);o!==null&&this.onInitializationData(o)},r.signal),Us(e,t,r.signal).then(i=>{let{options:o,mediaKeySystemAccess:a}=i;this._supportedCodecWhenEncrypted=i.codecSupport;let s;(E(o.persistentLicenseConfig)||o.persistentLicenseConfig.disableRetroCompatibility===!0)&&(s=Gs(a.keySystem)),this.systemId=s,this._stateData.state===0&&(m.debug("DRM: Waiting for attachment."),this._stateData={state:1,isInitDataQueueLocked:!0,isMediaKeysAttached:0,data:{mediaKeysInfo:i,mediaElement:e}},this.trigger("stateChange",this._stateData.state))}).catch(i=>{this._onFatalError(i)})}getState(){return this._stateData.state}attach(){if(this._stateData.state!==1)throw new Error("`attach` should only be called when in the WaitingForAttachment state");if(this._stateData.isMediaKeysAttached!==0){m.warn("DRM: ContentDecryptor's `attach` method called more than once.");return}let{mediaElement:e,mediaKeysInfo:t}=this._stateData.data,{options:r,mediaKeys:i,mediaKeySystemAccess:o,stores:a,askedConfiguration:s}=t;if(r.disableMediaKeysAttachmentLock===!0&&(m.debug("DRM: disabling MediaKeys attachment lock. Ready for content"),this._stateData={state:2,isInitDataQueueLocked:!0,isMediaKeysAttached:1,data:{mediaKeysInfo:t,mediaElement:e}},this.trigger("stateChange",this._stateData.state),this._isStopped()))return;this._stateData.isMediaKeysAttached=1;let u={emeImplementation:Zt,loadedSessionsStore:a.loadedSessionsStore,mediaKeySystemAccess:o,mediaKeys:i,askedConfiguration:s,keySystemOptions:r};m.debug("DRM: Attaching current MediaKeys"),qe.attach(e,u).then(async()=>{if(this._isStopped())return;this._stateData.isMediaKeysAttached=2;let{serverCertificate:l}=r;if(!E(l)){let f=await Hs(i,l);f.type==="error"&&this.trigger("warning",f.value)}if(this._isStopped())return;let c=this._stateData.state;this._stateData={state:2,isMediaKeysAttached:2,isInitDataQueueLocked:!1,data:{mediaKeysData:t}},c!==2&&this.trigger("stateChange",2),this._isStopped()||this._processCurrentInitDataQueue()}).catch(l=>{this._onFatalError(l)})}dispose(){this.removeEventListener(),this._stateData={state:4,isMediaKeysAttached:void 0,isInitDataQueueLocked:void 0,data:null},this._canceller.cancel(),this.trigger("stateChange",this._stateData.state)}isCodecSupported(e,t){if(this._stateData.state===0){m.error("DRM: Asking for codec support while the ContentDecryptor is still initializing");return}return(this._stateData.state===3||this._stateData.state===4)&&m.error("DRM: Asking for codec support while the ContentDecryptor is disposed"),qs(e,t,this._supportedCodecWhenEncrypted)}onInitializationData(e){if(this._stateData.isInitDataQueueLocked!==!1){if(this._isStopped())throw new Error("ContentDecryptor either disposed or stopped.");this._initDataQueue.push(e);return}let{mediaKeysData:t}=this._stateData.data,r=ue(oe({},e),{values:new Yr(e.values)});this._processInitializationData(r,t).catch(i=>{this._onFatalError(i)})}async _processInitializationData(e,t){var I,y,b;m.hasLevel("DEBUG")&&m.debug("DRM: processing init data",(I=e.content)==null?void 0:I.adaptation.type,(y=e.content)==null?void 0:y.representation.bitrate,((b=e.keyIds)!=null?b:[]).map(T=>Ue(T)).join(", "));let{mediaKeySystemAccess:r,stores:i,options:o}=t;if(this._tryToUseAlreadyCreatedSession(e,t)||this._isStopped())return;if(o.singleLicensePer==="content"){let T=Z(this._currentSessions,v=>v.source==="created-session");if(T!==void 0){let v=e.keyIds;if(v===void 0){e.content===void 0?m.warn("DRM: Unable to fallback from a non-decipherable quality."):(m.debug("DRM: Blacklisting new init data (due to singleLicensePer content policy)"),this.trigger("blackListProtectionData",e));return}if(T.record.associateKeyIds(v),e.content===void 0)m.warn("DRM: Unable to fallback from a non-decipherable quality.");else{if(m.hasLevel("DEBUG")){let _=v.reduce((R,k)=>`${R}, ${Ue(k)}`,"");m.debug("DRM: Blacklisting new key ids",_)}this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:v,delistedKeyIds:[]})}return}}else if(o.singleLicensePer==="periods"&&e.content!==void 0){let{period:T}=e.content,v=this._currentSessions.filter(R=>R.source==="created-session"),_=new Set;Ys(_,T);for(let R of v){let k=Array.from(_);for(let x of k)if(R.record.isAssociatedWithKeyId(x)){R.record.associateKeyIds(_.values());for(let M of k)!R.keyStatuses.whitelisted.some(P=>ge(P,M))&&!R.keyStatuses.blacklisted.some(P=>ge(P,M))&&R.keyStatuses.blacklisted.push(M);m.hasLevel("DEBUG")&&m.debug("DRM: Session already created for",Ue(x),'under singleLicensePer "periods" policy'),this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:R.keyStatuses.whitelisted,blacklistedKeyIds:R.keyStatuses.blacklisted,delistedKeyIds:[]});return}}}this._lockInitDataQueue();let a;Vg(r)&&(!E(o.persistentLicenseConfig)||!zg(r))?a="persistent-license":a="temporary";let{EME_DEFAULT_MAX_SIMULTANEOUS_MEDIA_KEY_SESSIONS:s,EME_MAX_STORED_PERSISTENT_SESSION_INFORMATION:d}=U.getCurrent(),u=typeof o.maxSessionCacheSize=="number"?o.maxSessionCacheSize:s,l=await ws(e,i,a,u,this._canceller.signal);if(this._isStopped())return;let c={record:l.value.keySessionRecord,source:l.type,keyStatuses:{whitelisted:[],blacklisted:[]},blacklistedSessionError:null};this._currentSessions.push(c);let{mediaKeySession:f,sessionType:g}=l.value,p=!1;if(zs(f,o,r.keySystem,{onKeyUpdate:T=>{let v=Gg(e,c.record,o.singleLicensePer,c.source==="created-session",T.whitelistedKeyIds,T.blacklistedKeyIds);if(c.record.associateKeyIds(v.whitelisted),c.record.associateKeyIds(v.blacklisted),c.keyStatuses={whitelisted:v.whitelisted,blacklisted:v.blacklisted},c.record.getAssociatedKeyIds().length!==0&&g==="persistent-license"&&i.persistentSessionsStore!==null&&!p){let{persistentSessionsStore:_}=i;Ws(_,d-1),_.add(e,c.record.getAssociatedKeyIds(),f),p=!0}e.content!==void 0&&this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:v.whitelisted,blacklistedKeyIds:v.blacklisted,delistedKeyIds:[]}),this._unlockInitDataQueue()},onWarning:T=>{this.trigger("warning",T)},onError:T=>{var v;if(T instanceof Vn){m.warn("DRM: A session's closing condition has been triggered"),this._lockInitDataQueue();let _=this._currentSessions.indexOf(c);_>=0&&this._currentSessions.splice(_),e.content!==void 0&&this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:[],delistedKeyIds:c.record.getAssociatedKeyIds()}),(v=i.persistentSessionsStore)==null||v.delete(f.sessionId),i.loadedSessionsStore.closeSession(f).catch(R=>{let k=R instanceof Error?R:"unknown error";m.warn("DRM: failed to close expired session",k)}).then(()=>this._unlockInitDataQueue()).catch(R=>this._onFatalError(R)),this._isStopped()||this.trigger("warning",T.reason);return}if(!(T instanceof zn)){this._onFatalError(T);return}c.blacklistedSessionError=T,e.content!==void 0&&(m.info("DRM: blacklisting Representations based on protection data."),this.trigger("blackListProtectionData",e)),this._unlockInitDataQueue()}},this._canceller.signal),(o.singleLicensePer===void 0||o.singleLicensePer==="init-data")&&this._unlockInitDataQueue(),l.type==="created-session"){let T=e.values.constructRequestData();try{await i.loadedSessionsStore.generateLicenseRequest(f,e.type,T)}catch(v){let _=i.loadedSessionsStore.getEntryForSession(f);if(_===null||_.closingStatus.type!=="none"){let R=this._currentSessions.indexOf(c);return R>=0&&this._currentSessions.splice(R,1),Promise.resolve()}throw new pe("KEY_GENERATE_REQUEST_ERROR",v instanceof Error?v.toString():"Unknown error")}}return Promise.resolve()}_tryToUseAlreadyCreatedSession(e,t){let{stores:r,options:i}=t,o=Z(this._currentSessions,l=>l.record.isCompatibleWith(e));if(o===void 0)return!1;if(e.forceSessionRecreation===!0)return this.removeSessionForInitData(e,t),!1;let s=o.blacklistedSessionError;if(!E(s))return e.type===void 0||e.content===void 0?(m.error("DRM: This initialization data has already been blacklisted but the current content is not known."),!0):(m.info("DRM: This initialization data has already been blacklisted. Blacklisting the related content."),this.trigger("blackListProtectionData",e),!0);if(e.keyIds!==void 0){let l;if(i.singleLicensePer===void 0||i.singleLicensePer==="init-data"){let{blacklisted:c}=o.keyStatuses;l=$c(e.keyIds,c)}else{let{whitelisted:c}=o.keyStatuses;l=!Fn(e.keyIds,c)}if(l)return e.content===void 0?(m.error("DRM: Cannot forbid key id, the content is unknown."),!0):(m.info("DRM: Current initialization data is linked to blacklisted keys. Marking Representations as not decipherable"),this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:e.keyIds,delistedKeyIds:[]}),!0)}if(r.loadedSessionsStore.reuse(e)!==null)return m.debug("DRM: Init data already processed. Skipping it."),!0;let u=this._currentSessions.indexOf(o);return u===-1?m.error("DRM: Unable to remove processed init data: not found."):(m.debug("DRM: A session from a processed init data is not available anymore. Re-processing it."),this._currentSessions.splice(u,1)),!1}removeSessionForInitData(e,t){let{stores:r}=t,i=r.loadedSessionsStore.reuse(e);i!==null&&r.loadedSessionsStore.closeSession(i.mediaKeySession).catch(()=>m.error("DRM: Cannot close the session from the loaded session store"));let o=Z(this._currentSessions,s=>s.record.isCompatibleWith(e));if(o===void 0)return;let a=this._currentSessions.indexOf(o);a!==-1&&(m.debug("DRM: A session from a processed init is removed due to forceSessionRecreation policy."),this._currentSessions.splice(a,1))}_onFatalError(e){if(this._canceller.isUsed())return;let t=e instanceof Error?e:new Le("NONE","Unknown decryption error");this.error=t,this._initDataQueue.length=0,this._stateData={state:3,isMediaKeysAttached:void 0,isInitDataQueueLocked:void 0,data:null},this._canceller.cancel(),this.trigger("error",t),this._stateData.state===3&&this.trigger("stateChange",this._stateData.state)}_isStopped(){return this._stateData.state===4||this._stateData.state===3}_processCurrentInitDataQueue(){for(;this._stateData.isInitDataQueueLocked===!1;){let e=this._initDataQueue.shift();if(e===void 0)return;this.onInitializationData(e)}}_lockInitDataQueue(){this._stateData.isInitDataQueueLocked===!1&&(this._stateData.isInitDataQueueLocked=!0)}_unlockInitDataQueue(){if(this._stateData.isMediaKeysAttached!==2){m.error("DRM: Trying to unlock in the wrong state");return}this._stateData.isInitDataQueueLocked=!1,this._processCurrentInitDataQueue()}};function Vg(n){let{sessionTypes:e}=n.getConfiguration();return e!==void 0&&Q(e,"persistent-license")}function zg(n){let{sessionTypes:e}=n.getConfiguration();return e!==void 0&&Q(e,"temporary")}function Zc(n,e){return n.filter(t=>!e.some(r=>ge(r,t)))}function Hg(n,e){let t=n.getAssociatedKeyIds(),r=Zc(t,e);return r.length>0&&m.hasLevel("DEBUG")&&m.debug("DRM: KeySessionRecord's keys missing in the license, blacklisting them",r.map(i=>Ue(i)).join(", ")),r}function Wg(n,e){let t=[],{keyIds:r}=n;return r!==void 0&&(t=Zc(r,e)),t.length>0&&m.hasLevel("DEBUG")&&m.debug("DRM: init data keys missing in the license, blacklisting them",t.map(i=>Ue(i)).join(", ")),t}function Gg(n,e,t,r,i,o){var u;let a=[...i,...o],s=Hg(e,a),d=a.concat(s);if(t!==void 0&&t!=="init-data"){let l=Wg(n,d);d.push(...l);let{content:c}=n;if(r&&c!==void 0){if(t==="content"){let f=new Set,{manifest:g}=c;for(let p of g.periods)Ys(f,p);js(f,d)}else if(t==="periods"){let{manifest:f}=c;for(let g of f.periods){let p=new Set;if(Ys(p,g),((u=n.content)==null?void 0:u.period.id)===g.id)js(p,d);else{let I=Array.from(p);for(let y of I)if(d.some(T=>ge(T,y))){js(p,d);break}}}}}}return{whitelisted:i,blacklisted:d.slice(i.length)}}function js(n,e){let t=Array.from(n.values());for(let r of t)e.some(o=>ge(o,r))||e.push(r)}function Ys(n,e){let t=e.adaptations,r=Sr(t).reduce((i,o)=>E(o)?i:i.concat(o),[]);for(let i of r)for(let o of i.representations)if(o.contentProtections!==void 0&&o.contentProtections.keyIds!==void 0)for(let a of o.contentProtections.keyIds)n.add(a)}function Hn(n){let e=qe.getAwaitedState(n);return e===null?null:[e.mediaKeySystemAccess.keySystem,e.mediaKeySystemAccess.getConfiguration()]}var Jc=$r;function ef(n){var t,r,i,o,a;let e=[];for(let s of n.periods){let d=[...(t=s.adaptations.video)!=null?t:[],...(r=s.adaptations.audio)!=null?r:[]];for(let u of d)if(u.supportStatus.hasCodecWithUndefinedSupport)for(let l of u.representations)l.isSupported===void 0&&e.push({mimeType:(i=l.mimeType)!=null?i:"",codec:(a=(o=l.codecs)==null?void 0:o[0])!=null?a:""})}return e}var tf=[];function At(n){Q(tf,n)||(console.warn(n),tf.push(n))}var Qr=class{constructor(e){this.supportMap=new Map,this.addCodecs(e)}addCodecs(e){for(let t of e){let r=this.supportMap.get(t.mimeType);r===void 0&&(r=new Map,this.supportMap.set(t.mimeType,r)),r.set(t.codec,{supported:t.supported,supportedIfEncrypted:t.supportedIfEncrypted})}}isSupported(e,t,r){let i=this.supportMap.get(e);if(i===void 0)return;let o=i.get(t);if(o!==void 0)return r?o.supportedIfEncrypted:o.supported}};var Xr=class{constructor(e,t,r,i){if(this.id=e.id,this.adaptations=Object.keys(e.adaptations).reduce((o,a)=>{let s=e.adaptations[a];if(E(s))return o;let d=s.map(u=>{let l=new Pr(u,r,{representationFilter:i});return l.representations.length>0&&l.supportStatus.hasSupportedCodec===!1&&t.push(l),l}).filter(u=>u.representations.length>0);if(d.every(u=>u.supportStatus.hasSupportedCodec===!1)&&s.length>0&&(a==="video"||a==="audio"))throw new te("MANIFEST_INCOMPATIBLE_CODECS_ERROR","No supported "+a+" adaptations",{tracks:void 0});return d.length>0&&(o[a]=d),o},{}),!Array.isArray(this.adaptations.video)&&!Array.isArray(this.adaptations.audio))throw new te("MANIFEST_PARSE_ERROR","No supported audio and video tracks.");this.duration=e.duration,this.start=e.start,!E(this.duration)&&!E(this.start)&&(this.end=this.start+this.duration),this.streamEvents=e.streamEvents===void 0?[]:e.streamEvents}refreshCodecSupport(e,t){Object.keys(this.adaptations).forEach(r=>{let i=this.adaptations[r];if(i===void 0)return;let o=!1;for(let a of i){if(!a.supportStatus.hasCodecWithUndefinedSupport){a.supportStatus.hasSupportedCodec===!0&&(o=!0);continue}let s=a.supportStatus.hasSupportedCodec;a.refreshCodecSupport(t),s!==!1&&a.supportStatus.hasSupportedCodec===!1&&e.push(a),o===!1?o=a.supportStatus.hasSupportedCodec:o===void 0&&a.supportStatus.hasSupportedCodec===!0&&(o=!0)}if((r==="video"||r==="audio")&&o===!1)throw new te("MANIFEST_INCOMPATIBLE_CODECS_ERROR","No supported "+r+" adaptations",{tracks:void 0})},{})}getAdaptations(){return as(this)}getAdaptationsForType(e){let t=this.adaptations[e];return t!=null?t:[]}getAdaptation(e){return Z(this.getAdaptations(),({id:t})=>e===t)}getSupportedAdaptations(e){return ft(this,e)}containsTime(e,t){return os(this,e,t)}getMetadataSnapshot(){let e={},t=this.getAdaptations();for(let r of t){let i=e[r.type];i===void 0&&(i=[],e[r.type]=i),i.push(r.getMetadataSnapshot())}return{start:this.start,end:this.end,id:this.id,streamEvents:this.streamEvents,adaptations:e}}};function Zr(n,e,t){let r={updatedAdaptations:[],removedAdaptations:[],addedAdaptations:[]};n.start=e.start,n.end=e.end,n.duration=e.duration,n.streamEvents=e.streamEvents;let i=n.getAdaptations(),o=e.getAdaptations();for(let a=0;a<i.length;a++){let s=i[a],d=he(o,u=>u.id===s.id);if(d===-1){m.warn('Manifest: Adaptation "'+i[a].id+'" not found when merging.');let[u]=i.splice(a,1);a--,r.removedAdaptations.push({id:u.id,trackType:u.type})}else{let[u]=o.splice(d,1),l=[],c=[],f=[];r.updatedAdaptations.push({adaptation:s.id,trackType:s.type,updatedRepresentations:l,addedRepresentations:c,removedRepresentations:f});let g=s.representations,p=u.representations.slice();for(let I=0;I<g.length;I++){let y=g[I],b=he(p,T=>T.id===y.id);if(b===-1){m.warn(`Manifest: Representation "${g[I].id}" not found when merging.`);let[T]=g.splice(I,1);I--,f.push(T.id)}else{let[T]=p.splice(b,1);l.push(y.getMetadataSnapshot()),y.cdnMetadata=T.cdnMetadata,t===0?y.index._replace(T.index):y.index._update(T.index)}}p.length>0&&(m.warn(`Manifest: ${p.length} new Representations found when merging.`),s.representations.push(...p),c.push(...p.map(I=>I.getMetadataSnapshot())))}}if(o.length>0){m.warn(`Manifest: ${o.length} new Adaptations found when merging.`);for(let a of o){let s=n.adaptations[a.type];s===void 0?n.adaptations[a.type]=[a]:s.push(a),r.addedAdaptations.push(a.getMetadataSnapshot())}}return r}function nf(n,e){let t={updatedPeriods:[],addedPeriods:[],removedPeriods:[]},r=0;for(let o=0;o<e.length;o++){let a=e[o],s=r,d=n[s];for(;d!==void 0&&d.id!==a.id;)s++,d=n[s];if(d!==void 0){let u=Zr(d,a,0);t.updatedPeriods.push({period:{id:d.id,start:d.start,end:d.end,duration:d.duration,streamEvents:d.streamEvents},result:u});let l=e.slice(r,o),c=s-r,f=n.splice(r,c,...l);t.removedPeriods.push(...f.map(g=>({id:g.id,start:g.start,end:g.end}))),t.addedPeriods.push(...l.map(g=>g.getMetadataSnapshot())),r=o+1}}if(r>n.length)return m.error("Manifest: error when updating Periods"),t;if(r<n.length){let o=n.splice(r,n.length-r);t.removedPeriods.push(...o.map(a=>({id:a.id,start:a.start,end:a.end})))}let i=e.slice(r,e.length);return i.length>0&&(n.push(...i),t.addedPeriods.push(...i.map(o=>o.getMetadataSnapshot()))),t}function rf(n,e){let t={updatedPeriods:[],addedPeriods:[],removedPeriods:[]};if(n.length===0)return n.splice(0,0,...e),t.addedPeriods.push(...e.map(s=>s.getMetadataSnapshot())),t;if(e.length===0)return t;let r=n[n.length-1];if(r.start<e[0].start){if(r.end!==e[0].start)throw new te("MANIFEST_UPDATE_ERROR","Cannot perform partial update: not enough data");return n.push(...e),t.addedPeriods.push(...e.map(s=>s.getMetadataSnapshot())),t}let i=he(n,({id:s})=>s===e[0].id);if(i<0)throw new te("MANIFEST_UPDATE_ERROR","Cannot perform partial update: incoherent data");let o=Zr(n[i],e[0],1);t.updatedPeriods.push({period:G(n[i].getMetadataSnapshot(),{adaptations:void 0}),result:o});let a=i+1;for(let s=1;s<e.length;s++){let d=e[s],u=-1;for(let l=a;l<n.length;l++)if(d.id===n[l].id){u=l;break}if(u<0){let l=-1;for(let g=a;g<n.length;g++)if(d.start<n[g].start){l=g;break}let c=l-a,f=n.splice(a,c,d);t.addedPeriods.push(d.getMetadataSnapshot()),t.removedPeriods.push(...f.map(g=>({id:g.id,start:g.start,end:g.end})))}else{if(u>a){m.warn("Manifest: old Periods not found in new when updating, removing");let c=n.splice(a,u-a);t.removedPeriods.push(...c.map(f=>({id:f.id,start:f.start,end:f.end}))),u=a}let l=Zr(n[u],d,0);t.updatedPeriods.push({period:G(n[u].getMetadataSnapshot(),{adaptations:void 0}),result:l})}a++}if(a<n.length){m.warn("Manifest: Ending Periods not found in new when updating, removing");let s=n.splice(a,n.length-a);t.removedPeriods.push(...s.map(d=>({id:d.id,start:d.start,end:d.end})))}return t}var qg=et(),Jr=class extends re{constructor(e,t,r){var s;super();let{representationFilter:i,manifestUpdateUrl:o}=t;this.manifestFormat=0,this.id=qg(),this.expired=(s=e.expired)!=null?s:null,this.transport=e.transportType,this.clockOffset=e.clockOffset,this._cachedCodecSupport=new Qr([]);let a=[];if(this.periods=e.periods.map(d=>new Xr(d,a,this._cachedCodecSupport,i)).sort((d,u)=>d.start-u.start),a.length>0){let d=new te("MANIFEST_INCOMPATIBLE_CODECS_ERROR","An Adaptation contains only incompatible codecs.",{tracks:a.map(Yt)});r.push(d)}this.adaptations=this.periods[0]===void 0?{}:this.periods[0].adaptations,this.timeBounds=e.timeBounds,this.isDynamic=e.isDynamic,this.isLive=e.isLive,this.isLastPeriodKnown=e.isLastPeriodKnown,this.uris=e.uris===void 0?[]:e.uris,this.updateUrl=o,this.lifetime=e.lifetime,this.clockOffset=e.clockOffset,this.suggestedPresentationDelay=e.suggestedPresentationDelay,this.availabilityStartTime=e.availabilityStartTime,this.publishTime=e.publishTime}updateCodecSupport(e=[]){if(e.length===0)return null;this._cachedCodecSupport.addCodecs(e);let t=[];for(let r of this.periods)r.refreshCodecSupport(t,this._cachedCodecSupport);return this.trigger("supportUpdate",null),t.length>0?new te("MANIFEST_INCOMPATIBLE_CODECS_ERROR","An Adaptation contains only incompatible codecs.",{tracks:t.map(Yt)}):null}getPeriod(e){return Z(this.periods,t=>e===t.id)}getPeriodForTime(e){return mc(this,e)}getNextPeriod(e){return Z(this.periods,t=>t.start>e)}getPeriodAfter(e){return Eo(this,e)}getUrls(){return this.uris}replace(e){this._performUpdate(e,0)}update(e){this._performUpdate(e,1)}getMinimumSafePosition(){return gn(this)}getLivePosition(){return hn(this)}getMaximumSafePosition(){return bt(this)}updateCodecSupportList(e){this._cachedCodecSupport=e}updateRepresentationsDeciperability(e){let t=jg(this,e);t.length>0&&this.trigger("decipherabilityUpdate",t)}getAdaptations(){At("manifest.getAdaptations() is deprecated. Please use manifest.period[].getAdaptations() instead");let e=this.periods[0];if(e===void 0)return[];let t=e.adaptations,r=[];for(let i in t)if(t.hasOwnProperty(i)){let o=t[i];r.push(...o)}return r}getAdaptationsForType(e){At("manifest.getAdaptationsForType(type) is deprecated. Please use manifest.period[].getAdaptationsForType(type) instead");let t=this.periods[0];if(t===void 0)return[];let r=t.adaptations[e];return r===void 0?[]:r}getAdaptation(e){return At("manifest.getAdaptation(id) is deprecated. Please use manifest.period[].getAdaptation(id) instead"),Z(this.getAdaptations(),({id:t})=>e===t)}getMetadataSnapshot(){let e=[];for(let t of this.periods)e.push(t.getMetadataSnapshot());return{manifestFormat:1,id:this.id,periods:e,isDynamic:this.isDynamic,isLive:this.isLive,isLastPeriodKnown:this.isLastPeriodKnown,suggestedPresentationDelay:this.suggestedPresentationDelay,clockOffset:this.clockOffset,uris:this.uris,availabilityStartTime:this.availabilityStartTime,timeBounds:this.timeBounds}}getCodecsWithUnknownSupport(){return ef(this)}_performUpdate(e,t){this.availabilityStartTime=e.availabilityStartTime,this.expired=e.expired,this.isDynamic=e.isDynamic,this.isLive=e.isLive,this.isLastPeriodKnown=e.isLastPeriodKnown,this.lifetime=e.lifetime,this.clockOffset=e.clockOffset,this.suggestedPresentationDelay=e.suggestedPresentationDelay,this.transport=e.transport,this.publishTime=e.publishTime;let r;if(t===0)this.timeBounds=e.timeBounds,this.uris=e.uris,r=nf(this.periods,e.periods);else{this.timeBounds.maximumTimeData=e.timeBounds.maximumTimeData,this.updateUrl=e.uris[0],r=rf(this.periods,e.periods);let i=this.getMinimumSafePosition();for(;this.periods.length>0;){let o=this.periods[0];if(o.end===void 0||o.end>i)break;this.periods.shift()}}this.updateCodecSupport(),this.adaptations=this.periods[0]===void 0?{}:this.periods[0].adaptations,this.trigger("manifestUpdate",r)}};function jg(n,e){let t=[];for(let r of n.periods)for(let i of r.getAdaptations()){let o=!0;for(let a of i.representations){let s={manifest:n,period:r,adaptation:i,representation:a},d=e(s);d!==!1&&(o=!1),d!==a.decipherable&&(t.push(s),a.decipherable=d,d===!0?i.supportStatus.isDecipherable=!0:d===void 0&&i.supportStatus.isDecipherable===!1&&(i.supportStatus.isDecipherable=void 0),m.debug(`Decipherability changed for "${a.id}"`,`(${a.bitrate})`,String(a.decipherable)))}o&&(i.supportStatus.isDecipherable=!1)}return t}function kt(n,e){return n.segment.id===e.segment.id&&n.representation.uniqueId===e.representation.uniqueId}function yn(n){if(E(n))return"";let{period:e,adaptation:t,representation:r,segment:i}=n,o;return i.isInit?o="init":i.complete?o=`${i.time}-${i.duration}`:o=`${i.time}`,`${t.type} P: ${e.id} A: ${t.id} R: ${r.id} S: ${o}`}var Wn=Jr;function xt(n){return n instanceof Ee?new it("PIPELINE_LOAD_ERROR",n):Oe(n,{defaultCode:"PIPELINE_LOAD_ERROR",defaultReason:"Unknown error when fetching the Manifest"})}function Yg(n){return n instanceof Ee?n.type===pn.ERROR_HTTP_CODE?n.status>=500||n.status===404||n.status===415||n.status===412:n.type===pn.TIMEOUT||n.type===pn.ERROR_EVENT:n instanceof rt?typeof n.canRetry=="boolean"?n.canRetry:n.xhr!==void 0?n.xhr.status>=500||n.xhr.status===404||n.xhr.status===415||n.xhr.status===412:!1:qt(n)&&n.code==="INTEGRITY_ERROR"}async function $s(n,e,t,r,i){if(i.cancellationError!==null)return Promise.reject(i.cancellationError);let{baseDelay:o,maxDelay:a,maxRetry:s,onRetry:d}=r;n!==null&&n.length===0&&m.warn("Fetchers: no CDN given to `scheduleRequestWithCdns`.");let u=new Map,l=c();if(l===void 0)throw new Error("No CDN to request");return f(l);function c(){if(n===null){let y=u.get(null);return y!==void 0&&y.isBlacklisted?void 0:null}else{if(e===null)return I(n);{let y=e.getCdnPreferenceForResource(n);return I(y)}}}async function f(y){try{return await t(y,i)}catch(b){if(B.isCancellationError(b))throw b;y!==null&&e!==null&&e.downgradeCdn(y);let T=u.get(y);if(T===void 0?(T={errorCounter:1,blockedUntil:void 0,isBlacklisted:!1},u.set(y,T)):T.errorCounter++,!Yg(b))return T.blockedUntil=void 0,T.isBlacklisted=!0,g(b);if(T.errorCounter>s)T.blockedUntil=void 0,T.isBlacklisted=!0;else{let v=T.errorCounter,_=Math.min(o*Math.pow(2,v-1),a),R=qr(_);T.blockedUntil=K()+R}return g(b)}}async function g(y){let b=c();if(i.isCancelled())throw i.cancellationError;if(b===void 0)throw y;if(d(y),i.isCancelled())throw i.cancellationError;return p(b,y)}function p(y,b){let T=u.get(y);if(T===void 0||T.blockedUntil===void 0)return f(y);let v=K(),_=T.blockedUntil-v;if(_<=0)return f(y);let R=new B,k=R.linkToSignal(i);return new Promise((x,M)=>{e==null||e.addEventListener("priorityChange",()=>{let O=c();if(i.isCancelled())throw i.cancellationError;if(O===void 0)return N(b);O!==y&&(R.cancel(),p(O,b).then(P,N))},R.signal),$t(_,R.signal).then(()=>f(y).then(P,N),X);function P(O){k(),x(O)}function N(O){k(),M(O)}})}function I(y){var T;if(u.size===0)return y[0];let b=K();return(T=y.filter(v=>{var _;return((_=u.get(v))==null?void 0:_.isBlacklisted)!==!0}).reduce((v,_)=>{var k;let R=(k=u.get(_))==null?void 0:k.blockedUntil;return R!==void 0&&R<=b&&(R=void 0),v===void 0?[_,R]:v[1]===void 0?v:R===void 0?[_,void 0]:R<v[1]?[_,R]:v},void 0))==null?void 0:T[0]}}function Qs(n,e,t){return $s(null,null,n,e,t)}var ei=class extends re{constructor(e,t,r){super(),this.scheduleManualRefresh=X,this._manifestUrls=e,this._pipelines=t.manifest,this._transportName=t.transportName,this._settings=r,this._canceller=new B,this._isStarted=!1,this._isRefreshPending=!1,this._consecutiveUnsafeMode=0,this._prioritizedContentUrl=null}dispose(){this._canceller.cancel(),this.removeEventListener()}start(){if(this._isStarted)return;this._isStarted=!0;let e,t=this._settings.initialManifest;t instanceof Wn?e=Promise.resolve({manifest:t}):t!==void 0?e=this.parse(t,{previousManifest:null,unsafeMode:!1},void 0):e=this._fetchManifest(void 0).then(r=>r.parse({previousManifest:null,unsafeMode:!1})),e.then(r=>{this.trigger("manifestReady",r.manifest),this._canceller.isUsed()||this._recursivelyRefreshManifest(r.manifest,r)}).catch(r=>this._onFatalError(r))}updateContentUrls(e,t){var r;this._prioritizedContentUrl=(r=e==null?void 0:e[0])!=null?r:void 0,t&&this.scheduleManualRefresh({enablePartialRefresh:!1,delay:0,canUseUnsafeMode:!1})}async _fetchManifest(e){var u;let t=this._canceller.signal,r=this._settings,i=this._transportName,o=this._pipelines,a=e!=null?e:(u=this._manifestUrls)==null?void 0:u[0],s=this._getBackoffSetting(l=>{this.trigger("warning",xt(l))});try{let l=await d(a);return{parse:c=>this._parseLoadedManifest(l,c,a)}}catch(l){throw xt(l)}function d(l){var y;let{loadManifest:c}=o,f=r.requestTimeout===void 0?U.getCurrent().DEFAULT_REQUEST_TIMEOUT:r.requestTimeout,g=r.connectionTimeout===void 0?U.getCurrent().DEFAULT_CONNECTION_TIMEOUT:r.connectionTimeout;f<0&&(f=void 0),g<0&&(g=void 0);let p={timeout:f,connectionTimeout:g,cmcdPayload:(y=r.cmcdDataBuilder)==null?void 0:y.getCmcdDataForManifest(i)};return Qs(()=>c(l,p,t),s,t)}}parse(e,t,r){return this._parseLoadedManifest({responseData:e,size:void 0,requestDuration:void 0},t,r)}async _parseLoadedManifest(e,t,r){var I;let i=K(),o=this._canceller.signal,a=this.trigger.bind(this),{sendingTime:s,receivedTime:d}=e,u=this._getBackoffSetting(y=>{this.trigger("warning",xt(y))}),l=r!=null?r:(I=this._manifestUrls)==null?void 0:I[0],c={externalClockOffset:t.externalClockOffset,unsafeMode:t.unsafeMode,previousManifest:t.previousManifest,originalUrl:l};try{let y=this._pipelines.parseManifest(e,c,g,o,f);if($g(y)){let{manifest:b,warnings:T}=await y;return p(b,T)}else return p(y.manifest,y.warnings)}catch(y){throw Oe(y,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"})}async function f(y){try{return await Qs(y,u,o)}catch(b){throw xt(b)}}function g(y){for(let b of y){if(o.isCancelled())return;let T=Oe(b,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"});a("warning",T)}}function p(y,b){g(b);let T=K()-i;return m.info(`MF: Manifest parsed in ${T}ms`),{manifest:y,sendingTime:s,receivedTime:d,parsingTime:T}}}_getBackoffSetting(e){let{DEFAULT_MAX_MANIFEST_REQUEST_RETRY:t,INITIAL_BACKOFF_DELAY_BASE:r,MAX_BACKOFF_DELAY_BASE:i}=U.getCurrent(),{lowLatencyMode:o,maxRetry:a}=this._settings,s=o?r.LOW_LATENCY:r.REGULAR,d=o?i.LOW_LATENCY:i.REGULAR,u=a!=null?a:t;return{onRetry:e,baseDelay:s,maxDelay:d,maxRetry:u}}_recursivelyRefreshManifest(e,{sendingTime:t,parsingTime:r,updatingTime:i}){let{MAX_CONSECUTIVE_MANIFEST_PARSING_IN_UNSAFE_MODE:o,MIN_MANIFEST_PARSING_TIME_TO_ENTER_UNSAFE_MODE:a}=U.getCurrent(),s=r!==void 0?r+(i!=null?i:0):void 0,d=!1;this._consecutiveUnsafeMode>0?d=this._consecutiveUnsafeMode<o:s!==void 0&&(d=s>=a);let u=t===void 0?0:K()-t,l=Math.max(this._settings.minimumManifestUpdateInterval-u,0),c=new B;if(c.linkToSignal(this._canceller.signal),this.scheduleManualRefresh=f=>{let{enablePartialRefresh:g,delay:p,canUseUnsafeMode:I}=f,y=I&&d,b=t===void 0?0:K()-t,T=Math.max(this._settings.minimumManifestUpdateInterval-b,0),v=setTimeout(()=>{c.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:g,unsafeMode:y})},Math.max((p!=null?p:0)-b,T));c.signal.register(()=>{clearTimeout(v)})},e.expired!==null){let f=setTimeout(()=>{var g;(g=e.expired)==null||g.then(()=>{c.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},X)},l);c.signal.register(()=>{clearTimeout(f)})}if(e.lifetime!==void 0&&e.lifetime>=0){let f=e.lifetime*1e3-u,g;s===void 0?g=f:e.lifetime<3&&s>=100?(g=Math.min(Math.max(3e3-u,Math.max(f,0)+s),f*6),m.info("MUS: Manifest update rythm is too frequent. Postponing next request.",f,g)):s>=e.lifetime*1e3/10?(g=Math.min(Math.max(f,0)+s,f*6),m.info("MUS: Manifest took too long to parse. Postponing next request",g,g)):g=f;let p=setTimeout(()=>{c.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},Math.max(g,l));c.signal.register(()=>{clearTimeout(p)})}}_triggerNextManifestRefresh(e,{enablePartialRefresh:t,unsafeMode:r}){let i=e.updateUrl,o,a;this._prioritizedContentUrl!==null?(o=!0,a=this._prioritizedContentUrl,this._prioritizedContentUrl=null):(o=!t||i===void 0,a=o?e.getUrls()[0]:i);let s=e.clockOffset;r?(this._consecutiveUnsafeMode+=1,m.info('Init: Refreshing the Manifest in "unsafeMode" for the '+String(this._consecutiveUnsafeMode)+" consecutive time.")):this._consecutiveUnsafeMode>0&&(m.info('Init: Not parsing the Manifest in "unsafeMode" anymore after '+String(this._consecutiveUnsafeMode)+" consecutive times."),this._consecutiveUnsafeMode=0),!this._isRefreshPending&&(this._isRefreshPending=!0,this._fetchManifest(a).then(d=>d.parse({externalClockOffset:s,previousManifest:e,unsafeMode:r})).then(d=>{this._isRefreshPending=!1;let{manifest:u,sendingTime:l,parsingTime:c}=d,f=K();if(o)e.replace(u);else try{e.update(u)}catch(p){let I=p instanceof Error?p.message:"unknown error";m.warn(`MUS: Attempt to update Manifest failed: ${I}`,"Re-downloading the Manifest fully");let{FAILED_PARTIAL_UPDATE_MANIFEST_REFRESH_DELAY:y}=U.getCurrent(),b=l===void 0?0:K()-l,T=Math.max(this._settings.minimumManifestUpdateInterval-b,0),v=X,_=setTimeout(()=>{v(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:!1})},Math.max(y-b,T));v=this._canceller.signal.register(()=>{clearTimeout(_)});return}let g=K()-f;this._recursivelyRefreshManifest(e,{sendingTime:l,parsingTime:c,updatingTime:g})}).catch(d=>{this._isRefreshPending=!1,this._onFatalError(d)}))}_onFatalError(e){this._canceller.isUsed()||(this.trigger("error",e),this.dispose())}};function $g(n){return n instanceof Promise}var Xs=ei;var ti=class extends re{constructor(e){super(),this._downgradedCdnList={metadata:[],timeouts:[]},e.register(()=>{for(let t of this._downgradedCdnList.timeouts)clearTimeout(t);this._downgradedCdnList={metadata:[],timeouts:[]}})}getCdnPreferenceForResource(e){return e.length<=1?e:this._innerGetCdnPreferenceForResource(e)}downgradeCdn(e){let t=of(this._downgradedCdnList.metadata,e);t>=0&&this._removeIndexFromDowngradeList(t);let{DEFAULT_CDN_DOWNGRADE_TIME:r}=U.getCurrent(),i=r;this._downgradedCdnList.metadata.push(e);let o=setTimeout(()=>{let a=of(this._downgradedCdnList.metadata,e);a>=0&&this._removeIndexFromDowngradeList(a),this.trigger("priorityChange",null)},i);this._downgradedCdnList.timeouts.push(o),this.trigger("priorityChange",null)}_innerGetCdnPreferenceForResource(e){let[t,r]=e.reduce((i,o)=>(this._downgradedCdnList.metadata.some(a=>a.id===o.id&&a.baseUrl===o.baseUrl)?i[1].push(o):i[0].push(o),i),[[],[]]);return t.concat(r)}_removeIndexFromDowngradeList(e){this._downgradedCdnList.metadata.splice(e,1);let t=this._downgradedCdnList.timeouts.splice(e,1);clearTimeout(t[0])}};function of(n,e){return n.length===0?-1:e.id!==void 0?he(n,t=>t.id===e.id):he(n,t=>t.baseUrl===e.baseUrl)}function Zs(n,e){let t=new WeakMap;return{createRequest(r,i,o,a){let s=u=>e(r,o,u),d=n.create(s,i,o,a);return t.set(d,s),d},updatePriority(r,i){let o=t.get(r);if(o===void 0){m.warn("Fetchers: Cannot update the priority of a request: task not found.");return}n.updatePriority(o,i)}}}var Js=class{constructor(){this._cache=new WeakMap}add({representation:e,segment:t},r){t.isInit&&this._cache.set(e,r)}get({representation:e,segment:t}){if(t.isInit){let r=this._cache.get(e);if(r!==void 0)return r}return null}},af=Js;var Qg=et();function ed({bufferType:n,pipeline:e,cdnPrioritizer:t,cmcdDataBuilder:r,eventListeners:i,requestOptions:o}){let a;o.connectionTimeout===void 0||o.connectionTimeout<0?a=void 0:a=o.connectionTimeout;let s={timeout:o.requestTimeout<0?void 0:o.requestTimeout,connectionTimeout:a,cmcdPayload:void 0},d=Q(["audio","video"],n)?new af:void 0,{loadSegment:u,parseSegment:l}=e;return async function(f,g,p){var $,j,z;let{segment:I,adaptation:y,representation:b,manifest:T,period:v}=f,_=yn(f),R=Qg(),k,x=[],M=0,P=!1,N={segment:I,type:y.type,language:y.language,isLive:T.isLive,periodStart:v.start,periodEnd:v.end,mimeType:b.mimeType,codecs:b.codecs[0],manifestPublishTime:T.publishTime},O={onProgress(q){var W;k===void 0&&q.totalSize!==void 0&&q.size<q.totalSize&&((W=i.onProgress)==null||W.call(i,{duration:q.duration,size:q.size,totalSize:q.totalSize,timestamp:K(),id:R}))},onNewChunk(q){g.onChunk(D(q,!0))}},F=d!==void 0?d.get(f):null;if(F!==null)return m.debug("SF: Found wanted segment in cache",_),g.onChunk(D(F,!1)),Promise.resolve();m.debug("SF: Beginning request",_),($=i.onRequestBegin)==null||$.call(i,{requestTimestamp:K(),id:R,content:f}),p.register(A);try{let q=await $s(f.representation.cdnMetadata,t,C,G({onRetry:L},o),p);if(q.resultType==="segment-loaded"){let W=q.resultData.responseData;d!==void 0&&d.add(f,q.resultData.responseData),g.onChunk(D(W,!1))}else q.resultType==="segment-created"&&g.onChunk(D(q.resultData,!1));m.debug("SF: Segment request ended with success",_),g.onAllChunksReceived(),q.resultType!=="segment-created"?(k=q.resultData,V()):k=null,p.isCancelled()||(j=i.onRequestEnd)==null||j.call(i,{id:R}),p.deregister(A)}catch(q){throw p.deregister(A),k=null,q instanceof Me?(m.debug("SF: Segment request aborted",_),q):(m.debug("SF: Segment request failed",_),(z=i.onRequestEnd)==null||z.call(i,{id:R}),xt(q))}function A(){var q;k===void 0&&(m.debug("SF: Segment request cancelled",_),k=null,(q=i.onRequestEnd)==null||q.call(i,{id:R}))}function C(q){return s.cmcdPayload=r==null?void 0:r.getCmcdDataForSegmentRequest(f),u(q,N,s,p,O)}function D(q,W){x.push(!1);let se=x.length-1;return function(de){let Se={data:q,isChunked:W};try{let Y=l(Se,N,de);return x[se]||(M=M!==void 0&&Y.segmentType==="media"&&Y.chunkInfos!==null&&Y.chunkInfos.duration!==void 0?M+Y.chunkInfos.duration:void 0,x[se]=!0,V()),Y}catch(Y){throw Oe(Y,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}}}function L(q){g.onRetry(xt(q))}function V(){var q;P||!E(k)&&k.size!==void 0&&k.requestDuration!==void 0&&x.length>0&&x.every(W=>W)&&(P=!0,(q=i.onMetrics)==null||q.call(i,{size:k.size,requestDuration:k.requestDuration,content:f,segmentDuration:M}))}}}function sf({maxRetry:n,lowLatencyMode:e,requestTimeout:t,connectionTimeout:r}){let{DEFAULT_MAX_REQUESTS_RETRY_ON_ERROR:i,DEFAULT_REQUEST_TIMEOUT:o,DEFAULT_CONNECTION_TIMEOUT:a,INITIAL_BACKOFF_DELAY_BASE:s,MAX_BACKOFF_DELAY_BASE:d}=U.getCurrent();return{maxRetry:n!=null?n:i,baseDelay:e?s.LOW_LATENCY:s.REGULAR,maxDelay:e?d.LOW_LATENCY:d.REGULAR,requestTimeout:t===void 0?o:t,connectionTimeout:r===void 0?a:r}}var ni=class extends re{constructor(e,t){super(),this._segmentFetcher=e,this._currentContentInfo=null,this.isMediaSegmentQueueInterrupted=t}getRequestedInitSegment(){var e,t,r;return(r=(t=(e=this._currentContentInfo)==null?void 0:e.initSegmentRequest)==null?void 0:t.segment)!=null?r:null}getRequestedMediaSegment(){var e,t,r;return(r=(t=(e=this._currentContentInfo)==null?void 0:e.mediaSegmentRequest)==null?void 0:t.segment)!=null?r:null}resetForContent(e,t){var a;(a=this._currentContentInfo)==null||a.currentCanceller.cancel();let r=new H({initSegment:null,segmentQueue:[]}),i=new B;i.signal.register(()=>{r.finish()});let o={content:e,downloadQueue:r,initSegmentInfoRef:t?new H(void 0):new H(null),currentCanceller:i,initSegmentRequest:null,mediaSegmentRequest:null,mediaSegmentAwaitingInitMetadata:null};return this._currentContentInfo=o,this.isMediaSegmentQueueInterrupted.onUpdate(s=>{s||(m.debug("SQ: Media segment can be loaded again, restarting queue.",e.adaptation.type),this._restartMediaSegmentDownloadingQueue(o))},{clearSignal:i.signal}),r.onUpdate(s=>{let{segmentQueue:d}=s;if(d.length>0&&d[0].segment.id===o.mediaSegmentAwaitingInitMetadata)return;let u=o.mediaSegmentRequest;if(d.length===0){if(u===null)return;m.debug("SQ: no more media segment to request. Cancelling queue.",e.adaptation.type),this._restartMediaSegmentDownloadingQueue(o);return}else if(u===null){m.debug("SQ: Media segments now need to be requested. Starting queue.",e.adaptation.type,d.length),this._restartMediaSegmentDownloadingQueue(o);return}else{let l=d[0];if(u.segment.id!==l.segment.id){m.debug("SQ: Next media segment changed, cancelling previous",e.adaptation.type),this._restartMediaSegmentDownloadingQueue(o);return}u.priority!==l.priority&&(m.debug("SQ: Priority of next media segment changed, updating",e.adaptation.type,u.priority,l.priority),this._segmentFetcher.updatePriority(u.request,l.priority));return}},{emitCurrentValue:!0,clearSignal:i.signal}),r.onUpdate(s=>{var u;let d=o.initSegmentRequest;if(s.initSegment!==null&&d!==null){s.initSegment.priority!==d.priority&&this._segmentFetcher.updatePriority(d.request,s.initSegment.priority);return}else if(((u=s.initSegment)==null?void 0:u.segment.id)===(d==null?void 0:d.segment.id))return;s.initSegment===null&&m.debug("SQ: no more init segment to request. Cancelling queue.",e.adaptation.type),this._restartInitSegmentDownloadingQueue(o,s.initSegment)},{emitCurrentValue:!0,clearSignal:i.signal}),r}stop(){var e;(e=this._currentContentInfo)==null||e.currentCanceller.cancel(),this._currentContentInfo=null}_restartMediaSegmentDownloadingQueue(e){e.mediaSegmentRequest!==null&&e.mediaSegmentRequest.canceller.cancel();let{downloadQueue:t,content:r,initSegmentInfoRef:i,currentCanceller:o}=e,a=()=>{var v;if(this.isMediaSegmentQueueInterrupted.getValue()){m.debug("SQ: Segment fetching postponed because it cannot stream now.");return}let{segmentQueue:s}=t.getValue(),d=s[0];if(o!==null&&o.isUsed()){e.mediaSegmentRequest=null;return}if(d===void 0){e.mediaSegmentRequest=null,this.trigger("emptyQueue",null);return}let u=new B,l=o===null?X:u.linkToSignal(o.signal),{segment:c,priority:f}=d,g=G({segment:c,nextSegment:(v=s[1])==null?void 0:v.segment},r),p=!1,I=!1;u.signal.register(()=>{e.mediaSegmentRequest=null,!p&&(e.mediaSegmentAwaitingInitMetadata===c.id&&(e.mediaSegmentAwaitingInitMetadata=null),p=!0,I=!1)});let y=_=>{ee(_.segmentType==="media","Should have loaded a media segment."),this.trigger("parsedMediaSegment",G({},_,{segment:c}))},b=()=>{let _=t.getValue().segmentQueue;if(_.length===0){p=!0,this.trigger("emptyQueue",null);return}else _[0].segment.id===c.id&&_.shift();p=!0,a()},T=this._segmentFetcher.createRequest(g,f,{onRetry:_=>{this.trigger("requestRetry",{segment:c,error:_})},beforeInterrupted(){m.info("SQ: segment request interrupted temporarly.",c.id,c.time)},onChunk:_=>{let R=i.getValue();R!==void 0?y(_(R!=null?R:void 0)):(I=!0,i.waitUntilDefined(k=>{y(_(k!=null?k:void 0))},{clearSignal:u.signal}))},onAllChunksReceived:()=>{I?(e.mediaSegmentAwaitingInitMetadata=c.id,i.waitUntilDefined(()=>{e.mediaSegmentAwaitingInitMetadata=null,I=!1,this.trigger("fullyLoadedSegment",c)},{clearSignal:u.signal})):this.trigger("fullyLoadedSegment",c)},beforeEnded:()=>{l(),e.mediaSegmentRequest=null,I?i.waitUntilDefined(b,{clearSignal:u.signal}):b()}},u.signal);T.catch(_=>{l(),p||(p=!0,this.stop(),this.trigger("error",_))}),e.mediaSegmentRequest={segment:c,priority:f,request:T,canceller:u}};a()}_restartInitSegmentDownloadingQueue(e,t){let{content:r,initSegmentInfoRef:i}=e;if(e.initSegmentRequest!==null&&e.initSegmentRequest.canceller.cancel(),t===null)return;let o=new B,a=e.currentCanceller===null?X:o.linkToSignal(e.currentCanceller.signal),{segment:s,priority:d}=t,u=G({segment:s,nextSegment:void 0},r),l=!1,c=this._segmentFetcher.createRequest(u,d,{onRetry:f=>{this.trigger("requestRetry",{segment:s,error:f})},beforeInterrupted:()=>{m.info("SQ: init segment request interrupted temporarly.",s.id)},beforeEnded:()=>{a(),e.initSegmentRequest=null,l=!0},onChunk:f=>{var p;let g=f(void 0);ee(g.segmentType==="init","Should have loaded an init segment."),this.trigger("parsedInitSegment",G({},g,{segment:s})),g.segmentType==="init"&&i.setValue((p=g.initTimescale)!=null?p:null)},onAllChunksReceived:()=>{this.trigger("fullyLoadedSegment",s)}},o.signal);c.catch(f=>{a(),l||(l=!0,this.stop(),this.trigger("error",f))}),o.signal.register(()=>{e.initSegmentRequest=null,!l&&(l=!0)}),e.initSegmentRequest={segment:s,priority:d,request:c,canceller:o}}};var ii=class{constructor({prioritySteps:e}){if(this._minPendingPriority=null,this._waitingQueue=[],this._pendingTasks=[],this._prioritySteps=e,this._prioritySteps.high>=this._prioritySteps.low)throw new Error("TP: the max high level priority should be given a lowerpriority number than the min low priority.")}create(e,t,r,i){let o;return at(i,(a,s)=>(o={hasEnded:!1,priority:t,trigger:()=>{if(o.hasEnded)return;let u=()=>{g(),this._endTask(o)},l=p=>{r.beforeEnded(),u(),a(p)},c=p=>{u(),s(p)},f=new B,g=f.linkToSignal(i);o.interrupter=f,f.signal.register(()=>{o.interrupter=null,i.isCancelled()||r.beforeInterrupted()}),this._minPendingPriority=this._minPendingPriority===null?o.priority:Math.min(this._minPendingPriority,o.priority),this._pendingTasks.push(o),o.taskFn(f.signal).then(l).catch(p=>{!i.isCancelled()&&f.isUsed()&&p instanceof Me||c(p)})},taskFn:e,interrupter:null},this._canBeStartedNow(o)?(o.trigger(),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks()):this._waitingQueue.push(o),()=>this._endTask(o)))}_endTask(e){e.hasEnded=!0;let t=ri(e.taskFn,this._waitingQueue);if(t>=0)this._waitingQueue.splice(t,1);else{let r=ri(e.taskFn,this._pendingTasks);if(r<0)return;this._pendingTasks.splice(r,1),this._pendingTasks.length>0?this._minPendingPriority===e.priority&&(this._minPendingPriority=Math.min(...this._pendingTasks.map(i=>i.priority))):this._minPendingPriority=null,this._loopThroughWaitingQueue()}}updatePriority(e,t){let r=ri(e,this._waitingQueue);if(r>=0){let s=this._waitingQueue[r];if(s.priority===t||(s.priority=t,!this._canBeStartedNow(s)))return;this._findAndRunWaitingQueueTask(r),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks();return}let i=ri(e,this._pendingTasks);if(i<0){m.warn("TP: request to update the priority of a non-existent task");return}let o=this._pendingTasks[i];if(o.priority===t)return;let a=o.priority;o.priority=t,this._minPendingPriority===null||t<this._minPendingPriority?this._minPendingPriority=t:this._minPendingPriority===a&&(this._pendingTasks.length===1?this._minPendingPriority=t:this._minPendingPriority=Math.min(...this._pendingTasks.map(s=>s.priority)),this._loopThroughWaitingQueue()),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks()}_loopThroughWaitingQueue(){let e=this._waitingQueue.reduce((t,r)=>t===null||t>r.priority?r.priority:t,null);if(!(e===null||this._minPendingPriority!==null&&this._minPendingPriority<e))for(let t=0;t<this._waitingQueue.length;t++){let r=this._minPendingPriority===null?e:Math.min(this._minPendingPriority,e);this._waitingQueue[t].priority<=r&&(this._findAndRunWaitingQueueTask(t),t--)}}_interruptCancellableTasks(){for(let e of this._pendingTasks)if(e.priority>=this._prioritySteps.low)return this._interruptPendingTask(e),this._interruptCancellableTasks()}_findAndRunWaitingQueueTask(e){return e>=this._waitingQueue.length||e<0?(m.warn("TP : Tried to start a non existing task"),!1):(this._waitingQueue.splice(e,1)[0].trigger(),!0)}_interruptPendingTask(e){var r;let t=ri(e.taskFn,this._pendingTasks);if(t<0){m.warn("TP: Interrupting a non-existent pending task. Aborting...");return}this._pendingTasks.splice(t,1),this._waitingQueue.push(e),this._pendingTasks.length===0?this._minPendingPriority=null:this._minPendingPriority===e.priority&&(this._minPendingPriority=Math.min(...this._pendingTasks.map(i=>i.priority))),(r=e.interrupter)==null||r.cancel()}_canBeStartedNow(e){return this._minPendingPriority===null||e.priority<=this._minPendingPriority}_isRunningHighPriorityTasks(){return this._minPendingPriority!==null&&this._minPendingPriority<=this._prioritySteps.high}};function ri(n,e){return he(e,t=>t.taskFn===n)}var oi=class{constructor(e,t,r,i){let o=new ti(i),{MIN_CANCELABLE_PRIORITY:a,MAX_HIGH_PRIORITY_LEVEL:s}=U.getCurrent();this._transport=e,this._prioritizer=new ii({prioritySteps:{high:s,low:a}}),this._cdnPrioritizer=o,this._backoffOptions=r,this._cmcdDataBuilder=t}createSegmentQueue(e,t,r){let i=sf(this._backoffOptions),o=this._transport[e],a=ed({bufferType:e,pipeline:o,cdnPrioritizer:this._cdnPrioritizer,cmcdDataBuilder:this._cmcdDataBuilder,eventListeners:t,requestOptions:i}),s=Zs(this._prioritizer,a);return new ni(s,r)}};var td=oi;var _n=class{constructor(e){this._array=[],this._sortingFn=e}add(...e){e.sort(this._sortingFn);let t=0;for(let r=0;r<e.length;r++){let i=e[r],o=!1;for(;!o&&t<this._array.length;)this._sortingFn(i,this._array[t])<0?(this._array.splice(t,0,i),o=!0):t++;o||this._array.push(i)}}length(){return this._array.length}get(e){if(e<0||e>=this._array.length)throw new Error("Invalid index.");return this._array[e]}toArray(){return this._array.slice()}findFirst(e){return Z(this._array,e)}has(e){return Q(this._array,e)}removeElement(e){let t=this._array.indexOf(e);if(t>=0)return this._array.splice(t,1),t}head(){return this._array[0]}last(){return this._array[this._array.length-1]}shift(){return this._array.shift()}pop(){return this._array.pop()}};var ai=class extends re{constructor(e,t,r){super(),this._canceller=new B,this._manifest=e,this._activeStreams=new Map,this._allBufferTypes=r,this._lastCurrentPeriodId=null;let i=new nd(e);this._maximumPositionCalculator=i;let o=this._canceller.signal;t.listen(({position:a})=>{let s=a.getWanted();if(s<e.getMinimumSafePosition()){let d=new te("MEDIA_TIME_BEFORE_MANIFEST","The current position is behind the earliest time announced in the Manifest.");this.trigger("warning",d)}else if(s>i.getMaximumAvailablePosition()){let d=new te("MEDIA_TIME_AFTER_MANIFEST","The current position is after the latest time announced in the Manifest.");this.trigger("warning",d)}},{includeLastObservation:!0,clearSignal:o}),e.addEventListener("manifestUpdate",()=>{this.trigger("endingPositionChange",this._getManifestEndTime()),!o.isCancelled()&&this._checkEndOfStream()},o)}getCurrentEndingTime(){return this._getManifestEndTime()}onAdaptationChange(e,t,r){if(this._manifest.isLastPeriodKnown){let i=this._manifest.periods[this._manifest.periods.length-1];if(t.id===(i==null?void 0:i.id)&&(e==="audio"||e==="video")){e==="audio"?this._maximumPositionCalculator.updateLastAudioAdaptation(r):this._maximumPositionCalculator.updateLastVideoAdaptation(r);let o=this._maximumPositionCalculator.getEndingPosition(),a=o!==void 0?{isEnd:!0,endingPosition:o}:{isEnd:!1,endingPosition:this._maximumPositionCalculator.getMaximumAvailablePosition()};this.trigger("endingPositionChange",a)}}this._canceller.isUsed()||r===null&&this._addActivelyLoadedPeriod(t,e)}onRepresentationChange(e,t){this._addActivelyLoadedPeriod(t,e)}onPeriodCleared(e,t){this._removeActivelyLoadedPeriod(t,e)}onLastSegmentFinishedLoading(e){let t=this._lazilyCreateActiveStreamInfo(e);t.hasFinishedLoadingLastPeriod||(t.hasFinishedLoadingLastPeriod=!0,this._checkEndOfStream())}onLastSegmentLoadingResume(e){let t=this._lazilyCreateActiveStreamInfo(e);t.hasFinishedLoadingLastPeriod&&(t.hasFinishedLoadingLastPeriod=!1,this._checkEndOfStream())}dispose(){this.removeEventListener(),this._canceller.cancel()}_addActivelyLoadedPeriod(e,t){let r=this._lazilyCreateActiveStreamInfo(t);r.activePeriods.has(e)||(r.activePeriods.add(e),this._checkCurrentPeriod())}_removeActivelyLoadedPeriod(e,t){let r=this._activeStreams.get(t);r!==void 0&&r.activePeriods.has(e)&&(r.activePeriods.removeElement(e),this._checkCurrentPeriod())}_checkCurrentPeriod(){if(this._allBufferTypes.length===0)return;let e=this._activeStreams.get(this._allBufferTypes[0]);if(e!==void 0)for(let t of e.activePeriods.toArray()){let r=!0;for(let i of this._allBufferTypes){let o=this._activeStreams.get(i);if(o===void 0)return;if(!o.activePeriods.toArray().some(d=>d.id===t.id)){r=!1;break}}if(r){this._lastCurrentPeriodId!==t.id&&(this._lastCurrentPeriodId=t.id,this.trigger("periodChange",t));return}}}_getManifestEndTime(){let e=this._maximumPositionCalculator.getEndingPosition();return e!==void 0?{isEnd:!0,endingPosition:e}:{isEnd:!1,endingPosition:this._maximumPositionCalculator.getMaximumAvailablePosition()}}_lazilyCreateActiveStreamInfo(e){let t=this._activeStreams.get(e);return t===void 0&&(t={activePeriods:new _n((r,i)=>r.start-i.start),hasFinishedLoadingLastPeriod:!1},this._activeStreams.set(e,t)),t}_checkEndOfStream(){if(!this._manifest.isLastPeriodKnown)return;this._allBufferTypes.every(t=>{let r=this._activeStreams.get(t);return r!==void 0&&r.hasFinishedLoadingLastPeriod})?this.trigger("endOfStream",null):this.trigger("resumeStream",null)}},nd=class{constructor(e){this._manifest=e,this._lastAudioAdaptation=void 0,this._lastVideoAdaptation=void 0}updateLastAudioAdaptation(e){this._lastAudioAdaptation=e}updateLastVideoAdaptation(e){this._lastVideoAdaptation=e}getMaximumAvailablePosition(){if(this._manifest.isDynamic)return this._manifest.getMaximumSafePosition();if(this._lastVideoAdaptation===void 0||this._lastAudioAdaptation===void 0)return this._manifest.getMaximumSafePosition();if(this._lastAudioAdaptation===null){if(this._lastVideoAdaptation===null)return this._manifest.getMaximumSafePosition();{let e=Zo(this._lastVideoAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}}else if(this._lastVideoAdaptation===null){let e=Zo(this._lastAudioAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}else{let e=Zo(this._lastAudioAdaptation),t=Zo(this._lastVideoAdaptation);return typeof e!="number"||typeof t!="number"?this._manifest.getMaximumSafePosition():Math.min(e,t)}}getEndingPosition(){var e,t;if(!this._manifest.isDynamic)return this.getMaximumAvailablePosition();if(!(this._lastVideoAdaptation===void 0||this._lastAudioAdaptation===void 0)){if(this._lastAudioAdaptation===null)return this._lastVideoAdaptation===null?void 0:(e=Jo(this._lastVideoAdaptation))!=null?e:void 0;if(this._lastVideoAdaptation===null)return(t=Jo(this._lastAudioAdaptation))!=null?t:void 0;{let r=Jo(this._lastAudioAdaptation),i=Jo(this._lastVideoAdaptation);return typeof r!="number"||typeof i!="number"?void 0:Math.min(r,i)}}}};function Zo(n){let{representations:e}=n,t=null,r;for(let i of e)if(i.index!==r){r=i.index;let o=i.index.getLastAvailablePosition();if(o===void 0)return;o!==null&&(t=E(t)?o:Math.min(t,o))}return t}function Jo(n){let{representations:e}=n,t=null,r;for(let i of e)if(i.index!==r){r=i.index;let o=i.index.getEnd();if(o===void 0)return;o!==null&&(t=E(t)?o:Math.min(t,o))}return t}function rd(n,e,t,r,i,o){o.register(()=>{e.interruptDurationSetting()});let a=new ai(n,t,r.getBufferTypes());o.register(()=>{a.dispose()}),a.addEventListener("warning",d=>i.onWarning(d)),a.addEventListener("periodChange",d=>i.onPeriodChanged(d)),a.addEventListener("endingPositionChange",d=>{e.setDuration(d.endingPosition,d.isEnd)}),a.addEventListener("endOfStream",()=>{m.debug("Init: end-of-stream order received."),e.maintainEndOfStream()}),a.addEventListener("resumeStream",()=>{e.stopEndOfStream()});let s=a.getCurrentEndingTime();return e.setDuration(s.endingPosition,s.isEnd),a}var si=class{constructor(e){this._segmentSinksStore=e,this._currentFreezeTimestamp=null}needToReload(e){let{readyState:t,rebuffering:r,freezing:i}=e;if((e.bufferGap!==void 0&&isFinite(e.bufferGap)?e.bufferGap:0)<6||r===null&&i===null||t>1)return this._currentFreezeTimestamp=null,!1;let a=K();this._currentFreezeTimestamp===null&&(this._currentFreezeTimestamp=a);let s=r!==null&&a-r.timestamp>4e3,d=i!==null&&a-i.timestamp>4e3;if((s||d)&&K()-this._currentFreezeTimestamp>4e3){let u=this._segmentSinksStore.getStatus("audio"),l=this._segmentSinksStore.getStatus("video"),c=!0,f=!0;for(let g of[u,l])if(g.type==="initialized")for(let p of g.value.getLastKnownInventory()){let{representation:I}=p.infos;if(I.decipherable===!1)return m.warn("Init: we have undecipherable segments left in the buffer, reloading"),this._currentFreezeTimestamp=null,!0;I.contentProtections!==void 0&&(f=!1,I.decipherable!==!0&&(c=!1))}if(!f&&c)return m.warn("Init: we are frozen despite only having decipherable segments left in the buffer, reloading"),this._currentFreezeTimestamp=null,!0}return!1}};function ea({segmentSink:n,playbackObserver:e,maxBufferBehind:t,maxBufferAhead:r},i){let o,a=[];e.listen(d=>{o=d.position.getWanted(),a=d.buffered[n.bufferType],s()},{includeLastObservation:!0,clearSignal:i});function s(){a!==null&&Xg(n,o,a,t.getValue(),r.getValue(),i).catch(d=>{let u=d instanceof Error?d.message:"Unknown error";m.error("Could not run BufferGarbageCollector:",u)})}t.onUpdate(s,{clearSignal:i}),r.onUpdate(s,{clearSignal:i}),s()}async function Xg(n,e,t,r,i,o){if(!isFinite(r)&&!isFinite(i))return Promise.resolve();let a=[],{innerRange:s,outerRanges:d}=Ql(t,e),u=()=>{if(isFinite(r)){for(let c of d)e-r>=c.end?a.push(c):e>=c.end&&e-r>c.start&&e-r<c.end&&a.push({start:c.start,end:e-r});E(s)||e-r>s.start&&a.push({start:s.start,end:e-r})}},l=()=>{if(isFinite(i)){for(let c of d)e+i<=c.start?a.push(c):e<=c.start&&e+i<c.end&&e+i>c.start&&a.push({start:e+i,end:c.end});E(s)||e+i<s.end&&a.push({start:e+i,end:s.end})}};u(),l();for(let c of a)if(c.start<c.end){if(m.debug("GC: cleaning range from SegmentSink",c.start,c.end),o.cancellationError!==null)throw o.cancellationError;await n.removeBuffer(c.start,c.end)}}var di=class{constructor(e,t){this._history=[],this._lifetime=e,this._maxHistoryLength=t}addBufferedSegment(e,t){let r=K();this._history.push({date:r,buffered:t,context:e}),this._cleanHistory(r)}getHistoryFor(e){return this._history.filter(t=>kt(t.context,e))}_cleanHistory(e){let t=e-this._lifetime,r=0;for(let i of this._history)if(i.date<t)r++;else break;if(r>0&&(this._history=this._history.splice(r)),this._history.length>this._maxHistoryLength){let i=this._history.length-this._maxHistoryLength;this._history=this._history.splice(i)}}};var ui=class{constructor(){let{BUFFERED_HISTORY_RETENTION_TIME:e,BUFFERED_HISTORY_MAXIMUM_ENTRIES:t}=U.getCurrent();this._inventory=[],this._bufferedHistory=new di(e,t)}reset(){this._inventory.length=0}synchronizeBuffered(e){var d,u,l,c,f,g,p;let t=this._inventory,r=0,i=t[0],{MINIMUM_SEGMENT_SIZE:o}=U.getCurrent(),a=i==null?void 0:i.infos.adaptation.type;if(m.hasLevel("DEBUG")){let I=e.map(y=>`${y.start}-${y.end}`).join(",");m.debug(`SI: synchronizing ${a!=null?a:"unknown"} buffered ranges:`,I)}let s=e.length;for(let I=0;I<s;I++){if(i===void 0)return;let y=e[I].start,b=e[I].end;if(b-y<o){m.warn("SI: skipped range when synchronizing because it was too small",a,y,b);continue}let T=r;for(;i!==void 0&&((d=i.bufferedEnd)!=null?d:i.end)-y<o;)i=t[++r];let v=null,_=r-T;if(_>0){let k=t[T+_-1];v={end:(u=k.bufferedEnd)!=null?u:k.end,precizeEnd:k.precizeEnd},m.debug(`SI: ${_} segments GCed.`,a);let x=t.splice(T,_);for(let M of x)M.bufferedStart===void 0&&M.bufferedEnd===void 0&&M.status!==2&&this._bufferedHistory.addBufferedSegment(M.infos,null);r=T}if(i===void 0)return;if(b-((l=i.bufferedStart)!=null?l:i.start)>=o){if(Zg(i,y,v,a),r===t.length-1){uf(i,b,a);return}i=t[++r];let k=(c=i.bufferedStart)!=null?c:i.start,x=(f=i.bufferedEnd)!=null?f:i.end,M=I<s-1?e[I+1].start:void 0;for(;i!==void 0&&!(b<k||b-k<o&&x-b>=o||M!==void 0&&b-k<x-M);){let P=t[r-1];P.bufferedEnd===void 0&&(i.precizeStart?P.bufferedEnd=i.start:P.infos.segment.complete?P.bufferedEnd=P.end:P.bufferedEnd=i.start,m.debug("SI: calculating buffered end of contiguous segment",a,P.bufferedEnd,P.end)),i.bufferedStart=P.bufferedEnd,i=t[++r],i!==void 0&&(k=(g=i.bufferedStart)!=null?g:i.start,x=(p=i.bufferedEnd)!=null?p:i.end)}}let R=t[r-1];R!==void 0&&uf(R,b,a)}if(!E(i)){let{SEGMENT_SYNCHRONIZATION_DELAY:I}=U.getCurrent(),y=K();for(let b=r;b<t.length;b++){let T=t[b];y-T.insertionTs>=I&&(m.debug("SI: A segment at the end has been completely GCed",a,`${T.start}-${T.end}`),T.bufferedStart===void 0&&T.bufferedEnd===void 0&&T.status!==2&&this._bufferedHistory.addBufferedSegment(T.infos,null),t.splice(b,1),b--)}}a!==void 0&&m.hasLevel("DEBUG")&&m.debug(`SI: current ${a} inventory timeline:
|
|
2
|
+
`+Jg(this._inventory))}insertChunk({period:e,adaptation:t,representation:r,segment:i,chunkSize:o,start:a,end:s},d,u){if(i.isInit)return;let l=t.type;if(a>=s){m.warn("SI: Invalid chunked inserted: starts before it ends",l,a,s);return}let c=this._inventory,f={status:d?0:2,insertionTs:u,chunkSize:o,splitted:!1,start:a,end:s,precizeStart:!1,precizeEnd:!1,bufferedStart:void 0,bufferedEnd:void 0,infos:{segment:i,period:e,adaptation:t,representation:r}};for(let p=c.length-1;p>=0;p--){let I=c[p];if(I.start<=a)if(I.end<=a){for(m.debug("SI: Pushing segment strictly after previous one.",l,a,I.end),this._inventory.splice(p+1,0,f),p+=2;p<c.length&&c[p].start<f.end;){if(c[p].end>f.end){m.debug("SI: Segment pushed updates the start of the next one",l,f.end,c[p].start),c[p].start=f.end,c[p].bufferedStart=void 0,c[p].precizeStart=c[p].precizeStart&&f.precizeEnd;return}m.debug("SI: Segment pushed removes the next one",l,a,s,c[p].start,c[p].end),c.splice(p,1)}return}else if(I.start===a)if(I.end<=s){for(m.debug("SI: Segment pushed replace another one",l,a,s,I.end),this._inventory.splice(p,1,f),p+=1;p<c.length&&c[p].start<f.end;){if(c[p].end>f.end){m.debug("SI: Segment pushed updates the start of the next one",l,f.end,c[p].start),c[p].start=f.end,c[p].bufferedStart=void 0,c[p].precizeStart=c[p].precizeStart&&f.precizeEnd;return}m.debug("SI: Segment pushed removes the next one",l,a,s,c[p].start,c[p].end),c.splice(p,1)}return}else{m.debug("SI: Segment pushed ends before another with the same start",l,a,s,I.end),c.splice(p,0,f),I.start=f.end,I.bufferedStart=void 0,I.precizeStart=I.precizeStart&&f.precizeEnd;return}else if(I.end<=f.end){for(m.debug("SI: Segment pushed updates end of previous one",l,a,s,I.start,I.end),this._inventory.splice(p+1,0,f),I.end=f.start,I.bufferedEnd=void 0,I.precizeEnd=I.precizeEnd&&f.precizeStart,p+=2;p<c.length&&c[p].start<f.end;){if(c[p].end>f.end){m.debug("SI: Segment pushed updates the start of the next one",l,f.end,c[p].start),c[p].start=f.end,c[p].bufferedStart=void 0,c[p].precizeStart=c[p].precizeStart&&f.precizeEnd;return}m.debug("SI: Segment pushed removes the next one",l,a,s,c[p].start,c[p].end),c.splice(p,1)}return}else{m.warn("SI: Segment pushed is contained in a previous one",l,a,s,I.start,I.end);let y={status:I.status,insertionTs:I.insertionTs,chunkSize:I.chunkSize,splitted:!0,start:f.end,end:I.end,precizeStart:I.precizeStart&&I.precizeEnd&&f.precizeEnd,precizeEnd:I.precizeEnd,bufferedStart:void 0,bufferedEnd:I.end,infos:I.infos};I.end=f.start,I.splitted=!0,I.bufferedEnd=void 0,I.precizeEnd=I.precizeEnd&&f.precizeStart,c.splice(p+1,0,f),c.splice(p+2,0,y);return}}let g=this._inventory[0];if(g===void 0){m.debug("SI: first segment pushed",l,a,s),this._inventory.push(f);return}if(g.start>=s)m.debug("SI: Segment pushed comes before all previous ones",l,a,s,g.start),this._inventory.splice(0,0,f);else if(g.end<=s){for(m.debug("SI: Segment pushed starts before and completely recovers the previous first one",l,a,s,g.start,g.end),this._inventory.splice(0,1,f);c.length>1&&c[1].start<f.end;){if(c[1].end>f.end){m.debug("SI: Segment pushed updates the start of the next one",l,f.end,c[1].start),c[1].start=f.end,c[1].bufferedStart=void 0,c[1].precizeStart=f.precizeEnd;return}m.debug("SI: Segment pushed removes the next one",l,a,s,c[1].start,c[1].end),c.splice(1,1)}return}else{m.debug("SI: Segment pushed start of the next one",l,a,s,g.start,g.end),g.start=s,g.bufferedStart=void 0,g.precizeStart=f.precizeEnd,this._inventory.splice(0,0,f);return}}completeSegment(e){if(e.segment.isInit)return;let t=this._inventory,r=[];for(let i=0;i<t.length;i++)if(kt(t[i].infos,e)){let o=!1;r.length>0&&(o=!0,r.length===1&&(m.warn("SI: Completed Segment is splitted.",e.segment.id,e.segment.time,e.segment.end),r[0].splitted=!0));let a=i,s=t[i].chunkSize;for(i+=1;i<t.length&&kt(t[i].infos,e);){let f=t[i].chunkSize;s!==void 0&&f!==void 0&&(s+=f),i++}let d=i-1,u=d-a,l=t[d].end,c=t[d].bufferedEnd;u>0&&(this._inventory.splice(a+1,u),i-=u),this._inventory[a].status===0&&(this._inventory[a].status=1),this._inventory[a].chunkSize=s,this._inventory[a].end=l,this._inventory[a].bufferedEnd=c,this._inventory[a].splitted=o,r.push(this._inventory[a])}if(r.length===0)m.warn("SI: Completed Segment not found",e.segment.id,e.segment.time);else for(let i of r)i.bufferedStart!==void 0&&i.bufferedEnd!==void 0?i.status!==2&&this._bufferedHistory.addBufferedSegment(i.infos,{start:i.bufferedStart,end:i.bufferedEnd}):m.debug("SI: buffered range not known after sync. Skipping history.",i.start,i.end)}getInventory(){return this._inventory}getHistoryFor(e){return this._bufferedHistory.getHistoryFor(e)}};function id(n){if(n.bufferedStart===void 0||n.status!==1)return!1;let{start:e,end:t}=n,r=t-e,{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:i,MAX_MANIFEST_BUFFERED_DURATION_DIFFERENCE:o}=U.getCurrent();return Math.abs(e-n.bufferedStart)<=i&&(n.bufferedEnd===void 0||n.bufferedEnd>n.bufferedStart&&Math.abs(n.bufferedEnd-n.bufferedStart-r)<=Math.min(o,r/3))}function df(n){if(n.bufferedEnd===void 0||!n.infos.segment.complete||n.status!==1)return!1;let{start:e,end:t}=n,r=t-e,{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:i,MAX_MANIFEST_BUFFERED_DURATION_DIFFERENCE:o}=U.getCurrent();return Math.abs(t-n.bufferedEnd)<=i&&n.bufferedStart!==void 0&&n.bufferedEnd>n.bufferedStart&&Math.abs(n.bufferedEnd-n.bufferedStart-r)<=Math.min(o,r/3)}function Zg(n,e,t,r){let{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:i,MISSING_DATA_TRIGGER_SYNC_DELAY:o,SEGMENT_SYNCHRONIZATION_DELAY:a}=U.getCurrent();if(n.bufferedStart!==void 0)n.bufferedStart<e&&(m.debug("SI: Segment partially GCed at the start",r,n.bufferedStart,e),n.bufferedStart=e),!n.precizeStart&&id(n)&&(n.start=n.bufferedStart,n.precizeStart=!0);else if(n.precizeStart)m.debug("SI: buffered start is precize start",r,n.start),n.bufferedStart=n.start;else if(t!==null&&t.end>e&&(t.precizeEnd||n.start-t.end<=i))m.debug("SI: buffered start is end of previous segment",r,e,n.start,t.end),n.bufferedStart=t.end,id(n)&&(n.start=t.end,n.precizeStart=!0);else if(n.start-e<=i){let s=K();if(n.start-e>=o&&s-n.insertionTs<a){m.debug("SI: Ignored bufferedStart synchronization",r,e,n.start,s-n.insertionTs);return}m.debug("SI: found true buffered start",r,e,n.start),n.bufferedStart=e,id(n)&&(n.start=e,n.precizeStart=!0)}else if(e<n.start)m.debug("SI: range start too far from expected start",r,e,n.start),n.bufferedStart=n.start;else{let s=K();if(n.start-e>=o&&s-n.insertionTs<a){m.debug("SI: Ignored bufferedStart synchronization",r,e,n.start,s-n.insertionTs);return}m.debug("SI: Segment appears immediately garbage collected at the start",r,e,n.start),n.bufferedStart=e}}function uf(n,e,t){let{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:r,MISSING_DATA_TRIGGER_SYNC_DELAY:i,SEGMENT_SYNCHRONIZATION_DELAY:o}=U.getCurrent();if(n.bufferedEnd!==void 0)n.bufferedEnd>e&&(m.debug("SI: Segment partially GCed at the end",t,n.bufferedEnd,e),n.bufferedEnd=e),!n.precizeEnd&&e-n.end<=r&&df(n)&&(n.precizeEnd=!0,n.end=e);else if(n.precizeEnd)m.debug("SI: buffered end is precize end",t,n.end),n.bufferedEnd=n.end;else if(e-n.end<=r||!n.infos.segment.complete){let a=K();if(e-n.end>=i&&a-n.insertionTs<o){m.debug("SI: Ignored bufferedEnd synchronization",t,e,n.end,a-n.insertionTs);return}m.debug("SI: found true buffered end",t,e,n.end),n.bufferedEnd=e,df(n)&&(n.end=e,n.precizeEnd=!0)}else if(e>n.end)m.debug("SI: range end too far from expected end",t,e,n.end),n.bufferedEnd=n.end;else{let a=K();if(e-n.end>=i&&a-n.insertionTs<o){m.debug("SI: Ignored bufferedEnd synchronization",t,e,n.end,a-n.insertionTs);return}m.debug("SI: Segment appears immediately garbage collected at the end",t,n.bufferedEnd,e),n.bufferedEnd=e}}function Jg(n){let e=.016666666666666666,t={},r=[],i=null,o=null;function a(d){let u=String.fromCharCode(r.length+65);return r.push({letter:u,periodId:d.period.id,representationId:d.representation.id,bitrate:d.representation.bitrate}),u}let s="";for(let d of n)if(d.bufferedStart!==void 0&&d.bufferedEnd!==void 0){let u=d.infos.period.id,l=d.infos.representation.id,c=t[u],f;if(c===void 0)f=a(d.infos),t[u]={[l]:f};else{let g=c[l];g===void 0?(f=a(d.infos),c[l]=f):f=g}i===null?s+=`${d.bufferedStart.toFixed(2)}|${f}|`:o===f?i.bufferedEnd+e<d.bufferedStart&&(s+=`${i.bufferedEnd.toFixed(2)} ~ ${d.bufferedStart.toFixed(2)}|${f}|`):s+=`${i.bufferedEnd.toFixed(2)} ~ ${d.bufferedStart.toFixed(2)}|${f}|`,i=d,o=f}return i!==null&&(s+=String(i.end.toFixed(2))),r.forEach(d=>{var u;s+=`
|
|
3
|
+
[${d.letter}] P: ${d.periodId} || R: ${d.representationId}(${(u=d.bitrate)!=null?u:"unknown bitrate"})`}),s}function Gn(n,e){for(let t=0;t<n.length;t++)if(n[t].infos.period.start>=e.start)return t>0?n[t-1]:null;return n.length>0?n[n.length-1]:null}function qn(n,e){for(let t of n)if(t.infos.period.start>e.start)return t;return null}var lf=ui;var jn=class{constructor(){this._segmentInventory=new lf}synchronizeInventory(e){this._segmentInventory.synchronizeBuffered(e)}getLastKnownInventory(){return this._segmentInventory.getInventory()}getSegmentHistory(e){return this._segmentInventory.getHistoryFor(e)}};var li=class extends jn{constructor(e,t,r){super(),m.info("AVSB: calling `mediaSource.addSourceBuffer`",t);let i=r.addSourceBuffer(e,t);this.bufferType=e,this._sourceBuffer=i,this._lastInitSegmentUniqueId=null,this.codec=t,this._initSegmentsMap=new Map,this._pendingOperations=[]}declareInitSegment(e,t){cf(t),this._initSegmentsMap.set(e,t)}freeInitSegment(e){this._initSegmentsMap.delete(e)}async pushChunk(e){cf(e.data.chunk),m.debug("AVSB: receiving order to push data to the SourceBuffer",this.bufferType,yn(e.inventoryInfos));let t=this._getActualDataToPush(e.data);t.length===0&&t.push(new Uint8Array);let r=Promise.all(t.map(a=>{let{codec:s,timestampOffset:d,appendWindow:u}=e.data;return m.debug("AVSB: pushing segment",this.bufferType,yn(e.inventoryInfos)),this._sourceBuffer.appendBuffer(a,{codec:s,timestampOffset:d,appendWindow:u})}));this._addToOperationQueue(r,{type:0,value:e});let i;try{i=await r}catch(a){throw this._segmentInventory.insertChunk(e.inventoryInfos,!1,K()),a}e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,K());let o=i[i.length-1];return this._segmentInventory.synchronizeBuffered(o),o}async removeBuffer(e,t){m.debug("AVSB: receiving order to remove data from the SourceBuffer",this.bufferType,e,t);let r=this._sourceBuffer.remove(e,t);this._addToOperationQueue(r,{type:1,value:{start:e,end:t}});let i=await r;return this._segmentInventory.synchronizeBuffered(i),i}async signalSegmentComplete(e){if(this._pendingOperations.length>0){let{promise:t}=this._pendingOperations[this._pendingOperations.length-1];this._addToOperationQueue(t,{type:2,value:e});try{await t}catch(r){}}this._segmentInventory.completeSegment(e)}getPendingOperations(){return this._pendingOperations.map(e=>e.operation)}dispose(){try{m.debug("AVSB: Calling `dispose` on the SourceBufferInterface"),this._sourceBuffer.dispose()}catch(e){m.debug(`AVSB: Failed to dispose a ${this.bufferType} SourceBufferInterface:`,e instanceof Error?e:"")}}_getActualDataToPush(e){let t=[];if(e.initSegmentUniqueId!==null&&!this._isLastInitSegment(e.initSegmentUniqueId)){let r=this._initSegmentsMap.get(e.initSegmentUniqueId);if(r===void 0)throw new Error("Invalid initialization segment uniqueId");let i=new ArrayBuffer(r.byteLength),o=new Uint8Array(i);o.set(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer)),r=o,t.push(r),this._lastInitSegmentUniqueId=e.initSegmentUniqueId}return e.chunk!==null&&t.push(e.chunk),t}_isLastInitSegment(e){return this._lastInitSegmentUniqueId===null?!1:this._lastInitSegmentUniqueId===e}_addToOperationQueue(e,t){let r={operation:t,promise:e};this._pendingOperations.push(r);let i=()=>{let o=this._pendingOperations.indexOf(r);o>=0&&this._pendingOperations.splice(o,1)};e.then(i,i)}};function cf(n){if(h.CURRENT_ENV!==h.PRODUCTION&&(typeof n!="object"||n!==null&&!(n instanceof ArrayBuffer)&&!(n.buffer instanceof ArrayBuffer)))throw new Error("Invalid data given to the AudioVideoSegmentSink")}var na=li;var ci=class extends jn{constructor(e){m.debug("HTSB: Creating TextSegmentSink"),super(),this.bufferType="text",this._sender=e,this._pendingOperations=[],this._sender.reset()}declareInitSegment(e){m.warn("HTSB: Declaring initialization segment for Text SegmentSink",e)}freeInitSegment(e){m.warn("HTSB: Freeing initialization segment for Text SegmentSink",e)}async pushChunk(e){let{data:t}=e;th(t.chunk);let r=this._sender.pushTextData(ue(oe({},t),{chunk:t.chunk}));this._addToOperationQueue(r,{type:0,value:e});let i=await r;return e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,K()),this._segmentInventory.synchronizeBuffered(i),i}async removeBuffer(e,t){let r=this._sender.remove(e,t);this._addToOperationQueue(r,{type:1,value:{start:e,end:t}});let i=await r;return this._segmentInventory.synchronizeBuffered(i),i}async signalSegmentComplete(e){if(this._pendingOperations.length>0){let{promise:t}=this._pendingOperations[this._pendingOperations.length-1];this._addToOperationQueue(t,{type:2,value:e});try{await t}catch(r){}}this._segmentInventory.completeSegment(e)}getPendingOperations(){return this._pendingOperations.map(e=>e.operation)}dispose(){m.debug("HTSB: Disposing TextSegmentSink"),this._sender.reset()}_addToOperationQueue(e,t){let r={operation:t,promise:e};this._pendingOperations.push(r);let i=()=>{let o=this._pendingOperations.indexOf(r);o>=0&&this._pendingOperations.splice(o,1)};e.then(i,i)}};function th(n){if(h.CURRENT_ENV!==h.PRODUCTION&&(typeof n!="object"||n===null||typeof n.data!="string"||typeof n.type!="string"||n.language!==void 0&&typeof n.language!="string"||n.start!==void 0&&typeof n.start!="number"||n.end!==void 0&&typeof n.end!="number"))throw new Error("Invalid format given to a TextSegmentSink")}h.CURRENT_ENV===h.DEV&&(nh=function(e){function t(r){}});var nh;var ff=ci;var rh=["audio","video","text"],fi=class n{static isNative(e){return mf(e)}constructor(e,t,r){this._mediaSource=e,this._textInterface=r,this._hasVideo=t,this._initializedSegmentSinks={},this._onNativeBufferAddedOrDisabled=[]}getBufferTypes(){let e=this.getNativeBufferTypes();return this._textInterface!==null&&e.push("text"),e}getNativeBufferTypes(){return this._hasVideo?["video","audio"]:["audio"]}getStatus(e){let t=this._initializedSegmentSinks[e];return t===void 0?{type:"uninitialized"}:t===null?{type:"disabled"}:{type:"initialized",value:t}}waitForUsableBuffers(e){return this._areNativeBuffersUsable()?Promise.resolve():at(e,t=>{let r=X,i=()=>{let o=this._onNativeBufferAddedOrDisabled.indexOf(r);o>=0&&this._onNativeBufferAddedOrDisabled.splice(o,1)};return r=()=>{this._areNativeBuffersUsable()&&(i(),t())},this._onNativeBufferAddedOrDisabled.push(r),i})}disableSegmentSink(e){let t=this._initializedSegmentSinks[e];if(t===null){m.warn(`SBS: The ${e} SegmentSink was already disabled.`);return}if(t!==void 0)throw new Error("Cannot disable an active SegmentSink.");this._initializedSegmentSinks[e]=null,n.isNative(e)&&(this._onNativeBufferAddedOrDisabled.slice().forEach(r=>r()),ee(this._onNativeBufferAddedOrDisabled.length===0))}createSegmentSink(e,t){let r=this._initializedSegmentSinks[e];if(mf(e)){if(!E(r))return r instanceof na&&r.codec!==t?m.warn("SB: Reusing native SegmentSink with codec",r.codec,"for codec",t):m.info("SB: Reusing native SegmentSink with codec",t),r;m.info("SB: Adding native SegmentSink with codec",t);let o=e==="audio"?"audio":"video",a=new na(o,t,this._mediaSource);return this._initializedSegmentSinks[e]=a,this._onNativeBufferAddedOrDisabled.slice().forEach(s=>s()),ee(this._onNativeBufferAddedOrDisabled.length===0),a}if(!E(r))return m.info("SB: Reusing a previous custom SegmentSink for the type",e),r;let i;if(e==="text"){if(m.info("SB: Creating a new text SegmentSink"),this._textInterface===null)throw new Error("HTML Text track feature not activated");return i=new ff(this._textInterface),this._initializedSegmentSinks.text=i,i}throw m.error("SB: Unknown buffer type:",e),new te("BUFFER_TYPE_UNKNOWN","The player wants to create a SegmentSink of an unknown type.")}disposeSegmentSink(e){let t=this._initializedSegmentSinks[e];if(E(t)){m.warn("SB: Trying to dispose a SegmentSink that does not exist");return}m.info("SB: Aborting SegmentSink",e),t.dispose(),delete this._initializedSegmentSinks[e]}disposeAll(){rh.forEach(e=>{this.getStatus(e).type==="initialized"&&this.disposeSegmentSink(e)})}_areNativeBuffersUsable(){let e=this.getNativeBufferTypes();return!(e.some(i=>this._initializedSegmentSinks[i]===void 0)||e.every(i=>this._initializedSegmentSinks[i]===null))}createSegmentSinkMetricsForType(e){var i,o;let t=(i=this._initializedSegmentSinks[e])==null?void 0:i.getLastKnownInventory(),r;if(t!==void 0){r=0;for(let a of t){if(a.chunkSize===void 0||r===void 0){r=void 0;break}r+=a.chunkSize}}return{bufferType:e,sizeEstimate:r,codec:(o=this._initializedSegmentSinks[e])==null?void 0:o.codec,segmentInventory:t==null?void 0:t.map(a=>ue(oe({},a),{infos:ih(a.infos)}))}}getSegmentSinksMetrics(){return{segmentSinks:{audio:this.createSegmentSinkMetricsForType("audio"),video:this.createSegmentSinkMetricsForType("video"),text:this.createSegmentSinkMetricsForType("text")}}}};function mf(n){return n==="audio"||n==="video"}function ih(n){return{adaptation:n.adaptation.getMetadataSnapshot(),period:n.period.getMetadataSnapshot(),representation:n.representation.getMetadataSnapshot()}}var en=fi;var mi=class{constructor(e){this._weakMap=new WeakMap,this._fn=e}get(e){let t=this._weakMap.get(e);if(t===void 0){let r=this._fn(e);return this._weakMap.set(e,r),r}else return t}destroy(e){this._weakMap.delete(e)}};function od(n,e,t,r,i){let{period:o,adaptation:a,representation:s}=n,d=oh(i,e);if(d===null){if(t===null){if(r&&o.end!==void 0&&e.end>=o.end)return{start:void 0,end:null};let c=s.index.checkDiscontinuity(e.start);if(c!==null)return{start:void 0,end:c}}return null}let u=i[d];if(u.bufferedStart!==void 0&&u.bufferedStart>e.start&&(t===null||u.infos.segment.end<=t)){let c=u.bufferedStart;return!r&&s.index.awaitSegmentBetween(e.start,c)!==!1?null:(m.debug("RS: current discontinuity encountered",a.type,u.bufferedStart),{start:void 0,end:c})}let l=ah(i,e,d+1);if(l!==null){let c=i[l-1],f=i[l];if(t===null||f.infos.segment.end<=t){if(!r&&s.index.awaitSegmentBetween(c.infos.segment.end,f.infos.segment.time)!==!1)return null;let g=c.bufferedEnd,p=f.bufferedStart;return m.debug("RS: future discontinuity encountered",a.type,g,p),{start:g,end:p}}}if(t===null){if(r&&o.end!==void 0){if(e.end<o.end)return null;let c=sh(i,o.end);if(c!==null){let f=i[c];if(f.bufferedEnd!==void 0&&f.bufferedEnd<o.end)return m.debug("RS: discontinuity encountered at the end of the current period",a.type,f.bufferedEnd,o.end),{start:f.bufferedEnd,end:null}}}if(o.end!==void 0&&e.end>=o.end)return null;for(let c=i.length-1;c>=0;c--){let f=i[c];if(f.bufferedStart===void 0)break;if(f.bufferedStart<e.end){if(f.bufferedEnd!==void 0&&f.bufferedEnd<e.end){let g=s.index.checkDiscontinuity(e.end);if(g!==null)return{start:f.bufferedEnd,end:g}}return null}}}return null}function oh(n,e){for(let t=0;t<n.length;t++){let r=n[t];if(r.bufferedStart===void 0||r.bufferedEnd===void 0||r.bufferedStart>=e.end)return null;if(r.bufferedEnd>e.start)return t}return null}function ah(n,e,t){if(t<=0)return m.error("RS: Asked to check a discontinuity before the first chunk."),null;for(let r=t;r<n.length;r++){let i=n[r],o=n[r-1];if(i.bufferedStart===void 0||o.bufferedEnd===void 0||i.bufferedStart>=e.end)return null;if(i.bufferedStart-o.bufferedEnd>0)return r}return null}function sh(n,e){for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.bufferedStart===void 0)return null;if(r.bufferedStart<e)return t}return null}function ad({bufferedSegments:n,content:e,currentPlaybackTime:t,fastSwitchThreshold:r,getBufferedHistory:i,neededRange:o,segmentsBeingPushed:a,maxBufferSize:s}){let{adaptation:d,representation:u}=e,l=dh(n,a,s),c=u.index.getSegments(o.start,o.end-o.start),f=n.filter(R=>!pf(R.infos,e,t,r)),g=gh(f,o,i),{MINIMUM_SEGMENT_SIZE:p,MIN_BUFFER_AHEAD:I}=U.getCurrent(),y=!1,b=Math.min(1/60,p),T=!1,v=[];return{segmentsToLoad:c.filter(R=>{let k=G({segment:R},e);if(a.length>0&&a.some(A=>kt(k,A)))return!1;let{duration:x,time:M,end:P}=R;if(R.isInit)return!0;if(y)return v.push(R),!1;if(R.complete&&x<p||a.length>0&&a.some(A=>{if(A.period.id!==e.period.id||A.adaptation.id!==e.adaptation.id)return!1;let{segment:C}=A;if(C.time-b>M)return!1;if(C.complete){if(C.end+b<P)return!1}else if(Math.abs(M-C.time)>M)return!1;return!pf(A,k,t,r)}))return!1;for(let F of g){let A=F.infos.period.id===e.period.id;if(F.status===1&&A){let C=F.infos.segment;if(M-C.time>-b){if(C.complete){if(C.end-P>-b)return!1}else if(Math.abs(M-C.time)<b)return!1}}}let N=x*e.representation.bitrate;if(l-N<0&&(T=!0,M>o.start+I))return y=!0,v.push(R),!1;let O=i(k);if(O.length>1){let F=O[O.length-1],A=O[O.length-2];if(F.buffered===null&&A.buffered===null)return m.warn("Stream: Segment GCed multiple times in a row, ignoring it.","If this happens a lot and lead to unpleasant experience, please check your device's available memory. If it's low when this message is emitted, you might want to update the RxPlayer's settings (`maxBufferAhead`, `maxVideoBufferSize` etc.) so less memory is used by regular media data buffering."+d.type,u.id,R.time),!1}for(let F=0;F<g.length;F++){let A=g[F];if(A.end+b>M){let C=A.start>M+b||uh(g,F).end<P-b;return C&&(l-=N),C}}return l-=N,!0}),segmentsOnHold:v,isBufferFull:T}}function dh(n,e,t){let r=t*8e3;return r-=e.reduce((i,o)=>{let{bitrate:a}=o.representation,{duration:s}=o.segment;return i+a*s},0),n.reduce((i,o)=>o.chunkSize!==void 0?i-o.chunkSize*8:i,r)}function uh(n,e){let t=e+1,{MINIMUM_SEGMENT_SIZE:r}=U.getCurrent(),i=Math.min(1/60,r);for(;t<n.length-1&&n[t-1].end+i>n[t].start;)t++;return t--,n[t]}function pf(n,e,t,r){let{CONTENT_REPLACEMENT_PADDING:i}=U.getCurrent();if(n.period.id!==e.period.id)return!1;let{segment:o}=n;return o.time<t+i?!1:n.adaptation.id!==e.adaptation.id?!0:lh(n.representation,e.representation,r)}function lh(n,e,t){let r=n.bitrate,{BITRATE_REBUFFERING_RATIO:i}=U.getCurrent();if(t===void 0){let o=r*i;return e.bitrate>o}return r<t&&e.bitrate>r}function ch(n,e,t){let{MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:r}=U.getCurrent();return n.bufferedStart===void 0||e!==null&&e.bufferedEnd!==void 0&&n.bufferedStart-e.bufferedEnd<.1?!1:t<n.bufferedStart&&n.bufferedStart-n.start>r?(m.info("Stream: The start of the wanted segment has been garbage collected",n.start,n.bufferedStart),!0):!1}function fh(n,e,t){let{MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:r}=U.getCurrent();return n.bufferedEnd===void 0||e!==null&&e.bufferedStart!==void 0&&e.bufferedStart-n.bufferedEnd<.1?!1:t>n.bufferedEnd&&n.end-n.bufferedEnd>r?(m.info("Stream: The end of the wanted segment has been garbage collected",n.end,n.bufferedEnd),!0):!1}function mh(n,e){var a,s;if(n.length<2)return!0;let r=(a=n[n.length-1].buffered)==null?void 0:a.start;if(e!==void 0&&r!==void 0&&e-r>.05)return!0;let o=(s=n[n.length-2].buffered)==null?void 0:s.start;return o===void 0||r===void 0?!0:Math.abs(o-r)>.01}function ph(n,e){var a,s;if(n.length<2)return!0;let r=(a=n[n.length-1].buffered)==null?void 0:a.end;if(e!==void 0&&r!==void 0&&r-e>.05)return!0;let o=(s=n[n.length-2].buffered)==null?void 0:s.end;return o===void 0||r===void 0?!0:Math.abs(o-r)>.01}function gh(n,e,t){return n.filter((r,i,o)=>{let a=i===0?null:o[i-1],s=i>=o.length-1?null:o[i+1],d=null;if(ch(r,a,e.start)){if(d=t(r.infos),mh(d,r.bufferedStart))return!1;m.debug("Stream: skipping segment gc-ed at the start",r.start,r.bufferedStart)}if(fh(r,s,e.end)){if(d=d!=null?d:t(r.infos),ph(d,r.bufferedEnd))return!1;m.debug("Stream: skipping segment gc-ed at the end",r.end,r.bufferedEnd)}return!0})}function pi(n,e){let t=n-e,{SEGMENT_PRIORITIES_STEPS:r}=U.getCurrent();for(let i=0;i<r.length;i++)if(t<r[i])return i;return r.length}function sd(n,e,t,r,i,o,a){var M,P,N;let{representation:s}=n,d=(P=(M=t.getIsPaused())!=null?M:t.getReference().getValue().paused.pending)!=null?P:t.getReference().getValue().paused.last,u=(N=t.getPlaybackRate())!=null?N:t.getReference().getValue().speed,l=e;(d===void 0||u===void 0||d||u<=0)&&(l-=.1);let c=hh(n,l,i),f=s.index.shouldRefresh(c.start,c.end),g=a.getPendingOperations().filter(O=>O.type===2).map(O=>O.value),p=a.getLastKnownInventory(),I=t.getCurrentTime();I===void 0&&(I=t.getReference().getValue().position.getWanted());let y=a.getSegmentHistory.bind(a),{segmentsToLoad:b,segmentsOnHold:T,isBufferFull:v}=ad({content:n,bufferedSegments:p,currentPlaybackTime:I,fastSwitchThreshold:r,getBufferedHistory:y,neededRange:c,segmentsBeingPushed:g,maxBufferSize:o}),_=b.map(O=>({priority:pi(O.time,l),segment:O})),R=s.index.isInitialized()&&!s.index.isStillAwaitingFutureSegments()&&c.hasReachedPeriodEnd&&_.length===0&&T.length===0,k=null;return g.length>0&&(k=Math.min(...g.map(O=>O.segment.time))),T.length>0&&(k=k!==null?Math.min(k,T[0].time):T[0].time),_.length>0&&(k=k!==null?Math.min(k,_[0].segment.time):_[0].segment.time),{imminentDiscontinuity:od(n,c,k,R,p),hasFinishedLoading:R,neededSegments:_,isBufferFull:v,shouldRefreshManifest:f}}function hh(n,e,t){var c;let r,{manifest:i,period:o,representation:a}=n,s=a.index.getLastAvailablePosition(),d=a.index;!E(s)&&en.isNative(n.adaptation.type)&&e>=s&&d.isInitialized()&&!d.isStillAwaitingFutureSegments()&&yh(i,o,e)?r=s-1:r=e-.1;let u=r+t,l;return!a.index.isInitialized()||a.index.isStillAwaitingFutureSegments()||o.end===void 0?l=!1:s===void 0?l=u>=o.end:s===null?l=!0:l=u>=s,{start:Math.max(r,o.start),end:Math.min(u,(c=o.end)!=null?c:1/0),hasReachedPeriodEnd:l}}function yh(n,e,t){var i;let r=n.getPeriodAfter(e);return e.containsTime(t,r)&&n.isLastPeriodKnown&&e.id===((i=n.periods[n.periods.length-1])==null?void 0:i.id)}async function gi(n,e,t,r,i){try{return await e.pushChunk(t)}catch(o){if(i.isCancelled()&&o instanceof Me)throw o;if(!(o instanceof ot)||!o.isBufferFull){let d=o instanceof Error?o.toString():"An unknown error happened when pushing content";throw new te("BUFFER_APPEND_ERROR",d,{tracks:[Yt(t.inventoryInfos.adaptation)]})}let{position:a}=n.getReference().getValue(),s=a.getWanted();try{m.warn("Stream: Running garbage collector");let d=Math.max(s-5,0),u=s+r.getValue()+12;if(d>0&&await e.removeBuffer(0,d),u<Number.MAX_VALUE&&await e.removeBuffer(u,Number.MAX_VALUE),await In(200),i.cancellationError!==null)throw i.cancellationError;return await e.pushChunk(t)}catch(d){if(d instanceof Me)throw d;let u=d instanceof Error?d.toString():"Could not clean the buffer";throw new te("BUFFER_FULL_ERROR",u,{tracks:[Yt(t.inventoryInfos.adaptation)]})}}}async function dd({playbackObserver:n,content:e,initSegmentUniqueId:t,segment:r,segmentSink:i,bufferGoal:o},a){if(a.cancellationError!==null)throw a.cancellationError;let s=e.representation.getMimeTypeString(),d={initSegmentUniqueId:t,chunk:null,timestampOffset:0,appendWindow:[void 0,void 0],codec:s},u=G({segment:r,chunkSize:void 0,start:0,end:0},e),l=await gi(n,i,{data:d,inventoryInfos:u},o,a);return{content:e,segment:r,buffered:l}}async function ud({playbackObserver:n,bufferGoal:e,content:t,initSegmentUniqueId:r,parsedSegment:i,segment:o,segmentSink:a},s){var k,x;if(i.chunkData===null)return null;if(s.cancellationError!==null)throw s.cancellationError;let{chunkData:d,chunkInfos:u,chunkOffset:l,chunkSize:c,appendWindow:f}=i,g=t.representation.getMimeTypeString(),{APPEND_WINDOW_SECURITIES:p}=U.getCurrent(),I=[f[0]!==void 0?Math.max(0,f[0]-p.START):void 0,f[1]!==void 0?f[1]+p.END:void 0],y={initSegmentUniqueId:r,chunk:d,timestampOffset:l,appendWindow:I,codec:g},b=(k=u==null?void 0:u.time)!=null?k:o.time,T=(x=u==null?void 0:u.duration)!=null?x:o.duration,v=b+T;I[0]!==void 0&&(b=Math.max(b,I[0])),I[1]!==void 0&&(v=Math.min(v,I[1]));let _=G({segment:o,chunkSize:c,start:b,end:v},t),R=await gi(n,a,{data:y,inventoryInfos:_},e,s);return{content:t,segment:o,buffered:R}}function ld({content:n,options:e,playbackObserver:t,segmentSink:r,segmentQueue:i,terminate:o},a,s){m.debug("Stream: Creating RepresentationStream",n.adaptation.type,n.representation.bitrate);let{period:d,adaptation:u,representation:l}=n,{bufferGoal:c,maxBufferSize:f,drmSystemId:g,fastSwitchThreshold:p}=e,I=u.type,y=new B;y.linkToSignal(s);let b=new B;b.linkToSignal(y.signal);let T={segment:l.index.getInitSegment(),uniqueId:null,isLoaded:!1};y.signal.register(()=>{T.uniqueId!==null&&r.freeInitSegment(T.uniqueId)});let v=T.segment!==null;v||(T.isLoaded=!0);let _=!1;if(g!==void 0){let P=l.getEncryptionData(g);if(P.length>0&&P.every(N=>N.keyIds!==void 0)&&(_=!0,a.encryptionDataEncountered(P.map(N=>G({content:n},N))),y.isUsed()))return}i.addEventListener("error",P=>{b.signal.isCancelled()||(y.cancel(),a.error(P))}),i.addEventListener("parsedInitSegment",x,b.signal),i.addEventListener("parsedMediaSegment",x,b.signal),i.addEventListener("emptyQueue",k,b.signal),i.addEventListener("requestRetry",P=>{if(a.warning(P.error),b.signal.isCancelled())return;let N=P.segment,{index:O}=l;O.isSegmentStillAvailable(N)===!1?k():O.canBeOutOfSyncError(P.error,N)&&a.manifestMightBeOufOfSync()},b.signal),i.addEventListener("fullyLoadedSegment",P=>{r.signalSegmentComplete(G({segment:P},n)).catch(M)},b.signal);let R=i.resetForContent(n,v);b.signal.register(()=>{i.stop()}),t.listen(k,{includeLastObservation:!1,clearSignal:b.signal}),n.manifest.addEventListener("manifestUpdate",k,b.signal),c.onUpdate(k,{emitCurrentValue:!1,clearSignal:b.signal}),f.onUpdate(k,{emitCurrentValue:!1,clearSignal:b.signal}),o.onUpdate(k,{emitCurrentValue:!1,clearSignal:b.signal}),k();return;function k(){if(b.isUsed())return;let P=t.getReference().getValue(),N=P.position.getWanted(),O=sd(n,N,t,p.getValue(),c.getValue(),f.getValue(),r),{neededSegments:F}=O,A=null;if(l.index.isInitialized()){if(F.length>0&&!T.isLoaded&&T.segment!==null){let L=F[0].priority;A={segment:T.segment,priority:L}}}else if(T.segment===null)m.warn("Stream: Uninitialized index without an initialization segment");else if(T.isLoaded)m.warn("Stream: Uninitialized index with an already loaded initialization segment");else{let L=P.position.getWanted();A={segment:T.segment,priority:pi(d.start,L)}}let C=o.getValue();if(C===null)R.setValue({initSegment:A,segmentQueue:F});else if(C.urgent){m.debug("Stream: Urgent switch, terminate now.",I),R.setValue({initSegment:null,segmentQueue:[]}),R.finish(),b.cancel(),a.terminating();return}else{let L=F[0],V=i.getRequestedInitSegment(),$=i.getRequestedMediaSegment(),j=$===null||L===void 0||$.id!==L.segment.id?[]:[L],z=V===null?null:A;if(R.setValue({initSegment:z,segmentQueue:j}),j.length===0&&z===null){m.debug("Stream: No request left, terminate",I),R.finish(),b.cancel(),a.terminating();return}}if(a.streamStatusUpdate({period:d,position:P.position.getWanted(),bufferType:I,imminentDiscontinuity:O.imminentDiscontinuity,isEmptyStream:!1,hasFinishedLoading:O.hasFinishedLoading,neededSegments:O.neededSegments}),b.signal.isCancelled())return;let{UPTO_CURRENT_POSITION_CLEANUP:D}=U.getCurrent();if(O.isBufferFull){let L=Math.max(0,N-D);L>0&&r.removeBuffer(0,L).catch(M)}O.shouldRefreshManifest&&a.needsManifestRefresh()}function x(P){if(!y.isUsed()){for(let N of P.protectionData)l.addProtectionData(N.initDataType,N.keyId,N.initData);if(!_){let N=l.getAllEncryptionData();if(N.length>0&&(a.encryptionDataEncountered(N.map(O=>G({content:n},O))),_=!0,y.isUsed()))return}if(P.segmentType==="init"){if(!l.index.isInitialized()&&P.segmentList!==void 0&&l.index.initialize(P.segmentList),T.isLoaded=!0,P.initializationData!==null){let N=l.uniqueId;T.uniqueId=N,r.declareInitSegment(N,P.initializationData),dd({playbackObserver:t,bufferGoal:c,content:n,initSegmentUniqueId:N,segment:P.segment,segmentData:P.initializationData,segmentSink:r},y.signal).then(O=>{O!==null&&a.addedSegment(O)}).catch(M)}k();return}else{let{inbandEvents:N,predictedSegments:O,needsManifestRefresh:F}=P;if(O!==void 0&&l.index.addPredictedSegments(O,P.segment),F===!0&&(a.needsManifestRefresh(),y.isUsed())||N!==void 0&&N.length>0&&(a.inbandEvent(N),y.isUsed()))return;let A=T.uniqueId;ud({playbackObserver:t,bufferGoal:c,content:n,initSegmentUniqueId:A,parsedSegment:P,segment:P.segment,segmentSink:r},y.signal).then(C=>{C!==null&&a.addedSegment(C)}).catch(M)}}}function M(P){y.isUsed()&&P instanceof Me||(m.warn("Stream: Received fatal buffer error",u.type,l.bitrate,P instanceof Error?P:null),y.cancel(),a.error(P))}}var gf=ld;function cd(n,e,t,r,i){var f,g,p,I;if(t.switchingMode==="lazy")return{type:"continue",value:void 0};let o=r.getLastKnownInventory(),a=[];for(let y of o)y.infos.period.id===n.id&&(y.infos.adaptation.id!==e.id||!Q(t.representationIds,y.infos.representation.id))&&Gt(a,{start:(f=y.bufferedStart)!=null?f:y.start,end:(g=y.bufferedEnd)!=null?g:y.end});let s=r.getPendingOperations();for(let y of s)if(y.type===0){let b=y.value.inventoryInfos;if(b.period.id===n.id&&(b.adaptation.id!==e.id||!Q(t.representationIds,b.representation.id))){let T=b.segment.time,v=T+b.segment.duration;Gt(a,{start:T,end:v})}}if(a.length===0)return{type:"continue",value:void 0};if(t.switchingMode==="reload"){let y=i.getReadyState();if(y===void 0||y>1)return{type:"needs-reload",value:void 0}}let d=t.switchingMode==="direct",u=[],l=Gn(o,n);if(l!==null&&(l.bufferedEnd===void 0||n.start-l.bufferedEnd<1)&&u.push({start:0,end:n.start+1}),!d){let{ADAP_REP_SWITCH_BUFFER_PADDINGS:y}=U.getCurrent(),b=e.type,T=(p=y[b].before)!=null?p:0,v=(I=y[b].after)!=null?I:0,_=i.getCurrentTime();_===void 0&&(_=i.getReference().getValue().position.getPolled()),u.push({start:_-T,end:_+v})}if(n.end!==void 0){let y=qn(o,n);y!==null&&(y.bufferedStart===void 0||y.bufferedStart-n.end<1)&&u.push({start:n.end-1,end:Number.MAX_VALUE})}let c=ho(a,u);return c.length===0?{type:"continue",value:void 0}:d?{type:"flush-buffer",value:c}:{type:"clean-buffer",value:c}}function fd({playbackObserver:n,content:e,options:t,representationEstimator:r,segmentSink:i,segmentQueueCreator:o,wantedBufferAhead:a,maxVideoBufferSize:s},d,u){let{manifest:l,period:c,adaptation:f}=e,g=new B;g.linkToSignal(u);let p=new Map,I=new H(null,g.signal),y,b=e.representations.getValue().representationIds,T=e.adaptation.representations.filter(C=>Q(b,C.id)&&C.isPlayable()!==!1),v=new H(T,g.signal),{estimates:_,callbacks:R}=r({manifest:l,period:c,adaptation:f},I,v,n,g.signal),k=new H(!1);n.listen(C=>{var L;let D=(L=C.canStream)!=null?L:!0;k.getValue()===D&&(m.debug("Stream: isMediaSegmentQueueInterrupted updated to",!D),k.setValue(!D))},{clearSignal:g.signal});let x=o.createSegmentQueue(f.type,{onRequestBegin:R.requestBegin,onRequestEnd:R.requestEnd,onProgress:R.requestProgress,onMetrics:R.metrics},k),M=new H(0);_.onUpdate(({bitrate:C,knownStableBitrate:D})=>{t.enableFastSwitching&&M.setValueIfChanged(D),!(C===void 0||C===y)&&(y=C,m.debug(`Stream: new ${f.type} bitrate estimate`,C),d.bitrateEstimateChange({type:f.type,bitrate:C}))},{emitCurrentValue:!0,clearSignal:g.signal});let P;e.representations.onUpdate(C=>{P!==void 0&&P.cancel();let D=e.representations.getValue().representationIds,L=e.adaptation.representations.filter(V=>Q(D,V.id));v.setValueIfChanged(L),P=new B,P.linkToSignal(g.signal),N(C,P.signal).catch(V=>{(P==null?void 0:P.isUsed())===!0&&B.isCancellationError(V)||(g.cancel(),d.error(V))})},{clearSignal:g.signal,emitCurrentValue:!0});return;async function N(C,D){let L=cd(c,f,C,i,n);switch(L.type){case"continue":break;case"needs-reload":return vt(()=>{n.listen(()=>{if(D.isCancelled())return;let{DELTA_POSITION_AFTER_RELOAD:V}=U.getCurrent(),$=V.bitrateSwitch;return d.waitingMediaSourceReload({bufferType:f.type,period:c,timeOffset:$,stayInPeriod:!0})},{includeLastObservation:!0,clearSignal:D})});case"flush-buffer":case"clean-buffer":for(let V of L.value)if(await i.removeBuffer(V.start,V.end),D.isCancelled())return;if(L.type==="flush-buffer"&&(d.needsBufferFlush(),D.isCancelled()))return;break;default:Xe(L)}O(D)}function O(C){let D=new B;D.linkToSignal(C);let{representation:L}=_.getValue();if(L===null)return;let V=new H(null,D.signal);_.onUpdate(z=>{if(!(z.representation===null||z.representation.id===L.id))return z.urgent?(m.info("Stream: urgent Representation switch",f.type),V.setValue({urgent:!0})):(m.info("Stream: slow Representation switch",f.type),V.setValue({urgent:!1}))},{clearSignal:D.signal,emitCurrentValue:!0});let $={type:f.type,adaptation:f,period:c,representation:L};if(I.setValue(L),C.isCancelled()||(d.representationChange($),C.isCancelled()))return;let j={streamStatusUpdate:d.streamStatusUpdate,encryptionDataEncountered:d.encryptionDataEncountered,manifestMightBeOufOfSync:d.manifestMightBeOufOfSync,needsManifestRefresh:d.needsManifestRefresh,inbandEvent:d.inbandEvent,warning:d.warning,error(z){g.cancel(),d.error(z)},addedSegment(z){R.addedSegment(z)},terminating(){if(!D.isUsed())return D.cancel(),O(C)}};F(L,V,j,C)}function F(C,D,L,V){let $=!1,j=new B;j.linkToSignal(V);let z=dn(a,se=>A(C,se),j.signal),q=f.type==="video"?s:new H(1/0);m.info("Stream: changing representation",f.type,C.id,C.bitrate);let W=G({},L,{error(se){var de;if($){m.warn("Stream: Ignoring RepresentationStream error",se);return}$=!0;let ae=Oe(se,{defaultCode:"NONE",defaultReason:"Unknown `RepresentationStream` error"});if(ae.code!=="BUFFER_FULL_ERROR")L.error(se);else{m.warn("Stream: received BUFFER_FULL_ERROR",f.type,C.bitrate);let Se=a.getValue(),ce=((de=p.get(C.id))!=null?de:1)*.7;if(p.set(C.id,ce),ce<=.05||A(C,Se)<=2){L.error(ae);return}$t(4e3,V).then(()=>F(C,D,L,V)).catch(X)}},terminating(){j.cancel(),L.terminating()}});gf({playbackObserver:n,content:{representation:C,adaptation:f,period:c,manifest:l},segmentSink:i,segmentQueue:x,terminate:D,options:{bufferGoal:z,maxBufferSize:q,drmSystemId:t.drmSystemId,fastSwitchThreshold:M}},W,V),l.addEventListener("manifestUpdate",se=>{for(let ae of se.updatedPeriods)if(ae.period.id===c.id){for(let de of ae.result.updatedAdaptations)if(de.adaptation===f.id){for(let Se of de.removedRepresentations)if(Se===C.id)return V.isCancelled()?void 0:d.waitingMediaSourceReload({bufferType:f.type,period:c,timeOffset:0,stayInPeriod:!0})}}else if(ae.period.start>c.start)break},V)}function A(C,D){let L=p.get(C.id),V=L!==void 0?L:1;return L===void 0&&p.set(C.id,V),V<1&&D===1/0?5*60*1e3*V:D*V}}var hf=fd;function md(n,e,t,r,i,o){var g,p,I,y;if(n.codec!==void 0&&o.onCodecSwitch==="reload"&&!Ih(t,n.codec))return{type:"needs-reload",value:void 0};let a=n.getLastKnownInventory(),s=[];for(let b of a)b.infos.period.id===e.id&&b.infos.adaptation.id!==t.id&&Gt(s,{start:(g=b.bufferedStart)!=null?g:b.start,end:(p=b.bufferedEnd)!=null?p:b.end});let d=n.getPendingOperations();for(let b of d)if(b.type===0){let T=b.value.inventoryInfos;if(T.period.id===e.id&&T.adaptation.id!==t.id){let v=T.segment.time,_=v+T.segment.duration;Gt(s,{start:v,end:_})}}if(s.length===0)return{type:"continue",value:void 0};if(r==="reload"){let b=i.getReadyState();if(b===void 0||b>1)return{type:"needs-reload",value:void 0}}let u=r==="direct",l=[],c=Gn(a,e);if(c!==null&&(c.bufferedEnd===void 0||e.start-c.bufferedEnd<1)&&l.push({start:0,end:e.start+1}),!u){let b=t.type,{ADAP_REP_SWITCH_BUFFER_PADDINGS:T}=U.getCurrent(),v=(I=T[b].before)!=null?I:0,_=(y=T[b].after)!=null?y:0,R=i.getCurrentTime();R===void 0&&(R=i.getReference().getValue().position.getPolled()),l.push({start:R-v,end:R+_})}if(e.end!==void 0){let b=qn(a,e);b!==null&&(b.bufferedStart===void 0||b.bufferedStart-e.end<1)&&l.push({start:e.end-1,end:Number.MAX_VALUE})}let f=ho(s,l);return f.length===0?{type:"continue",value:void 0}:u&&t.type!=="text"?{type:"flush-buffer",value:f}:{type:"clean-buffer",value:f}}function Ih(n,e){return n.representations.some(t=>t.isPlayable()===!0&&Qo(t.getMimeTypeString(),e))}function pd({bufferType:n,content:e,garbageCollectors:t,playbackObserver:r,representationEstimator:i,segmentQueueCreator:o,segmentSinksStore:a,options:s,wantedBufferAhead:d,maxVideoBufferSize:u},l,c){let{manifest:f,period:g}=e,p=new H(void 0,c);if(l.periodStreamReady({type:n,manifest:f,period:g,adaptationRef:p}),c.isCancelled())return;let I,y=!0;p.onUpdate(v=>{(async()=>{var A;if(v===void 0)return;let _=new B;if(_.linkToSignal(c),I==null||I.cancel(),I=_,v===null){m.info(`Stream: Set no ${n} Adaptation. P:`,g.start);let C=a.getStatus(n);if(C.type==="initialized"){if(m.info(`Stream: Clearing previous ${n} SegmentSink`),en.isNative(n))return T(0,!0,_.signal);{let D=(A=g.end)!=null?A:1/0;if(g.start>D)m.warn("Stream: Can't free buffer: period's start is after its end");else if(await C.value.removeBuffer(g.start,D),_.isUsed())return}}else if(C.type==="uninitialized"&&(a.disableSegmentSink(n),_.isUsed()))return;return l.adaptationChange({type:n,adaptation:null,period:g}),_.isUsed()?void 0:yf(r,d,n,{period:g},l,_.signal)}let R=g.adaptations[n],k=Z(R!=null?R:[],C=>C.id===v.adaptationId);if(k===void 0){I.cancel(),m.warn("Stream: Unfound chosen Adaptation choice",v.adaptationId);return}let{DELTA_POSITION_AFTER_RELOAD:x}=U.getCurrent(),M=!1,P;if(y)P=0;else if(v.relativeResumingPosition!==void 0)P=v.relativeResumingPosition;else switch(M=!0,n){case"audio":P=x.trackSwitch.audio;break;case"video":P=x.trackSwitch.video;break;default:P=x.trackSwitch.other;break}if(y=!1,en.isNative(n)&&a.getStatus(n).type==="disabled")return T(P,!0,_.signal);f.addEventListener("manifestUpdate",C=>{for(let D of C.updatedPeriods)if(D.period.id===g.id){for(let L of D.result.removedAdaptations)if(L.id===k.id)return T(P,!0,_.signal)}else if(D.period.start>g.start)break},I.signal);let{representations:N}=v;if(m.info(`Stream: Updating ${n} adaptation`,`A: ${k.id}`,`P: ${g.start}`),l.adaptationChange({type:n,adaptation:k,period:g}),_.isUsed())return;let O=bh(a,n,k),F=md(O,g,k,v.switchingMode,r,s);if(F.type==="needs-reload")return T(P,!0,_.signal);if(await a.waitForUsableBuffers(_.signal),!_.isUsed()){if(F.type==="flush-buffer"||F.type==="clean-buffer"){for(let{start:C,end:D}of F.value)if(await O.removeBuffer(C,D),_.isUsed())return;if(F.type==="flush-buffer"&&(l.needsBufferFlush({relativeResumingPosition:P,relativePosHasBeenDefaulted:M}),_.isUsed()))return}t.get(O)(_.signal),b(k,N,O,_.signal)}})().catch(_=>{_ instanceof Me||(I==null||I.cancel(),l.error(_))})},{clearSignal:c,emitCurrentValue:!0});function b(v,_,R,k){let x=Th(r,v.type);hf({content:{manifest:f,period:g,adaptation:v,representations:_},options:s,playbackObserver:x,representationEstimator:i,segmentSink:R,segmentQueueCreator:o,wantedBufferAhead:d,maxVideoBufferSize:u},ue(oe({},l),{error:M}),k);function M(P){if(!en.isNative(n)){m.error(`Stream: ${n} Stream crashed. Aborting it.`,P instanceof Error?P:""),a.disposeSegmentSink(n);let N=Oe(P,{defaultCode:"NONE",defaultReason:"Unknown `AdaptationStream` error"});return l.warning(N),k.isCancelled()?void 0:yf(r,d,n,{period:g},l,k)}m.error(`Stream: ${n} Stream crashed. Stopping playback.`,P instanceof Error?P:""),l.error(P)}}function T(v,_,R){vt(()=>{r.listen(()=>{R.isCancelled()||l.waitingMediaSourceReload({bufferType:n,period:g,timeOffset:v,stayInPeriod:_})},{includeLastObservation:!0,clearSignal:R})})}}function bh(n,e,t){let r=n.getStatus(e);if(r.type==="initialized")return m.info("Stream: Reusing a previous SegmentSink for the type",e),r.value;let i=Sh(t);return n.createSegmentSink(e,i)}function Sh(n){let e=n.representations.filter(t=>t.isPlayable()!==!1);if(e.length===0)throw new te("NO_PLAYABLE_REPRESENTATION","No Representation in the chosen "+n.type+" Adaptation can be played",{tracks:[Yt(n)]});return e[0].getMimeTypeString()}function Th(n,e){return n.deriveReadOnlyObserver(function(r,i){let o=new H(a(),i);return r.onUpdate(s,{clearSignal:i,emitCurrentValue:!1}),o;function a(){let d=r.getValue(),u=d.buffered[e],l=u!==null?go(u,d.position.getWanted()):0;return G({},d,{bufferGap:l,buffered:u})}function s(){o.setValue(a())}})}function yf(n,e,t,r,i,o){let{period:a}=r,s=!1;e.onUpdate(d,{emitCurrentValue:!1,clearSignal:o}),n.listen(d,{includeLastObservation:!1,clearSignal:o}),d();function d(){let u=n.getReference().getValue(),l=e.getValue(),c=u.position.getWanted();a.end!==void 0&&c+l>=a.end&&(m.debug('Stream: full "empty" AdaptationStream',t),s=!0),i.streamStatusUpdate({period:a,bufferType:t,imminentDiscontinuity:null,position:c,isEmptyStream:!0,hasFinishedLoading:s,neededSegments:[]})}}var If=pd;function ra(n,e){if(e.length===0)return[];let t=[],r=n.getLastKnownInventory();for(let i of r)if(e.some(a=>i.infos.period.id===a.period.id&&i.infos.adaptation.id===a.adaptation.id&&i.infos.representation.id===a.representation.id)){let{bufferedStart:a,bufferedEnd:s}=i;if(a===void 0||s===void 0)return m.warn("SO: No buffered start or end found from a segment."),[{start:0,end:Number.MAX_VALUE}];let d=t[t.length-1];d!==void 0&&d.end===a?d.end=s:t.push({start:a,end:s})}return t}function gd(n,e,t,r,i,o,a,s){let{manifest:d,initialPeriod:u}=n,{maxBufferAhead:l,maxBufferBehind:c,wantedBufferAhead:f,maxVideoBufferSize:g}=o,{MINIMUM_MAX_BUFFER_AHEAD:p,MAXIMUM_MAX_BUFFER_AHEAD:I,MAXIMUM_MAX_BUFFER_BEHIND:y}=U.getCurrent(),b=new mi(_=>{var M,P;let{bufferType:R}=_,k=(M=y[R])!=null?M:1/0,x=(P=I[R])!=null?P:1/0;return N=>{ea({segmentSink:_,playbackObserver:e,maxBufferBehind:dn(c,O=>Math.min(O,k),N),maxBufferAhead:dn(l,O=>{var A;let F=Math.max(O,(A=p[R])!=null?A:0);return Math.min(F,x)},N)},N)}});for(let _ of r.getBufferTypes())T(_,u);function T(_,R){let k=new _n((F,A)=>F.start-A.start),x=!1,M=new B;return M.linkToSignal(s),e.listen(({position:F})=>{var D;let A=F.getWanted();if(!x||!N(A))return;for(m.info("Stream: Destroying all PeriodStreams due to out of bounds situation",_,A),x=!1;k.length()>0;){let L=k.get(k.length()-1);k.removeElement(L),a.periodStreamCleared({type:_,manifest:d,period:L})}M.cancel(),M=new B,M.linkToSignal(s);let C=(D=d.getPeriodForTime(A))!=null?D:d.getNextPeriod(A);if(C===void 0){m.warn("Stream: The wanted position is not found in the Manifest."),x=!0;return}P(C)},{clearSignal:s,includeLastObservation:!0}),d.addEventListener("decipherabilityUpdate",F=>{s.isCancelled()||O(F).catch(A=>{s.isCancelled()||(M.cancel(),a.error(A))})},s),P(R);function P(F){let A=ue(oe({},a),{waitingMediaSourceReload(C){let D=k.head();D===void 0||D.id!==C.period.id?a.lockedStream({bufferType:C.bufferType,period:C.period}):a.needsMediaSourceReload({timeOffset:C.timeOffset,minimumPosition:C.stayInPeriod?C.period.start:void 0,maximumPosition:C.stayInPeriod?C.period.end:void 0})},periodStreamReady(C){x=!0,k.add(C.period),a.periodStreamReady(C)},periodStreamCleared(C){k.removeElement(C.period),a.periodStreamCleared(C)},error(C){M.cancel(),a.error(C)}});v(_,F,A,M.signal)}function N(F){let A=k.head(),C=k.last();return A===void 0||C===void 0?!0:A.start>F||(E(C.end)?1/0:C.end)<F}async function O(F){let A=r.getStatus(_),C=F.filter(z=>z.adaptation.type===_);if(C.length===0||A.type!=="initialized"||C.every(z=>z.representation.decipherable===!0))return;let D=A.value,L=C.filter(z=>z.representation.decipherable===void 0),V=C.filter(z=>z.representation.decipherable===!1),$=ra(D,V),j=ra(D,L);for(x=!1,m.info("Stream: Destroying all PeriodStreams for decipherability matters",_);k.length()>0;){let z=k.get(k.length()-1);k.removeElement(z),a.periodStreamCleared({type:_,manifest:d,period:z})}M.cancel(),M=new B,M.linkToSignal(s);for(let{start:z,end:q}of[...$,...j]){if(s.isCancelled())return;if(z<q){if(s.isCancelled())return;await D.removeBuffer(z,q)}}vt(()=>{if(s.isCancelled())return;let z=e.getReference().getValue();if(bf(z,$)){if(a.needsDecipherabilityFlush(),s.isCancelled())return}else if(bf(z,j)&&(a.needsBufferFlush(),s.isCancelled()))return;let q=z.position.getWanted(),W=d.getPeriodForTime(q);if(W===void 0){a.error(new te("MEDIA_TIME_NOT_FOUND","The wanted position is not found in the Manifest."));return}P(W)})}}function v(_,R,k,x){m.info("Stream: Creating new Stream for",_,R.start);let M=null,P=new B;P.linkToSignal(x),e.listen(({position:C},D)=>{if(R.end!==void 0&&C.getWanted()>=R.end){let L=d.getPeriodAfter(R);if(R.containsTime(C.getWanted(),L))return;m.info("Stream: Destroying PeriodStream as the current playhead moved above it",_,R.start,C.getWanted(),R.end),D(),k.periodStreamCleared({type:_,manifest:d,period:R}),P.cancel()}},{clearSignal:x,includeLastObservation:!0});let N={bufferType:_,content:{manifest:d,period:R},garbageCollectors:b,maxVideoBufferSize:g,segmentQueueCreator:i,segmentSinksStore:r,options:o,playbackObserver:e,representationEstimator:t,wantedBufferAhead:f},O=ue(oe({},k),{streamStatusUpdate(C){if(C.hasFinishedLoading){let D=d.getPeriodAfter(R);D!==null&&F(D)}else M!==null&&(m.info("Stream: Destroying next PeriodStream due to current one being active",_,M.period.start),k.periodStreamCleared({type:_,manifest:d,period:M.period}),M.canceller.cancel(),M=null);k.streamStatusUpdate(C)},error(C){M!==null&&(M.canceller.cancel(),M=null),P.cancel(),k.error(C)}});If(N,O,P.signal),A(P.signal);function F(C){if(M!==null){if(M.period.id===C.id)return;m.warn("Stream: Creating next `PeriodStream` while one was already created.",_,C.id,M.period.id),k.periodStreamCleared({type:_,manifest:d,period:M.period}),M.canceller.cancel()}let D=new B;D.linkToSignal(x),M={canceller:D,period:C},v(_,C,k,M.canceller.signal)}function A(C){d.addEventListener("manifestUpdate",D=>{for(let L of D.removedPeriods)if(L.id===R.id){if(d.periods.length>0&&d.periods[0].start<=L.start)return vt(()=>{if(!C.isCancelled())return a.needsMediaSourceReload({timeOffset:0,minimumPosition:void 0,maximumPosition:void 0})})}else if(L.start>R.start)break;if(D.addedPeriods.length>0&&M!==null){let L=d.getPeriodAfter(R);(L===null||M.period.id!==L.id)&&(m.warn("Stream: Destroying next PeriodStream due to new one being added",_,M.period.start),k.periodStreamCleared({type:_,manifest:d,period:M.period}),M.canceller.cancel(),M=null)}},C)}}}function bf(n,e){if(e.length===0)return!1;let t=n.position.getPolled();return n.speed>=0?e[e.length-1].end>=t-5:e[0].start<=t+5}var Sf=gd;var Tf=Sf;var _h={dashParsers:{wasm:null,native:null,fastJs:null},createDebugElement:null,directfile:null,decrypt:null,htmlTextDisplayer:null,htmlTextTracksParsers:{},mainThreadMediaSourceInit:null,multithread:null,nativeTextDisplayer:null,nativeTextTracksParsers:{},transports:{}},hi=_h;function ia(n){for(let e of n)if(typeof e=="function")e(hi);else if(!E(e)&&typeof e._addFeature=="function")e._addFeature(hi);else throw new Error("Unrecognized feature")}var me=hi;var Eh={createSync(n){return{syncValue:n,getValueAsAsync(){return Promise.resolve(n)}}},createAsync(n){let e=null;return n.then(t=>{e=t},X),{get syncValue(){return e},getValueAsAsync(){return n}}}},_f=Eh;var Yn=class extends re{};function hd(n,e){let t={audio:null,video:null,text:null};if(e!==null&&(t.text=e.getBufferedRanges()),n===null)return t;let r=Z(n.sourceBuffers,s=>s.type==="audio"),i=Z(n.sourceBuffers,s=>s.type==="video"),o=r==null?void 0:r.getBuffered();o!==void 0&&(t.audio=o);let a=i==null?void 0:i.getBuffered();return a!==void 0&&(t.video=a),t}function yd(n,{autoPlay:e,initialPlayPerformed:t,manifest:r,mediaSource:i,speed:o,textDisplayer:a},s){return n.deriveReadOnlyObserver(function(u,l){let c=new B;c.linkToSignal(l),c.linkToSignal(s);let f=new H(g(),c.signal);return o.onUpdate(p,{clearSignal:c.signal,emitCurrentValue:!1}),u.onUpdate(p,{clearSignal:c.signal,emitCurrentValue:!1}),i==null||i.addEventListener("streamingChanged",()=>{p()},c.signal),f;function g(){var b;let I=u.getValue(),y=o.getValue();return vh(I,r),{maximumPosition:bt(r),bufferGap:I.bufferGap,position:I.position,buffered:hd(i,a),duration:I.duration,rebuffering:I.rebuffering,freezing:I.freezing,paused:{last:I.paused,pending:Rh(t,e)},readyState:I.readyState,speed:y,canStream:(b=i==null?void 0:i.streaming)!=null?b:!0}}function p(){f.setValue(g())}})}function vh(n,e){if(!e.isDynamic||e.isLastPeriodKnown){let t=e.periods[e.periods.length-1];if(t!==void 0&&t.end!==void 0){let r=n.position.getWanted();if(r>=t.start&&r>=t.end-1){let i=n.buffered;(i.length===0||i.end(i.length-1)<n.duration-1)&&n.position.forceWantedPosition(t.end-1)}}}}function Rh(n,e){return n.getValue()?void 0:!e}function $n(n){let{textTracks:e}=n;if(!E(e)){for(let t=0;t<e.length;t++)e[t].mode="disabled";if(n.hasChildNodes()){let{childNodes:t}=n;for(let r=t.length-1;r>=0;r--)if(t[r].nodeName==="track")try{n.removeChild(t[r])}catch(i){m.warn("Compat: Could not remove text track child from element.")}}}n.src="",n.removeAttribute("src")}function Id(n,e){if(typeof n.changeType=="function"){try{n.changeType(e)}catch(t){return m.warn("Could not call 'changeType' on the given SourceBuffer:",t instanceof Error?t:""),!1}return!0}return!1}function kh(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t];r.updating&&e.push(r)}return e}function yi(n,e){if(m.debug("Init: Trying to call endOfStream"),n.readyState!=="open"){m.debug("Init: MediaSource not open, cancel endOfStream");return}let{sourceBuffers:t}=n,r=kh(t);if(r.length===0){m.info("Init: Triggering end of stream");try{n.endOfStream()}catch(o){m.error("Unable to call endOfStream",o instanceof Error?o:new Error("Unknown error"))}return}m.debug("Init: Waiting SourceBuffers to be updated before calling endOfStream.");let i=new B;i.linkToSignal(e);for(let o of r)Tc(o,()=>{i.cancel(),yi(n,e)},i.signal);_c(t,()=>{i.cancel(),yi(n,e)},i.signal)}function Ef(n,e){let t=new B;t.linkToSignal(e),Un(n,()=>{m.debug("Init: MediaSource re-opened while end-of-stream is active"),t.cancel(),t=new B,t.linkToSignal(e),yi(n,t.signal)},e),yi(n,t.signal)}function bd(){return fn}var Ch=365*24*3600,Ii=class{constructor(e){this._mediaSource=e,this._currentMediaSourceDurationUpdateCanceller=null}updateDuration(e,t){this._currentMediaSourceDurationUpdateCanceller!==null&&this._currentMediaSourceDurationUpdateCanceller.cancel(),this._currentMediaSourceDurationUpdateCanceller=new B;let r=this._mediaSource,i=this._currentMediaSourceDurationUpdateCanceller.signal,o=Ah(r,i),a=new B;a.linkToSignal(i),o.onUpdate(s,{emitCurrentValue:!0,clearSignal:i});function s(){if(a.cancel(),!o.getValue())return;a=new B,a.linkToSignal(i);let d=Mh(r.sourceBuffers,a.signal),u=new B;return u.linkToSignal(a.signal),d.onUpdate(l=>{u.cancel(),u=new B,u.linkToSignal(a.signal),!l&&Rf(r,e,t,u.signal)},{clearSignal:a.signal,emitCurrentValue:!0})}}stopUpdating(){this._currentMediaSourceDurationUpdateCanceller!==null&&(this._currentMediaSourceDurationUpdateCanceller.cancel(),this._currentMediaSourceDurationUpdateCanceller=null)}};function Ph(n,e,t){let r=e;t||(r=bd()?1/0:vf(e));let i=0;for(let o=0;o<n.sourceBuffers.length;o++){let a=n.sourceBuffers[o],s=a.buffered.length;s>0&&(i=Math.max(a.buffered.end(s-1)))}if(r===n.duration)return"success";if(i>r){if(i<n.duration)try{m.info("Init: Updating duration to what is currently buffered",i),n.duration=i}catch(o){return m.warn("Duration Updater: Can't update duration on the MediaSource.",o instanceof Error?o:""),"failed"}return"partial"}else{let o=n.duration;try{if(m.info("Init: Updating duration",r),n.duration=r,n.readyState==="open"&&!isFinite(r)){let s=vf(e);m.info("Init: calling `mediaSource.setLiveSeekableRange`",s),n.setLiveSeekableRange(0,s)}}catch(s){return m.warn("Duration Updater: Can't update duration on the MediaSource.",s instanceof Error?s:""),"failed"}let a=Math.abs(n.duration-r);if(a>=.1){let s=Math.abs(n.duration-o);return a<s?"partial":"failed"}return"success"}}function Mh(n,e){if(n.length===0){let i=new H(!1);return i.finish(),i}let t=new H(!1,e);r();for(let i=0;i<n.length;i++){let o=n[i];o.addEventListener("updatestart",r),o.addEventListener("update",r),e.register(()=>{o.removeEventListener("updatestart",r),o.removeEventListener("update",r)})}return t;function r(){for(let i=0;i<n.length;i++)if(n[i].updating){t.setValueIfChanged(!0);return}t.setValueIfChanged(!1)}}function Ah(n,e){let t=new H(n.readyState==="open",e);return Un(n,()=>{m.debug("Init: Reacting to MediaSource open in duration updater"),t.setValueIfChanged(!0)},e),Ao(n,()=>{m.debug("Init: Reacting to MediaSource ended in duration updater"),t.setValueIfChanged(!1)},e),Mo(n,()=>{m.debug("Init: Reacting to MediaSource close in duration updater"),t.setValueIfChanged(!1)},e),t}function Rf(n,e,t,r){if(Ph(n,e,t)==="success")return;let o=setTimeout(()=>{a(),Rf(n,e,t,r)},2e3),a=r.register(()=>{clearTimeout(o)})}function vf(n){return Math.max(Math.pow(2,32),n+Ch)}var bi=class extends re{constructor(e){if(super(),this.id=e,this.sourceBuffers=[],this._canceller=new B,E(Rt))throw new te("MEDIA_SOURCE_NOT_SUPPORTED","No MediaSource Object was found in the current browser.");m.info("Init: Creating MediaSource");let t=new Rt,r=t.handle;this.handle=E(r)?{type:"media-source",value:t}:{type:"handle",value:r},this._mediaSource=t,this.readyState=t.readyState,this._durationUpdater=new Ii(t),this._endOfStreamCanceller=null,Un(t,()=>{this.readyState=t.readyState,this.trigger("mediaSourceOpen",null)},this._canceller.signal),Ao(t,()=>{this.readyState=t.readyState,this.trigger("mediaSourceEnded",null)},this._canceller.signal),Mo(t,()=>{this.readyState=t.readyState,this.trigger("mediaSourceClose",null)},this._canceller.signal),this._mediaSource.streaming!==void 0&&(this.streaming=this._mediaSource.streaming),this._mediaSource.addEventListener("startstreaming",()=>{this.streaming=!0,this.trigger("streamingChanged",null)}),this._mediaSource.addEventListener("endstreaming",()=>{this.streaming=!1,this.trigger("streamingChanged",null)})}addSourceBuffer(e,t){let r=this._mediaSource.addSourceBuffer(t),i=new Sd(e,t,r);return this.sourceBuffers.push(i),i}setDuration(e,t){this._durationUpdater.updateDuration(e,t)}interruptDurationSetting(){this._durationUpdater.stopUpdating()}maintainEndOfStream(){this._endOfStreamCanceller===null&&(this._endOfStreamCanceller=new B,this._endOfStreamCanceller.linkToSignal(this._canceller.signal),m.debug("Init: end-of-stream order received."),Ef(this._mediaSource,this._endOfStreamCanceller.signal))}stopEndOfStream(){this._endOfStreamCanceller!==null&&(m.debug("Init: resume-stream order received."),this._endOfStreamCanceller.cancel(),this._endOfStreamCanceller=null)}dispose(){this.sourceBuffers.forEach(e=>e.dispose()),this._canceller.cancel(),xh(this._mediaSource)}},Sd=class{constructor(e,t,r){this.type=e,this.codec=t,this._canceller=new B,this._sourceBuffer=r,this._operationQueue=[],this._currentOperations=[];let i=this._onError.bind(this),o=this._onUpdateEnd.bind(this);r.addEventListener("updateend",o),r.addEventListener("error",i),this._canceller.signal.register(()=>{r.removeEventListener("updateend",o),r.removeEventListener("error",i)})}appendBuffer(...e){return m.debug("SBI: receiving order to push data to the SourceBuffer",this.type),this._addToQueue({operationName:0,params:e})}remove(e,t){return m.debug("SBI: receiving order to remove data from the SourceBuffer",this.type,e,t),this._addToQueue({operationName:1,params:[e,t]})}getBuffered(){try{return Pe(this._sourceBuffer.buffered)}catch(e){return m.error("Failed to get buffered time range of SourceBuffer",this.type,e instanceof Error?e:null),[]}}abort(){try{this._sourceBuffer.abort()}catch(e){m.debug("Init: Failed to abort SourceBuffer:",e instanceof Error?e:null)}this._emptyCurrentQueue()}dispose(){try{this._sourceBuffer.abort()}catch(e){}this._emptyCurrentQueue()}_onError(e){let t;e instanceof Error?t=e:e.error instanceof Error?t=e.error:t=new Error("Unknown SourceBuffer Error");let r=this._currentOperations;if(this._currentOperations=[],r.length===0)m.error("SBI: error for an unknown operation",t);else{let i=new ot(t.name,t.message,t.name==="QuotaExceededError");for(let o of r)o.reject(i)}}_onUpdateEnd(){let e=this._currentOperations;this._currentOperations=[];try{for(let t of e)t.resolve(Pe(this._sourceBuffer.buffered))}catch(t){for(let r of e)t instanceof Error&&t.name==="InvalidStateError"?r.resolve([]):r.reject(t)}this._performNextOperation()}_emptyCurrentQueue(){let e=new Me;this._currentOperations.length>0&&(this._currentOperations.forEach(t=>{t.reject(e)}),this._currentOperations=[]),this._operationQueue.length>0&&(this._operationQueue.forEach(t=>{t.reject(e)}),this._operationQueue=[])}_addToQueue(e){return new Promise((t,r)=>{let i=this._operationQueue.length===0&&this._currentOperations.length===0,o=G({resolve:t,reject:r},e);this._operationQueue.push(o),i&&this._performNextOperation()})}_performNextOperation(){var t,r,i,o,a;if(this._currentOperations.length!==0||this._sourceBuffer.updating)return;let e=this._operationQueue.shift();if(e!==void 0)if(e.operationName===0){this._currentOperations=[{operationName:0,resolve:e.resolve,reject:e.reject}];let s=e.params[0],d=e.params[1],u=s;if(this._operationQueue.length>0&&this._operationQueue[0].operationName===0){let l;s instanceof ArrayBuffer?l=new Uint8Array(s):s instanceof Uint8Array?l=s:l=new Uint8Array(s.buffer);let c=[l];for(;((t=this._operationQueue[0])==null?void 0:t.operationName)===0;){let f=this._operationQueue[0],g=(r=d.appendWindow)!=null?r:[void 0,void 0],p=(i=f.params[1].appendWindow)!=null?i:[void 0,void 0],I=(o=d.timestampOffset)!=null?o:0,y=(a=f.params[1].timestampOffset)!=null?a:0;if(g[0]===p[0]&&g[1]===p[1]&&d.codec===f.params[1].codec&&I===y){let b=f.params[0],T;b instanceof ArrayBuffer?T=new Uint8Array(b):b instanceof Uint8Array?T=b:T=new Uint8Array(b.buffer),c.push(T),this._operationQueue.splice(0,1),this._currentOperations.push({operationName:0,resolve:f.resolve,reject:f.reject})}else break}c.length>1&&(m.info(`MMSI: Merging ${c.length} segments together for perf`,this.type),u=ie(...c))}try{this._appendBufferNow(u,d)}catch(l){let c=l instanceof Error?new ot(l.name,l.message,l.name==="QuotaExceededError"):new ot("Error","Unknown SourceBuffer Error during appendBuffer",!1);this._currentOperations.forEach(f=>{f.reject(c)}),this._currentOperations=[],this._performNextOperation()}}else{this._currentOperations=[e];let[s,d]=e.params;m.debug("SBI: removing data from SourceBuffer",this.type,s,d);try{this._sourceBuffer.remove(s,d)}catch(u){let l=u instanceof Error?new ot(u.name,u.message,!1):new ot("Error","Unknown SourceBuffer Error during remove",!1);e.reject(l),this._currentOperations.forEach(c=>{c.reject(l)}),this._currentOperations=[],this._performNextOperation()}}}_appendBufferNow(e,t){let r=this._sourceBuffer,{codec:i,timestampOffset:o,appendWindow:a=[]}=t;if(i!==void 0&&i!==this.codec&&(m.debug("SBI: updating codec",i),Id(r,i)?this.codec=i:m.debug("SBI: could not update codec",i,this.codec)),o!==void 0&&r.timestampOffset!==o){let s=o;m.debug("SBI: updating timestampOffset",i,r.timestampOffset,s),r.timestampOffset=s}if(a[0]===void 0)r.appendWindowStart>0&&(m.debug("SBI: re-setting `appendWindowStart` to `0`"),r.appendWindowStart=0);else if(a[0]!==r.appendWindowStart){if(a[0]>=r.appendWindowEnd){let s=a[0]+1;m.debug("SBI: pre-updating `appendWindowEnd`",s),r.appendWindowEnd=s}m.debug("SBI: setting `appendWindowStart`",a[0]),r.appendWindowStart=a[0]}a[1]===void 0?r.appendWindowEnd!==1/0&&(m.debug("SBI: re-setting `appendWindowEnd` to `Infinity`"),r.appendWindowEnd=1/0):a[1]!==r.appendWindowEnd&&(m.debug("SBI: setting `appendWindowEnd`",a[1]),r.appendWindowEnd=a[1]),m.debug("SBI: pushing segment",this.type),r.appendBuffer(e)}};function xh(n){if(n.readyState!=="closed"){let{readyState:e,sourceBuffers:t}=n;for(let r=t.length-1;r>=0;r--){let i=t[r];try{if(e==="open"){m.info("Init: Aborting SourceBuffer before removing");try{i.abort()}catch(o){}}m.info("Init: Removing SourceBuffer from mediaSource"),n.removeSourceBuffer(i)}catch(o){}}t.length>0&&m.info("Init: Not all SourceBuffers could have been removed.")}}var wh=et();function Td(n,e){if(e!==null&&n.src===e&&(m.info("Init: Clearing HTMLMediaElement's src"),$n(n)),e!==null)try{m.debug("Init: Revoking previous URL"),URL.revokeObjectURL(e)}catch(t){m.warn("Init: Error while revoking the media source URL",t instanceof Error?t:"")}}function Oh(n,e){if(Kl&&"disableRemotePlayback"in n){let t=n.disableRemotePlayback;e.register(()=>{n.disableRemotePlayback=t}),n.disableRemotePlayback=!0}}function Dh(n,e){let t=w(n.src)?n.src:null;Td(n,t);let r=new bi(wh());return Oh(n,e),e.register(()=>{r.dispose()}),r}function oa(n,e){return at(e,t=>{let r=Dh(n,e);if(r.addEventListener("mediaSourceOpen",()=>{m.info("Init: MediaSource opened"),t(r)},e),m.info("MTCI: Attaching MediaSource URL to the media element"),r.handle.type==="handle")n.srcObject=r.handle.value,e.register(()=>{Td(n,null)});else{let i=URL.createObjectURL(r.handle.value);n.src=i,e.register(()=>{Td(n,i)})}})}function _d(n,e,t){var i;if(!E(t)){let o=gn(n),a=bt(n);if(E(t.position))if(E(t.wallClockTime))if(E(t.fromFirstPosition))if(E(t.fromLastPosition))if(E(t.fromLivePosition)){if(!E(t.percentage)){m.debug("Init: using startAt.percentage");let{percentage:s}=t;if(s>100)return a;if(s<0)return o;let d=+s/100,u=a-o;return o+u*d}}else{m.debug("Init: using startAt.fromLivePosition");let s=(i=hn(n))!=null?i:a,{fromLivePosition:d}=t;return d>=0?s:Math.max(o,s+d)}else{m.debug("Init: using startAt.fromLastPosition");let{fromLastPosition:s}=t;return s>=0?a:Math.max(o,a+s)}else{m.debug("Init: using startAt.fromFirstPosition");let{fromFirstPosition:s}=t;return s<=0?o:Math.min(a,o+s)}else{m.debug("Init: using startAt.wallClockTime");let s=n.availabilityStartTime===void 0?0:n.availabilityStartTime,d=t.wallClockTime-s;return Math.max(Math.min(d,a),o)}else return m.debug("Init: using startAt.minimumPosition"),Math.max(Math.min(t.position,a),o)}let r=gn(n);if(n.isLive){let{suggestedPresentationDelay:o,clockOffset:a}=n,s=bt(n),d,{DEFAULT_LIVE_GAP:u}=U.getCurrent();if(a===void 0)m.info("Init: no clock offset found for a live content, starting close to maximum available position"),d=s;else{m.info("Init: clock offset found for a live content, checking if we can start close to it");let c=n.availabilityStartTime===void 0?0:n.availabilityStartTime,f=(K()+a)/1e3-c;d=Math.min(s,f)}let l=o!=null?o:e?u.LOW_LATENCY:u.DEFAULT;return m.debug(`Init: ${d} defined as the live time, applying a live gap of ${l}`),Math.max(d-l,r)}return m.info("Init: starting at the minimum available position:",r),r}function Si(){return Ka}function Ed(n){return!(n&&cn)}function vd(){return fn}function Ti(n,e,t,r){let i=new B;i.linkToSignal(r);let o=new H(!1,i.signal);return n.listen(a=>{if(a.rebuffering!==null||a.freezing!==null||a.readyState===0)return;if(!Ed(t)){if(isNaN(e.duration))return;if(e.duration>0){o.setValue(!0),i.cancel();return}}let s=vd()?4:3;if(a.readyState>=s&&(a.currentRange!==null||a.ended)&&(!Si()||e.duration>0)){o.setValue(!0),i.cancel();return}},{includeLastObservation:!0,clearSignal:i.signal}),o}var Lh=!cn,kf=Lh;var Qn=class{constructor(e,t){this._last=e,this._wanted=t}serialize(){return[this._last,this._wanted]}getPolled(){return this._last}getWanted(){var e;return(e=this._wanted)!=null?e:this._last}forceWantedPosition(e){this._wanted=e}isAwaitingFuturePosition(){return this._wanted!==null}};function _i({mediaElement:n,playbackObserver:e,startTime:t,mustAutoPlay:r,isDirectfile:i,onWarning:o},a){let s=new H(!1,a);return{autoPlayResult:new Promise((u,l)=>{let c=a.register(b=>{l(b)});if(a.isCancelled())return;let f=!1,g=b=>{e.setCurrentTime(b),f=!0};if(!i||typeof t=="number"){let b=typeof t=="number"?t:t();b!==0&&b!==void 0&&g(b),p()}else e.listen((b,T)=>{let v=typeof t=="number"?t:t();v===void 0&&b.readyState<HTMLMediaElement.HAVE_CURRENT_DATA||b.readyState>=1&&(T(),v!==0&&v!==void 0&&(kf?g(v):setTimeout(()=>{g(v)},0)),p())},{includeLastObservation:!0,clearSignal:a});function p(){let b=!1;e.listen((T,v)=>{if(!b&&(T.seeking!==0||T.event==="seeking"||T.event==="internal-seeking")&&(b=!0),!(f&&!b||T.readyState===0)){if(v(),Si()&&n.duration===0){let _=new te("MEDIA_ERR_NOT_LOADED_METADATA","Cannot load automatically: your browser falsely announced having loaded the content.");o(_)}a.isCancelled()||I()}},{includeLastObservation:!0,clearSignal:a})}function I(){e.listen((b,T)=>{b.seeking===0&&b.rebuffering===null&&b.readyState>=1&&(T(),y())},{includeLastObservation:!0,clearSignal:a})}function y(){var T;if(m.info("Init: Can begin to play content"),r){if(n.ended)return m.warn("Init: autoplay is enabled but the video is ended. Skipping autoplay to prevent video to start again"),s.setValue(!0),s.finish(),c(),u({type:"skipped"})}else return n.autoplay&&m.warn("Init: autoplay is enabled on HTML media element. Media will play as soon as possible."),s.setValue(!0),s.finish(),c(),u({type:"skipped"});let b;try{b=(T=n.play())!=null?T:Promise.resolve()}catch(v){return c(),l(v)}b.then(()=>{if(!a.isCancelled())return s.setValue(!0),s.finish(),c(),u({type:"autoplay"})}).catch(v=>{if(c(),!a.isCancelled())if(v instanceof Error&&v.name==="NotAllowedError"){m.warn("Init: Media element can't play. It may be due to browser auto-play policies.");let _=new te("MEDIA_ERR_BLOCKED_AUTOPLAY","Cannot trigger auto-play automatically: your browser does not allow it.");return o(_),a.isCancelled()?void 0:u({type:"autoplay-blocked"})}else l(v)})}}),initialPlayPerformed:s}}function Ei(n,e,t,r){if(e.length===0)return u("No `keySystems` option given.");if(me.decrypt===null)return u("EME feature not activated.");let i=new B;i.linkToSignal(r);let o=new H({initializationState:{type:"uninitialized",value:null},drmSystemId:void 0},r),a=me.decrypt;if(!a.hasEmeApis())return u("EME API not available on the current page.");m.debug("Init: Creating ContentDecryptor");let s=new a(n,e),d=l=>{var c;l>0&&((c=t.onCodecSupportUpdate)==null||c.call(t),s.removeEventListener("stateChange",d))};return s.addEventListener("stateChange",d),s.addEventListener("stateChange",l=>{if(l===1){let c=new H(!1);c.onUpdate((f,g)=>{f&&(g(),l===1&&s.attach())},{clearSignal:i.signal}),o.setValue({initializationState:{type:"awaiting-media-link",value:{isMediaLinked:c}},drmSystemId:s.systemId})}else l===2&&(o.setValue({initializationState:{type:"initialized",value:null},drmSystemId:s.systemId}),s.removeEventListener("stateChange"))}),s.addEventListener("error",l=>{i.cancel(),t.onError(l)}),s.addEventListener("warning",l=>{t.onWarning(l)}),s.addEventListener("blackListProtectionData",l=>{t.onBlackListProtectionData(l)}),s.addEventListener("keyIdsCompatibilityUpdate",l=>{t.onKeyIdsCompatibilityUpdate(l)}),i.signal.register(()=>{s.dispose()}),{statusRef:o,contentDecryptor:{enabled:!0,value:s}};function u(l){let c=new pe("MEDIA_IS_ENCRYPTED_ERROR",l),f=new H({initializationState:{type:"initialized",value:null},drmSystemId:void 0});return f.finish(),{statusRef:f,contentDecryptor:{enabled:!1,value:c}}}}var vi=class{constructor(e){this._displayer=e}pushTextData(e){try{return Promise.resolve(this._displayer.pushTextData(e))}catch(t){return Promise.reject(t)}}remove(e,t){try{return Promise.resolve(this._displayer.removeBuffer(e,t))}catch(r){return Promise.reject(r)}}reset(){this._displayer.reset()}stop(){this._displayer.stop()}};var Nh=lr,Xn=Nh;var Ri=1/60,En=class extends re{constructor(e,t,r){super(),this._playbackObserver=e,this._manifest=t,this._speed=r,this._discontinuitiesStore=[],this._isStarted=!1,this._canceller=new B}start(){if(this._isStarted)return;this._isStarted=!0;let e=new Cd(this._playbackObserver,this._speed);this._canceller.signal.register(()=>{e.dispose()});let t=null;this._playbackObserver.listen(r=>{let i=this._discontinuitiesStore,{buffered:o,position:a,readyState:s,rebuffering:d,freezing:u}=r,{BUFFER_DISCONTINUITY_THRESHOLD:l,FREEZING_STALLED_DELAY:c,UNFREEZING_SEEK_DELAY:f,UNFREEZING_DELTA_POSITION:g}=U.getCurrent();if(u!==null){let v=K(),_=t===null?u.timestamp:t.attemptTimestamp;if(v-_>f&&(m.warn("Init: trying to seek to un-freeze player"),this._playbackObserver.setCurrentTime(r.position.getWanted()+g),t={attemptTimestamp:v}),v-u.timestamp>c){d===null?e.stopRebuffering():e.startRebuffering(),this.trigger("stalled","freezing");return}}else t=null;if(d===null){if(e.stopRebuffering(),s===1){let v;r.seeking!==0?v=r.seeking===1?"internal-seek":"seeking":v="not-ready",this.trigger("stalled",v);return}this.trigger("unstalled",null);return}let p=d.reason==="seeking"&&r.seeking===1?"internal-seek":d.reason;if(a.isAwaitingFuturePosition()?(e.stopRebuffering(),m.debug("Init: let rebuffering happen as we're awaiting a future position")):e.startRebuffering(),this._manifest===null||Xn&&K()-d.timestamp<=1e3){this.trigger("stalled",p);return}let{position:I}=d,y=r.position.isAwaitingFuturePosition()?r.position.getWanted():this._playbackObserver.getCurrentTime();if(I!=null&&this._speed.getValue()>0){let v=Uh(i,this._manifest,I);if(v!==null){let _=v+.001;if(_<=y)m.info("Init: position to seek already reached, no seeking",y,_);else{m.warn("SA: skippable discontinuity found in the stream",a.getPolled(),_),this._playbackObserver.setCurrentTime(_),this.trigger("warning",kd(I,_));return}}}let b=I!=null?I:a.getPolled(),T=$l(o,b);if((!Xn||K()-d.timestamp>1e3)&&this._speed.getValue()>0&&T<l){let v=b+T+Ri;if(y<v){m.warn("Init: discontinuity encountered inferior to the threshold",b,v,l),this._playbackObserver.setCurrentTime(v),this.trigger("warning",kd(b,v));return}}for(let v=this._manifest.periods.length-2;v>=0;v--){let _=this._manifest.periods[v];if(_.end!==void 0&&_.end<=b){if(this._manifest.periods[v+1].start>b&&this._manifest.periods[v+1].start>y){let R=this._manifest.periods[v+1];this._playbackObserver.setCurrentTime(R.start),this.trigger("warning",kd(b,R.start));return}break}}this.trigger("stalled",p)},{includeLastObservation:!0,clearSignal:this._canceller.signal})}updateDiscontinuityInfo(e){this._isStarted||this.start();let t=this._playbackObserver.getReference().getValue();Bh(this._discontinuitiesStore,e,t)}onLockedStream(e,t){var s;this._isStarted||this.start();let r=this._playbackObserver.getReference().getValue();if(r.rebuffering===null||r.paused||this._speed.getValue()<=0||e!=="audio"&&e!=="video")return;let i=r.position.getWanted(),o=(s=r.rebuffering.position)!=null?s:i,a=t.start;i<a&&Math.abs(o-a)<1&&(m.warn(`Init: rebuffering because of a future locked stream.
|
|
4
|
+
Trying to unlock by seeking to the next Period`),this._playbackObserver.setCurrentTime(a+.001))}destroy(){this._canceller.cancel()}};function Uh(n,e,t){if(n.length===0)return null;let r=null;for(let i of n){let{period:o}=i;if(o.start>t)return r;let a;if(o.end===void 0||o.end>t){let{discontinuity:s,position:d}=i,{start:u,end:l}=s,c=u!=null?u:d;if(t>=c-Ri)if(l===null){let f=Eo(e,o);f!==null?a=f.start+Ri:m.warn("Init: discontinuity at Period's end but no next Period")}else t<l+Ri&&(a=l+Ri);a!==void 0&&(m.info("Init: discontinuity found",t,a),r=r!==null&&r>a?r:a)}}return r}function Rd(n){return n.discontinuity!==null}function Bh(n,e,t){let r=Math.min(t.position.getPolled(),t.position.getWanted());for(;n.length>0&&n[0].period.end!==void 0&&n[0].period.end+10<r;)n.shift();let{period:i,bufferType:o}=e;if(!(o!=="audio"&&o!=="video")){for(let a=0;a<n.length;a++)if(n[a].period.id===i.id){if(n[a].bufferType===o){Rd(e)?n[a]=e:n.splice(a,1);return}}else if(n[a].period.start>i.start){Rd(e)&&n.splice(a,0,e);return}Rd(e)&&n.push(e)}}function kd(n,e){return new te("DISCONTINUITY_ENCOUNTERED","A discontinuity has been encountered at position "+String(n)+", seeking at position "+String(e))}var Cd=class{constructor(e,t){this._speedUpdateCanceller=new B,this._isRebuffering=!1,this._playbackObserver=e,this._isDisposed=!1,this._speed=t,this._updateSpeed()}startRebuffering(){this._isRebuffering||this._isDisposed||(this._isRebuffering=!0,this._speedUpdateCanceller.cancel(),m.info("Init: Pause playback to build buffer"),this._playbackObserver.setPlaybackRate(0))}stopRebuffering(){!this._isRebuffering||this._isDisposed||(this._isRebuffering=!1,this._speedUpdateCanceller=new B,this._updateSpeed())}dispose(){this._speedUpdateCanceller.cancel(),this._isDisposed=!0}_updateSpeed(){this._speed.onUpdate(e=>{m.info("Init: Resume playback speed",e),this._playbackObserver.setPlaybackRate(e)},{clearSignal:this._speedUpdateCanceller.signal,emitCurrentValue:!0})}};function Fh(n,e){return n.id===e.id&&n.start===e.start&&n.end===e.end}var Cf=Fh;function Kh(n,e){let t=[],{periods:r}=e;for(let i of r){let{streamEvents:o}=i;o.forEach(({start:a,end:s,id:d,data:u})=>{for(let f of n)if(Cf(f,{id:d,start:a,end:s})){t.push(f);return}let l;if(u.value.element!==void 0)l=u.value.element;else if(u.value.xmlData!==void 0){let f=u.value.xmlData.namespaces.reduce((p,I)=>p+"xmlns:"+I.key+'="'+I.value+'" ',"<toremove ");f+=">";let g=new DOMParser().parseFromString(f+u.value.xmlData.data+"</toremove>","application/xml").documentElement;l=g.children.length>0?g.children[0]:g.childNodes[0]}else return;let c={type:u.type,value:ue(oe({},u.value),{element:l})};if(s===void 0){let f={start:a,id:d,data:c,publicEvent:{start:a,data:c}};t.push(f)}else{let f={start:a,end:s,id:d,data:c,publicEvent:{start:a,end:s,data:c}};t.push(f)}})}return t}var Pd=Kh;var ki=class extends re{constructor(e,t,r){super(),this._manifest=e,this._mediaElement=t,this._playbackObserver=r,this._canceller=null,this._scheduledEventsRef=new H([]),this._eventsBeingPlayed=new WeakMap}start(){if(this._canceller!==null)return;this._canceller=new B;let e=this._canceller.signal,t=this._playbackObserver,r=this._mediaElement,i=!1,o=new B;o.linkToSignal(e),this._scheduledEventsRef.setValue(Pd([],this._manifest)),this._scheduledEventsRef.onUpdate(({length:a})=>{if(a===0){i&&(o.cancel(),o=new B,o.linkToSignal(e),i=!1);return}else if(i)return;i=!0;let s=c(),d=()=>{let f=c();this._emitStreamEvents(this._scheduledEventsRef.getValue(),s,f,o.signal),s=f},{STREAM_EVENT_EMITTER_POLL_INTERVAL:u}=U.getCurrent(),l=setInterval(d,u);t.listen(d,{includeLastObservation:!1,clearSignal:o.signal}),o.signal.register(()=>{clearInterval(l)});function c(){let f=t.getReference().getValue(),g=r.currentTime,p=f.seeking!==0;return{currentTime:g,isSeeking:p}}},{emitCurrentValue:!0,clearSignal:e})}onManifestUpdate(e){let t=this._scheduledEventsRef.getValue();this._scheduledEventsRef.setValue(Pd(t,e))}stop(){this._canceller!==null&&(this._canceller.cancel(),this._canceller=null)}_emitStreamEvents(e,t,r,i){let{currentTime:o}=t,{isSeeking:a,currentTime:s}=r,d=[],u=[];for(let l=0;l<e.length;l++){let c=e[l],f=c.start,g=Md(c)?c.end:void 0;this._eventsBeingPlayed.has(c)?(f>s||g!==void 0&&s>=g)&&(Md(c)&&u.push(c.publicEvent),this._eventsBeingPlayed.delete(c)):f<=s&&g!==void 0&&s<g?(d.push({type:"stream-event",value:c.publicEvent}),this._eventsBeingPlayed.set(c,!0)):o<f&&s>=(g!=null?g:f)&&(a?d.push({type:"stream-event-skip",value:c.publicEvent}):(d.push({type:"stream-event",value:c.publicEvent}),Md(c)&&u.push(c.publicEvent)))}if(d.length>0){for(let l of d)if(l.type==="stream-event"?this.trigger("event",l.value):this.trigger("eventSkip",l.value),i.isCancelled())return}if(u.length>0){for(let l of u)if(typeof l.onExit=="function"&&l.onExit(),i.isCancelled())return}}};function Md(n){return n.end!==void 0}var Pf=ki;function Ci(n,e,t){if(t.isCancelled())return;n.addEventListener("error",r),t.register(()=>{n.removeEventListener("error",r)});function r(){let i=n.error,o,a;switch(E(i)||(o=i.code,a=i.message),o){case 1:return a=a!=null?a:"The fetching of the associated resource was aborted by the user's request.",e(new te("MEDIA_ERR_ABORTED",a));case 2:return a=a!=null?a:"A network error occurred which prevented the media from being successfully fetched",e(new te("MEDIA_ERR_NETWORK",a));case 3:return a=a!=null?a:"An error occurred while trying to decode the media resource",e(new te("MEDIA_ERR_DECODE",a));case 4:return a=a!=null?a:"The media resource has been found to be unsuitable.",e(new te("MEDIA_ERR_SRC_NOT_SUPPORTED",a));default:return a=a!=null?a:"The HTMLMediaElement errored due to an unknown reason.",e(new te("MEDIA_ERR_UNKNOWN",a))}}}var vn=class extends Yn{constructor(e){super(),this._initSettings=e,this._initCanceller=new B,this._manifest=null,this._decryptionCapabilities={status:"uninitialized",value:null};let t=e.url===void 0?void 0:[e.url];this._cmcdDataBuilder=e.cmcd===void 0?null:new dc(e.cmcd),this._manifestFetcher=new Xs(t,e.transport,ue(oe({},e.manifestRequestSettings),{lowLatencyMode:e.lowLatencyMode,cmcdDataBuilder:this._cmcdDataBuilder}))}prepare(){this._manifest===null&&(this._manifest=_f.createAsync(at(this._initCanceller.signal,(e,t)=>{this._manifestFetcher.addEventListener("warning",r=>this.trigger("warning",r)),this._manifestFetcher.addEventListener("error",r=>{this.trigger("error",r),t(r)}),this._manifestFetcher.addEventListener("manifestReady",r=>{e(r)})})),this._manifestFetcher.start(),this._initCanceller.signal.register(()=>{this._manifestFetcher.dispose()}))}start(e,t){this.prepare(),Ci(e,r=>this._onFatalError(r),this._initCanceller.signal),this._setupInitialMediaSourceAndDecryption(e).then(r=>this._onInitialMediaSourceReady(e,r.mediaSource,t,r.drmSystemId,r.unlinkMediaSource)).catch(r=>{this._onFatalError(r)})}updateContentUrls(e,t){this._manifestFetcher.updateContentUrls(e,t)}dispose(){this._initCanceller.cancel()}_onFatalError(e){this._initCanceller.isUsed()||(this._initCanceller.cancel(),this.trigger("error",e))}_setupInitialMediaSourceAndDecryption(e){let t=this._initCanceller;return at(t.signal,r=>{let{keySystems:i}=this._initSettings,{statusRef:o,contentDecryptor:a}=Ei(e,i,{onWarning:s=>this.trigger("warning",s),onError:s=>this._onFatalError(s),onBlackListProtectionData:s=>{(async()=>{var u;if(this._manifest===null)return;let d=(u=this._manifest.syncValue)!=null?u:await this._manifest.getValueAsAsync();Hh(d,s)})().catch(X)},onKeyIdsCompatibilityUpdate:s=>{(async()=>{var u;if(this._manifest===null)return;let d=(u=this._manifest.syncValue)!=null?u:await this._manifest.getValueAsAsync();zh(d,s.whitelistedKeyIds,s.blacklistedKeyIds,s.delistedKeyIds)})().catch(X)},onCodecSupportUpdate:()=>{var d,u;let s=(d=this._manifest)==null?void 0:d.syncValue;E(s)?(u=this._manifest)==null||u.getValueAsAsync().then(l=>{this._initCanceller.isUsed()||this._refreshManifestCodecSupport(l)},X):this._refreshManifestCodecSupport(s)}},t.signal);a.enabled?this._decryptionCapabilities={status:"enabled",value:a.value}:this._decryptionCapabilities={status:"disabled",value:a.value},o.onUpdate((s,d)=>{if(s.initializationState.type==="uninitialized")return;d();let u=new B;u.linkToSignal(t.signal),oa(e,u.signal).then(l=>{let c=o.getValue();if(c.initializationState.type==="awaiting-media-link")c.initializationState.value.isMediaLinked.setValue(!0),o.onUpdate((f,g)=>{if(f.initializationState.type==="initialized"){g(),r({mediaSource:l,drmSystemId:f.drmSystemId,unlinkMediaSource:u});return}},{emitCurrentValue:!0,clearSignal:t.signal});else if(s.initializationState.type==="initialized"){r({mediaSource:l,drmSystemId:s.drmSystemId,unlinkMediaSource:u});return}}).catch(l=>{u.isUsed()||this._onFatalError(l)})},{emitCurrentValue:!0,clearSignal:t.signal})})}async _onInitialMediaSourceReady(e,t,r,i,o){var R;let{adaptiveOptions:a,autoPlay:s,bufferOptions:d,lowLatencyMode:u,segmentRequestOptions:l,speed:c,startAt:f,textTrackOptions:g,transport:p}=this._initSettings,I=this._initCanceller;ee(this._manifest!==null);let y;try{y=(R=this._manifest.syncValue)!=null?R:await this._manifest.getValueAsAsync()}catch(k){return}y.addEventListener("manifestUpdate",k=>{this.trigger("manifestUpdate",k),this._refreshManifestCodecSupport(y)},I.signal),y.addEventListener("decipherabilityUpdate",k=>{this.trigger("decipherabilityUpdate",k)},I.signal),y.addEventListener("supportUpdate",()=>{this.trigger("codecSupportUpdate",null)},I.signal),m.debug("Init: Calculating initial time");let b=_d(y,u,f);m.debug("Init: Initial time calculated:",b);let T=ac(a),v=G({textTrackOptions:g,drmSystemId:i},d),_=new td(p,this._cmcdDataBuilder,l,I.signal);this._refreshManifestCodecSupport(y),this.trigger("manifestReady",y),!I.isUsed()&&this._setupContentWithNewMediaSource({mediaElement:e,playbackObserver:r,mediaSource:t,initialTime:b,autoPlay:s,manifest:y,representationEstimator:T,segmentQueueCreator:_,speed:c,bufferOptions:v},o)}_setupContentWithNewMediaSource(e,t){this._startLoadingContentOnMediaSource(e,this._createReloadMediaSourceCallback(e,t),t.signal)}_createReloadMediaSourceCallback(e,t){let r=this._initCanceller;return i=>{if(t.cancel(),r.isUsed()||(this.trigger("reloadingMediaSource",i),r.isUsed()))return;let o=new B;o.linkToSignal(r.signal),oa(e.mediaElement,o.signal).then(a=>{this._setupContentWithNewMediaSource(ue(oe({},e),{mediaSource:a,initialTime:i.position,autoPlay:i.autoPlay}),o)}).catch(a=>{o.isUsed()||this._onFatalError(a)})}}_startLoadingContentOnMediaSource(e,t,r){var O,F;let{autoPlay:i,bufferOptions:o,initialTime:a,manifest:s,mediaElement:d,mediaSource:u,playbackObserver:l,representationEstimator:c,segmentQueueCreator:f,speed:g}=e,p=(O=s.getPeriodForTime(a))!=null?O:s.getNextPeriod(a);if(p===void 0){let A=new te("MEDIA_STARTING_TIME_NOT_FOUND","Wanted starting time not found in the Manifest.");return this._onFatalError(A)}let I=null,y=Vh(d,this._initSettings.textTrackOptions);if(y!==null){let A=new vi(y);I=A,r.register(()=>{A.stop(),y==null||y.stop()})}let b=new en(u,d.nodeName==="VIDEO",I);r.register(()=>{b.disposeAll()});let{autoPlayResult:T,initialPlayPerformed:v}=_i({mediaElement:d,playbackObserver:l,startTime:a,mustAutoPlay:i,onWarning:A=>{this.trigger("warning",A)},isDirectfile:!1},r);if(r.isCancelled())return;v.onUpdate((A,C)=>{if(A){C();let D=new Pf(s,d,l);s.addEventListener("manifestUpdate",()=>{D.onManifestUpdate(s)},r),D.addEventListener("event",L=>{this.trigger("streamEvent",L)},r),D.addEventListener("eventSkip",L=>{this.trigger("streamEventSkip",L)},r),D.start(),r.register(()=>{D.stop()})}},{clearSignal:r,emitCurrentValue:!0});let _=yd(l,{autoPlay:i,manifest:s,mediaSource:u,textDisplayer:y,initialPlayPerformed:v,speed:g},r);(F=this._cmcdDataBuilder)==null||F.startMonitoringPlayback(_),r.register(()=>{var A;(A=this._cmcdDataBuilder)==null||A.stopMonitoringPlayback()});let R=this._createRebufferingController(l,s,g,r),k=new si(b);Vl&&s.addEventListener("decipherabilityUpdate",A=>{A.some(C=>C.representation.decipherable!==!0)&&N(0,void 0,void 0)},r),l.listen(A=>{if(k.needToReload(A)){let C,D=l.getReference().getValue();D.position.isAwaitingFuturePosition()?C=D.position.getWanted():C=l.getCurrentTime();let L=v.getValue()?!l.getIsPaused():i;t({position:C,autoPlay:L})}},{clearSignal:r}),_.listen(A=>{["video","audio","text"].forEach(C=>{var L;let D=b.getStatus(C);D.type==="initialized"&&D.value.synchronizeInventory((L=A.buffered[C])!=null?L:[])})},{clearSignal:r});let x=rd(s,u,_,b,{onWarning:A=>this.trigger("warning",A),onPeriodChanged:A=>this.trigger("activePeriodChanged",{period:A})},r);T.then(()=>{Ti(l,d,!1,r).onUpdate((A,C)=>{A&&(C(),this.trigger("loaded",{getSegmentSinkMetrics:async()=>new Promise(D=>D(b.getSegmentSinksMetrics()))}))},{emitCurrentValue:!0,clearSignal:r})}).catch(A=>{r.isCancelled()||this._onFatalError(A)});let M=this;Tf({manifest:s,initialPeriod:p},_,c,b,f,o,P(),r);function P(){return{needsBufferFlush:A=>{var $;let C,D=l.getCurrentTime(),L=($=A==null?void 0:A.relativeResumingPosition)!=null?$:0,V=!!(A!=null&&A.relativePosHasBeenDefaulted);L===0&&V?C=D+.001:C=D+L,l.setCurrentTime(C),l.listen((j,z)=>{(j.currentRange!==null||j.position.getPolled()>C+.1)&&(z(),l.setCurrentTime(j.position.getWanted()+.001))},{includeLastObservation:!1,clearSignal:r})},streamStatusUpdate(A){let{period:C,bufferType:D,imminentDiscontinuity:L,position:V}=A;R.updateDiscontinuityInfo({period:C,bufferType:D,discontinuity:L,position:V}),!r.isCancelled()&&s.isLastPeriodKnown&&A.period.id===s.periods[s.periods.length-1].id&&(A.hasFinishedLoading||A.isEmptyStream?x.onLastSegmentFinishedLoading(A.bufferType):x.onLastSegmentLoadingResume(A.bufferType))},needsManifestRefresh:()=>M._manifestFetcher.scheduleManualRefresh({enablePartialRefresh:!0,canUseUnsafeMode:!0}),manifestMightBeOufOfSync:()=>{let{OUT_OF_SYNC_MANIFEST_REFRESH_DELAY:A}=U.getCurrent();M._manifestFetcher.scheduleManualRefresh({enablePartialRefresh:!1,canUseUnsafeMode:!1,delay:A})},lockedStream:A=>R.onLockedStream(A.bufferType,A.period),adaptationChange:A=>{M.trigger("adaptationChange",A),!r.isCancelled()&&x.onAdaptationChange(A.type,A.period,A.adaptation)},representationChange:A=>{M.trigger("representationChange",A),!r.isCancelled()&&x.onRepresentationChange(A.type,A.period)},inbandEvent:A=>M.trigger("inbandEvents",A),warning:A=>M.trigger("warning",A),periodStreamReady:A=>M.trigger("periodStreamReady",A),periodStreamCleared:A=>{x.onPeriodCleared(A.type,A.period),!r.isCancelled()&&M.trigger("periodStreamCleared",A)},bitrateEstimateChange:A=>{var C;(C=M._cmcdDataBuilder)==null||C.updateThroughput(A.type,A.bitrate),M.trigger("bitrateEstimateChange",A)},needsMediaSourceReload:A=>{N(A.timeOffset,A.minimumPosition,A.maximumPosition)},needsDecipherabilityFlush(){var C,D,L,V;let A=Hn(d);if(Ga(A==null?void 0:A[0])){let $=_.getReference().getValue(),j=$.position.isAwaitingFuturePosition()?$.position.getWanted():(C=_.getCurrentTime())!=null?C:$.position.getPolled(),z=(L=(D=$.paused.pending)!=null?D:_.getIsPaused())!=null?L:$.paused.last;t({position:j,autoPlay:!z})}else{let $=_.getReference().getValue(),j=$.position.isAwaitingFuturePosition()?$.position.getWanted():(V=_.getCurrentTime())!=null?V:$.position.getPolled();j+.001<$.duration?l.setCurrentTime(d.currentTime+.001):l.setCurrentTime(j)}},encryptionDataEncountered:A=>{if(M._decryptionCapabilities.status==="disabled"){M._onFatalError(M._decryptionCapabilities.value);return}else if(M._decryptionCapabilities.status==="uninitialized"){m.error("Init: received encryption data without known decryption capabilities");return}for(let C of A)if(M._decryptionCapabilities.value.onInitializationData(C),r.isCancelled())return},error:A=>M._onFatalError(A)}}function N(A,C,D){var z,q,W;let L=_.getReference().getValue(),V=L.position.isAwaitingFuturePosition()?L.position.getWanted():(z=_.getCurrentTime())!=null?z:L.position.getPolled(),$=(W=(q=L.paused.pending)!=null?q:_.getIsPaused())!=null?W:L.paused.last,j=V+A;C!==void 0&&(j=Math.max(C,j)),D!==void 0&&(j=Math.min(D,j)),t({position:j,autoPlay:!$})}}_createRebufferingController(e,t,r,i){let o=new En(e,t,r);return o.addEventListener("stalled",a=>this.trigger("stalled",a)),o.addEventListener("unstalled",()=>this.trigger("unstalled",null)),o.addEventListener("warning",a=>this.trigger("warning",a)),i.register(()=>o.destroy()),o.start(),o}getCodecsSupportInfo(e){return e.map(r=>{var s;let i=`${r.mimeType};codecs="${r.codec}"`,o=Ba(i);if(!o)return{mimeType:r.mimeType,codec:r.codec,supported:!1,supportedIfEncrypted:!1};let a;if(this._decryptionCapabilities.status==="uninitialized")a=void 0;else if(this._decryptionCapabilities.status==="disabled")a=!0;else{let d=this._decryptionCapabilities.value;d.getState()!==0&&(a=(s=d.isCodecSupported(r.mimeType,r.codec))!=null?s:!0)}return{mimeType:r.mimeType,codec:r.codec,supported:o,supportedIfEncrypted:a}})}_refreshManifestCodecSupport(e){let t=e.getCodecsWithUnknownSupport(),r=this.getCodecsSupportInfo(t);if(r.length>0)try{e.updateCodecSupport(r)}catch(i){this._onFatalError(i)}}};function Vh(n,e){return e.textTrackMode==="html"&&me.htmlTextDisplayer!==null?new me.htmlTextDisplayer(n,e.textTrackElement):me.nativeTextDisplayer!==null?new me.nativeTextDisplayer(n):null}function zh(n,e,t,r){n.updateRepresentationsDeciperability(i=>{let{representation:o}=i;if(o.contentProtections===void 0)return o.decipherable;let a=o.contentProtections.keyIds;if(a!==void 0)for(let s of a){for(let d of t)if(ge(d,s))return!1;for(let d of e)if(ge(d,s))return!0;for(let d of r)if(ge(d,s))return}return o.decipherable})}function Hh(n,e){n.updateRepresentationsDeciperability(t=>{var o,a;let r=t.representation;if(r.decipherable===!1)return!1;let i=(a=(o=r.contentProtections)==null?void 0:o.initData)!=null?a:[];for(let s of i)if((e.type===void 0||s.type===e.type)&&e.values.getFormattedValues().every(u=>s.values.some(l=>(u.systemId===void 0||l.systemId===u.systemId)&&ge(l.data,u.data))))return!1;return r.decipherable})}function Ad(n,e,t){let{repeatCount:r}=n;if(r>=0)return r;let i;return E(e)?t!==void 0?i=t:i=Number.MAX_VALUE:i=e.start,Math.ceil((i-n.start)/n.duration)-1}function ke(n,e,t){let{start:r,duration:i}=n;if(i<=0)return r;let o=Ad(n,e,t);return r+(o+1)*i}function He(n,e){var t;return n*e.timescale+((t=e.indexTimeOffset)!=null?t:0)}function _t(n,e){var t;return(n-((t=e.indexTimeOffset)!=null?t:0))/e.timescale}function Mf(n,e,t){return[n*t,(n+e)*t]}function Wh(n,e){let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i].start<=e?t=i+1:r=i}return t-1}function aa(n,e,t){let{timeline:r}=n,i=He(e,n);if(i<0)return null;let o=Wh(r,i);if(o<0||o>=r.length-1)return null;let a=r[o];if(a.duration<=0)return null;let s=r[o+1];if(s===void 0)return null;let d=s.start,u=ke(a,s,t);return i>=u&&i<d?_t(d,n):null}function wt(n,e){var i;let{initialization:t}=n,r={};return e!==void 0&&(r.isEMSGWhitelisted=e),{id:"init",isInit:!0,time:0,end:0,duration:0,timescale:1,range:E(t)?void 0:t.range,indexRange:n.indexRange,url:(i=t==null?void 0:t.url)!=null?i:null,complete:!0,privateInfos:r,timestampOffset:-(n.indexTimeOffset/n.timescale)}}function Gh(n,e){let t=n.toString();return t.length>=e?t:(new Array(e+1).join("0")+t).slice(-e)}function xd(n){return(e,t,r)=>{let i=w(r)?parseInt(r,10):1;return Gh(String(n),i)}}function dt(n,e,t){return qh(n,e,t)}function qh(n,e,t){return n.indexOf("$")===-1?n:n.replace(/\$\$/g,"$").replace(/\$RepresentationID\$/g,String(e)).replace(/\$Bandwidth(\%0(\d+)d)?\$/g,xd(t===void 0?0:t))}function sa(n,e){return function(r){return r.indexOf("$")===-1?r:r.replace(/\$\$/g,"$").replace(/\$Number(\%0(\d+)d)?\$/g,(i,o,a)=>{if(e===void 0)throw new Error("Segment number not defined in a $Number$ scheme");return xd(e)(i,o,a)}).replace(/\$Time(\%0(\d+)d)?\$/g,(i,o,a)=>{if(n===void 0)throw new Error("Segment time not defined in a $Time$ scheme");return xd(n)(i,o,a)})}}function jh(n,e,t){let r=t-n;return r>0?Math.floor(r/e):0}function Pi(n,e,t,r,i,o){var T;let a=r.getEstimatedMaximumPosition((T=n.availabilityTimeOffset)!=null?T:0),s=Math.min(e+t,a!=null?a:1/0),d=He(e,n),u=He(s,n),{timeline:l,timescale:c,segmentUrlTemplate:f,startNumber:g,endNumber:p}=n,I=g!=null?g:1,y=[],b=l.length;for(let v=0;v<b;v++){let _=l[v],{duration:R,start:k,range:x}=_,M;a===void 0?M=i:M=Math.min(a*c,i!=null?i:1/0);let P=Ad(_,l[v+1],M),N=n.availabilityTimeComplete!==!1||v!==b-1&&P!==0,O=jh(k,R,d),F=k+O*R;for(;F<u&&O<=P;){let A=I+O;if(p!==void 0&&A>p)break;let C=f===null?null:sa(F,A)(f),D=F-n.indexTimeOffset,L=R;D<0&&(L=R+D,D=0);let V={id:String(F),time:D/c,end:(D+L)/c,duration:L/c,isInit:!1,range:x,timescale:1,url:C,number:A,timestampOffset:-(n.indexTimeOffset/c),complete:N,privateInfos:{isEMSGWhitelisted:o}};y.push(V),O++,F=k+O*R}if(F>=u||(I+=P+1,p!==void 0&&I>p))return y}return y}function Yh(n,e){if(e.timescale!==n.timescale){let{timescale:t}=n;n.timeline.push({start:e.time/e.timescale*t,duration:e.duration/e.timescale*t,repeatCount:e.count===void 0?0:e.count,range:e.range})}else n.timeline.push({start:e.time,duration:e.duration,repeatCount:e.count===void 0?0:e.count,range:e.range});return!0}var Rn=class{constructor(e,t){var p,I,y,b;let{periodStart:r,periodEnd:i,representationId:o,representationBitrate:a,isEMSGWhitelisted:s}=t,d=(p=e.timescale)!=null?p:1,l=((I=e.presentationTimeOffset)!=null?I:0)-r*d,c=((y=e.initialization)==null?void 0:y.media)===void 0?null:dt(e.initialization.media,o,a),f=e.media===void 0?null:dt(e.media,o,a),g;e.initialization!==void 0?g=e.initialization.range:e.indexRange!==void 0&&(g=[0,e.indexRange[0]-1]),this._index={indexRange:e.indexRange,indexTimeOffset:l,initialization:{url:c,range:g},segmentUrlTemplate:f,startNumber:e.startNumber,endNumber:e.endNumber,timeline:(b=e.timeline)!=null?b:[],timescale:d},this._manifestBoundsCalculator=t.manifestBoundsCalculator,this._scaledPeriodStart=He(r,this._index),this._scaledPeriodEnd=E(i)?void 0:He(i,this._index),this._isInitialized=this._index.timeline.length>0,this._isEMSGWhitelisted=s}getInitSegment(){return wt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){return Pi(this._index,e,t,this._manifestBoundsCalculator,this._scaledPeriodEnd,this._isEMSGWhitelisted)}shouldRefresh(){return!1}getFirstAvailablePosition(){let e=this._index;return e.timeline.length===0?null:_t(Math.max(this._scaledPeriodStart,e.timeline[0].start),e)}getLastAvailablePosition(){var i;let{timeline:e}=this._index;if(e.length===0)return null;let t=e[e.length-1],r=Math.min(ke(t,null,this._scaledPeriodEnd),(i=this._scaledPeriodEnd)!=null?i:1/0);return _t(r,this._index)}getEnd(){return this.getLastAvailablePosition()}awaitSegmentBetween(){return!1}isSegmentStillAvailable(){return!0}checkDiscontinuity(){return null}canBeOutOfSyncError(){return!1}isStillAwaitingFutureSegments(){return!1}isInitialized(){return this._isInitialized}initialize(e){if(!this._isInitialized){for(let t=0;t<e.length;t++)Yh(this._index,e[t]);this._isInitialized=!0}}addPredictedSegments(){m.warn("Cannot add predicted segments to a `BaseRepresentationIndex`")}_replace(e){this._index=e._index,this._isInitialized=e._isInitialized,this._scaledPeriodEnd=e._scaledPeriodEnd,this._isEMSGWhitelisted=e._isEMSGWhitelisted}_update(){m.error("Base RepresentationIndex: Cannot update a SegmentList")}};var kn=class{constructor(e,t){var g,p,I;if(e.duration===void 0)throw new Error("Invalid SegmentList: no duration");let{periodStart:r,periodEnd:i,representationId:o,representationBitrate:a,isEMSGWhitelisted:s}=t;this._isEMSGWhitelisted=s,this._periodStart=r,this._periodEnd=i;let d=(g=e.presentationTimeOffset)!=null?g:0,u=(p=e.timescale)!=null?p:1,l=d-r*u,c=((I=e.initialization)==null?void 0:I.media)===void 0?null:dt(e.initialization.media,o,a),f=e.list.map(y=>({url:y.media===void 0?null:dt(y.media,o,a),mediaRange:y.mediaRange}));this._index={list:f,timescale:u,duration:e.duration,indexTimeOffset:l,indexRange:e.indexRange,initialization:E(e.initialization)?void 0:{url:c,range:e.initialization.range}}}getInitSegment(){let e=wt(this._index);return e.privateInfos===void 0&&(e.privateInfos={}),e.privateInfos.isEMSGWhitelisted=this._isEMSGWhitelisted,e}getSegments(e,t){let r=this._index,{duration:i,list:o,timescale:a}=r,s=i/a,d=e-this._periodStart,[u,l]=Mf(d,t,a),c=Math.min(o.length-1,Math.floor(l/i)),f=[],g=Math.floor(u/i);for(;g<=c;){let p=o[g].mediaRange,I=o[g].url,y=g*s+this._periodStart,b={id:String(g),time:y,isInit:!1,range:p,duration:s,timescale:1,end:y+s,url:I,timestampOffset:-(r.indexTimeOffset/a),complete:!0,privateInfos:{isEMSGWhitelisted:this._isEMSGWhitelisted}};f.push(b),g++}return f}shouldRefresh(e,t){return!1}getFirstAvailablePosition(){return this._periodStart}getLastAvailablePosition(){var i;let e=this._index,{duration:t,list:r}=e;return Math.min(r.length*t/e.timescale+this._periodStart,(i=this._periodEnd)!=null?i:1/0)}getEnd(){return this.getLastAvailablePosition()}awaitSegmentBetween(){return!1}isSegmentStillAvailable(){return!0}checkDiscontinuity(){return null}canBeOutOfSyncError(){return!1}isStillAwaitingFutureSegments(){return!1}isInitialized(){return!0}initialize(){m.error("A `ListRepresentationIndex` does not need to be initialized")}addPredictedSegments(){m.warn("Cannot add predicted segments to a `ListRepresentationIndex`")}_replace(e){this._index=e._index}_update(){m.error("A `ListRepresentationIndex` cannot be updated")}};function Zn(n){return U.getCurrent().DEFAULT_MAXIMUM_TIME_ROUNDING_ERROR*n}var Cn=class{constructor(e,t){var b,T,v;let{availabilityTimeOffset:r,manifestBoundsCalculator:i,isDynamic:o,periodEnd:a,periodStart:s,representationId:d,representationBitrate:u,isEMSGWhitelisted:l}=t,c=(b=e.timescale)!=null?b:1;this._availabilityTimeOffset=r,this._manifestBoundsCalculator=i;let f=(T=e.presentationTimeOffset)!=null?T:0,g=s*c,p=f-g;if(e.duration===void 0)throw new Error("Invalid SegmentTemplate: no duration");let I=((v=e.initialization)==null?void 0:v.media)===void 0?null:dt(e.initialization.media,d,u),y=e.media===void 0?null:dt(e.media,d,u);this._index={duration:e.duration,timescale:c,indexRange:e.indexRange,indexTimeOffset:p,initialization:E(e.initialization)?void 0:{url:I,range:e.initialization.range},url:y,presentationTimeOffset:f,startNumber:e.startNumber,endNumber:e.endNumber},this._isDynamic=o,this._periodStart=s,this._scaledRelativePeriodEnd=a===void 0?void 0:(a-s)*c,this._isEMSGWhitelisted=l}getInitSegment(){return wt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){let r=this._index,{duration:i,startNumber:o,endNumber:a,timescale:s,url:d}=r,u=this._periodStart*s,l=this._scaledRelativePeriodEnd,c=e*s-u,f=(e+t)*s-u,g=this._getFirstSegmentStart(),p=this._getLastSegmentStart();if(E(g)||E(p))return[];let I=Math.max(g,c),y=Math.min(p,f);if(y+i<=I)return[];let b=[],T=o!=null?o:1,v=Math.floor(I/i);for(let _=v*i;_<=y;_+=i){let R=v+T;if(a!==void 0&&R>a)return b;let k=!E(l)&&_+i>l?l-_:i,x=_+u,M=_+this._index.presentationTimeOffset,P=d===null?null:sa(M,R)(d),N={id:String(R),number:R,time:x/s,end:(x+k)/s,duration:k/s,timescale:1,isInit:!1,scaledDuration:k/s,url:P,timestampOffset:-(r.indexTimeOffset/s),complete:!0,privateInfos:{isEMSGWhitelisted:this._isEMSGWhitelisted}};b.push(N),v++}return b}getFirstAvailablePosition(){let e=this._getFirstSegmentStart();return E(e)?e:e/this._index.timescale+this._periodStart}getLastAvailablePosition(){let e=this._getLastSegmentStart();if(E(e))return e;let t=this._estimateRelativeScaledEnd();return Math.min(e+this._index.duration,t!=null?t:1/0)/this._index.timescale+this._periodStart}getEnd(){if(!this._isDynamic)return this.getLastAvailablePosition();let e=this._estimateRelativeScaledEnd();if(e===void 0)return;let{timescale:t}=this._index;return(e+this._periodStart*t)/t}awaitSegmentBetween(e,t){if(ee(e<=t),!this._isDynamic)return!1;let{timescale:r}=this._index,i=Zn(r),o=this._periodStart*r,a=e*r-o,s=t*r-o,d=this._getLastSegmentStart();if(E(d)){let c=this._estimateRelativeScaledEnd();return c===void 0?s+i>=0:s+i>=0&&a<c-i}let u=d+this._index.duration,l=this._estimateRelativeScaledEnd();return l===void 0?s>u-i:s>u-i&&a<l-i}shouldRefresh(){return!1}checkDiscontinuity(){return null}isSegmentStillAvailable(e){if(e.isInit)return!0;let t=this.getSegments(e.time,.1);return t.length===0?!1:t[0].time===e.time&&t[0].end===e.end&&t[0].number===e.number}canBeOutOfSyncError(){return!1}isStillAwaitingFutureSegments(){if(!this._isDynamic)return!1;let e=this._estimateRelativeScaledEnd();if(e===void 0)return!0;let{timescale:t}=this._index,r=this._getLastSegmentStart();if(E(r))return!0;let i=r+this._index.duration,o=Zn(t);return i+o<e}isInitialized(){return!0}initialize(){m.error("A `TemplateRepresentationIndex` does not need to be initialized")}addPredictedSegments(){m.warn("Cannot add predicted segments to a `TemplateRepresentationIndex`")}_replace(e){this._index=e._index,this._isDynamic=e._isDynamic,this._periodStart=e._periodStart,this._scaledRelativePeriodEnd=e._scaledRelativePeriodEnd,this._manifestBoundsCalculator=e._manifestBoundsCalculator}_update(e){this._replace(e)}_getFirstSegmentStart(){var a;if(!this._isDynamic)return 0;if(this._scaledRelativePeriodEnd===0||this._scaledRelativePeriodEnd===void 0){let s=this._manifestBoundsCalculator.getEstimatedMaximumPosition((a=this._availabilityTimeOffset)!=null?a:0);if(s!==void 0&&s<this._periodStart)return null}let{duration:e,timescale:t}=this._index,r=this._manifestBoundsCalculator.getEstimatedMinimumSegmentTime(e/t);if(r===void 0)return;let i=r>this._periodStart?(r-this._periodStart)*t:0;return Math.floor(i/e)*e}_getLastSegmentStart(){var o,a;let{duration:e,timescale:t,endNumber:r,startNumber:i=1}=this._index;if(this._isDynamic){let s=this._manifestBoundsCalculator.getEstimatedLiveEdge();if(s!==void 0&&this._scaledRelativePeriodEnd!==void 0&&this._scaledRelativePeriodEnd<s-this._periodStart*this._index.timescale){let c=Math.ceil(this._scaledRelativePeriodEnd/e);return r!==void 0&&r-i+1<c&&(c=r-i+1),(c-1)*e}let d=this._manifestBoundsCalculator.getEstimatedMaximumPosition((o=this._availabilityTimeOffset)!=null?o:0);if(d===void 0)return;let u=(d-this._periodStart)*t;if(u<0)return null;let l=Math.floor(u/e);return r!==void 0&&r-i+1<l&&(l=r-i+1),l<=0?null:(l-1)*e}else{let s=(a=this._scaledRelativePeriodEnd)!=null?a:0,d=Math.ceil(s/e);r!==void 0&&r-i+1<d&&(d=r-i+1);let u=(d-1)*e,l=U.getCurrent().MINIMUM_SEGMENT_SIZE*t;return r!==void 0||s-u>l||d<2?u:(d-2)*e}}_estimateRelativeScaledEnd(){var e,t;if(this._index.endNumber!==void 0){let r=this._index.endNumber-((e=this._index.startNumber)!=null?e:1)+1;return Math.max(Math.min(r*this._index.duration,(t=this._scaledRelativePeriodEnd)!=null?t:1/0),0)}if(this._scaledRelativePeriodEnd!==void 0)return Math.max(this._scaledRelativePeriodEnd,0)}};function Mi(n,e){let t=0;for(;n.length>0;){let r=n[0];if(r.start>=e||r.repeatCount===-1)return t;if(r.repeatCount===0)n.shift(),t+=1;else{let i=n[1];if(i!==void 0&&i.start<=e)n.shift(),t+=1;else{if(r.duration<=0)return t;let o=r.start+r.duration,a=1;for(;o<e&&a<=r.repeatCount;)o+=r.duration,a++;if(a>r.repeatCount)n.shift(),t=r.repeatCount+1;else{let s=r.repeatCount-a;return r.start=o,r.repeatCount=s,t+=a,t}}}}return t}function Ai(n,e){if(n.length===0)return n.push(...e),!0;if(e.length===0)return!1;let t=n.length,r=e[0].start,i=n[t-1];if(ke(i,e[0])<r)throw new te("MANIFEST_UPDATE_ERROR","Cannot perform partial update: not enough data");for(let l=t-1;l>=0;l--){let c=n[l].start;if(c===r){let f=t-l;return n.splice(l,f,...e),!1}else if(c<r){let f=n[l];if(f.start+f.duration>r)return m.warn("RepresentationIndex: Manifest update removed all previous segments"),n.splice(0,t,...e),!0;if(f.repeatCount===void 0||f.repeatCount<=0)return f.repeatCount<0&&(f.repeatCount=Math.floor((r-f.start)/f.duration)-1),n.splice(l+1,t-(l+1),...e),!1;if(f.start+f.duration*(f.repeatCount+1)<=r)return n.splice(l+1,t-(l+1),...e),!1;let p=(r-f.start)/f.duration-1;if(p%1===0&&f.duration===e[0].duration){let I=e[0].repeatCount<0?-1:e[0].repeatCount+p+1;return n.splice(l,t-l,...e),n[l].start=f.start,n[l].repeatCount=I,!1}return m.warn("RepresentationIndex: Manifest update removed previous segments"),n[l].repeatCount=Math.floor(p),n.splice(l+1,t-(l+1),...e),!1}}let a=n[n.length-1],s=e[e.length-1];if(a.repeatCount!==void 0&&a.repeatCount<0)return a.start>s.start?(m.warn("RepresentationIndex: The new index is older than the previous one"),!1):(m.warn('RepresentationIndex: The new index is "bigger" than the previous one'),n.splice(0,t,...e),!0);let d=a.start+a.duration*(a.repeatCount+1),u=s.start+s.duration*(s.repeatCount+1);return d>=u?(m.warn("RepresentationIndex: The new index is older than the previous one"),!1):(m.warn('RepresentationIndex: The new index is "bigger" than the previous one'),n.splice(0,t,...e),!0)}function xi(n,e,t){let r=n.start,i=n.duration,o=n.repeatCount;return r===void 0&&(e===null?r=0:E(e.duration)||(r=e.start+e.duration*(e.repeatCount+1))),(i===void 0||isNaN(i))&&t!==null&&t.start!==void 0&&!isNaN(t.start)&&r!==void 0&&!isNaN(r)&&(i=t.start-r),r!==void 0&&!isNaN(r)&&i!==void 0&&!isNaN(i)&&(o===void 0||!isNaN(o))?{start:r,duration:i,repeatCount:o===void 0?0:o}:(m.warn('DASH: A "S" Element could not have been parsed.'),null)}function wi(n){let e={};for(let t of Object.keys(n.attributes)){let r=n.attributes[t];if(!E(r))switch(t){case"t":{let i=parseInt(r,10);isNaN(i)?m.warn(`DASH: invalid t ("${r}")`):e.start=i;break}case"d":{let i=parseInt(r,10);isNaN(i)?m.warn(`DASH: invalid d ("${r}")`):e.duration=i;break}case"r":{let i=parseInt(r,10);isNaN(i)?m.warn(`DASH: invalid r ("${r}")`):e.repeatCount=i;break}}}return e}function Oi(n){let e={};for(let t=0;t<n.attributes.length;t++){let r=n.attributes[t];switch(r.name){case"t":{let i=parseInt(r.value,10);isNaN(i)?m.warn(`DASH: invalid t ("${r.value}")`):e.start=i;break}case"d":{let i=parseInt(r.value,10);isNaN(i)?m.warn(`DASH: invalid d ("${r.value}")`):e.duration=i;break}case"r":{let i=parseInt(r.value,10);isNaN(i)?m.warn(`DASH: invalid r ("${r.value}")`):e.repeatCount=i;break}}}return e}function tn(n){let e=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)e.push(wi(n[r]));else for(let r=0;r<n.length;r++)e.push(Oi(n[r]));let t=[];for(let r=0;r<e.length;r++){let i=e[r],o=t[t.length-1]===void 0?null:t[t.length-1],a=e[r+1]===void 0?null:e[r+1],s=xi(i,o,a);s!==null&&t.push(s)}return t}function wd(n,e){if(n.length===0||e.length===0)return null;let t=n[0].start,r=Array.isArray(e)?e[0].attributes.t:e[0].getAttribute("t"),i=E(r)?null:parseInt(r,10);if(i===null||Number.isNaN(i))return null;if(t===i)return{prevSegmentsIdx:0,newElementsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(t<i){let o=n[0],a=0;for(;;){if(o.repeatCount>0){let s=i-o.start;if(s%o.duration===0&&s/o.duration<=o.repeatCount)return{repeatNumberInPrevSegments:s/o.duration,prevSegmentsIdx:a,newElementsIdx:0,repeatNumberInNewElements:0}}if(a++,a>=n.length)return null;if(o=n[a],o.start===i)return{prevSegmentsIdx:a,newElementsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(o.start>i)return null}}else{let o=0,a=Array.isArray(e)?e[0]:null,s=Array.isArray(e)?null:e[0],d=i;for(;;){let u=a!==null?a.attributes.d:s==null?void 0:s.getAttribute("d"),l=E(u)?null:parseInt(u,10);if(l===null||Number.isNaN(l))return null;let c=a!==null?a.attributes.r:s==null?void 0:s.getAttribute("r"),f=E(c)?null:parseInt(c,10);if(f!==null){if(Number.isNaN(f)||f<0)return null;if(f>0){let I=t-d;if(I%l===0&&I/l<=f)return{repeatNumberInPrevSegments:0,repeatNumberInNewElements:I/l,prevSegmentsIdx:0,newElementsIdx:o}}d+=l*(f+1)}else d+=l;if(o++,o>=e.length)return null;Array.isArray(e)?a=e[o]:s=e[o];let g=a!==null?a.attributes.t:s==null?void 0:s.getAttribute("t"),p=E(g)?null:parseInt(g,10);if(p!==null){if(Number.isNaN(p))return null;d=p}if(d===t)return{newElementsIdx:o,prevSegmentsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(d>i)return null}}}function Od(n,e){var I;let t=wd(e,n);if(t===null)return m.warn('DASH: Cannot perform "based" update. Common segment not found.'),tn(n);let{prevSegmentsIdx:r,newElementsIdx:i,repeatNumberInPrevSegments:o,repeatNumberInNewElements:a}=t,d=e.length-r+i-1;if(d>=n.length)return m.info('DASH: Cannot perform "based" update. New timeline too short'),tn(n);let u=e.slice(r);if(o>0){let y=u[0];y.start+=y.duration*o,u[0].repeatCount-=o}if(a>0&&i!==0)return m.info('DASH: Cannot perform "based" update. The new timeline has a different form.'),tn(n);let l=u[u.length-1],c=Array.isArray(n)?wi(n[d]):Oi(n[d]),f=((I=c.repeatCount)!=null?I:0)-a;if(c.duration!==l.duration||l.repeatCount>f)return m.info('DASH: Cannot perform "based" update. The new timeline has a different form at the beginning.'),tn(n);c.repeatCount!==void 0&&c.repeatCount>l.repeatCount&&(l.repeatCount=c.repeatCount);let g=[],p=[];if(Array.isArray(n))for(let y=d+1;y<n.length;y++)p.push(wi(n[y]));else for(let y=d+1;y<n.length;y++)p.push(Oi(n[y]));for(let y=0;y<p.length;y++){let b=p[y],T=g[g.length-1]===void 0?l:g[g.length-1],v=p[y+1]===void 0?null:p[y+1],_=xi(b,T,v);_!==null&&g.push(_)}return u.concat(g)}var Di=class n{constructor(e,t){var _,R,k,x,M;if(!n.isTimelineIndexArgument(e))throw new Error("The given index is not compatible with a TimelineRepresentationIndex.");let{availabilityTimeComplete:r,availabilityTimeOffset:i,manifestBoundsCalculator:o,isDynamic:a,isLastPeriod:s,representationId:d,representationBitrate:u,periodStart:l,periodEnd:c,isEMSGWhitelisted:f}=t,g=(_=e.timescale)!=null?_:1,p=(R=e.presentationTimeOffset)!=null?R:0,I=l*g,y=p-I;this._manifestBoundsCalculator=o,this._isEMSGWhitelisted=f,this._isLastPeriod=s,this._lastUpdate=(k=t.receivedTime)!=null?k:K(),this._unsafelyBaseOnPreviousIndex=null,t.unsafelyBaseOnPreviousRepresentation!==null&&t.unsafelyBaseOnPreviousRepresentation.index instanceof n&&(t.unsafelyBaseOnPreviousRepresentation.index._unsafelyBaseOnPreviousIndex=null,this._unsafelyBaseOnPreviousIndex=t.unsafelyBaseOnPreviousRepresentation.index),this._isDynamic=a,this._parseTimeline=(x=e.timelineParser)!=null?x:null;let b=((M=e.initialization)==null?void 0:M.media)===void 0?null:dt(e.initialization.media,d,u),T=e.media===void 0?null:dt(e.media,d,u),v;i===void 0&&r===void 0?v=1/0:v=i!=null?i:0,this._index={availabilityTimeComplete:r!=null?r:!0,availabilityTimeOffset:v,indexRange:e.indexRange,indexTimeOffset:y,initialization:E(e.initialization)?void 0:{url:b,range:e.initialization.range},segmentUrlTemplate:T,startNumber:e.startNumber,endNumber:e.endNumber,timeline:e.timeline===void 0?null:Dd(e.timeline,e.startNumber,e.endNumber),timescale:g},this._scaledPeriodStart=He(l,this._index),this._scaledPeriodEnd=c===void 0?void 0:He(c,this._index)}getInitSegment(){return wt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){return this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),Pi(this._index,e,t,this._manifestBoundsCalculator,this._scaledPeriodEnd,this._isEMSGWhitelisted)}shouldRefresh(){return!1}getFirstAvailablePosition(){this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let e=this._index.timeline;return e.length===0?null:_t(Math.max(this._scaledPeriodStart,e[0].start),this._index)}getLastAvailablePosition(){var r;this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let e=da(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(e===null)return null;let t=Math.min(e.end,(r=this._scaledPeriodEnd)!=null?r:1/0);return _t(t,this._index)}getEnd(){var r;if(this._isDynamic&&!this._isLastPeriod)return;if(this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),this._index.timeline.length<=0)return null;let e=this._index.timeline[this._index.timeline.length-1],t=Math.min(ke(e,null,this._scaledPeriodEnd),(r=this._scaledPeriodEnd)!=null?r:1/0);return _t(t,this._index)}awaitSegmentBetween(e,t){var u,l;if(ee(e<=t),!this._isDynamic)return!1;this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let{timescale:r,timeline:i}=this._index,o=Zn(r),a=He(t,this._index),s=da(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(s!==null&&Math.min(s.end,(u=this._scaledPeriodEnd)!=null?u:1/0)+o>=Math.min(a,(l=this._scaledPeriodEnd)!=null?l:1/0))return!1;let d=He(e,this._index);if(i.length>0&&s!==null&&!s.isLastOfTimeline){let c=i[i.length-1],g=ke(c,null,this._scaledPeriodEnd)+o;if(d<g+o)return!0}return this._isLastPeriod?this._scaledPeriodEnd===void 0?a+o>this._scaledPeriodStart?void 0:!1:d-o<this._scaledPeriodEnd&&a+o>this._scaledPeriodStart:!1}isSegmentStillAvailable(e){return e.isInit?!0:(this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),$h(e,this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd))}checkDiscontinuity(e){this._refreshTimeline();let t=this._index.timeline;return t===null&&(t=this._getTimeline(),this._index.timeline=t),aa({timeline:t,timescale:this._index.timescale,indexTimeOffset:this._index.indexTimeOffset},e,this._scaledPeriodEnd)}canBeOutOfSyncError(e){return this._isDynamic?e instanceof it&&e.isHttpError(404):!1}_replace(e){this._parseTimeline=e._parseTimeline,this._index=e._index,this._isDynamic=e._isDynamic,this._scaledPeriodStart=e._scaledPeriodStart,this._scaledPeriodEnd=e._scaledPeriodEnd,this._lastUpdate=e._lastUpdate,this._manifestBoundsCalculator=e._manifestBoundsCalculator,this._isLastPeriod=e._isLastPeriod}_update(e){this._index.timeline===null&&(this._index.timeline=this._getTimeline()),e._index.timeline===null&&(e._index.timeline=e._getTimeline()),Ai(this._index.timeline,e._index.timeline)&&(this._index.startNumber=e._index.startNumber),this._index.availabilityTimeOffset=e._index.availabilityTimeOffset,this._index.availabilityTimeComplete=e._index.availabilityTimeComplete,this._index.endNumber=e._index.endNumber,this._isDynamic=e._isDynamic,this._scaledPeriodStart=e._scaledPeriodStart,this._scaledPeriodEnd=e._scaledPeriodEnd,this._lastUpdate=e._lastUpdate,this._isLastPeriod=e._isLastPeriod}isStillAwaitingFutureSegments(){var a;if(!this._isDynamic)return!1;this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline());let{timeline:e}=this._index;if(e.length===0){if(this._scaledPeriodEnd!==void 0){let s=this._manifestBoundsCalculator.getEstimatedLiveEdge();if(s!==void 0&&He(s,this._index)>this._scaledPeriodEnd)return!1}return this._isLastPeriod}let t=Zn(this._index.timescale),r=da(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(r!==null&&!r.isLastOfTimeline){let s=Math.min(r.end,(a=this._scaledPeriodEnd)!=null?a:1/0);return!(this._scaledPeriodEnd!==void 0&&s+t>=this._scaledPeriodEnd)}if(!this._isLastPeriod)return!1;if(this._scaledPeriodEnd===void 0)return!0;let i=e[e.length-1];return ke(i,null,this._scaledPeriodEnd)+t<this._scaledPeriodEnd}isInitialized(){return!0}initialize(){m.error("A `TimelineRepresentationIndex` does not need to be initialized")}addPredictedSegments(){m.warn("Cannot add predicted segments to a `TimelineRepresentationIndex`")}static isTimelineIndexArgument(e){return typeof e.timelineParser=="function"||Array.isArray(e.timeline)}_refreshTimeline(){var i,o;if(this._index.timeline===null&&(this._index.timeline=this._getTimeline()),!this._isDynamic)return;let e=this._manifestBoundsCalculator.getEstimatedMinimumSegmentTime(((o=(i=this._index.timeline[0])==null?void 0:i.duration)!=null?o:0)/this._index.timescale);if(E(e))return;let t=He(e,this._index),r=Mi(this._index.timeline,t);this._index.startNumber!==void 0?this._index.startNumber+=r:this._index.endNumber!==void 0&&(this._index.startNumber=r+1)}_getTimeline(){if(this._parseTimeline===null)return this._index.timeline!==null?this._index.timeline:(m.error("DASH: Timeline already lazily parsed."),[]);let e=this._parseTimeline();this._parseTimeline=null;let{MIN_DASH_S_ELEMENTS_TO_PARSE_UNSAFELY:t}=U.getCurrent();if(this._unsafelyBaseOnPreviousIndex===null||e.length<t)return Dd(tn(e),this._index.startNumber,this._index.endNumber);let r;return this._unsafelyBaseOnPreviousIndex._index.timeline===null?(r=this._unsafelyBaseOnPreviousIndex._getTimeline(),this._unsafelyBaseOnPreviousIndex._index.timeline=r):r=this._unsafelyBaseOnPreviousIndex._index.timeline,this._unsafelyBaseOnPreviousIndex=null,Dd(Od(e,r),this._index.startNumber,this._index.endNumber)}};function Dd(n,e,t){if(t===void 0)return n;let r=e!=null?e:1;for(let i=0;i<n.length;i++){let o=n[i];if(r+=o.repeatCount+1,r>t){if(r===t+1)return n.slice(0,i+1);{let a=n.slice(0,i),s=oe({},o),d=r-o.repeatCount-1;return s.repeatCount=Math.max(0,t-d),a.push(s),a}}}return n}function $h(n,e,t,r){let i=da(e,t,r);if(i===null)return!1;for(let o=0;o<e.timeline.length;o++){if(i.timelineIdx<o)return!1;let a=e.timeline[o],s=(a.start-e.indexTimeOffset)/e.timescale;if(s>n.time)return!1;if(s===n.time)return a.range===void 0?n.range===void 0:!E(n.range)&&a.range[0]===n.range[0]&&a.range[1]===n.range[1];if(a.repeatCount>=0&&a.duration!==void 0){let u=(s-a.start)/a.duration-1;return u%1===0&&u<=i.newRepeatCount}}return!1}function da(n,e,t){if(n.timeline.length<=0)return null;if(n.availabilityTimeOffset===1/0){let i=n.timeline.length-1,o=n.timeline[i];return{isLastOfTimeline:!0,timelineIdx:i,newRepeatCount:o.repeatCount,end:ke(o,null,t)}}let r=e.getEstimatedMaximumPosition(n.availabilityTimeOffset);if(r===void 0){let i=n.timeline.length-1,o=n.timeline[i];return{isLastOfTimeline:!0,timelineIdx:i,newRepeatCount:o.repeatCount,end:ke(o,null,t)}}for(let i=n.timeline.length-1;i>=n.timeline.length;i--){let o=n.timeline[i],a=o.start+o.duration;if(_t(a,n)<=r){let s=ke(o,n.timeline[i+1],t);if(_t(s,n)<=r)return{isLastOfTimeline:i===n.timeline.length-1,timelineIdx:i,newRepeatCount:o.repeatCount,end:a};{let u=He(r,n)-o.start,l=Math.floor(u/o.duration);return ee(l>=1),{isLastOfTimeline:!1,timelineIdx:i,newRepeatCount:l-1,end:o.start+l*o.duration}}}}return null}var ua=Di;var Li=class{constructor(){this._refs=new Map,this._stored=[]}addReferences(e){for(let t of e)t.attributes.refId!==void 0&&this._refs.set(t.attributes.refId,t)}add(e,t){this._tryParsing(e,t,!1)||this._stored.push([e,t]),t.attributes.refId!==void 0&&(this._refs.set(t.attributes.refId,t),this._resolveStoredRefs(!1))}finalize(){this._resolveStoredRefs(!0)}_resolveStoredRefs(e){for(let t=this._stored.length-1;t>=0;t--){let[r,i]=this._stored[t];(this._tryParsing(r,i,e)||e)&&this._stored.splice(t,1)}return this._stored.length===0}_tryParsing(e,t,r){if(t.attributes.ref===void 0)return Ld(e,t),!0;let i=this._getReferenced(t.attributes.ref);return i===void 0?(r&&(m.warn("DASH: forcing the parsing of a referencing ContentProtection"),Ld(e,t)),!1):(t.children.cencPssh.push(...i.children.cencPssh),t.attributes.keyId===void 0&&i.attributes.keyId!==void 0&&(t.attributes.keyId=i.attributes.keyId),t.attributes.schemeIdUri===void 0&&i.attributes.schemeIdUri!==void 0&&(t.attributes.schemeIdUri=i.attributes.schemeIdUri),t.attributes.value===void 0&&i.attributes.value!==void 0&&(t.attributes.value=i.attributes.value),Ld(e,t),!0)}_getReferenced(e){return this._refs.get(e)}};function Ld(n,e){let t;if(e.attributes.schemeIdUri!==void 0&&e.attributes.schemeIdUri.substring(0,9)==="urn:uuid:"&&(t=e.attributes.schemeIdUri.substring(9).replace(/-/g,"").toLowerCase()),e.attributes.keyId!==void 0&&e.attributes.keyId.length>0){let a=e.attributes.keyId;n.contentProtections===void 0?n.contentProtections={keyIds:[a],initData:[]}:n.contentProtections.keyIds===void 0?n.contentProtections.keyIds=[a]:n.contentProtections.keyIds.push(a)}if(t===void 0)return;let{cencPssh:r}=e.children,i=[];for(let a of r)i.push({systemId:t,data:a});if(i.length===0)return;if(n.contentProtections===void 0){n.contentProtections={keyIds:[],initData:[{type:"cenc",values:i}]};return}let o=Z(n.contentProtections.initData,a=>a.type==="cenc");o===void 0?n.contentProtections.initData.push({type:"cenc",values:i}):o.values.push(...i)}function la(n){let e=Date.parse(n)-K();if(isNaN(e)){m.warn("DASH Parser: Invalid clock received: ",n);return}return e}function Nd(n){let e=n.children.utcTimings.filter(t=>(t.schemeIdUri==="urn:mpeg:dash:utc:http-iso:2014"||t.schemeIdUri==="urn:mpeg:dash:utc:http-xsdate:2014")&&t.value!==void 0);return e.length>0?e[0].value:void 0}function ca(n){let{representations:e}=n,t=null;for(let r of e){let i=r.index.getLastAvailablePosition();if(i===void 0)return;i!==null&&(t=t===null?i:Math.min(t,i))}return t===null?null:t}function Ud(n){for(let e=n.length-1;e>=0;e--){let t=n[e].adaptations,r=t.audio===void 0?void 0:t.audio[0],i=t.video===void 0?void 0:t.video[0];if(r!==void 0||i!==void 0){let o=null,a=null;if(r!==void 0){let s=ca(r);if(s===void 0)return{safe:void 0,unsafe:void 0};o=s}if(i!==void 0){let s=ca(i);if(s===void 0)return{safe:void 0,unsafe:void 0};a=s}if(r!==void 0&&o===null||i!==void 0&&a===null)return m.info("Parser utils: found Period with no segment. ","Going to previous one to calculate last position"),{safe:void 0,unsafe:void 0};if(a!==null)return o!==null?{safe:Math.min(o,a),unsafe:Math.max(o,a)}:{safe:a,unsafe:a};if(o!==null)return{safe:o,unsafe:o}}}return{safe:void 0,unsafe:void 0}}function fa(n){let{representations:e}=n,t=null;for(let r of e){let i=r.index.getFirstAvailablePosition();if(i===void 0)return;i!==null&&(t=t===null?i:Math.max(t,i))}return t===null?null:t}function Bd(n){for(let e=0;e<=n.length-1;e++){let t=n[e].adaptations,r=t.audio===void 0?void 0:t.audio[0],i=t.video===void 0?void 0:t.video[0];if(r!==void 0||i!==void 0){let o=null,a=null;if(r!==void 0){let s=fa(r);if(s===void 0)return;o=s}if(i!==void 0){let s=fa(i);if(s===void 0)return;a=s}if(r!==void 0&&o===null||i!==void 0&&a===null){m.info("Parser utils: found Period with no segment. ","Going to next one to calculate first position");return}if(a!==null)return o!==null?Math.max(o,a):a;if(o!==null)return o}}}function Fd(n){if(n.length===0)throw new Error("DASH Parser: no period available for a dynamic content");let e=Bd(n),t=Ud(n);return{minimumSafePosition:e,maximumSafePosition:t.safe,maximumUnsafePosition:t.unsafe}}var Ni=class{constructor(e){this._isDynamic=e.isDynamic,this._timeShiftBufferDepth=!e.isDynamic||e.timeShiftBufferDepth===void 0?null:e.timeShiftBufferDepth,this._serverTimestampOffset=e.serverTimestampOffset,this._availabilityStartTime=e.availabilityStartTime}setLastPosition(e,t){this._lastPosition=e,this._positionTime=t}lastPositionIsKnown(){return this._isDynamic?this._positionTime!==void 0&&this._lastPosition!==void 0:this._lastPosition!==void 0}getEstimatedMinimumSegmentTime(e){var i;if(!this._isDynamic||this._timeShiftBufferDepth===null)return 0;let t=(i=this.getEstimatedLiveEdge())!=null?i:this.getEstimatedMaximumPosition(0);return t===void 0?void 0:t-(this._timeShiftBufferDepth+e)}getEstimatedLiveEdge(){if(!(!this._isDynamic||this._serverTimestampOffset===void 0))return(K()+this._serverTimestampOffset)/1e3-this._availabilityStartTime}getEstimatedMaximumPosition(e){if(!this._isDynamic)return this._lastPosition;let t=this.getEstimatedLiveEdge();return t!==void 0&&e!==1/0?t+e:this._positionTime!==void 0&&this._lastPosition!==void 0?Math.max(this._lastPosition-this._positionTime+K()/1e3,0):this._lastPosition}};function Kd(n,e){return n.type!=="dynamic"?0:E(n.availabilityStartTime)?e!=null?e:0:n.availabilityStartTime}function Vd(n){if(n.length===0)return[];let e=[n[0]];for(let t=1;t<n.length;t++){let r=n[t],i=e[e.length-1];for(;(i.duration===void 0||i.start+i.duration>r.start)&&(m.warn("DASH: Updating overlapping Periods.",i==null?void 0:i.start,r.start),i.duration=r.start-i.start,i.end=r.start,!(i.duration>0));){if(e.pop(),e.length===0)break;i=e[e.length-1]}e.push(r)}return e}function zd(n,e){let t=[];return n.forEach((r,i)=>{let o;if(!E(r.attributes.start))o=r.attributes.start;else if(i===0)o=!e.isDynamic||E(e.availabilityStartTime)?0:e.availabilityStartTime;else{let u=t[t.length-1];if(!E(u)&&!E(u.periodEnd))o=u.periodEnd;else throw new Error("Missing start time when parsing periods.")}let a,s=n[i+1];E(r.attributes.duration)?i===n.length-1?a=e.duration:E(s.attributes.start)||(a=s.attributes.start-o):a=r.attributes.duration;let d=E(a)?void 0:o+a;t.push({periodStart:o,periodDuration:a,periodEnd:d})}),t}function Qh(n,e){for(let t of e){let{adaptation:r,trickModeAttachedAdaptationIds:i}=t;for(let o of i)for(let a of jt){let s=n[a];if(s!==void 0)for(let d of s)d.id===o&&(d.trickModeTracks===void 0&&(d.trickModeTracks=[]),d.trickModeTracks.push(r))}}}var Af=Qh;var Xh=["subtitle","caption"];function Hd(n,e,t,r){function i(a,s){let d=a.split("/")[0];if(Q(jt,d))return d;if(a==="application/ttml+xml")return"text";if(a==="application/mp4")return s!==null&&Z(s,u=>u.schemeIdUri==="urn:mpeg:dash:role:2011"&&Q(Xh,u.value))!==void 0?"text":void 0}function o(a){switch(a.substring(0,3)){case"avc":case"hev":case"hvc":case"vp8":case"vp9":case"av1":return"video";case"vtt":return"text"}switch(a.substring(0,4)){case"mp4a":return"audio";case"wvtt":case"stpp":return"text"}}if(e!==null){let a=i(e,r);if(a!==void 0)return a}if(t!==null){let a=o(t);if(a!==void 0)return a}for(let a=0;a<n.length;a++){let s=n[a],{mimeType:d,codecs:u}=s.attributes;if(d!==void 0){let l=i(d,r);if(l!==void 0)return l}if(u!==void 0){let l=o(u);if(l!==void 0)return l}}}var Zh=/[, ]+/g;function xf(n){return w(n)?n.trim().replace(Zh,", "):""}function wf(n){let[e,t,r,i,o,a,s,d]=n.split(".");if(e!=="vp08"&&e!=="vp09"&&e!=="vp10")return;let u,l,c;if((i!==void 0&&i==="10"||i==="12")&&(u=parseInt(i,10)),s!==void 0&&(s==="16"?l="pq":s==="18"&&(l="hlg")),a!==void 0&&d!==void 0&&a==="09"&&d==="09"&&(c="rec2020"),!(u===void 0||l===void 0))return{colorDepth:u,eotf:l,colorSpace:c}}function Wd(n,e){var p,I,y;let{availabilityTimeOffset:t,manifestBoundsCalculator:r,isDynamic:i,end:o,start:a,receivedTime:s,unsafelyBaseOnPreviousRepresentation:d,inbandEventStreams:u,isLastPeriod:l}=e,f={availabilityTimeComplete:void 0,availabilityTimeOffset:t,unsafelyBaseOnPreviousRepresentation:d,isEMSGWhitelisted:b=>u===void 0?!1:u.some(({schemeIdUri:T})=>T===b.schemeIdUri),isLastPeriod:l,manifestBoundsCalculator:r,isDynamic:i,periodEnd:o,periodStart:a,receivedTime:s,representationBitrate:n.attributes.bitrate,representationId:n.attributes.id},g;if(n.children.segmentBase!==void 0){let{segmentBase:b}=n.children;g=new Rn(b,f)}else if(n.children.segmentList!==void 0){let{segmentList:b}=n.children;g=new kn(b,f)}else if(n.children.segmentTemplate!==void 0||e.parentSegmentTemplates.length>0){let b=e.parentSegmentTemplates.slice(),T=n.children.segmentTemplate;T!==void 0&&b.push(T);let v=G({},...b);(v.availabilityTimeOffset!==void 0||e.availabilityTimeOffset!==void 0)&&(f.availabilityTimeOffset=((p=v.availabilityTimeOffset)!=null?p:0)+((I=e.availabilityTimeOffset)!=null?I:0)),(v.availabilityTimeComplete!==void 0||e.availabilityTimeComplete!==void 0)&&(f.availabilityTimeComplete=(y=v.availabilityTimeComplete)!=null?y:e.availabilityTimeComplete),g=ua.isTimelineIndexArgument(v)?new ua(v,f):new Cn(v,f)}else{let b=e.adaptation.children;if(b.segmentBase!==void 0){let{segmentBase:T}=b;g=new Rn(T,f)}else if(b.segmentList!==void 0){let{segmentList:T}=b;g=new kn(T,f)}else g=new Cn({duration:Number.MAX_VALUE,timescale:1,startNumber:0,media:""},f)}return g}function Ot(n,e){var i;if(e.length===0)return n;let t=e.map(o=>({url:o.value}));if(n.length===0)return t;let r=[];for(let o=0;o<n.length;o++){let a=n[o];for(let s=0;s<t.length;s++){let d=t[s],u=mn(a.url,d.url);r.push({url:u,serviceLocation:(i=d.serviceLocation)!=null?i:a.serviceLocation})}}return r}function Jh(n,e){let t=[];if(n.children.inbandEventStreams!==void 0&&t.push(...n.children.inbandEventStreams),e.children.inbandEventStreams!==void 0&&t.push(...e.children.inbandEventStreams),t.length!==0)return t}function ey({adaptationProfiles:n,essentialProperties:e,supplementalProperties:t,manifestProfiles:r,codecs:i}){if(((n!=null?n:"")+(r!=null?r:"")).indexOf("http://dashif.org/guidelines/dash-if-uhd#hevc-hdr-pq10")!==-1&&(i==="hvc1.2.4.L153.B0"||i==="hev1.2.4.L153.B0"))return{colorDepth:10,eotf:"pq",colorSpace:"rec2020"};let a=Z([...e!=null?e:[],...t!=null?t:[]],s=>s.schemeIdUri==="urn:mpeg:mpegB:cicp:TransferCharacteristics");if(a!==void 0)switch(a.value){case"15":return;case"16":return{eotf:"pq"};case"18":return{eotf:"hlg"}}if(i!==void 0&&/^vp(08|09|10)/.test(i))return wf(i)}function Gd(n,e,t){var i,o,a,s,d,u,l;let r=[];for(let c of n){let f=c.attributes.id!==void 0?c.attributes.id:String(c.attributes.bitrate)+(c.attributes.height!==void 0?`-${c.attributes.height}`:"")+(c.attributes.width!==void 0?`-${c.attributes.width}`:"")+(c.attributes.mimeType!==void 0?`-${c.attributes.mimeType}`:"")+(c.attributes.codecs!==void 0?`-${c.attributes.codecs}`:"");for(;r.some(P=>P.id===f);)f+="-dup";let g=(o=(i=t.unsafelyBaseOnPreviousAdaptation)==null?void 0:i.getRepresentation(f))!=null?o:null,p=Jh(c,e),I=(a=c.attributes.availabilityTimeComplete)!=null?a:t.availabilityTimeComplete,y;(c.attributes.availabilityTimeOffset!==void 0||t.availabilityTimeOffset!==void 0)&&(y=((s=c.attributes.availabilityTimeOffset)!=null?s:0)+((d=t.availabilityTimeOffset)!=null?d:0));let b=G({},t,{availabilityTimeOffset:y,availabilityTimeComplete:I,unsafelyBaseOnPreviousRepresentation:g,adaptation:e,inbandEventStreams:p}),T=Wd(c,b),v;c.attributes.bitrate===void 0?(m.warn("DASH: No usable bitrate found in the Representation."),v=0):v=c.attributes.bitrate;let _=Ot(t.baseURLs,c.children.baseURLs),R=_.length===0?[{baseUrl:"",id:void 0}]:_.map(P=>({baseUrl:P.url,id:P.serviceLocation})),k={bitrate:v,cdnMetadata:R,index:T,id:f};c.children.supplementalProperties!==void 0&&Z(c.children.supplementalProperties,P=>P.schemeIdUri==="tag:dolby.com,2018:dash:EC3_ExtensionType:2018"&&P.value==="JOC")!==void 0&&(k.isSpatialAudio=!0);let x;c.attributes.codecs!==void 0?x=c.attributes.codecs:e.attributes.codecs!==void 0&&(x=e.attributes.codecs),x!==void 0&&(x=x==="mp4a.40.02"?"mp4a.40.2":x,k.codecs=x);let M;c.attributes.supplementalCodecs!==void 0?M=c.attributes.supplementalCodecs:e.attributes.supplementalCodecs!==void 0&&(M=e.attributes.supplementalCodecs),M!==void 0&&(k.supplementalCodecs=xf(M)),c.attributes.frameRate!==void 0?k.frameRate=c.attributes.frameRate:e.attributes.frameRate!==void 0&&(k.frameRate=e.attributes.frameRate),c.attributes.height!==void 0?k.height=c.attributes.height:e.attributes.height!==void 0&&(k.height=e.attributes.height),c.attributes.mimeType!==void 0?k.mimeType=c.attributes.mimeType:e.attributes.mimeType!==void 0&&(k.mimeType=e.attributes.mimeType),c.attributes.width!==void 0?k.width=c.attributes.width:e.attributes.width!==void 0&&(k.width=e.attributes.width);{let P=[...(u=e.children.contentProtections)!=null?u:[],...(l=c.children.contentProtections)!=null?l:[]];for(let N of P)t.contentProtectionParser.add(k,N)}k.hdrInfo=ey({adaptationProfiles:e.attributes.profiles,supplementalProperties:e.children.supplementalProperties,essentialProperties:e.children.essentialProperties,manifestProfiles:t.manifestProfiles,codecs:x}),r.push(k)}return r}function ty(n){if(n===void 0)return!1;let e=n.schemeIdUri==="urn:tva:metadata:cs:AudioPurposeCS:2007"&&n.value==="1",t=n.schemeIdUri==="urn:mpeg:dash:role:2011"&&n.value==="description";return e||t}function ny(n,e){return!!(n!==void 0&&n.some(r=>r.schemeIdUri==="urn:tva:metadata:cs:AudioPurposeCS:2007"&&r.value==="2")||e!==void 0&&e.some(r=>r.schemeIdUri==="urn:mpeg:dash:role:2011"&&r.value==="caption"))}function ry(n){return n===void 0?!1:n.schemeIdUri==="urn:mpeg:dash:role:2011"&&n.value==="sign"}function iy(n,e){if(w(n.attributes.id))return n.attributes.id;let{isClosedCaption:t,isForcedSubtitle:r,isAudioDescription:i,isSignInterpreted:o,isTrickModeTrack:a,type:s}=e,d=s;return w(n.attributes.language)&&(d+=`-${n.attributes.language}`),t===!0&&(d+="-cc"),r===!0&&(d+="-cc"),i===!0&&(d+="-ad"),o===!0&&(d+="-si"),a&&(d+="-trickMode"),w(n.attributes.contentType)&&(d+=`-${n.attributes.contentType}`),w(n.attributes.codecs)&&(d+=`-${n.attributes.codecs}`),w(n.attributes.mimeType)&&(d+=`-${n.attributes.mimeType}`),n.attributes.frameRate!==void 0&&(d+=`-${String(n.attributes.frameRate)}`),d}function oy(n){if(!E(n.children.supplementalProperties)){let{supplementalProperties:e}=n.children;for(let t of e)if(t.schemeIdUri==="urn:mpeg:dash:adaptation-set-switching:2016"&&!E(t.value))return t.value.split(",").map(r=>r.trim()).filter(r=>r)}return[]}function qd(n,e){var s,d,u,l,c,f,g;let t={video:[],audio:[],text:[]},r=[],i={},o=[];for(let p=0;p<n.length;p++){let I=n[p],y=I.children,{essentialProperties:b,roles:T,label:v}=y,_=Array.isArray(T)&&T.some(ye=>ye.value==="main")&&T.some(ye=>ye.schemeIdUri==="urn:mpeg:dash:role:2011"),R=I.children.representations,k=(s=I.attributes.availabilityTimeComplete)!=null?s:e.availabilityTimeComplete,x;(I.attributes.availabilityTimeOffset!==void 0||e.availabilityTimeOffset!==void 0)&&(x=((d=I.attributes.availabilityTimeOffset)!=null?d:0)+((u=e.availabilityTimeOffset)!=null?u:0));let M=I.attributes.mimeType,P=I.attributes.codecs,N=Hd(R,w(M)?M:null,w(P)?P:null,E(y.roles)?null:y.roles);if(N===void 0)continue;let O=(l=I.attributes.selectionPriority)!=null?l:1,F=I.attributes.id,A=oy(I),C=[];e.segmentTemplate!==void 0&&C.push(e.segmentTemplate),I.children.segmentTemplate!==void 0&&C.push(I.children.segmentTemplate);let D={availabilityTimeComplete:k,availabilityTimeOffset:x,baseURLs:Ot(e.baseURLs,y.baseURLs),contentProtectionParser:e.contentProtectionParser,manifestBoundsCalculator:e.manifestBoundsCalculator,end:e.end,isDynamic:e.isDynamic,isLastPeriod:e.isLastPeriod,manifestProfiles:e.manifestProfiles,parentSegmentTemplates:C,receivedTime:e.receivedTime,start:e.start,unsafelyBaseOnPreviousAdaptation:null},L=Array.isArray(b)?Z(b,ye=>ye.schemeIdUri==="http://dashif.org/guidelines/trickmode"):void 0,V=(c=L==null?void 0:L.value)==null?void 0:c.split(" "),$=V!==void 0,{accessibilities:j}=y,z;T!==void 0&&T.some(ye=>ye.value==="dub")&&(z=!0);let q;N!=="text"?q=!1:q=ny(j,T);let W;N==="text"&&T!==void 0&&T.some(ye=>ye.value==="forced-subtitle"||ye.value==="forced_subtitle")&&(W=!0);let se;N!=="audio"?se=!1:j!==void 0&&(se=j.some(ty));let ae;N!=="video"?ae=!1:j!==void 0&&(ae=j.some(ry));let de=iy(I,{isAudioDescription:se,isForcedSubtitle:W,isClosedCaption:q,isSignInterpreted:ae,isTrickModeTrack:$,type:N});for(;Q(o,de);)de+="-dup";let Se=de;o.push(de),D.unsafelyBaseOnPreviousAdaptation=(g=(f=e.unsafelyBaseOnPreviousPeriod)==null?void 0:f.getAdaptation(de))!=null?g:null;let Y=Gd(R,I,D),ce={id:de,representations:Y,type:N,isTrickModeTrack:$};if(E(I.attributes.language)||(ce.language=I.attributes.language),E(q)||(ce.closedCaption=q),E(se)||(ce.audioDescription=se),z===!0&&(ce.isDub=!0),W!==void 0&&(ce.forcedSubtitles=W),ae===!0&&(ce.isSignInterpreted=!0),v!==void 0&&(ce.label=v),V!==void 0)r.push({adaptation:ce,trickModeAttachedAdaptationIds:V});else{let ye=-1;for(let Vt of A){let Qe=i[Vt];if(Qe!==void 0&&Qe.newID!==Se&&Q(Qe.adaptationSetSwitchingIDs,F)){ye=he(t[N],Et=>Et[0].id===Vt);let Be=t[N][ye];if(Be!==void 0&&Be[0].audioDescription===ce.audioDescription&&Be[0].closedCaption===ce.closedCaption&&Be[0].language===ce.language){m.info('DASH Parser: merging "switchable" AdaptationSets',F,Vt),Be[0].representations.push(...ce.representations),Be[1]={priority:Math.max(O,Be[1].priority),isMainAdaptation:_||Be[1].isMainAdaptation,indexInMpd:Math.min(p,Be[1].indexInMpd)};break}}}ye<0&&t[N].push([ce,{priority:O,isMainAdaptation:_,indexInMpd:p}])}!E(F)&&E(i[F])&&(i[F]={newID:Se,adaptationSetSwitchingIDs:A})}let a=jt.reduce((p,I)=>{let y=t[I];return y.length>0&&(y.sort(Of),p[I]=y.map(([b])=>b)),p},{});return t.video.sort(Of),Af(a,r),a}function Of(n,e){let t=e[1].priority-n[1].priority;return t!==0?t:n[1].isMainAdaptation!==e[1].isMainAdaptation?n[1].isMainAdaptation?-1:1:n[1].indexInMpd-e[1].indexInMpd}var ay=et();function jd(n,e){var a,s,d,u,l;let t=[],r=zd(n,e);if(r.length!==n.length)throw new Error("MPD parsing error: the time information are incoherent.");let{isDynamic:i,manifestBoundsCalculator:o}=e;!i&&!E(e.duration)&&o.setLastPosition(e.duration);for(let c=n.length-1;c>=0;c--){let f=c===n.length-1,g=n[c],p=e.xlinkInfos.get(g),I=Ot(e.baseURLs,g.children.baseURLs),{periodStart:y,periodDuration:b,periodEnd:T}=r[c],v;for(E(g.attributes.id)?(m.warn("DASH: No usable id found in the Period. Generating one."),v="gen-dash-period-"+ay()):v=g.attributes.id;t.some(L=>L.id===v);)v+="-dup";let _=p!==void 0?p.receivedTime:e.receivedTime,R=(s=(a=e.unsafelyBaseOnPreviousManifest)==null?void 0:a.getPeriod(v))!=null?s:null,k=g.attributes.availabilityTimeComplete,x=g.attributes.availabilityTimeOffset,{manifestProfiles:M,contentProtectionParser:P}=e,{segmentTemplate:N}=g.children;P.addReferences((d=g.children.contentProtections)!=null?d:[]);let O={availabilityTimeComplete:k,availabilityTimeOffset:x,baseURLs:I,contentProtectionParser:P,manifestBoundsCalculator:o,end:T,isDynamic:i,isLastPeriod:f,manifestProfiles:M,receivedTime:_,segmentTemplate:N,start:y,unsafelyBaseOnPreviousPeriod:R},F=qd(g.children.adaptations,O),A=((u=e.xmlNamespaces)!=null?u:[]).concat((l=g.attributes.namespaces)!=null?l:[]),C=dy(g.children.eventStreams,y,A),D={id:v,start:y,end:T,duration:b,adaptations:F,streamEvents:C};if(t.unshift(D),!o.lastPositionIsKnown()){let L=sy(F);if(!i)typeof L=="number"&&o.setLastPosition(L);else if(typeof L=="number"){let V=K()/1e3;o.setLastPosition(L,V)}else{let V=Df(e,y);if(V!==void 0){let[$,j]=V;o.setLastPosition($,j)}}}}if(e.isDynamic&&!o.lastPositionIsKnown()){let c=Df(e,0);if(c!==void 0){let[f,g]=c;o.setLastPosition(f,g)}}return Vd(t)}function Df(n,e){if(E(n.clockOffset)){let t=Date.now()/1e3;if(t>=e){m.warn("DASH Parser: no clock synchronization mechanism found. Using the system clock instead.");let r=t-n.availabilityStartTime,i=K()/1e3;return[r,i]}}else{let t=n.clockOffset/1e3-n.availabilityStartTime,r=K()/1e3,i=r+t;if(i>=e)return[i,r]}}function sy(n){let e=null,t=!0,r=Ln(n).filter(o=>!E(o)),i=Bn(r,o=>o);for(let o of i){let a=o.representations;for(let s of a){let d=s.index.getLastAvailablePosition();d!==null&&(t=!1,typeof d=="number"&&(e=E(e)?d:Math.max(e,d)))}}if(E(e)){if(t)return null}else return e}function dy(n,e,t){var i,o;let r=[];for(let a of n){let{schemeIdUri:s="",timescale:d=1}=a.attributes,u=t.concat((i=a.attributes.namespaces)!=null?i:[]);for(let l of a.children.events)if(l.eventStreamData!==void 0){let c=((o=l.presentationTime)!=null?o:0)/d+e,f=l.duration===void 0?void 0:c+l.duration/d,g,p;if(!zt&&l.eventStreamData instanceof Element)g=l.eventStreamData;else try{p={namespaces:u,data:typeof l.eventStreamData=="string"?l.eventStreamData:Ne(new Uint8Array(l.eventStreamData))}}catch(I){m.error("DASH: Error while parsing event-stream:",I instanceof Error?I.message:"Unknown error")}r.push({start:c,end:f,id:l.id,data:{type:"dash-event-stream",value:{schemeIdUri:s,timescale:d,element:g,xmlData:p}}})}}return r}function Jn(n,e,t,r,i=new WeakMap){let{children:o,attributes:a}=n;if(E(e.externalClockOffset)){let d=a.type==="dynamic",u=Z(o.utcTimings,f=>f.schemeIdUri==="urn:mpeg:dash:utc:direct:2014"&&!E(f.value)),l=!E(u)&&!E(u.value)?la(u.value):void 0,c=!E(l)&&!isNaN(l)?l:void 0;if(!E(c)&&r!==!0)e.externalClockOffset=c;else if(d&&r!==!0){let f=Nd(n);if(!E(f)&&f.length>0)return{type:"needs-clock",value:{url:f,continue:function(p){return p.success?(e.externalClockOffset=la(p.data),Jn(n,e,t,!0)):(t.push(p.error),m.warn("DASH Parser: Error on fetching the clock ressource",p.error),Jn(n,e,t,!0))}}}}}let s=[];for(let d=0;d<o.periods.length;d++){let{xlinkHref:u,xlinkActuate:l}=o.periods[d].attributes;!E(u)&&l==="onLoad"&&s.push({index:d,ressource:u})}return s.length===0?uy(n,e,t,i):{type:"needs-xlinks",value:{xlinksUrls:s.map(({ressource:d})=>d),continue:function(u){if(u.length!==s.length)throw new Error("DASH parser: wrong number of loaded ressources.");for(let l=u.length-1;l>=0;l--){let c=s[l].index,{parsed:f,warnings:g,receivedTime:p,sendingTime:I,url:y}=u[l];g.length>0&&t.push(...g);for(let b of f)i.set(b,{receivedTime:p,sendingTime:I,url:y});o.periods.splice(c,1,...f)}return Jn(n,e,t,r,i)}}}}function uy(n,e,t,r){var C,D,L,V,$;let{children:i,attributes:o}=n,a=o.type==="dynamic",s=e.url!==void 0?[{url:e.url.substring(0,vr(e.url))}]:[],d=Ot(s,i.baseURLs),u=Kd(o,e.referenceDateTime),l=o.timeShiftBufferDepth,c=o.maxSegmentDuration,{externalClockOffset:f,unsafelyBaseOnPreviousManifest:g}=e,{externalClockOffset:p}=e,I=new Ni({availabilityStartTime:u,isDynamic:a,timeShiftBufferDepth:l,serverTimestampOffset:p}),y=new Li;y.addReferences((C=i.contentProtections)!=null?C:[]);let b={availabilityStartTime:u,baseURLs:d,clockOffset:f,contentProtectionParser:y,duration:o.duration,isDynamic:a,manifestBoundsCalculator:I,manifestProfiles:n.attributes.profiles,receivedTime:e.manifestReceivedTime,unsafelyBaseOnPreviousManifest:g,xlinkInfos:r,xmlNamespaces:n.attributes.namespaces},T=jd(i.periods,b);y.finalize();let v=o.duration,_,R,k=null,x;o.minimumUpdatePeriod!==void 0&&o.minimumUpdatePeriod>=0&&(_=o.minimumUpdatePeriod===0?U.getCurrent().DASH_FALLBACK_LIFETIME_WHEN_MINIMUM_UPDATE_PERIOD_EQUAL_0:o.minimumUpdatePeriod);let{minimumSafePosition:M,maximumSafePosition:P,maximumUnsafePosition:N}=Fd(T),O=K();if(a){let j;P!==void 0?j=P:p===void 0?(m.warn("DASH Parser: use system clock to define maximum position"),j=Date.now()/1e3-u):j=(K()+p)/1e3-u;let z=I.getEstimatedLiveEdge();z===void 0&&(N!==void 0?z=N:z=j),x={isLinear:!0,maximumSafePosition:j,livePosition:z,time:O},R=M,k=l!=null?l:null,k!==null&&(k+=c!=null?c:0),k!==null&&R!==void 0&&z-R>k&&(k=z-R)}else{R=M,R===void 0&&(R=(L=(D=T[0])==null?void 0:D.start)!=null?L:0);let j=v!=null?v:1/0;if(T[T.length-1]!==void 0){let z=T[T.length-1],q=(V=z.end)!=null?V:z.duration!==void 0?z.start+z.duration:void 0;q!==void 0&&q<j&&(j=q)}P!==void 0&&P<j&&(j=P),x={isLinear:!1,maximumSafePosition:j,livePosition:void 0,time:O}}let F=!a||n.attributes.minimumUpdatePeriod===void 0&&((($=T[T.length-1])==null?void 0:$.end)!==void 0||n.attributes.duration!==void 0);return{type:"done",value:{parsed:{availabilityStartTime:u,clockOffset:e.externalClockOffset,isDynamic:a,isLive:a,isLastPeriodKnown:F,periods:T,publishTime:o.publishTime,suggestedPresentationDelay:o.suggestedPresentationDelay,transportType:"dash",timeBounds:{minimumSafePosition:R,timeshiftDepth:k,maximumTimeData:x},lifetime:_,uris:E(e.url)?i.locations:[e.url,...i.locations]},warnings:t}}}var Lf=Jn;function Dt(n){let e=n.textContent,t=[];return e===null||e.length===0?[void 0,t]:[{value:e},t]}var ly=/^P(([\d.]*)Y)?(([\d.]*)M)?(([\d.]*)D)?T?(([\d.]*)H)?(([\d.]*)M)?(([\d.]*)S)?/,cy=/([0-9]+)-([0-9]+)/;function We(n,e){return n==="true"?[!0,null]:n==="false"?[!1,null]:[!1,new tt(`\`${e}\` property is not a boolean value but "${n}"`)]}function be(n,e){let t=parseInt(n,10);return isNaN(t)?[null,new tt(`\`${e}\` property is not an integer value but "${n}"`)]:[t,null]}function Ye(n,e){if(n==="INF")return[1/0,null];let t=parseFloat(n);return isNaN(t)?[null,new tt(`\`${e}\` property is invalid: "${n}"`)]:[t,null]}function Yd(n,e){if(n==="true")return[!0,null];if(n==="false")return[!1,null];let t=parseInt(n,10);return isNaN(t)?[null,new tt(`\`${e}\` property is not a boolean nor an integer but "${n}"`)]:[t,null]}function ma(n,e){let t=Date.parse(n);return isNaN(t)?[null,new tt(`\`${e}\` is in an invalid date format: "${n}"`)]:[new Date(Date.parse(n)).getTime()/1e3,null]}function gt(n,e){if(!w(n))return[0,new tt(`\`${e}\` property is empty`)];let t=ly.exec(n);return t===null?[null,new tt(`\`${e}\` property has an unrecognized format "${n}"`)]:[parseFloat(w(t[2])?t[2]:"0")*365*24*60*60+parseFloat(w(t[4])?t[4]:"0")*30*24*60*60+parseFloat(w(t[6])?t[6]:"0")*24*60*60+parseFloat(w(t[8])?t[8]:"0")*60*60+parseFloat(w(t[10])?t[10]:"0")*60+parseFloat(w(t[12])?t[12]:"0"),null]}function Pn(n,e){let t=cy.exec(n);return t===null?[null,new tt(`\`${e}\` property has an unrecognized format "${n}"`)]:[[+t[1],+t[2]],null]}function Nf(n,e){try{return[pt(n),null]}catch(t){return[null,new tt(`\`${e}\` is not a valid base64 string: "${n}"`)]}}function er(n,e){let t=/^(\d+)\/(\d+)$/.exec(n);return t!==null?[+t[1]/+t[2],null]:Ye(n,e)}function ze(n){let e,t;for(let r=0;r<n.attributes.length;r++){let i=n.attributes[r];switch(i.name){case"schemeIdUri":e=i.value;break;case"value":t=i.value;break}}return{schemeIdUri:e,value:t}}function xe(n,e){return function(t,{asKey:r,parser:i,dashName:o}){let[a,s]=i(t,o);s!==null&&(m.warn(s.message),e.push(s)),a!==null&&(n[r]=a)}}var tt=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype),this.name="MPDError"}};function fy(n){let e=[],t=[];for(let r=0;r<n.length;r++)if(n[r].nodeType===Node.ELEMENT_NODE){let i=n[r];if(i.nodeName==="cenc:pssh"){let o=i.textContent;if(o!==null&&o.length>0){let[a,s]=Nf(o,"cenc:pssh");s!==null&&(m.warn(s.message),e.push(s)),a!==null&&t.push(a)}}}return[{cencPssh:t},e]}function my(n){let e={};for(let t=0;t<n.attributes.length;t++){let r=n.attributes[t];switch(r.name){case"schemeIdUri":e.schemeIdUri=r.value;break;case"value":e.value=r.value;break;case"cenc:default_KID":e.keyId=je(r.value.replace(/-/g,""));break;case"ref":e.ref=r.value;break;case"refId":e.refId=r.value;break}}return e}function Lt(n){let[e,t]=fy(n.childNodes),r=my(n);return[{children:e,attributes:r},t]}function $d(n){let e={};for(let t=0;t<n.attributes.length;t++){let r=n.attributes[t];switch(r.name){case"id":e.id=r.value;break;case"lang":e.language=r.value;break;case"contentType":e.contentType=r.value;break;case"par":e.par=r.value;break}}return e}function Qd(n){let e={},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"range":r(o.value,{asKey:"range",parser:Pn,dashName:"range"});break;case"sourceURL":e.media=o.value;break}}return[e,t]}function Nt(n){let e={},t=[],r=xe(e,t),i=n.childNodes;for(let o=0;o<i.length;o++)if(i[o].nodeType===Node.ELEMENT_NODE){let a=i[o];if(a.nodeName==="Initialization"){let[s,d]=Qd(a);e.initialization=s,t=t.concat(d)}}for(let o=0;o<n.attributes.length;o++){let a=n.attributes[o];switch(a.name){case"timescale":r(a.value,{asKey:"timescale",parser:be,dashName:"timescale"});break;case"presentationTimeOffset":r(a.value,{asKey:"presentationTimeOffset",parser:Ye,dashName:"presentationTimeOffset"});break;case"indexRange":r(a.value,{asKey:"indexRange",parser:Pn,dashName:"indexRange"});break;case"indexRangeExact":r(a.value,{asKey:"indexRangeExact",parser:We,dashName:"indexRangeExact"});break;case"availabilityTimeOffset":r(a.value,{asKey:"availabilityTimeOffset",parser:Ye,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(a.value,{asKey:"availabilityTimeComplete",parser:We,dashName:"availabilityTimeComplete"});break;case"duration":r(a.value,{asKey:"duration",parser:be,dashName:"duration"});break;case"startNumber":r(a.value,{asKey:"startNumber",parser:be,dashName:"startNumber"});break;case"endNumber":r(a.value,{asKey:"endNumber",parser:be,dashName:"endNumber"});break}}return[e,t]}function Xd(n){let e={},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"media":e.media=o.value;break;case"indexRange":r(o.value,{asKey:"indexRange",parser:Pn,dashName:"indexRange"});break;case"index":e.index=o.value;break;case"mediaRange":r(o.value,{asKey:"mediaRange",parser:Pn,dashName:"mediaRange"});break}}return[e,t]}function Ui(n){let[e,t]=Nt(n),r=t,i=[],o=n.childNodes;for(let s=0;s<o.length;s++)if(o[s].nodeType===Node.ELEMENT_NODE){let d=o[s];if(d.nodeName==="SegmentURL"){let[u,l]=Xd(d);i.push(u),r=r.concat(l)}}return[G(e,{list:i}),r]}function Zd(n){let e=null;return function(){if(e===null){let t=n.getElementsByTagName("S");return e=t,t}return e}}function Mn(n){let[e,t]=Nt(n),r=t,i;for(let s=0;s<n.childNodes.length;s++)if(n.childNodes[s].nodeType===Node.ELEMENT_NODE){let d=n.childNodes[s];d.nodeName==="SegmentTimeline"&&(i=Zd(d))}let o=G({},e,{duration:e.duration,timelineParser:i}),a=xe(o,r);for(let s=0;s<n.attributes.length;s++){let d=n.attributes[s];switch(d.nodeName){case"initialization":E(o.initialization)&&(o.initialization={media:d.value});break;case"index":o.index=d.value;break;case"availabilityTimeOffset":a(d.value,{asKey:"availabilityTimeOffset",parser:Ye,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":a(d.value,{asKey:"availabilityTimeComplete",parser:We,dashName:"availabilityTimeComplete"});break;case"media":o.media=d.value;break;case"bitstreamSwitching":a(d.value,{asKey:"bitstreamSwitching",parser:We,dashName:"bitstreamSwitching"});break}}return[o,r]}function py(n){let e={baseURLs:[]},t=[],r=[];for(let i=0;i<n.length;i++)if(n[i].nodeType===Node.ELEMENT_NODE){let o=n[i];switch(o.nodeName){case"BaseURL":{let[a,s]=Dt(o);a!==void 0&&e.baseURLs.push(a),r=r.concat(s);break}case"InbandEventStream":e.inbandEventStreams===void 0&&(e.inbandEventStreams=[]),e.inbandEventStreams.push(ze(o));break;case"SegmentBase":{let[a,s]=Nt(o);e.segmentBase=a,s.length>0&&(r=r.concat(s));break}case"SegmentList":{let[a,s]=Ui(o);r=r.concat(s),e.segmentList=a;break}case"SegmentTemplate":{let[a,s]=Mn(o);r=r.concat(s),e.segmentTemplate=a;break}case"ContentProtection":{let[a,s]=Lt(o);s.length>0&&(r=r.concat(s)),a!==void 0&&t.push(a);break}case"SupplementalProperty":E(e.supplementalProperties)?e.supplementalProperties=[ze(o)]:e.supplementalProperties.push(ze(o));break}}return t.length>0&&(e.contentProtections=t),[e,r]}function gy(n){let e={},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"audioSamplingRate":e.audioSamplingRate=o.value;break;case"bandwidth":r(o.value,{asKey:"bitrate",parser:be,dashName:"bandwidth"});break;case"codecs":e.codecs=o.value;break;case"codingDependency":r(o.value,{asKey:"codingDependency",parser:We,dashName:"codingDependency"});break;case"frameRate":r(o.value,{asKey:"frameRate",parser:er,dashName:"frameRate"});break;case"height":r(o.value,{asKey:"height",parser:be,dashName:"height"});break;case"id":e.id=o.value;break;case"maxPlayoutRate":r(o.value,{asKey:"maxPlayoutRate",parser:Ye,dashName:"maxPlayoutRate"});break;case"maximumSAPPeriod":r(o.value,{asKey:"maximumSAPPeriod",parser:Ye,dashName:"maximumSAPPeriod"});break;case"mimeType":e.mimeType=o.value;break;case"profiles":e.profiles=o.value;break;case"qualityRanking":r(o.value,{asKey:"qualityRanking",parser:be,dashName:"qualityRanking"});break;case"scte214:supplementalCodecs":e.supplementalCodecs=o.value;break;case"segmentProfiles":e.segmentProfiles=o.value;break;case"width":r(o.value,{asKey:"width",parser:be,dashName:"width"});break;case"availabilityTimeOffset":r(o.value,{asKey:"availabilityTimeOffset",parser:Ye,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(o.value,{asKey:"availabilityTimeComplete",parser:We,dashName:"availabilityTimeComplete"});break}}return e.bitrate===void 0&&t.push(new tt("No bitrate found on a Representation")),[e,t]}function Uf(n){let[e,t]=py(n.childNodes),[r,i]=gy(n),o=t.concat(i);return[{children:e,attributes:r},o]}function hy(n){let e={baseURLs:[],representations:[]},t=[],r=[];for(let i=0;i<n.length;i++)if(n[i].nodeType===Node.ELEMENT_NODE){let o=n[i];switch(o.nodeName){case"Accessibility":e.accessibilities===void 0?e.accessibilities=[ze(o)]:e.accessibilities.push(ze(o));break;case"BaseURL":{let[a,s]=Dt(o);a!==void 0&&e.baseURLs.push(a),s.length>0&&(r=r.concat(s));break}case"ContentComponent":e.contentComponent=$d(o);break;case"EssentialProperty":E(e.essentialProperties)?e.essentialProperties=[ze(o)]:e.essentialProperties.push(ze(o));break;case"InbandEventStream":e.inbandEventStreams===void 0&&(e.inbandEventStreams=[]),e.inbandEventStreams.push(ze(o));break;case"Label":{let a=o.textContent;a!=null&&(e.label=a);break}case"Representation":{let[a,s]=Uf(o);e.representations.push(a),s.length>0&&(r=r.concat(s));break}case"Role":E(e.roles)?e.roles=[ze(o)]:e.roles.push(ze(o));break;case"SupplementalProperty":E(e.supplementalProperties)?e.supplementalProperties=[ze(o)]:e.supplementalProperties.push(ze(o));break;case"SegmentBase":{let[a,s]=Nt(o);e.segmentBase=a,s.length>0&&(r=r.concat(s));break}case"SegmentList":{let[a,s]=Ui(o);e.segmentList=a,s.length>0&&(r=r.concat(s));break}case"SegmentTemplate":{let[a,s]=Mn(o);e.segmentTemplate=a,s.length>0&&(r=r.concat(s));break}case"ContentProtection":{let[a,s]=Lt(o);s.length>0&&(r=r.concat(s)),a!==void 0&&t.push(a);break}}}return t.length>0&&(e.contentProtections=t),[e,r]}function yy(n){let e={},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"id":e.id=o.value;break;case"group":r(o.value,{asKey:"group",parser:be,dashName:"group"});break;case"lang":e.language=o.value;break;case"contentType":e.contentType=o.value;break;case"par":e.par=o.value;break;case"minBandwidth":r(o.value,{asKey:"minBitrate",parser:be,dashName:"minBandwidth"});break;case"maxBandwidth":r(o.value,{asKey:"maxBitrate",parser:be,dashName:"maxBandwidth"});break;case"minWidth":r(o.value,{asKey:"minWidth",parser:be,dashName:"minWidth"});break;case"maxWidth":r(o.value,{asKey:"maxWidth",parser:be,dashName:"maxWidth"});break;case"minHeight":r(o.value,{asKey:"minHeight",parser:be,dashName:"minHeight"});break;case"maxHeight":r(o.value,{asKey:"maxHeight",parser:be,dashName:"maxHeight"});break;case"minFrameRate":r(o.value,{asKey:"minFrameRate",parser:er,dashName:"minFrameRate"});break;case"maxFrameRate":r(o.value,{asKey:"maxFrameRate",parser:er,dashName:"maxFrameRate"});break;case"selectionPriority":r(o.value,{asKey:"selectionPriority",parser:be,dashName:"selectionPriority"});break;case"segmentAlignment":r(o.value,{asKey:"segmentAlignment",parser:Yd,dashName:"segmentAlignment"});break;case"subsegmentAlignment":r(o.value,{asKey:"subsegmentAlignment",parser:Yd,dashName:"subsegmentAlignment"});break;case"bitstreamSwitching":r(o.value,{asKey:"bitstreamSwitching",parser:We,dashName:"bitstreamSwitching"});break;case"audioSamplingRate":e.audioSamplingRate=o.value;break;case"codecs":e.codecs=o.value;break;case"scte214:supplementalCodecs":e.supplementalCodecs=o.value;break;case"codingDependency":r(o.value,{asKey:"codingDependency",parser:We,dashName:"codingDependency"});break;case"frameRate":r(o.value,{asKey:"frameRate",parser:er,dashName:"frameRate"});break;case"height":r(o.value,{asKey:"height",parser:be,dashName:"height"});break;case"maxPlayoutRate":r(o.value,{asKey:"maxPlayoutRate",parser:Ye,dashName:"maxPlayoutRate"});break;case"maximumSAPPeriod":r(o.value,{asKey:"maximumSAPPeriod",parser:Ye,dashName:"maximumSAPPeriod"});break;case"mimeType":e.mimeType=o.value;break;case"profiles":e.profiles=o.value;break;case"segmentProfiles":e.segmentProfiles=o.value;break;case"width":r(o.value,{asKey:"width",parser:be,dashName:"width"});break;case"availabilityTimeOffset":r(o.value,{asKey:"availabilityTimeOffset",parser:Ye,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(o.value,{asKey:"availabilityTimeComplete",parser:We,dashName:"availabilityTimeComplete"});break}}return[e,t]}function Bf(n){let e=n.childNodes,[t,r]=hy(e),[i,o]=yy(n),a=r.concat(o);return[{children:t,attributes:i},a]}function Jd(n){let e={children:{events:[]},attributes:{}},t=[],r=xe(e.attributes,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"schemeIdUri":e.attributes.schemeIdUri=o.value;break;case"timescale":r(o.value,{asKey:"timescale",parser:be,dashName:"timescale"});break;case"value":e.attributes.value=o.value;break}}for(let i=0;i<n.childNodes.length;i++)if(n.childNodes[i].nodeType===Node.ELEMENT_NODE){let o=n.childNodes[i];switch(o.nodeName){case"Event":{let[a,s]=Iy(o);e.children.events.push(a),s.length>0&&(t=t.concat(s));break}}}return[e,t]}function Iy(n){let e={eventStreamData:n},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"presentationTime":r(o.value,{asKey:"presentationTime",parser:be,dashName:"presentationTime"});break;case"duration":r(o.value,{asKey:"duration",parser:be,dashName:"duration"});break;case"id":e.id=o.value;break}}return[e,t]}function by(n){let e=[],t=[],r,i=[],o=[],a=[];for(let s=0;s<n.length;s++)if(n[s].nodeType===Node.ELEMENT_NODE){let d=n[s];switch(d.nodeName){case"BaseURL":{let[u,l]=Dt(d);u!==void 0&&e.push(u),o=o.concat(l);break}case"AdaptationSet":{let[u,l]=Bf(d);t.push(u),o=o.concat(l);break}case"EventStream":{let[u,l]=Jd(d);a.push(u),o=o.concat(l);break}case"SegmentTemplate":{let[u,l]=Mn(d);r=u,l.length>0&&(o=o.concat(l));break}case"ContentProtection":{let[u,l]=Lt(d);l.length>0&&(o=o.concat(l)),u!==void 0&&i.push(u);break}}}return[{baseURLs:e,adaptations:t,eventStreams:a,segmentTemplate:r,contentProtections:i},o]}function Sy(n){let e={},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"id":e.id=o.value;break;case"start":r(o.value,{asKey:"start",parser:gt,dashName:"start"});break;case"duration":r(o.value,{asKey:"duration",parser:gt,dashName:"duration"});break;case"bitstreamSwitching":r(o.value,{asKey:"bitstreamSwitching",parser:We,dashName:"bitstreamSwitching"});break;case"xlink:href":e.xlinkHref=o.value;break;case"xlink:actuate":e.xlinkActuate=o.value;break}}return[e,t]}function pa(n){let[e,t]=by(n.childNodes),[r,i]=Sy(n),o=t.concat(i);return[{children:e,attributes:r},o]}function Ty(n){let e=[],t=[],r=[],i=[],o=[],a=[];for(let s=0;s<n.length;s++)if(n[s].nodeType===Node.ELEMENT_NODE){let d=n[s];switch(d.nodeName){case"BaseURL":{let[u,l]=Dt(d);u!==void 0&&e.push(u),a=a.concat(l);break}case"Location":t.push(d.textContent===null?"":d.textContent);break;case"Period":{let[u,l]=pa(d);r.push(u),a=a.concat(l);break}case"UTCTiming":{let u=ze(d);i.push(u);break}case"ContentProtection":{let[u,l]=Lt(d);l.length>0&&(a=a.concat(l)),u!==void 0&&o.push(u);break}}}return[{baseURLs:e,locations:t,periods:r,utcTimings:i,contentProtections:o},a]}function _y(n){let e={},t=[],r=xe(e,t);for(let i=0;i<n.attributes.length;i++){let o=n.attributes[i];switch(o.name){case"id":e.id=o.value;break;case"profiles":e.profiles=o.value;break;case"type":e.type=o.value;break;case"availabilityStartTime":r(o.value,{asKey:"availabilityStartTime",parser:ma,dashName:"availabilityStartTime"});break;case"availabilityEndTime":r(o.value,{asKey:"availabilityEndTime",parser:ma,dashName:"availabilityEndTime"});break;case"publishTime":r(o.value,{asKey:"publishTime",parser:ma,dashName:"publishTime"});break;case"mediaPresentationDuration":r(o.value,{asKey:"duration",parser:gt,dashName:"mediaPresentationDuration"});break;case"minimumUpdatePeriod":r(o.value,{asKey:"minimumUpdatePeriod",parser:gt,dashName:"minimumUpdatePeriod"});break;case"minBufferTime":r(o.value,{asKey:"minBufferTime",parser:gt,dashName:"minBufferTime"});break;case"timeShiftBufferDepth":r(o.value,{asKey:"timeShiftBufferDepth",parser:gt,dashName:"timeShiftBufferDepth"});break;case"suggestedPresentationDelay":r(o.value,{asKey:"suggestedPresentationDelay",parser:gt,dashName:"suggestedPresentationDelay"});break;case"maxSegmentDuration":r(o.value,{asKey:"maxSegmentDuration",parser:gt,dashName:"maxSegmentDuration"});break;case"maxSubsegmentDuration":r(o.value,{asKey:"maxSubsegmentDuration",parser:gt,dashName:"maxSubsegmentDuration"});break}}return[e,t]}function Ff(n){let[e,t]=Ty(n.childNodes),[r,i]=_y(n),o=t.concat(i);return[{children:e,attributes:r},o]}function eu(n,e){let t=n.documentElement;if(E(t)||t.nodeName!=="MPD")throw new Error("DASH Parser: document root should be MPD");let[r,i]=Ff(t),o=Lf(r,e,i);return a(o);function a(s){if(s.type==="done")return s;if(s.type==="needs-clock")return{type:"needs-resources",value:{urls:[s.value.url],format:"string",continue(d){if(d.length!==1)throw new Error("DASH parser: wrong number of loaded ressources.");let u=s.value.continue(d[0].responseData);return a(u)}}};if(s.type==="needs-xlinks")return{type:"needs-resources",value:{urls:s.value.xlinksUrls,format:"string",continue(d){let u=[];for(let c=0;c<d.length;c++){let{responseData:f,receivedTime:g,sendingTime:p,url:I}=d[c];if(!f.success)throw f.error;let y="<root>"+f.data+"</root>",b=new DOMParser().parseFromString(y,"text/xml");if(E(b)||b.children.length===0)throw new Error("DASH parser: Invalid external ressources");let T=b.children[0].children,v=[],_=[];for(let R=0;R<T.length;R++)if(T[R].nodeType===Node.ELEMENT_NODE){let[k,x]=pa(T[R]);_.push(...x),v.push(k)}u.push({url:I,receivedTime:g,sendingTime:p,parsed:v,warnings:_})}let l=s.value.continue(u);return a(l)}}};Xe(s)}}var Kf=eu;function $e(n,e){if(e.length===0)return n;let t,r="",i=n.indexOf("#"),o=n;i>=0&&(r=n.substring(i),o=n.substring(0,i));let a=o.indexOf("?");a===-1?t="?":a+1===o.length?t="":t="&";let s=o+t;for(let d=0;d<e.length;d++){let u=e[d];u[1]===null?s+=u[0]:s+=`${u[0]}=${u[1]}`,d<e.length-1&&(s+="&")}return r.length>0&&(s+=r),s}function tu(n,e){return(t,r,i)=>new Promise((o,a)=>{let s=Date.now()-K(),d=!1,f={reject:I=>{var v,_;if(d||i.isCancelled())return;d=!0,i.deregister(p);let y=I,b=(v=y==null?void 0:y.message)!=null?v:"Unknown error when fetching the Manifest through a custom manifestLoader.",T=new rt(b,(_=y==null?void 0:y.canRetry)!=null?_:!1,y==null?void 0:y.xhr);a(T)},resolve:I=>{if(d||i.isCancelled())return;d=!0,i.deregister(p);let y=I.receivingTime!==void 0?I.receivingTime-s:void 0,b=I.sendingTime!==void 0?I.sendingTime-s:void 0;o({responseData:I.data,size:I.size,requestDuration:I.duration,url:I.url,receivedTime:y,sendingTime:b})},fallback:()=>{d||i.isCancelled()||(d=!0,i.deregister(p),e(t,r,i).then(o,a))}},g=n({url:t,timeout:r.timeout,cmcdPayload:r.cmcdPayload},f);i.register(p);function p(I){d||(d=!0,typeof g=="function"&&g(),a(I))}})}function Ey(n){return function(t,r,i){var s,d;if(t===void 0)throw new Error("Cannot perform HTTP(s) request. URL not known");let o=((s=r.cmcdPayload)==null?void 0:s.type)==="query"?$e(t,r.cmcdPayload.value):t,a=((d=r.cmcdPayload)==null?void 0:d.type)==="headers"?r.cmcdPayload.value:void 0;switch(n){case"arraybuffer":return Te({url:o,headers:a,responseType:"arraybuffer",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});case"text":return Te({url:o,headers:a,responseType:"text",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});case"document":return Te({url:o,headers:a,responseType:"document",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});default:Xe(n)}}}function Bi({customManifestLoader:n},e,t){let r=Ey(e),i=typeof n!="function"?r:tu(n,r);return t!==null?t(i):i}function nn(n,e){if(e){if(Tt(n,1718909296)<0)throw new Le("INTEGRITY_ERROR","Incomplete `ftyp` box");if(Tt(n,1836019574)<0)throw new Le("INTEGRITY_ERROR","Incomplete `moov` box")}else{if(Tt(n,1836019558)<0)throw new Le("INTEGRITY_ERROR","Incomplete `moof` box");if(Tt(n,1835295092)<0)throw new Le("INTEGRITY_ERROR","Incomplete `mdat` box")}}function ht(n,e){if(n==="audio"||n==="video")return e==="video/mp4"||e==="audio/mp4"?"mp4":e==="video/webm"||e==="audio/webm"?"webm":void 0;if(n==="text")return e==="application/mp4"?"mp4":void 0}function ga(n){return(e,t,r,i,o)=>{return new Promise((s,d)=>{let u=new B,l=u.linkToSignal(i);u.signal.register(d),n(e,t,r,u.signal,ue(oe({},o),{onNewChunk(f){try{a(f),o.onNewChunk(f)}catch(g){c(),u.cancel(),d(g)}}})).then(f=>{if(c(),!u.isUsed()){if(f.resultType==="segment-loaded")try{a(f.resultData.responseData)}catch(g){d(g);return}s(f)}},f=>{c(),d(f)});function c(){u.signal.deregister(d),l()}});function a(s){!(s instanceof ArrayBuffer)&&!(s instanceof Uint8Array)||ht(t.type,t.mimeType)!=="mp4"||nn(new Uint8Array(s),t.segment.isInit)}}}function Vf(n){return async(e,t,r)=>{let i=await n(e,t,r);return o(i.responseData),i;function o(a){if(typeof a=="string"){let s=a.length-1,d=["</","MPD",">"];for(let u=d.length-1;u>=0;u--){let l=d[u];for(;vy(a[s]);)s--;for(let c=l.length-1;c>=0;c--){if(a[s]!==l[c])throw new Error("INTEGRITY_ERROR MPD does not end with </MPD>");s--}}}else if(a instanceof ArrayBuffer){let s=a.byteLength-1,d=new DataView(a),u=[[60,47],[77,80,68],[62]];for(let l=u.length-1;l>=0;l--){let c=u[l];for(;Ry(d.getUint8(s));)s--;for(let f=c.length-1;f>=0;f--){if(d.getUint8(s)!==c[f])throw new Error("INTEGRITY_ERROR MPD does not end with </MPD>");s--}}}else if(!E(J.Document)&&a instanceof J.Document&&a.documentElement.nodeName!=="MPD")throw new Le("INTEGRITY_ERROR","MPD does not end with </MPD>")}}}function vy(n){return n===" "||n===" "||n==="\r"||n===`
|
|
5
|
+
`}function Ry(n){return n===32||n===9||n===13||n===10}function nu(n){let{referenceDateTime:e}=n,t=n.serverSyncInfos!==void 0?n.serverSyncInfos.serverTimestamp-n.serverSyncInfos.clientTime:void 0;return function(i,o,a,s,d){var T;let{responseData:u}=i,l=o.externalClockOffset,c=(T=i.url)!=null?T:o.originalUrl,f=t!=null?t:l,p={unsafelyBaseOnPreviousManifest:o.unsafeMode?o.previousManifest:null,url:c,referenceDateTime:e,externalClockOffset:f},I=me.dashParsers;if(I.wasm===null||I.wasm.status==="uninitialized"||I.wasm.status==="failure")return m.debug("DASH: WASM MPD Parser not initialized. Running JS one."),y();{let v=Ay(u);if(!xy(v))return m.info("DASH: MPD doesn't seem to be UTF-8-encoded. Running JS parser instead of the WASM one."),y();if(I.wasm.status==="initialized"){m.debug("DASH: Running WASM MPD Parser.");let _=I.wasm.runWasmParser(v,p);return b(_)}else return m.debug("DASH: Awaiting WASM initialization before parsing the MPD."),I.wasm.waitForInitialization().catch(()=>{}).then(()=>{if(I.wasm===null||I.wasm.status!=="initialized")return m.warn("DASH: WASM MPD parser initialization failed. Running JS parser instead"),y();m.debug("DASH: Running WASM MPD Parser.");let R=I.wasm.runWasmParser(v,p);return b(R)})}function y(){if(I.fastJs!==null){let v=Py(u),_=I.fastJs(v,p);return b(_)}else if(I.native!==null){let v=My(u),_=I.native(v,p);return b(_)}else throw new Error("No MPD parser is imported")}function b(v){if(v.type==="done"){if(v.value.warnings.length>0&&a(v.value.warnings),s.isCancelled())return Promise.reject(s.cancellationError);let k=[];return{manifest:new Wn(v.value.parsed,n,k),url:c,warnings:k}}let{value:_}=v,R=_.urls.map(k=>d(()=>{let x=U.getCurrent().DEFAULT_REQUEST_TIMEOUT,M=U.getCurrent().DEFAULT_CONNECTION_TIMEOUT;return _.format==="string"?Te({url:k,responseType:"text",timeout:x,connectionTimeout:M,cancelSignal:s}):Te({url:k,responseType:"arraybuffer",timeout:x,connectionTimeout:M,cancelSignal:s})}).then(x=>{if(_.format==="string"){if(typeof x.responseData!="string")throw new Error("External DASH resources should have been a string");return G(x,{responseData:{success:!0,data:x.responseData}})}else{if(!(x.responseData instanceof ArrayBuffer))throw new Error("External DASH resources should have been ArrayBuffers");return G(x,{responseData:{success:!0,data:x.responseData}})}},x=>{let M=Oe(x,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"An unknown error occured when parsing ressources."});return G({},{size:void 0,requestDuration:void 0,responseData:{success:!1,error:M}})}));return Promise.all(R).then(k=>_.format==="string"?(ky(k),b(_.continue(k))):(Cy(k),b(_.continue(k))))}}}function ky(n){h.CURRENT_ENV!==h.PRODUCTION&&n.forEach(e=>{let{responseData:t}=e;if(!(t.success&&typeof t.data=="string")&&t.success)throw new Error("Invalid data given to the LoadedRessource")})}function Cy(n){h.CURRENT_ENV!==h.PRODUCTION&&n.forEach(e=>{let{responseData:t}=e;if(!(t.success&&t.data instanceof ArrayBuffer)&&t.success)throw new Error("Invalid data given to the LoadedRessource")})}function Py(n){if(n instanceof ArrayBuffer)return Ne(new Uint8Array(n));if(typeof n=="string")return n;if(n instanceof Document)return n.documentElement.outerHTML;throw new Error("DASH Manifest Parser: Unrecognized Manifest format")}function My(n){if(n instanceof ArrayBuffer)return new DOMParser().parseFromString(Ne(new Uint8Array(n)),"text/xml");if(typeof n=="string")return new DOMParser().parseFromString(n,"text/xml");if(n instanceof Document)return n;throw new Error("DASH Manifest Parser: Unrecognized Manifest format")}function Ay(n){if(n instanceof ArrayBuffer)return n;if(typeof n=="string")return ve(n).buffer;if(n instanceof Document)return ve(n.documentElement.innerHTML).buffer;throw new Error("DASH Manifest Parser: Unrecognized Manifest format")}function xy(n){let e=new DataView(n);return e.getUint16(0)===61371&&e.getUint8(2)===191?!0:!(e.getUint16(0)===65279||e.getUint16(0)===65534)}function ut([n,e]){return e===1/0?`bytes=${n}-`:`bytes=${n}-${e}`}function Fi(n,e){return n===null?null:e.url===null?n.baseUrl:mn(n.baseUrl,e.url)}function Ki(n,e,t,r,i){var u,l;let o=n;((u=t.cmcdPayload)==null?void 0:u.type)==="query"&&(o=$e(o,t.cmcdPayload.value));let a=((l=t.cmcdPayload)==null?void 0:l.type)==="headers"?t.cmcdPayload.value:void 0;if(e.range===void 0)return Te({url:o,responseType:"arraybuffer",headers:a,timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(c=>({resultType:"segment-loaded",resultData:c}));if(e.indexRange===void 0)return Te({url:o,headers:ue(oe({},a),{Range:ut(e.range)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(c=>({resultType:"segment-loaded",resultData:c}));if(e.range[1]+1===e.indexRange[0])return Te({url:o,headers:ue(oe({},a),{Range:ut([e.range[0],e.indexRange[1]])}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(c=>({resultType:"segment-loaded",resultData:c}));let s=Te({url:o,headers:ue(oe({},a),{Range:ut(e.range)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}),d=Te({url:o,headers:ue(oe({},a),{Range:ut(e.indexRange)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress});return Promise.all([s,d]).then(([c,f])=>{let g=ie(new Uint8Array(c.responseData),new Uint8Array(f.responseData)),p=Math.min(c.sendingTime,f.sendingTime),I=Math.max(c.receivedTime,f.receivedTime);return{resultType:"segment-loaded",resultData:{url:o,responseData:g,size:c.size+f.size,requestDuration:I-p,sendingTime:p,receivedTime:I}}})}async function Vi(n,e,t,r){let i=null;function o(s){let d=new Uint8Array(s.chunk),u=i!==null?ie(i,d):d,l=Wo(u),c=l[0];i=l[1],!(c!==null&&(c.forEach(f=>{t.onNewChunk(f)}),r.isCancelled()))&&(t.onProgress({duration:s.duration,size:s.size,totalSize:s.totalSize}),r.isCancelled())}return{resultType:"chunk-complete",resultData:await _o({url:n,headers:e.headers,onData:o,timeout:e.timeout,connectionTimeout:e.connectionTimeout,cancelSignal:r})}}async function zf(n,e,t,r,i,o){var f,g;if(e.segment.isInit)return Ki(n,e.segment,r,o,i);let a=((f=r.cmcdPayload)==null?void 0:f.type)==="query"?$e(n,r.cmcdPayload.value):n,s=((g=r.cmcdPayload)==null?void 0:g.type)==="headers"?r.cmcdPayload.value:void 0,{segment:d}=e,u;d.range!==void 0?u=ue(oe({},s),{Range:ut(d.range)}):s!==void 0&&(u=s);let l=ht(e.type,e.mimeType);if(t&&(l==="mp4"||l===void 0)){if(kr())return Vi(a,{headers:u,timeout:r.timeout,connectionTimeout:r.connectionTimeout},i,o);At("DASH: Your browser does not have the fetch API. You will have a higher chance of rebuffering when playing close to the live edge")}return{resultType:"segment-loaded",resultData:await Te({url:a,responseType:"arraybuffer",headers:u,timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:o,onProgress:i.onProgress})}}function ru({lowLatencyMode:n,segmentLoader:e,checkMediaSegmentIntegrity:t}){return t!==!0?r:ga(r);function r(i,o,a,s,d){let u=Fi(i,o.segment);return u===null?Promise.resolve({resultType:"segment-created",resultData:null}):n||e===void 0?zf(u,o,n,a,d,s):new Promise((l,c)=>{let f=!1,b={reject:k=>{var N,O;if(f||s.isCancelled())return;f=!0,s.deregister(R);let x=k,M=(N=x==null?void 0:x.message)!=null?N:"Unknown error when fetching a DASH segment through a custom segmentLoader.",P=new rt(M,(O=x==null?void 0:x.canRetry)!=null?O:!1,x==null?void 0:x.xhr);c(P)},resolve:k=>{f||s.isCancelled()||(f=!0,s.deregister(R),l({resultType:"segment-loaded",resultData:{responseData:k.data,size:k.size,requestDuration:k.duration}}))},progress:k=>{f||s.isCancelled()||d.onProgress({duration:k.duration,size:k.size,totalSize:k.totalSize})},fallback:()=>{f||s.isCancelled()||(f=!0,s.deregister(R),zf(u,o,n,a,d,s).then(l,c))}},T;o.segment.range!==void 0&&(T=[o.segment.range],o.segment.indexRange!==void 0&&T.push(o.segment.indexRange));let v={isInit:o.segment.isInit,timeout:a.timeout,byteRanges:T,trackType:o.type,url:u,cmcdPayload:a.cmcdPayload},_=e(v,b);s.register(R);function R(k){f||(f=!0,typeof _=="function"&&_(),c(k))}})}}var ou=408125543,Hf=357149030,wy=2807729,Oy=17545,Dy=475249515,Ly=187,Ny=179,Uy=183,By=241;function rn(n,e,t,[r,i]){let o=r;for(;o<i;){let a=Ky(t,o);if(a===null)return null;let{value:s,length:d}=a,u=o+d,l=Vy(t,u);if(l===null)return null;let{length:c,value:f}=l,g=u+c,p=g+f;if(s===n)return[g,p];if(e.length>0){for(let I=0;I<e.length;I++)if(s===e[I]){let y=e.slice(I+1,e.length);return rn(n,y,t,[g,p])}}o=p}return null}function ha(n,e){let t=rn(wy,[ou,Hf],n,[e,n.length]);if(t===null)return null;let r=t[1]-t[0];return 1e9/iu(n,t[0],r)}function Fy(n,e){let t=rn(Oy,[ou,Hf],n,[e,n.length]);if(t===null)return null;let r=t[1]-t[0];return r===4?zy(n,t[0]):r===8?Hy(n,t[0]):null}function au(n,e){let t=rn(ou,[],n,[e,n.length]);if(t===null)return null;let[r,i]=t,o=ha(n,r);if(o===null)return null;let a=Fy(n,r);if(a===null)return null;let s=rn(Dy,[],n,[r,i]);if(s===null)return null;let d=[],u=s[0];for(;u<s[1];){let c=rn(Ly,[],n,[u,s[1]]);if(c===null)break;let f=rn(Ny,[],n,[c[0],c[1]]);if(f===null)return null;let g=iu(n,f[0],f[1]-f[0]),p=rn(By,[Uy],n,[c[0],c[1]]);if(p===null)return null;let I=iu(n,p[0],p[1]-p[0])+r;d.push({time:g,rangeStart:I}),u=c[1]}let l=[];for(let c=0;c<d.length;c++){let f=d[c];c===d.length-1?l.push({time:f.time,timescale:o,duration:c===0?a:a-f.time,range:[f.rangeStart,1/0]}):l.push({time:f.time,timescale:o,duration:d[c+1].time-f.time,range:[f.rangeStart,d[c+1].rangeStart-1]})}return l}function Wf(n,e){for(let t=1;t<=8;t++)if(n[e]>=Math.pow(2,8-t))return t}function Ky(n,e){let t=Wf(n,e);if(t===void 0)return m.warn("webm: unrepresentable length"),null;if(e+t>n.length)return m.warn("webm: impossible length"),null;let r=0;for(let i=0;i<t;i++)r=n[e+i]*Math.pow(2,(t-i-1)*8)+r;return{length:t,value:r}}function Vy(n,e){let t=Wf(n,e);if(t===void 0)return m.warn("webm: unrepresentable length"),null;if(e+t>n.length)return m.warn("webm: impossible length"),null;let r=(n[e]&(1<<8-t)-1)*Math.pow(2,(t-1)*8);for(let i=1;i<t;i++)r=n[e+i]*Math.pow(2,(t-i-1)*8)+r;return{length:t,value:r}}function zy(n,e){return new DataView(n.buffer).getFloat32(e)}function Hy(n,e){return new DataView(n.buffer).getFloat64(e)}function iu(n,e,t){let r=0;for(let i=0;i<t;i++)r=n[e+i]*Math.pow(2,(t-i-1)*8)+r;return r}function zi(n,e,t,r){let i=Ps(n);if(i===void 0||r===void 0)return null;let o=t.timestampOffset!==void 0?i+t.timestampOffset*r:i,a=Br(n);if(o<0&&(a!==void 0&&(a+=o),o=0),e||!t.complete)return a===void 0&&m.warn("DASH: Chunked segments should indicate a duration through their trun boxes"),{time:o/r,duration:a!==void 0?a/r:void 0};let s,d=t.duration*r,u=Math.min(r*.9,d/4);return a!==void 0&&Math.abs(a-d)<=u&&(s=a),{time:o/r,duration:s!==void 0?s/r:s}}function Wy(n,e){if(n.length<=0)return!1;let t=n.length;for(let r=0;r<t;r++){let i=n[r],o=e,{messageData:a}=i,s=Ne(a),d=Date.parse(s);if(o===void 0||d===void 0||isNaN(d)||d>=o)return!0}return!1}function su(n,e){if(n.length===0)return;let{manifestRefreshEventsFromEMSGs:t,EMSGs:r}=n.reduce((a,s)=>(s.schemeIdUri==="urn:mpeg:dash:event:2012"&&s.value==="1"?(a.manifestRefreshEventsFromEMSGs===void 0&&(a.manifestRefreshEventsFromEMSGs=[]),a.manifestRefreshEventsFromEMSGs.push(s)):(a.EMSGs===void 0&&(a.EMSGs=[]),a.EMSGs.push(s)),a),{manifestRefreshEventsFromEMSGs:void 0,EMSGs:void 0}),i=r==null?void 0:r.map(a=>({type:"emsg",value:a})),o=e===void 0||t===void 0?!1:Wy(t,e);return{inbandEvents:i,needsManifestRefresh:o}}function du({__priv_patchLastSegmentInSidx:n}){return function(t,r,i){var v,_;let{segment:o,periodStart:a,periodEnd:s}=r,{data:d,isChunked:u}=t,l=[a,s];if(d===null)return o.isInit?{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0}:{segmentType:"media",chunkData:null,chunkSize:0,chunkInfos:null,chunkOffset:0,protectionData:[],appendWindow:l};let c=d instanceof Uint8Array?d:new Uint8Array(d),f=ht(r.type,r.mimeType),g=f==="mp4"||f===void 0,p=[];if(g){let R=Go(c),k;o.isInit&&(k=(v=zc(c))!=null?v:void 0),(R.length>0||k!==void 0)&&p.push({initDataType:"cenc",keyId:k,initData:R})}if(!o.isInit){let R=g?zi(c,u,o,i):null,k=(_=o.timestampOffset)!=null?_:0;if(g){let x=Vc(c);if(x!==void 0){let M=x.filter(N=>o.privateInfos===void 0||o.privateInfos.isEMSGWhitelisted===void 0?!1:o.privateInfos.isEMSGWhitelisted(N)),P=su(M,r.manifestPublishTime);if(P!==void 0){let{needsManifestRefresh:N,inbandEvents:O}=P;return{segmentType:"media",chunkData:c,chunkSize:c.length,chunkInfos:R,chunkOffset:k,appendWindow:l,inbandEvents:O,protectionData:p,needsManifestRefresh:N}}}}return{segmentType:"media",chunkData:c,chunkSize:c.length,chunkInfos:R,chunkOffset:k,protectionData:p,appendWindow:l}}let{indexRange:I}=o,y;if(f==="webm")y=au(c,0);else if(g&&(y=Ur(c,Array.isArray(I)?I[0]:0),n===!0&&y!==null&&y.length>0)){let R=y[y.length-1];Array.isArray(R.range)&&(R.range[1]=1/0)}let b;g?b=Fr(c):f==="webm"&&(b=ha(c,0));let T=E(b)?void 0:b;return{segmentType:"init",initializationData:c,initializationDataSize:c.length,protectionData:p,initTimescale:T,segmentList:y!=null?y:void 0}}}function uu({lowLatencyMode:n,checkMediaSegmentIntegrity:e}){return e!==!0?t:ga(t);async function t(r,i,o,a,s){var y,b;let{segment:d}=i,u=Fi(r,d);if(u===null)return Promise.resolve({resultType:"segment-created",resultData:null});if(d.isInit)return Ki(u,d,o,a,s);let l=((y=o.cmcdPayload)==null?void 0:y.type)==="query"?$e(u,o.cmcdPayload.value):u,c=((b=o.cmcdPayload)==null?void 0:b.type)==="headers"?o.cmcdPayload.value:void 0,f;d.range!==void 0?f=ue(oe({},c),{Range:ut(d.range)}):c!==void 0&&(f=c);let g=ht(i.type,i.mimeType),p=g==="mp4"||g===void 0;if(n&&p){if(kr())return Vi(l,{headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout},s,a);At("DASH: Your browser does not have the fetch API. You will have a higher chance of rebuffering when playing close to the live edge")}let I;return p?I=await Te({url:l,responseType:"arraybuffer",headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout,onProgress:s.onProgress,cancelSignal:a}):I=await Te({url:l,responseType:"text",headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout,onProgress:s.onProgress,cancelSignal:a}),{resultType:"segment-loaded",resultData:I}}}function Gy(n){let e=Lr(n);return e===null?"":Ne(e)}function qy(n){if(n===void 0)throw new Error("Cannot parse subtitles: unknown format");switch(n.toLowerCase()){case"stpp":case"stpp.ttml":case"stpp.ttml.im1t":return"ttml";case"wvtt":return"vtt"}throw new Error(`The codec used for the subtitles "${n}" is not managed yet.`)}function jy(n,e){switch(e){case"application/ttml+xml":return"ttml";case"application/x-sami":case"application/smil":return"sami";case"text/vtt":return"vtt"}if(n!==void 0&&n.toLowerCase()==="srt")return"srt";throw new Error(`could not find a text-track parser for the type ${e!=null?e:""}`)}function Gf({segment:n,language:e,codecs:t},r,i,o){if(n.isInit)return null;let a,s;i===null?o?(a=n.time,s=n.end):m.warn("Transport: Unavailable time data for current text track."):(a=i.time,i.duration!==void 0?s=a+i.duration:!o&&n.complete&&(s=a+n.duration));let d=qy(t);return{data:Gy(r),type:d,language:e,start:a,end:s}}function qf(n,e,t){let{segment:r}=n;if(r.isInit)return null;let i,o;t?m.warn("Transport: Unavailable time data for current text track."):(i=r.time,r.complete&&(o=r.time+r.duration));let a=jy(n.codecs,n.mimeType);return{data:e,type:a,language:n.language,start:i,end:o}}function Yy(n,e,t,r,i){var f;let{segment:o}=t,{isInit:a,indexRange:s}=o,d;if(typeof n=="string"?d=ve(n):n instanceof Uint8Array?d=n:d=new Uint8Array(n),a){let g=Ur(d,Array.isArray(s)?s[0]:0);if(i===!0&&g!==null&&g.length>0){let I=g[g.length-1];Array.isArray(I.range)&&(I.range[1]=1/0)}let p=Fr(d);return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:p,segmentList:g!=null?g:void 0}}let u=zi(d,e,o,r),l=Gf(t,d,u,e),c=(f=o.timestampOffset)!=null?f:0;return{segmentType:"media",chunkData:l,chunkSize:d.length,chunkInfos:u,chunkOffset:c,protectionData:[],appendWindow:[t.periodStart,t.periodEnd]}}function $y(n,e,t){let{periodStart:r,periodEnd:i,segment:o}=t,{timestampOffset:a=0}=o;if(o.isInit)return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0};let s,d;if(typeof n!="string"){let l=n instanceof Uint8Array?n:new Uint8Array(n);s=Ne(l),d=l.length}else s=n;return{segmentType:"media",chunkData:qf(t,s,e),chunkSize:d,chunkInfos:null,chunkOffset:a,protectionData:[],appendWindow:[r,i]}}function lu({__priv_patchLastSegmentInSidx:n}){return function(t,r,i){var c;let{periodStart:o,periodEnd:a,segment:s}=r,{data:d,isChunked:u}=t;if(d===null)return s.isInit?{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0}:{segmentType:"media",chunkData:null,chunkSize:0,chunkInfos:null,chunkOffset:(c=s.timestampOffset)!=null?c:0,protectionData:[],appendWindow:[o,a]};let l=ht(r.type,r.mimeType);if(l==="webm")throw new Error("Text tracks with a WEBM container are not yet handled.");return l==="mp4"?Yy(d,u,r,i,n):$y(d,u,r)}}function jf(n){let e=Bi({customManifestLoader:n.manifestLoader},Qy()?"text":"arraybuffer",n.checkManifestIntegrity===!0?Vf:null),t=nu(n),r=ru(n),i=du(n),o=uu(n),a=lu(n);return{transportName:"dash",manifest:{loadManifest:e,parseManifest:t},audio:{loadSegment:r,parseSegment:i},video:{loadSegment:r,parseSegment:i},text:{loadSegment:o,parseSegment:a}}}function Qy(){return me.dashParsers.wasm!==null&&(me.dashParsers.wasm.status==="initialized"||me.dashParsers.wasm.status==="initializing")}var Yf=jf;function cu(n){n.transports.dash===void 0&&(n.transports.dash=Yf),n.dashParsers.native=Kf,n.mainThreadMediaSourceInit=vn}var Xy=typeof MediaSource=="function"&&MediaSource.canConstructInDedicatedWorker===!0,$f=Xy;var Hi=class extends Yn{constructor(e){super(),this._settings=e,this._initCanceller=new B}prepare(){}start(e,t){let r=this._initCanceller.signal,{keySystems:i,speed:o,url:a}=this._settings;$n(e);let{statusRef:s}=Ei(e,i,{onError:u=>this._onFatalError(u),onWarning:u=>this.trigger("warning",u),onBlackListProtectionData:X,onKeyIdsCompatibilityUpdate:X},r);Ci(e,u=>this._onFatalError(u),r);let d=new En(t,null,o);d.addEventListener("stalled",u=>this.trigger("stalled",u)),d.addEventListener("unstalled",()=>this.trigger("unstalled",null)),d.addEventListener("warning",u=>this.trigger("warning",u)),r.register(()=>{d.destroy()}),d.start(),s.onUpdate((u,l)=>{u.initializationState.type!=="uninitialized"&&(l(),m.info("Setting URL to HTMLMediaElement",a),e.src=a,r.register(()=>{m.info("Init: Removing directfile src from media element",e.src),$n(e)}),u.initializationState.type==="awaiting-media-link"?(u.initializationState.value.isMediaLinked.setValue(!0),s.onUpdate((c,f)=>{c.initializationState.type==="initialized"&&(f(),this._seekAndPlay(e,t))},{emitCurrentValue:!0,clearSignal:r})):(ee(u.initializationState.type==="initialized"),this._seekAndPlay(e,t)))},{emitCurrentValue:!0,clearSignal:r})}updateContentUrls(e,t){throw new Error("Cannot update content URL of directfile contents")}dispose(){this._initCanceller.cancel()}_onFatalError(e){this._initCanceller.cancel(),this.trigger("error",e)}_seekAndPlay(e,t){let r=this._initCanceller.signal,{autoPlay:i,startAt:o}=this._settings;_i({mediaElement:e,playbackObserver:t,startTime:()=>{m.debug("Init: Calculating initial time");let s=Zy(e,o);return m.debug("Init: Initial time calculated:",s),s},mustAutoPlay:i,onWarning:s=>this.trigger("warning",s),isDirectfile:!0},r).autoPlayResult.then(()=>Ti(t,e,!0,r).onUpdate((s,d)=>{s&&(d(),this.trigger("loaded",{getSegmentSinkMetrics:null}))},{emitCurrentValue:!0,clearSignal:r})).catch(s=>{r.isCancelled()||this._onFatalError(s)})}};function Zy(n,e){if(E(e))return 0;if(E(e.position))if(E(e.wallClockTime)){if(!E(e.fromFirstPosition))return e.fromFirstPosition}else return e.wallClockTime;else return e.position;let t=n.duration;if(typeof e.fromLastPosition=="number"){if(!E(t)&&isFinite(t))return Math.max(0,t+e.fromLastPosition);if(n.seekable.length>0){let r=n.seekable.end(n.seekable.length-1);if(isFinite(r))return Math.max(0,r+e.fromLastPosition)}m.warn("Init: startAt.fromLastPosition set but no known duration, it may be too soon to seek");return}else if(typeof e.fromLivePosition=="number"){let r=n.seekable.length>0?n.seekable.end(0):t;return E(r)?(m.warn("Init: startAt.fromLivePosition set but no known live position, beginning at 0."),0):Math.max(0,r+e.fromLivePosition)}else if(!E(e.percentage)){if(E(t)||!isFinite(t))return m.warn("Init: startAt.percentage set but no known duration, beginning at 0."),0;let{percentage:r}=e;if(r>=100)return t;if(r<=0)return 0;let i=+r/100;return t*i}return 0}function fu(n,e){for(let t=0;t<n.length;t++)(!lr||t!==e)&&(n[t].enabled=!1);return e<0||e>=n.length?!1:(n[e].enabled=!0,!0)}function tr(n,e){var t;if(e.length!==n.length)return!0;for(let r=0;r<e.length;r++)if(e[r].nativeTrack!==((t=n[r])==null?void 0:t.nativeTrack))return!0;return!1}function mu(n){var r;let e=[],t={};for(let i=0;i<n.length;i++){let o=n[i],a=o.language===""?"nolang":o.language,s=(r=t[a])!=null?r:1,d="gen_audio_"+a+"_"+s.toString();t[a]=s+1;let u={language:o.language,id:d,normalized:Cr(o.language),audioDescription:o.kind==="descriptions"||o.kind==="description",representations:[]};e.push({track:u,nativeTrack:o})}return e}function pu(n){var r;let e=[],t={};for(let i=0;i<n.length;i++){let o=n[i],a=o.language===""?"nolang":o.language,s=(r=t[a])!=null?r:1,d="gen_text_"+a+"_"+s.toString();t[a]=s+1;let u=o.kind==="forced"?!0:void 0,l={language:o.language,forced:u,label:o.label,id:d,normalized:Cr(o.language),closedCaption:o.kind==="captions"};e.push({track:l,nativeTrack:o})}return e}function gu(n){var r;let e=[],t={};for(let i=0;i<n.length;i++){let o=n[i],a=o.language===""?"nolang":o.language,s=(r=t[a])!=null?r:1,d="gen_video_"+a+"_"+s.toString();t[a]=s+1,e.push({track:{id:d,representations:[]},nativeTrack:o})}return e}var Wi=class extends re{constructor(e){var t,r,i;super(),this._nativeAudioTracks=e.audioTracks,this._nativeVideoTracks=e.videoTracks,this._nativeTextTracks=e.textTracks,this._audioTracks=this._nativeAudioTracks!==void 0?mu(this._nativeAudioTracks):[],this._videoTracks=this._nativeVideoTracks!==void 0?gu(this._nativeVideoTracks):[],this._textTracks=this._nativeTextTracks!==void 0?pu(this._nativeTextTracks):[],this._lastEmittedNativeAudioTrack=(t=this._getCurrentAudioTrack())==null?void 0:t.nativeTrack,this._lastEmittedNativeVideoTrack=(r=this._getCurrentVideoTrack())==null?void 0:r.nativeTrack,this._lastEmittedNativeTextTrack=(i=this._getCurrentTextTrack())==null?void 0:i.nativeTrack,this._handleNativeTracksCallbacks()}setAudioTrackById(e){for(let t=0;t<this._audioTracks.length;t++){let{track:r,nativeTrack:i}=this._audioTracks[t];if(r.id===e){this._enableAudioTrackFromIndex(t),this._audioTrackLockedOn=i;return}}throw new Error("Audio track not found.")}disableTextTrack(){Qf(this._textTracks),this._textTrackLockedOn=null}setTextTrackById(e){let t=!1;for(let r=0;r<this._textTracks.length;r++){let{track:i,nativeTrack:o}=this._textTracks[r];i.id===e?(o.mode="showing",t=!0,this._textTrackLockedOn=o):(o.mode==="showing"||o.mode==="hidden")&&(o.mode="disabled")}if(!t)throw new Error("Text track not found.")}disableVideoTrack(){Xf(this._videoTracks),this._videoTrackLockedOn=null}setVideoTrackById(e){for(let t=0;t<this._videoTracks.length;t++){let{track:r,nativeTrack:i}=this._videoTracks[t];if(r.id===e){i.selected=!0,this._videoTrackLockedOn=i;return}}throw new Error("Video track not found.")}getChosenAudioTrack(){let e=this._getCurrentAudioTrack();return E(e)?e:e.track}getChosenTextTrack(){let e=this._getCurrentTextTrack();return E(e)?e:e.track}getChosenVideoTrack(){let e=this._getCurrentVideoTrack();return E(e)?e:e.track}getAvailableAudioTracks(){return this._audioTracks.map(({track:e,nativeTrack:t})=>({id:e.id,language:e.language,normalized:e.normalized,audioDescription:e.audioDescription,active:t.enabled,representations:e.representations}))}getAvailableTextTracks(){return this._textTracks.map(({track:e,nativeTrack:t})=>({id:e.id,label:e.label,forced:e.forced,language:e.language,normalized:e.normalized,closedCaption:e.closedCaption,active:t.mode==="showing"}))}getAvailableVideoTracks(){return this._videoTracks.map(({track:e,nativeTrack:t})=>({id:e.id,representations:e.representations,active:t.selected}))}dispose(){this._nativeVideoTracks!==void 0&&(this._nativeVideoTracks.onchange=null,this._nativeVideoTracks.onaddtrack=null,this._nativeVideoTracks.onremovetrack=null),this._nativeAudioTracks!==void 0&&(this._nativeAudioTracks.onchange=null,this._nativeAudioTracks.onaddtrack=null,this._nativeAudioTracks.onremovetrack=null),this._nativeTextTracks!==void 0&&(this._nativeTextTracks.onchange=null,this._nativeTextTracks.onaddtrack=null,this._nativeTextTracks.onremovetrack=null),this.removeEventListener()}_getCurrentAudioTrack(){if(this._nativeAudioTracks!==void 0){for(let e=0;e<this._audioTracks.length;e++){let t=this._audioTracks[e];if(t.nativeTrack.enabled)return t}return null}}_getCurrentVideoTrack(){if(this._nativeVideoTracks!==void 0){for(let e=0;e<this._videoTracks.length;e++){let t=this._videoTracks[e];if(t.nativeTrack.selected)return t}return null}}_getCurrentTextTrack(){if(this._nativeTextTracks!==void 0){for(let e=0;e<this._textTracks.length;e++){let t=this._textTracks[e];if(t.nativeTrack.mode==="showing")return t}return null}}_setPreviouslyLockedAudioTrack(){if(this._audioTrackLockedOn!==void 0)if(this._audioTrackLockedOn===null)for(let e=0;e<this._audioTracks.length;e++){let{nativeTrack:t}=this._audioTracks[e];t.enabled=!1}else for(let e=0;e<this._audioTracks.length;e++){let{nativeTrack:t}=this._audioTracks[e];if(t===this._audioTrackLockedOn){this._enableAudioTrackFromIndex(e);return}}}_setPreviouslyLockedTextTrack(){if(this._textTrackLockedOn!==void 0)if(this._textTrackLockedOn===null){Qf(this._textTracks);return}else for(let e=0;e<this._textTracks.length;e++){let{nativeTrack:t}=this._textTracks[e];if(t===this._textTrackLockedOn){Jy(this._textTracks,t),t.mode!=="showing"&&(t.mode="showing");return}}}_setPreviouslyLockedVideoTrack(){if(this._videoTrackLockedOn!==void 0)if(this._videoTrackLockedOn===null){Xf(this._videoTracks);return}else for(let e=0;e<this._videoTracks.length;e++){let{nativeTrack:t}=this._videoTracks[e];if(t===this._videoTrackLockedOn){t.selected=!0;return}}}_handleNativeTracksCallbacks(){this._nativeAudioTracks!==void 0&&(this._nativeAudioTracks.onaddtrack=()=>{var e,t;if(this._nativeAudioTracks!==void 0){let r=mu(this._nativeAudioTracks);if(tr(this._audioTracks,r)){this._audioTracks=r,this._setPreviouslyLockedAudioTrack(),this.trigger("availableAudioTracksChange",this.getAvailableAudioTracks());let i=this._getCurrentAudioTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeAudioTrack&&(this.trigger("audioTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeAudioTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeAudioTracks.onremovetrack=()=>{var e,t;if(this._nativeAudioTracks!==void 0){let r=mu(this._nativeAudioTracks);if(tr(this._audioTracks,r)){this._audioTracks=r,this.trigger("availableAudioTracksChange",this.getAvailableAudioTracks());let i=this._getCurrentAudioTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeAudioTrack&&(this.trigger("audioTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeAudioTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeAudioTracks.onchange=()=>{if(this._audioTracks!==void 0)for(let e=0;e<this._audioTracks.length;e++){let{track:t,nativeTrack:r}=this._audioTracks[e];if(r.enabled){r!==this._lastEmittedNativeAudioTrack&&(this.trigger("audioTrackChange",t),this._lastEmittedNativeAudioTrack=r);return}}this._lastEmittedNativeAudioTrack!==null&&(this.trigger("audioTrackChange",null),this._lastEmittedNativeAudioTrack=null)}),this._nativeTextTracks!==void 0&&(this._nativeTextTracks.onaddtrack=()=>{var e,t;if(this._nativeTextTracks!==void 0){let r=pu(this._nativeTextTracks);if(tr(this._textTracks,r)){this._textTracks=r,this._setPreviouslyLockedTextTrack(),this.trigger("availableTextTracksChange",this.getAvailableTextTracks());let i=this._getCurrentTextTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeTextTrack&&(this.trigger("textTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeTextTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeTextTracks.onremovetrack=()=>{var e,t;if(this._nativeTextTracks!==void 0){let r=pu(this._nativeTextTracks);if(tr(this._textTracks,r)){this._textTracks=r,this._setPreviouslyLockedTextTrack(),this.trigger("availableTextTracksChange",this.getAvailableTextTracks());let i=this._getCurrentTextTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeTextTrack&&(this.trigger("textTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeTextTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeTextTracks.onchange=()=>{if(this._textTracks!==void 0)for(let e=0;e<this._textTracks.length;e++){let{track:t,nativeTrack:r}=this._textTracks[e];if(r.mode==="showing"){r!==this._lastEmittedNativeTextTrack&&(this.trigger("textTrackChange",t),this._lastEmittedNativeTextTrack=r);return}}this._lastEmittedNativeTextTrack!==null&&(this.trigger("textTrackChange",null),this._lastEmittedNativeTextTrack=null)}),this._nativeVideoTracks!==void 0&&(this._nativeVideoTracks.onaddtrack=()=>{var e,t;if(this._nativeVideoTracks!==void 0){let r=gu(this._nativeVideoTracks);if(tr(this._videoTracks,r)){this._videoTracks=r,this._setPreviouslyLockedVideoTrack(),this.trigger("availableVideoTracksChange",this.getAvailableVideoTracks());let i=this._getCurrentVideoTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeVideoTrack&&(this.trigger("videoTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeVideoTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeVideoTracks.onremovetrack=()=>{var e,t;if(this._nativeVideoTracks!==void 0){let r=gu(this._nativeVideoTracks);if(tr(this._videoTracks,r)){this._videoTracks=r,this._setPreviouslyLockedVideoTrack(),this.trigger("availableVideoTracksChange",this.getAvailableVideoTracks());let i=this._getCurrentVideoTrack();(i==null?void 0:i.nativeTrack)!==this._lastEmittedNativeVideoTrack&&(this.trigger("videoTrackChange",(e=i==null?void 0:i.track)!=null?e:null),this._lastEmittedNativeVideoTrack=(t=i==null?void 0:i.nativeTrack)!=null?t:null)}}},this._nativeVideoTracks.onchange=()=>{if(this._videoTracks!==void 0)for(let e=0;e<this._videoTracks.length;e++){let{track:t,nativeTrack:r}=this._videoTracks[e];if(r.selected){r!==this._lastEmittedNativeVideoTrack&&(this.trigger("videoTrackChange",t),this._lastEmittedNativeVideoTrack=r);return}}this._lastEmittedNativeVideoTrack!==null&&(this.trigger("videoTrackChange",null),this._lastEmittedNativeVideoTrack=null)})}_enableAudioTrackFromIndex(e){fu(this._audioTracks.map(({nativeTrack:t})=>t),e)}};function Qf(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.mode="disabled"}}function Jy(n,e){for(let t=0;t<n.length;t++){let{nativeTrack:r}=n[t];r!==e&&(r.mode==="showing"||r.mode==="hidden")&&(r.mode="disabled")}}function Xf(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.selected=!1}}function hu(n){n.directfile={initDirectFile:Hi,mediaElementTracksStore:Wi}}function yu(n){n.decrypt=Jc}var Zf=J.ResizeObserver;function Iu(n,e,t){let{height:r,width:i}=n.getBoundingClientRect(),o=new H({height:r,width:i},t),a=r,s=i;if(Zf!==void 0){let d=new Zf(u=>{if(u.length===0){m.error("Compat: Resized but no observed element.");return}let l=u[0],{height:c,width:f}=l.contentRect;(c!==a||f!==s)&&(a=c,s=f,o.setValue({height:c,width:f}))});d.observe(n),t.register(()=>{d.disconnect()})}else{let d=setInterval(()=>{let{height:u,width:l}=n.getBoundingClientRect();(u!==a||l!==s)&&(a=u,s=l,o.setValue({height:u,width:l}))},e);t.register(()=>{clearInterval(d)})}return o}var An=class{constructor(){this._ranges=[],this.length=0}insert(e,t){h.CURRENT_ENV===h.DEV&&(ee(e>=0,"invalid start time"),ee(t-e>0,"invalid end time")),Gt(this._ranges,{start:e,end:t}),this.length=this._ranges.length}remove(e,t){h.CURRENT_ENV===h.DEV&&(ee(e>=0,"invalid start time"),ee(t-e>0,"invalid end time"));let r=[];e>0&&r.push({start:0,end:e}),t<1/0&&r.push({start:t,end:1/0}),this._ranges=Jl(this._ranges,r),this.length=this._ranges.length}start(e){if(e>=this._ranges.length)throw new Error("INDEX_SIZE_ERROR");return this._ranges[e].start}end(e){if(e>=this._ranges.length)throw new Error("INDEX_SIZE_ERROR");return this._ranges[e].end}};function bu(n,e,t,r){m.debug("HTSB: Finding parser for html text tracks:",n);let i=me.htmlTextTracksParsers[n];if(typeof i!="function")throw new Error("no parser found for the given text track");m.debug("HTSB: Parser found, parsing...");let o=i(e,t,r);return m.debug("HTTB: Parsed successfully!",o.length),o}function Ut(n,e,t=.2){return Math.abs(n-e)<=Math.min(t,.2)}var eI=.05;function Jf(n,e){let t=n.end-n.start,r=e.end-e.start,i=Math.abs(n.start-e.start),o=Math.min(t,r,.2);return i/o<=eI}function Gi(n,e){for(let t=n.length-1;t>=0;t--)if(n[t].start<e)return n.slice(0,t+1);return[]}function nr(n,e){for(let t=0;t<n.length;t++)if(n[t].end>e)return n.slice(t,n.length);return[]}function Su(n,e,t){let r=Math.max(n.start,e),i=Gi(n.cues,e),o={start:n.start,end:r,cues:i},a=Math.min(t,n.end),s=nr(n.cues,t),d={start:a,end:n.end,cues:s};return[o,d]}var em=.001,tI=5,qi=class{constructor(){this._cuesBuffer=[]}isEmpty(){return this._cuesBuffer.length===0}get(e){let t=this._cuesBuffer,r=[];for(let i=t.length-1;i>=0;i--){let o=t[i];if(e<o.end&&e>=o.start){let a=o.cues;for(let s of a)e>=s.start&&e<s.end&&r.push(s.element);if(r.length===0&&a.length>0)for(let s of a)(Ut(e,s.start,em)||Ut(e,s.end,em))&&r.push(s.element);return r}}return[]}remove(e,t){h.CURRENT_ENV===h.DEV&&(ee(e>=0),ee(t>=0),ee(t>e));let r=Math.max(e,t),i=this._cuesBuffer;for(let o=0;o<i.length;o++)if(i[o].end>e){let a=i[o];if(a.start>=r)return;if(a.end>=r){if(e<=a.start)a.cues=nr(a.cues,r),a.start=r;else{let[s,d]=Su(a,e,r);this._cuesBuffer[o]=s,i.splice(o+1,0,d)}return}a.start>=e?(i.splice(o,1),o--):(a.cues=Gi(a.cues,e),a.end=Math.max(e,a.start))}}insert(e,t,r){let i=this._cuesBuffer,o={start:t,end:r,cues:e},a=Math.abs(t-r)/tI;function s(d){let u=i[d];u===void 0||Ut(o.end,u.end,a)?i[d]=o:(u.start>=o.end||(u.cues=nr(u.cues,o.end),u.start=o.end),i.splice(d,0,o))}for(let d=0;d<i.length;d++){let u=i[d];if(t<u.end){if(Jf(o,u)){if(Ut(r,u.end,a)){i[d]=o;return}else if(r<u.end){u.cues=nr(u.cues,r),u.start=r,i.splice(d,0,o);return}do i.splice(d,1),u=i[d];while(u!==void 0&&r>u.end);s(d);return}else if(t<u.start){if(r<u.start){i.splice(d,0,o);return}else if(Ut(r,u.start,a)){u.start=r,i.splice(d,0,o);return}else if(Ut(r,u.end,a)){i.splice(d,1,o);return}else if(r<u.end){u.cues=nr(u.cues,r),u.start=r,i.splice(d,0,o);return}do i.splice(d,1),u=i[d];while(u!==void 0&&r>u.end);s(d);return}if(Ut(u.end,r,a)){u.cues=Gi(u.cues,t),u.end=t,i.splice(d+1,0,o);return}else if(u.end>r){let[l,c]=Su(u,t,r);this._cuesBuffer[d]=l,i.splice(d+1,0,o),i.splice(d+2,0,c);return}else{u.cues=Gi(u.cues,t),u.end=t;let l=d+1;for(u=i[l];u!==void 0&&r>u.end;)i.splice(l,1),u=i[l];s(l);return}}}if(i.length>0){let d=i[i.length-1];Ut(d.end,t,a)&&(d.end=t)}i.push(o)}};function Tu(n,e,t,r){let i=[e/t.columns,n/t.rows],o=r.getElementsByClassName("proportional-style");for(let a=0;a<o.length;a++){let s=o[a];if(s instanceof HTMLElement){let d=s.getAttribute("data-proportional-font-size");d!==null&&!isNaN(+d)&&(s.style.fontSize=String(+d*i[1])+"px");let u=s.getAttribute("data-proportional-width");u!==null&&!isNaN(+u)&&(s.style.width=String(+u*i[0])+"px");let l=s.getAttribute("data-proportional-height");l!==null&&!isNaN(+l)&&(s.style.height=String(+l*i[1])+"px");let c=s.getAttribute("data-proportional-line-height");c!==null&&!isNaN(+c)&&(s.style.lineHeight=String(+c*i[1])+"px");let f=s.getAttribute("data-proportional-left");f!==null&&!isNaN(+f)&&(s.style.left=String(+f*i[0])+"px");let g=s.getAttribute("data-proportional-top");g!==null&&!isNaN(+g)&&(s.style.top=String(+g*i[1])+"px");let p=s.getAttribute("data-proportional-padding-top");p!==null&&!isNaN(+p)&&(s.style.paddingTop=String(+p*i[1])+"px");let I=s.getAttribute("data-proportional-padding-bottom");I!==null&&!isNaN(+I)&&(s.style.paddingBottom=String(+I*i[1])+"px");let y=s.getAttribute("data-proportional-padding-left");y!==null&&!isNaN(+y)&&(s.style.paddingLeft=String(+y*i[0])+"px");let b=s.getAttribute("data-proportional-padding-right");b!==null&&!isNaN(+b)&&(s.style.paddingRight=String(+b*i[0])+"px")}}return o.length>0}function tm(n,e){try{n.removeChild(e)}catch(t){m.warn("HTD: Can't remove text track: not in the element.")}}function nI(n){let e=n.getAttribute("data-resolution-rows"),t=n.getAttribute("data-resolution-columns");if(e===null||t===null)return null;let r=parseInt(e,10),i=parseInt(t,10);return r===null||i===null?null:{rows:r,columns:i}}var ji=class{constructor(e,t){m.debug("HTD: Creating HTMLTextDisplayer"),this._buffered=new An,this._videoElement=e,this._textTrackElement=t,this._sizeUpdateCanceller=new B,this._subtitlesIntervalCanceller=new B,this._buffer=new qi,this._currentCues=[],this._isAutoRefreshing=!1}pushTextData(e){var I,y;m.debug("HTD: Appending new html text tracks");let{timestampOffset:t,appendWindow:r,chunk:i}=e;if(i===null)return Pe(this._buffered);let{start:o,end:a,data:s,type:d,language:u}=i,l=(I=r[0])!=null?I:0,c=(y=r[1])!=null?y:1/0,f=bu(d,s,t,u);if(l!==0&&c!==1/0){let b=0;for(;b<f.length&&f[b].end<=l;)b++;for(f.splice(0,b),b=0;b<f.length&&f[b].start<l;)f[b].start=l,b++;for(b=f.length-1;b>=0&&f[b].start>=c;)b--;for(f.splice(b,f.length),b=f.length-1;b>=0&&f[b].end>c;)f[b].end=c,b--}let g;if(o!==void 0)g=Math.max(l,o);else{if(f.length<=0)return m.warn("HTD: Current text tracks have no cues nor start time. Aborting"),Pe(this._buffered);m.warn("HTD: No start time given. Guessing from cues."),g=f[0].start}let p;if(a!==void 0)p=Math.min(c,a);else{if(f.length<=0)return m.warn("HTD: Current text tracks have no cues nor end time. Aborting"),Pe(this._buffered);m.warn("HTD: No end time given. Guessing from cues."),p=f[f.length-1].end}return p<=g?(m.warn("HTD: Invalid text track appended: ","the start time is inferior or equal to the end time."),Pe(this._buffered)):(this._buffer.insert(f,g,p),this._buffered.insert(g,p),!this._isAutoRefreshing&&!this._buffer.isEmpty()&&this.autoRefreshSubtitles(this._subtitlesIntervalCanceller.signal),Pe(this._buffered))}removeBuffer(e,t){return m.debug("HTD: Removing html text track data",e,t),this._buffer.remove(e,t),this._buffered.remove(e,t),this._isAutoRefreshing&&this._buffer.isEmpty()&&(this.refreshSubtitles(),this._isAutoRefreshing=!1,this._subtitlesIntervalCanceller.cancel(),this._subtitlesIntervalCanceller=new B),Pe(this._buffered)}getBufferedRanges(){return Pe(this._buffered)}reset(){m.debug("HTD: Resetting HTMLTextDisplayer"),this.stop(),this._subtitlesIntervalCanceller=new B}stop(){this._subtitlesIntervalCanceller.isUsed()||(m.debug("HTD: Stopping HTMLTextDisplayer"),this._disableCurrentCues(),this._buffer.remove(0,1/0),this._buffered.remove(0,1/0),this._isAutoRefreshing=!1,this._subtitlesIntervalCanceller.cancel())}_disableCurrentCues(){if(this._sizeUpdateCanceller.cancel(),this._currentCues.length>0){for(let e of this._currentCues)tm(this._textTrackElement,e.element);this._currentCues=[]}}_displayCues(e){if(this._currentCues.length===e.length&&this._currentCues.every((i,o)=>i.element===e[o]))return;this._sizeUpdateCanceller.cancel();for(let i of this._currentCues)tm(this._textTrackElement,i.element);this._currentCues=[];for(let i of e){let o=nI(i);this._currentCues.push({element:i,resolution:o}),this._textTrackElement.appendChild(i)}let r=this._currentCues.filter(i=>i.resolution!==null);if(r.length>0){this._sizeUpdateCanceller=new B,this._sizeUpdateCanceller.linkToSignal(this._subtitlesIntervalCanceller.signal);let{TEXT_TRACK_SIZE_CHECKS_INTERVAL:i}=U.getCurrent();Iu(this._textTrackElement,i,this._sizeUpdateCanceller.signal).onUpdate(({height:a,width:s})=>{for(let d of r){let{resolution:u,element:l}=d;Tu(a,s,u,l)}},{clearSignal:this._sizeUpdateCanceller.signal,emitCurrentValue:!0})}}autoRefreshSubtitles(e){if(this._isAutoRefreshing||e.isCancelled())return;let t=null,{MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:r}=U.getCurrent(),i=()=>{this._isAutoRefreshing=!1,t!==null&&(t.cancel(),t=null)},o=()=>{i(),this._isAutoRefreshing=!0,t=new B,t.linkToSignal(e);let a=setInterval(()=>this.refreshSubtitles(),r);t.signal.register(()=>{clearInterval(a)}),this.refreshSubtitles()};Rc(this._videoElement,()=>{i(),this._disableCurrentCues()},e),kc(this._videoElement,o,e),Cc(this._videoElement,o,e),o()}refreshSubtitles(){let{MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:e}=U.getCurrent(),t;this._videoElement.paused||this._videoElement.playbackRate<=0?t=this._videoElement.currentTime:t=Math.max(this._videoElement.currentTime+e/1e3/2,0);let r=this._buffer.get(t);r.length===0?this._disableCurrentCues():this._displayCues(r)}};h.CURRENT_ENV===h.DEV&&(rI=function(e){function t(r){}});var rI;var on=ji;var iI=/&#([0-9]+);/g,oI=/<br>/gi,aI=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,sI=/\s*<p (?:class=([^>]+))?>(.*)/i,dI=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i;function uI(n){let e=/\.(\S+)\s*{([^}]*)}/gi,t={},r=e.exec(n);for(;r!==null;){let i=r[1],o=cI(r[2],"lang");!E(i)&&!E(o)&&(t[o]=i),r=e.exec(n)}return t}function lI(n){let t=/p\s*{([^}]*)}/gi.exec(n);return t===null?"":t[1]}function cI(n,e){let t=new RegExp("\\s*"+e+":\\s*(\\S+);","i").exec(n);return Array.isArray(t)?t[1]:null}function fI(n){return n.replace(iI,(e,t)=>String.fromCharCode(Number(t)))}function mI(n,e,t){let r=/<sync[ >]/gi,i=/<sync[ >]|<\/body>/gi,o=[],a=aI.exec(n),s=Array.isArray(a)?a[1]:"",d,u;i.exec(n);let l=uI(s),c=lI(s),f;if(w(t)&&(f=l[t],f===void 0))throw new Error(`sami: could not find lang ${t} in CSS`);for(;d=r.exec(n),u=i.exec(n),!(d===null&&u===null);){if(d===null||u===null||d.index>=u.index)throw new Error("parse error");let p=n.slice(d.index,u.index),I=dI.exec(p);if(!Array.isArray(I))throw new Error("parse error (sync time attribute)");let y=+I[1];if(isNaN(y))throw new Error("parse error (sync time attribute NaN)");g(p.split(`
|
|
6
|
+
`),y/1e3)}return o;function g(p,I){let y=p.length;for(;--y>=0;){let b=sI.exec(p[y]);if(!Array.isArray(b))continue;let[,T,v]=b;if(f===T)if(v===" ")o[o.length-1].end=I;else{let _=document.createElement("DIV");_.className="rxp-texttrack-region";let R=document.createElement("DIV");R.className="rxp-texttrack-div",R.style.position="absolute",R.style.bottom="0",R.style.width="100%",R.style.color="#fff",R.style.textShadow="-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000";let k=document.createElement("div");k.className="rxp-texttrack-p",w(c)&&(k.style.cssText=c);let x=v.split(oI);for(let M=0;M<x.length;M++){M!==0&&k.appendChild(document.createElement("BR"));let P=document.createElement("SPAN");P.className="rxp-texttrack-span",P.textContent=fI(x[M]),k.appendChild(P)}R.appendChild(k),_.appendChild(R),o.push({element:_,start:I+e,end:-1})}}}}var nm=mI;function _u(n){n.htmlTextTracksParsers.sami=nm,n.htmlTextDisplayer=on}function Eu(n,e){let t=e+1;for(;w(n[t]);)t++;return t}function Yi(n){let e=[];for(let t=0;t<n.length;t++)if(w(n[t])){let r=Eu(n,t),i=n.slice(t,r);i.length>0&&(i.length===1?i[0].indexOf("-->")>=0&&e.push(i):(i[1].indexOf("-->")>=0||i[0].indexOf("-->")>=0)&&e.push(i)),t=r}return e}function ya(n){let e=n.split(":");if(w(e[2])){let t=parseInt(e[0],10),r=parseInt(e[1],10),i=parseFloat(e[2].replace(",","."));return isNaN(t)||isNaN(r)||isNaN(i)?void 0:t*60*60+r*60+i}}function $i(n,e){if(n.length===0)return null;let t,r,i=[];if(w(n[1])&&n[1].indexOf("-->")!==-1&&([t,r]=n[1].split("-->").map(s=>s.trim()),i=n.slice(2,n.length)),(!w(t)||!w(r))&&([t,r]=n[0].split("-->").map(s=>s.trim()),i=n.slice(1,n.length)),!w(t)||!w(r))return null;let o=ya(t),a=ya(r);return o===void 0||a===void 0?null:{start:o+e,end:a+e,payload:i}}function vu(n,e){let t=n.split(/\r\n|\n|\r/),r=Yi(t),i=[];for(let o of r){let a=$i(o,e);if(a!==null){let s=pI(a);s!==null&&i.push(s)}}return i}function pI(n){let{start:e,end:t,payload:r}=n,i=document.createElement("div");i.className="rxp-texttrack-p",i.style.fontSize="28px",i.style.position="absolute",i.style.bottom="5%",i.style.width="100%",i.style.textAlign="center",i.style.color="#fff",i.style.textShadow="-1px -1px 2px #000,1px -1px 2px #000,-1px 1px 2px #000,1px 1px 2px #000";for(let o=0;o<r.length;o++){o!==0&&i.appendChild(document.createElement("br"));let a=gI(r[o]);i.appendChild(a)}return{start:e,end:t,element:i}}function gI(n){let e=document.createElement("div");e.innerHTML=n;let t=function(r){let i=r.childNodes,o=document.createElement("span");o.className="rxp-texttrack-span";for(let a=0;a<i.length;a++){let s=i[a];if(s.nodeName==="#text"){let d=s.wholeText.split(`
|
|
7
|
+
`);for(let u=0;u<d.length;u++)if(u!==0&&o.appendChild(document.createElement("br")),d[u].length>0){let l=document.createTextNode(d[u]);o.appendChild(l)}}else if(s.nodeName==="B"){let d=t(s);d.style.fontWeight="bold",o.appendChild(d)}else if(s.nodeName==="I"){let d=t(s);d.style.fontStyle="italic",o.appendChild(d)}else if(s.nodeName==="U"){let d=t(s);d.style.textDecoration="underline",o.appendChild(d)}else if(hI(s)&&typeof s.color=="string"){let d=t(s);d.style.color=s.color,o.appendChild(d)}else{let d=t(s);o.appendChild(d)}}return o};return t(e)}function hI(n){return n.nodeName==="FONT"&&"color"in n}function Ru(n){n.htmlTextTracksParsers.srt=vu,n.htmlTextDisplayer=on}var yI=/(\d+) (\d+)/;function ku(n){let e=n.getAttribute("ttp:frameRate"),t=n.getAttribute("ttp:subFramRate"),r=n.getAttribute("ttp:tickRate"),i=n.getAttribute("ttp:frameRateMultiplier"),o=n.getAttribute("xml:space"),a=n.getAttribute("ttp:cellResolution"),s={columns:32,rows:15};if(a!==null){let I=yI.exec(a);if(I===null||I.length<3)m.warn("TTML Parser: Invalid cellResolution");else{let y=parseInt(I[1],10),b=parseInt(I[2],10);isNaN(y)||isNaN(b)?m.warn("TTML Parser: Invalid cellResolution"):s={columns:y,rows:b}}}if(w(o)&&o!=="default"&&o!=="preserve")throw new Error("Invalid spacing style");let d=Number(e);(isNaN(d)||d<=0)&&(d=30);let u=Number(t);(isNaN(u)||u<=0)&&(u=1);let l=Number(r);(isNaN(l)||l<=0)&&(l=void 0);let c=d,f=u!=null?u:1,g=o!=null?o:"default",p=l!=null?l:d*u;if(i!==null){let I=/^(\d+) (\d+)$/g.exec(i);if(I!==null){let y=Number(I[1]),b=Number(I[2]),T=y/b;c=d*T}}return{cellResolution:s,tickRate:p,frameRate:c,subFrameRate:f,spaceStyle:g}}function xn(n,e,t,r){let i={},o=n.slice();for(let a=0;a<=e.length-1;a++){let s=e[a];if(s!==void 0){let d,u;if(s.nodeType===Node.ELEMENT_NODE){let l=s;for(let c=0;c<=l.attributes.length-1;c++){let f=l.attributes[c],g=f.name;if(g==="style")d=f.value;else if(g==="region")u=f.value;else{let p=g.substring(4);if(Q(o,p)&&(i[p]=f.value,o.splice(c,1),o.length===0))return i}}}if(w(d)){let l=Z(t,c=>c.id===d);if(l!==void 0)for(let c=0;c<=o.length-1;c++){let f=o[c];if(!w(i[f])&&w(l.style[f])){if(i[f]=l.style[f],o.splice(c,1),o.length===0)return i;c--}}}if(w(u)){let l=Z(r,c=>c.id===u);if(l!==void 0)for(let c=0;c<=o.length-1;c++){let f=o[c];if(!w(i[f])&&w(l.style[f])){if(i[f]=l.style[f],o.splice(c,1),o.length===0)return i;c--}}}}}return i}function Cu(n){if(n.nodeType!==Node.ELEMENT_NODE)return{};let e=n,t={};for(let r=0;r<=e.attributes.length-1;r++){let i=e.attributes[r];if(Ze(i.name,"tts")){let o=i.name.substring(4);t[o]=i.value}}return t}function Pu(n){let e=[];function t(r,i){e.push(i);for(let o of r.extendsStyles){let a=he(n,s=>s.id===o);if(a<0)m.warn("TTML Parser: unknown style inheritance: "+o);else{let s=n[a];Q(e,a)?m.warn("TTML Parser: infinite style inheritance loop avoided"):t(s,a),r.style=G({},s.style,r.style)}}r.extendsStyles.length=0}for(let r=0;r<n.length;r++)t(n[r],r),e.length=0}function rm(n,e){if(!(n.parentNode instanceof Element))return[];function t(r){let i=[];r.tagName.toLowerCase()===e.toLowerCase()&&i.push(r);let o=r.parentNode;return o instanceof Element&&i.push(...t(o)),i}return t(n.parentNode)}function Ia(n){let e=rm(n,"div");if(e.length===0){let t=rm(n,"tt:div");t.length>0&&(e=t)}return e}function im(n){let e=n.getElementsByTagName("body");if(e.length>0)return e[0];let t=n.getElementsByTagName("tt:body");return t.length>0?t[0]:null}function om(n){let e=n.getElementsByTagName("style");if(e.length>0)return e;let t=n.getElementsByTagName("tt:style");return t.length>0?t:e}function am(n){let e=n.getElementsByTagName("region");if(e.length>0)return e;let t=n.getElementsByTagName("tt:region");return t.length>0?t:e}function sm(n){let e=n.getElementsByTagName("p");if(e.length>0)return e;let t=n.getElementsByTagName("tt:p");return t.length>0?t:e}function ba(n){return n.nodeName==="br"||n.nodeName==="tt:br"}function Sa(n){return n.nodeName==="span"||n.nodeName==="tt:span"}var dm=["align","backgroundColor","color","direction","display","displayAlign","extent","fontFamily","fontSize","fontStyle","fontWeight","lineHeight","opacity","origin","overflow","padding","textAlign","textDecoration","textOutline","unicodeBidi","visibility","wrapOption","writingMode"];function Qi(n,e){let t=[],r=new DOMParser().parseFromString(n,"text/xml");if(r!=null){let o=r.getElementsByTagName("tt")[0];if(o===void 0&&(o=r.getElementsByTagNameNS("*","tt")[0],o===void 0))throw new Error("invalid XML");let a=im(o),s=om(o),d=am(o),u=sm(o),l=ku(o),c=[];for(let y=0;y<=s.length-1;y++){let b=s[y];if(b instanceof Element){let T=b.getAttribute("xml:id");if(T!==null){let v=b.getAttribute("style"),_=v===null?[]:v.split(" ");c.push({id:T,style:Cu(b),extendsStyles:_})}}}Pu(c);let f=[];for(let y=0;y<=d.length-1;y++){let b=d[y];if(b instanceof Element){let T=b.getAttribute("xml:id");if(T!==null){let v=Cu(b),_=b.getAttribute("style");if(w(_)){let R=Z(c,k=>k.id===_);R!==void 0&&(v=G({},R.style,v))}f.push({id:T,style:v,extendsStyles:[]})}}}let g=xn(dm,a!==null?[a]:[],c,f),I=(a!==null?a.getAttribute("xml:space"):void 0)==="default"||l.spaceStyle==="default";for(let y=0;y<u.length;y++){let b=u[y];if(b instanceof Element){let T=Ia(b),v=G({},g,xn(dm,[b,...T],c,f)),_=b.getAttribute("xml:space"),R=w(_)?_==="default":I,k={paragraph:b,timeOffset:e,idStyles:c,regionStyles:f,body:a,paragraphStyle:v,ttParams:l,shouldTrimWhiteSpace:R};k!==null&&t.push(k)}}}return t}function um(n){return n.extent===void 0&&n.origin===void 0&&n.displayAlign===void 0&&n.display===void 0&&n.textAlign===void 0&&n.fontSize===void 0}function lm(n){n.extent="70% 20%",n.fontSize="1c",n.origin="15% 80%",n.displayAlign="before",n.textAlign="center"}var Mu=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Au=/^(?:(\d{2,}):)?(\d{2}):(\d{2})$/,xu=/^(?:(\d{2,}):)?(\d{2}):(\d{2}\.\d{2,})$/,wu=/^(\d*\.?\d*)f$/,Ou=/^(\d*\.?\d*)t$/,Du=/^(?:(\d*\.?\d*)h)?(?:(\d*\.?\d*)m)?(?:(\d*\.?\d*)s)?(?:(\d*\.?\d*)ms)?$/,Lu=/^(\d{1,2}|100)% (\d{1,2}|100)%$/,Ge=/^((?:\+|\-)?\d*(?:\.\d+)?)(px|em|c|%|rh|rw)$/,cm=/^#([0-9A-f]{2})([0-9A-f]{2})([0-9A-f]{2})([0-9A-f]{2})$/,fm=/^#([0-9A-f])([0-9A-f])([0-9A-f])([0-9A-f])$/,mm=/^rgb\( *(\d+) *, *(\d+) *, *(\d+) *\)/,pm=/^rgba\( *(\d+) *, *(\d+) *, *(\d+) *, *(\d+) *\)/;function II(n,e){if(Mu.test(n))return TI(e,n);if(Au.test(n))return Nu(Au,n);if(xu.test(n))return Nu(xu,n);if(wu.test(n))return bI(e,n);if(Ou.test(n))return SI(e,n);if(Du.test(n))return Nu(Du,n)}function bI(n,e){let t=wu.exec(e);return Number(t[1])/n.frameRate}function SI(n,e){let t=Ou.exec(e);return Number(t[1])/n.tickRate}function TI(n,e){let t=Mu.exec(e),r=Number(t[1]),i=Number(t[2]),o=Number(t[3]),a=Number(t[4]),s=Number(t[5]);return isNaN(s)&&(s=0),a+=s/n.subFrameRate,o+=a/n.frameRate,o+i*60+r*3600}function Nu(n,e){let t=n.exec(e);if(t===null||t[0]==="")return null;let r=Number(t[1]);isNaN(r)&&(r=0);let i=Number(t[2]);isNaN(i)&&(i=0);let o=Number(t[3]);isNaN(o)&&(o=0);let a=Number(t[4]);return isNaN(a)&&(a=0),a/1e3+o+i*60+r*3600}var Ta=II;function Xi(n,e){let t=n.getAttribute("begin"),r=n.getAttribute("dur"),i=n.getAttribute("end"),o=w(t)?Ta(t,e):null,a=w(r)?Ta(r,e):null,s=w(i)?Ta(i,e):null;if(E(o)||E(s)&&E(a))throw new Error("Invalid text cue");let d=E(s)?o+a:s;return{start:o,end:d}}var Uu;function Ce(n,e){Uu===void 0&&(Uu=n.classList!==void 0&&typeof n.classList.add=="function"),Uu?n.classList.add(e):(" "+n.className+" ").indexOf(" "+e+" ")<0&&(n.className+=" "+e)}function Bu(n,e){let t=e.trim();if(t==="auto")return;let r=t.split(" ");if(r.length!==2)return;let i=Ge.exec(r[0]),o=Ge.exec(r[1]);i!==null&&o!==null&&(i[2]==="px"||i[2]==="%"||i[2]==="em"?n.style.width=i[1]+i[2]:i[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-width",i[1])):m.warn("TTML Parser: unhandled extent unit:",i[2]),o[2]==="px"||o[2]==="%"||o[2]==="em"?n.style.height=o[1]+o[2]:o[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-height",o[1])):m.warn("TTML Parser: unhandled extent unit:",o[2]))}function Fu(n,e){let r=e.trim().split(" ");if(r.length===0)return;let i=Ge.exec(r[0]);if(i!==null)if(i[2]==="px"||i[2]==="em")n.style.fontSize=i[1]+i[2];else if(i[2]==="c")n.style.position="relative",Ce(n,"proportional-style"),n.setAttribute("data-proportional-font-size",i[1]);else if(i[2]==="%"){let o=Number(i[1]);isNaN(o)?m.warn('TTML Parser: could not parse fontSize value "'+i[1]+'" into a number'):(n.style.position="relative",Ce(n,"proportional-style"),n.setAttribute("data-proportional-font-size",String(o/100)))}else m.warn("TTML Parser: unhandled fontSize unit:",i[2])}function Ku(n,e){let t=e.trim(),r=t.split(" ");if(t==="auto")return;let i=Ge.exec(r[0]);i!==null&&(i[2]==="px"||i[2]==="%"||i[2]==="em"?n.style.lineHeight=i[1]+i[2]:i[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-line-height",i[1])):m.warn("TTML Parser: unhandled lineHeight unit:",i[2]))}function Vu(n,e){let t=e.trim();if(t==="auto")return;let r=t.split(" ");if(r.length!==2)return;let i=Ge.exec(r[0]),o=Ge.exec(r[1]);i!==null&&o!==null&&(i[2]==="px"||i[2]==="%"||i[2]==="em"?n.style.left=i[1]+i[2]:i[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-left",i[1])):m.warn("TTML Parser: unhandled origin unit:",i[2]),o[2]==="px"||o[2]==="%"||o[2]==="em"?n.style.top=o[1]+o[2]:o[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-top",o[1])):m.warn("TTML Parser: unhandled origin unit:",o[2]))}function zu(n,e){let r=e.trim().split(" ");if(r.length<1)return;let i=Ge.exec(r[0]);if(i===null)return;if(i[2]==="px"||i[2]==="%"||i[2]==="em"){let d=i[1]+i[2];r.length===1?n.style.padding=d:r.length===2?(n.style.paddingTop=d,n.style.paddingBottom=d):n.style.paddingTop=d}else i[2]==="c"?(Ce(n,"proportional-style"),r.length===1?(n.setAttribute("data-proportional-padding-top",i[1]),n.setAttribute("data-proportional-padding-bottom",i[1]),n.setAttribute("data-proportional-padding-left",i[1]),n.setAttribute("data-proportional-padding-right",i[1])):r.length===2?(n.setAttribute("data-proportional-padding-top",i[1]),n.setAttribute("data-proportional-padding-bottom",i[1])):n.setAttribute("data-proportional-padding-top",i[1])):m.warn("TTML Parser: unhandled padding unit:",i[2]);if(r.length===1)return;let o=Ge.exec(r[1]);if(o===null)return;if(o[2]==="px"||o[2]==="%"||o[2]==="em"){let d=o[1]+o[2];r.length<4&&(n.style.paddingLeft=d),n.style.paddingRight=d}else o[2]==="c"?(Ce(n,"proportional-style"),r.length<4&&n.setAttribute("data-proportional-padding-left",o[1]),n.setAttribute("data-proportional-padding-right",o[1])):m.warn("TTML Parser: unhandled padding unit:",o[2]);if(r.length===2)return;let a=Ge.exec(r[2]);if(a===null)return;if(a[2]==="px"||a[2]==="%"||a[2]==="em"){let d=a[1]+a[2];n.style.paddingBottom=d}else a[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-padding-bottom",a[1])):m.warn("TTML Parser: unhandled padding unit:",a[2]);if(r.length===3)return;let s=Ge.exec(r[3]);if(s!==null)if(s[2]==="px"||s[2]==="%"||s[2]==="em"){let d=s[1]+s[2];n.style.paddingLeft=d}else s[2]==="c"?(Ce(n,"proportional-style"),n.setAttribute("data-proportional-padding-left",s[1])):m.warn("TTML Parser: unhandled padding unit:",s[2])}function rr(n,e){let t=e;return w(e)&&e.trim().endsWith("%")&&(t=e.trim().slice(0,-1),t=(parseInt(t,10)/100).toString()+"em"),`-1px -1px ${t} ${n},1px -1px ${t} ${n},-1px 1px ${t} ${n},1px 1px ${t} ${n}`}function an(n){let e;return e=cm.exec(n),E(e)?(e=fm.exec(n),E(e)?(e=mm.exec(n),E(e)?(e=pm.exec(n),E(e)?n:"rgba("+String(+e[1])+","+String(+e[2])+","+String(+e[3])+","+String(+e[4]/255)+")"):"rgb("+String(+e[1])+","+String(+e[2])+","+String(+e[3])+")"):"rgba("+String(parseInt(e[1]+e[1],16))+","+String(parseInt(e[2]+e[2],16))+","+String(parseInt(e[3]+e[3],16))+","+String(parseInt(e[4]+e[4],16)/255)+")"):"rgba("+String(parseInt(e[1],16))+","+String(parseInt(e[2],16))+","+String(parseInt(e[3],16))+","+String(parseInt(e[4],16)/255)+")"}var _I=["color","direction","display","fontFamily","fontSize","fontStyle","fontWeight","textDecoration","textOutline","unicodeBidi","visibility","wrapOption"];function EI(n,e,t){let r=e.color;w(r)&&(n.style.color=an(r));let i=e.backgroundColor;w(i)&&(n.style.backgroundColor=an(i));let o=e.textOutline;if(w(o)){let y=o.trim().replace(/\s+/g," ").split(" "),b=y.length;if(b===3){let T=an(y[0]),v=y[1];n.style.textShadow=rr(T,v)}else if(w(r)&&b===1){let T=y[0];n.style.textShadow=rr(r,T)}else if(b===2){let T=/^[#A-Z]/i.test(y[0]),v=/^[0-9]/.test(y[0]);if(T!==v){if(T){let _=an(y[0]),R=y[1];n.style.textShadow=rr(_,R)}else if(w(r)){let _=y[0];n.style.textShadow=rr(r,_)}}}}let a=e.textDecoration;if(w(a))switch(a){case"noUnderline":case"noLineThrough":case"noOverline":n.style.textDecoration="none";break;case"lineThrough":n.style.textDecoration="line-through";break;default:n.style.textDecoration=a;break}let s=e.fontFamily;if(w(s))switch(s){case"proportionalSansSerif":n.style.fontFamily="Arial, Helvetica, Liberation Sans, sans-serif";break;case"monospaceSansSerif":case"sansSerif":n.style.fontFamily="sans-serif";break;case"monospaceSerif":case"default":n.style.fontFamily="Courier New, Liberation Mono, monospace";break;case"proportionalSerif":n.style.fontFamily="serif";break;default:n.style.fontFamily=s}let d=e.fontStyle;w(d)&&(n.style.fontStyle=d);let u=e.fontWeight;w(u)&&(n.style.fontWeight=u);let l=e.fontSize;w(l)?Fu(n,l):(Ce(n,"proportional-style"),n.setAttribute("data-proportional-font-size","1"));let c=e.direction;w(c)&&(n.style.direction=c);let f=e.unicodeBidi;if(w(f))switch(f){case"bidiOverride":n.style.unicodeBidi="bidi-override";break;case"embed":n.style.unicodeBidi="embed";break;default:n.style.unicodeBidi="normal"}let g=e.visibility;w(g)&&(n.style.visibility=g),e.display==="none"&&(n.style.display="none"),e.wrapOption==="noWrap"?t?n.style.whiteSpace="nowrap":n.style.whiteSpace="pre":t?n.style.whiteSpace="normal":n.style.whiteSpace="pre-wrap"}function vI(n,e){n.style.color="white",n.style.position="absolute";let t=e.extent;w(t)&&Bu(n,t);let r=e.writingMode;w(r);let i=e.overflow;n.style.overflow=w(i)?i:"hidden";let o=e.padding;w(o)&&zu(n,o);let a=e.origin;w(a)&&Vu(n,a);let s=e.displayAlign;if(w(s))switch(n.style.display="flex",n.style.flexDirection="column",s){case"before":n.style.justifyContent="flex-start";break;case"center":n.style.justifyContent="center";break;case"after":n.style.justifyContent="flex-end";break}let d=e.opacity;w(d)&&(n.style.opacity=d);let u=e.visibility;w(u)&&(n.style.visibility=u),e.display==="none"&&(n.style.display="none")}function RI(n,e){n.style.margin="0px",Ce(n,"proportional-style"),n.setAttribute("data-proportional-font-size","1");let t=e.backgroundColor;w(t)&&(n.style.backgroundColor=an(t));let r=e.lineHeight;w(r)&&Ku(n,r);let i=e.textAlign;if(w(i))switch(i){case"center":n.style.textAlign="center";break;case"left":case"start":n.style.textAlign="left";break;case"right":case"end":n.style.textAlign="right";break}}function kI(n,e,t){let r=document.createElement("span"),i=n.textContent===null?"":n.textContent;if(t){let a=i.trim();a=a.replace(/\s+/g," "),i=a}let o=document.createTextNode(i);return r.appendChild(o),r.className="rxp-texttrack-span",EI(r,e,t),r}function CI(n,e,t,r,i){function o(a,s,d,u){let l=a.childNodes,c=[];for(let f=0;f<l.length;f++){let g=l[f];if(g.nodeName==="#text"){let{backgroundColor:p}=xn(["backgroundColor"],d,t,e);w(p)?s.backgroundColor=p:s.backgroundColor="";let I=kI(g,s,u);c.push(I)}else if(ba(g)){let p=document.createElement("BR");c.push(p)}else if(Sa(g)&&g.nodeType===Node.ELEMENT_NODE&&g.childNodes.length>0){let p=g.getAttribute("xml:space"),I=w(p)?p==="default":u,y=G({},s,xn(_I,[g],t,e));c.push(...o(g,y,[g,...d],I))}}return c}return o(n,G({},r),[],i)}function Hu(n,e,t,r,i,{cellResolution:o,shouldTrimWhiteSpace:a}){let s=Ia(n),d=document.createElement("DIV");if(d.className="rxp-texttrack-region",d.setAttribute("data-resolution-columns",String(o.columns)),d.setAttribute("data-resolution-rows",String(o.rows)),vI(d,i),e!==null){let{bodyBackgroundColor:c}=xn(["backgroundColor"],[...s,e],r,t);w(c)&&(d.style.backgroundColor=an(c))}let u=document.createElement("p");u.className="rxp-texttrack-p",RI(u,i);let l=CI(n,t,r,i,a);for(let c=0;c<l.length;c++)u.appendChild(l[c]);return d.appendChild(u),d}function Wu(n){let{paragraph:e,ttParams:t,body:r,regionStyles:i,idStyles:o,paragraphStyle:a,timeOffset:s,shouldTrimWhiteSpace:d}=n;if(!e.hasAttribute("begin")&&!e.hasAttribute("end")&&/^\s*$/.test(e.textContent===null?"":e.textContent))return null;let{cellResolution:u}=t,{start:l,end:c}=Xi(e,t),f=Hu(e,r,i,o,a,{cellResolution:u,shouldTrimWhiteSpace:d});return{start:l+s,end:c+s,element:f}}function Gu(n,e){let t=Qi(n,e),r=[];for(let i of t){let{paragraphStyle:o}=i;um(o)&&lm(o);let a=Wu(i);a!==null&&r.push(a)}return r}var gm=Gu;function qu(n){n.htmlTextTracksParsers.ttml=gm,n.htmlTextDisplayer=on}function _a(n){let e=0;for(;e<n.length;){if(n[e]==="")return e+1;e++}return e}function ju(n,e){return typeof n[e]=="string"&&/^STYLE( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function PI(n,e){return typeof n[e]=="string"&&/^NOTE( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function MI(n,e){return typeof n[e]=="string"&&/^REGION( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function hm(n,e){let t=n[e];if(t===void 0||t===""||ju(n,e)||MI(n,e)||PI(n,e))return!1;if(t.indexOf("-->")>=0)return!0;let r=n[e+1];return r!==void 0&&r.indexOf("-->")>=0}function ym(n,e){let t=e+1;for(;w(n[t]);)t++;return t}function Zi(n,e){let t=[];for(let r=e;r<n.length;r++)if(hm(n,r)){let i=ym(n,r);t.push(n.slice(r,i)),r=i}else if(w(n[r]))for(;w(n[r]);)r++;return t}function Yu(n,e){let t=[];for(let r=e;r<n.length;r++)if(ju(n,r)){let i=r;for(r++;w(n[r]);)r++;let o=n.slice(i,r);t.push(o)}else if(w(n[r]))for(;w(n[r]);)r++;return t}function Ea(n){let e=n.split(":").reverse();if(w(e[2])||w(e[1])){let t=w(e[2])?parseInt(e[2],10):0,r=parseInt(e[1],10),i=parseFloat(e[0].replace(",","."));return isNaN(t)||isNaN(r)||isNaN(i)?void 0:t*60*60+r*60+i}}function AI(n){return n.split(/ |\t/).reduce((t,r)=>{let i=r.split(":");return i.length===2&&(t[i[0]]=i[1]),t},{})}function xI(n){let t=/^([\d:.]+)[ |\t]+-->[ |\t]+([\d:.]+)[ |\t]*(.*)$/.exec(n);if(t===null)return null;let r=Ea(t[1]),i=Ea(t[2]);if(r===void 0||i===void 0)return null;let o=AI(t[3]);return{start:r,end:i,settings:o}}function Ji(n,e){let t=/-->/,r,i,o;if(t.test(n[0]))r=n[0],i=n.slice(1,n.length);else{if(!t.test(n[1]))return null;o=n[0],r=n[1],i=n.slice(2,n.length)}let a=xI(r);if(a===null)return null;let{start:s,end:d,settings:u}=a;return{start:s+e,end:d+e,settings:u,payload:i,header:o}}var $u={white:"#ffffff",lime:"#00ff00",cyan:"#00ffff",red:"#ff0000",yellow:"#ffff00",magenta:"#ff00ff",blue:"#0000ff",black:"#000000"};function Qu(){return Object.keys($u).reduce((n,e)=>(n[e]=`color: ${$u[e]};`,n[`bg_${e}`]=`background-color: ${$u[e]};`,n),{})}function Xu(n){let e=Qu(),t="";return n.forEach(r=>{if(r.length>=2)for(let i=1;i<r.length;i++){let o=r[i];if(Array.isArray(/::cue {/.exec(o)))for(o=r[++i];w(o)&&!(Array.isArray(/}/.exec(o))||o.length===0);)t+=o,o=r[++i];else{let a=[],s=/::cue\(\.?(.*?)\)(?:,| {)/.exec(o);for(;w(o)&&Array.isArray(s);)a.push(s[1]),o=r[++i],s=/::cue\(\.?(.*?)\)(?:,| {)/.exec(o);let d="";for(;w(o)&&!(Array.isArray(/}/.exec(o))||o.length===0);)d+=o,o=r[++i];a.forEach(u=>{e[u]===void 0?e[u]=d:e[u]+=d})}}}),{classes:e,global:t}}function eo(n,e){let t=["u","i","b"],r=["u","i","b","c","#text"],i=n.nodeName.toLowerCase().split(".")[0],o;if(Q(r,i))if(i==="#text"){let a=n.wholeText.split(`
|
|
8
|
+
`);o=document.createElement("span");for(let s=0;s<a.length;s++)if(s>0&&o.appendChild(document.createElement("br")),a[s].length>0){let d=document.createTextNode(a[s]);o.appendChild(d)}}else{let a=n.nodeName.toLowerCase().split("."),s=[];if(a.forEach(d=>{w(e[d])&&s.push(e[d])}),s.length!==0){let d=document.createAttribute("style");s.forEach(l=>{d.value+=l});let u=Q(t,i)?i:"span";o=document.createElement(u),o.setAttributeNode(d)}else{let d=Q(t,i)?i:"span";o=document.createElement(d)}for(let d=0;d<n.childNodes.length;d++){let u=eo(n.childNodes[d],e);o.appendChild(u)}}else{o=document.createElement("span");for(let a=0;a<n.childNodes.length;a++){let s=eo(n.childNodes[a],e);o.appendChild(s)}}return o}function Zu(n,e){let t=n.replace(/<[0-9]{2}:[0-9]{2}.[0-9]{3}>/,"").replace(/<([u,i,b,c])(\..*?)?(?: .*?)?>(.*?)<\/\1>/g,"<$1$2>$3</$1$2>"),i=new DOMParser().parseFromString(t,"text/html").body.childNodes,o=[];for(let a=0;a<i.length;a++)o.push(eo(i[a],e));return o}function Ju(n){let e=document.createAttribute("style");return e.value=wI(n),e}var wI=n=>{if(!(n!==void 0&&Ln(n).length!==0))return"text-align:center";let t=OI(n),r=NI(n);return`position: absolute;margin: 0;transform: translate(${t.offset}%,${r.offset}%);width: ${FI(n.size)}%;left: ${t.position}%;top: ${r.position!==null?`${r.position}%`:"auto"};text-align: ${el(n.align)};`};var OI=n=>({position:DI(n),offset:LI(n)}),DI=n=>{let e=tl(n.position);if(e!==null)return e;let t=el(n.align);return{left:0,center:50,right:100}[t]},LI=n=>{let e=a=>{let d=/,(line-left|line-right|center)/.exec(a);return!Array.isArray(d)||d.length<2?null:d[1]},t={"line-left":0,center:-50,"line-right":-100},r=n.position!==void 0?e(n.position):null;if(r!==null)return t[r];let i={left:0,center:-50,right:-100},o=n.align!==void 0?el(n.align):"center";return i[o]},NI=n=>({position:UI(n.line),offset:BI(n.line)}),UI=n=>tl(n),BI=n=>{let e=i=>{let a=/,(start|center|end)/.exec(i);return!Array.isArray(a)||a.length<2?null:a[1]},t={start:0,center:-50,end:-100};if(n===void 0)return t.start;let r=e(n);return r!==null?t[r]:t.start},el=n=>{switch(n){case"left":case"start":return"left";case"right":case"end":return"right";default:return"center"}},FI=n=>KI(n,100),KI=(n,e)=>{let t=tl(n);return t!==null?t:e},tl=n=>{if(n===void 0)return null;let t=/^([\d.]+)%/.exec(n);return!Array.isArray(t)||t.length<2?null:parseInt(t[1],10)};function nl(n,e){let{start:t,end:r,settings:i,header:o,payload:a}=n,s=document.createElement("div"),d=document.createAttribute("style");d.value="width:100%;height:100%;display:flex;flex-direction:column;justify-content:flex-end;align-items:center;",s.setAttributeNode(d);let u=document.createElement("p"),l=Ju(i);u.setAttributeNode(l);let c=document.createElement("span"),f=document.createAttribute("style");f.value="background-color:rgba(0,0,0,0.8);color:white;",c.setAttributeNode(f);let{global:g,classes:p}=e,I=w(o)?p[o]:void 0,y=[g,I].filter(b=>b!==void 0).join("");return f.value+=y,c.setAttributeNode(f),Zu(a.join(`
|
|
9
|
+
`),p).forEach(b=>{c.appendChild(b)}),s.appendChild(u),u.appendChild(c),{start:t,end:r,element:s}}function rl(n,e){let t=/\r\n|\n|\r/g,r=n.split(t),i=[];if(/^WEBVTT( |\t|\n|\r|$)/.exec(r[0])===null)throw new Error("Can't parse WebVTT: Invalid File.");let o=_a(r),a=Yu(r,o),s=Zi(r,o),d=Xu(a);for(let u=0;u<s.length;u++){let l=Ji(s[u],e);if(l!==null){let c=nl(l,d);i.push(c)}}return i}var Im=rl;function il(n){n.htmlTextTracksParsers.vtt=Im,n.htmlTextDisplayer=on}function ol(n){var i;let e,t,r="subtitles";if(Wt){let o=n.textTracks.length;e=o>0?n.textTracks[o-1]:n.addTextTrack(r),e.mode=(i=e.SHOWING)!=null?i:"showing"}else t=document.createElement("track"),n.appendChild(t),e=t.track,t.kind=r,e.mode="showing";return{track:e,trackElement:t}}function VI(n,e){let{activeCues:t}=n;if(t===null)return!1;for(let r=0;r<t.length;r++)if(t[r]===e)return!0;return!1}function al(n,e){if(ln&&VI(n,e)){let t=n.mode;n.mode="hidden";try{n.removeCue(e)}catch(r){m.warn("Compat: Could not remove cue from text track.")}n.mode=t;return}try{n.removeCue(e)}catch(t){m.warn("Compat: Could not remove cue from text track.")}}function sl(n,e,t,r){m.debug("NTSB: Finding parser for native text tracks:",n);let i=me.nativeTextTracksParsers[n];if(typeof i!="function")throw new Error("no parser found for the given text track");m.debug("NTSB: Parser found, parsing...");let o=i(e,t,r);return m.debug("NTSB: Parsed successfully!",o.length),o}var to=class{constructor(e){m.debug("NTD: Creating NativeTextDisplayer");let{track:t,trackElement:r}=ol(e);this._buffered=new An,this._videoElement=e,this._track=t,this._trackElement=r}pushTextData(e){var I,y;if(m.debug("NTD: Appending new native text tracks"),e.chunk===null)return Pe(this._buffered);let{timestampOffset:t,appendWindow:r,chunk:i}=e,{start:o,end:a,data:s,type:d,language:u}=i,l=(I=r[0])!=null?I:0,c=(y=r[1])!=null?y:1/0,f=sl(d,s,t,u);if(l!==0&&c!==1/0){let b=0;for(;b<f.length&&f[b].endTime<=l;)b++;for(f.splice(0,b),b=0;b<f.length&&f[b].startTime<l;)f[b].startTime=l,b++;for(b=f.length-1;b>=0&&f[b].startTime>=c;)b--;for(f.splice(b,f.length),b=f.length-1;b>=0&&f[b].endTime>c;)f[b].endTime=c,b--}let g;if(o!==void 0)g=Math.max(l,o);else{if(f.length<=0)return m.warn("NTD: Current text tracks have no cues nor start time. Aborting"),Pe(this._buffered);m.warn("NTD: No start time given. Guessing from cues."),g=f[0].startTime}let p;if(a!==void 0)p=Math.min(c,a);else{if(f.length<=0)return m.warn("NTD: Current text tracks have no cues nor end time. Aborting"),Pe(this._buffered);m.warn("NTD: No end time given. Guessing from cues."),p=f[f.length-1].endTime}if(p<=g)return m.warn("NTD: Invalid text track appended: ","the start time is inferior or equal to the end time."),Pe(this._buffered);if(f.length>0){let b=f[0],T=this._track.cues;T!==null&&T.length>0&&b.startTime<T[T.length-1].startTime&&this._removeData(b.startTime,1/0);for(let v of f)this._track.addCue(v)}return this._buffered.insert(g,p),Pe(this._buffered)}removeBuffer(e,t){return this._removeData(e,t),Pe(this._buffered)}getBufferedRanges(){return Pe(this._buffered)}reset(){m.debug("NTD: Aborting NativeTextDisplayer"),this._removeData(0,1/0),this._clearTrackElement()}stop(){m.debug("NTD: Aborting NativeTextDisplayer"),this._removeData(0,1/0);let{_trackElement:e,_videoElement:t}=this;if(e!==void 0&&t.hasChildNodes())try{t.removeChild(e)}catch(r){m.warn("NTD: Can't remove track element from the video")}this._track.mode="disabled",this._trackElement!==void 0&&(this._trackElement.innerHTML="")}_removeData(e,t){m.debug("NTD: Removing native text track data",e,t);let r=this._track,i=r.cues;if(i!==null)for(let o=i.length-1;o>=0;o--){let a=i[o],{startTime:s,endTime:d}=a;s>=e&&s<=t&&d<=t&&al(r,a)}this._buffered.remove(e,t)}_clearTrackElement(){let{_trackElement:e,_videoElement:t}=this;if(e!==void 0&&t.hasChildNodes())try{t.removeChild(e)}catch(i){m.warn("NTD: Can't remove track element from the video")}let r=this._track.mode;this._track.mode="disabled",this._track.mode=r,this._trackElement!==void 0&&(this._trackElement.innerHTML="")}};h.CURRENT_ENV===h.DEV&&(zI=function(e){function t(r){}});var zI;var sn=to;function Bt(n,e,t){if(n>=e)return m.warn(`Compat: Invalid cue times: ${n} - ${e}`),null;if(E(J.VTTCue)){if(E(J.TextTrackCue))throw new Error("VTT cues not supported in your target");return new TextTrackCue(n,e,t)}else return new VTTCue(n,e,t)}var HI=/&#([0-9]+);/g,WI=/<br>/gi,GI=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,qI=/\s*<p (?:class=([^>]+))?>(.*)/i,jI=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i;function YI(n){let e=[];for(let t=0;t<n.length;t++){let{start:r,end:i,text:o}=n[t];if(w(o)&&!E(i)){let a=Bt(r,i,o);a!==null&&e.push(a)}}return e}function $I(n){let e=/\.(\S+)\s*{([^}]*)}/gi,t={},r=e.exec(n);for(;Array.isArray(r);){let i=r[1],o=QI(r[2],"lang");!E(i)&&!E(o)&&(t[o]=i),r=e.exec(n)}return t}function QI(n,e){let t=new RegExp("\\s*"+e+":\\s*(\\S+);","i").exec(n);return Array.isArray(t)?t[1]:null}function XI(n){return n.replace(WI,`
|
|
10
|
+
`).replace(HI,(e,t)=>String.fromCharCode(Number(t)))}function ZI(n,e,t){let r=/<sync[ >]/gi,i=/<sync[ >]|<\/body>/gi,o=[],a=GI.exec(n),s=a!==null?a[1]:"",d,u;i.exec(n);let l=$I(s),c;if(w(t)&&(c=l[t],c===void 0))throw new Error(`sami: could not find lang ${t} in CSS`);for(;d=r.exec(n),u=i.exec(n),!(d===null&&u===null);){if(d===null||u===null||d.index>=u.index)throw new Error("parse error");let g=n.slice(d.index,u.index),p=jI.exec(g);if(p===null)throw new Error("parse error (sync time attribute)");let I=+p[1];if(isNaN(I))throw new Error("parse error (sync time attribute NaN)");f(g.split(`
|
|
11
|
+
`),I/1e3)}return YI(o);function f(g,p){let I=g.length,y;for(;--I>=0;){if(y=qI.exec(g[I]),y===null)continue;let[,b,T]=y;c===b&&(T===" "?o[o.length-1].end=p:o.push({text:XI(T),start:p+e}))}}}var bm=ZI;function dl(n){n.nativeTextTracksParsers.sami=bm,n.nativeTextDisplayer=sn}function ul(n,e){let t=n.split(/\r\n|\n|\r/),r=Yi(t),i=[];for(let o=0;o<r.length;o++){let a=$i(r[o],e);if(a!==null){let s=JI(a);s!==null&&i.push(s)}}return i}function JI(n){let{start:e,end:t,payload:r}=n,i=r.join(`
|
|
12
|
+
`);return Bt(e,t,i)}function ll(n){n.nativeTextTracksParsers.srt=ul,n.nativeTextDisplayer=sn}function no(n){return typeof J.VTTCue=="function"&&n instanceof J.VTTCue}var eb={left:"start",center:"center",right:"end",start:"start",end:"end"},tb={left:"line-left",center:"center",right:"line-right"};function cl(n){let{paragraph:e,timeOffset:t,paragraphStyle:r,ttParams:i,shouldTrimWhiteSpace:o}=n;if(!e.hasAttribute("begin")&&!e.hasAttribute("end")&&/^\s*$/.test(e.textContent===null?"":e.textContent))return null;let{start:a,end:s}=Xi(e,i),d=nb(e,o),u=Bt(a+t,s+t,d);return u===null?null:(no(u)&&rb(u,r),u)}function nb(n,e){function t(r,i){let o=r.childNodes,a="";for(let s=0;s<o.length;s++){let d=o[s];if(d.nodeName==="#text"){let u=d.textContent;if(u===null&&(u=""),i){let c=u.trim();c=c.replace(/\s+/g," "),u=c}let l=u.replace(/&|\u0026/g,"&").replace(/<|\u003C/g,"<").replace(/>|\u2265/g,">").replace(/\u200E/g,"‎").replace(/\u200F/g,"‏").replace(/\u00A0/g," ");a+=l}else if(ba(d))a+=`
|
|
13
|
+
`;else if(Sa(d)&&d.nodeType===Node.ELEMENT_NODE&&d.childNodes.length>0){let u=d.getAttribute("xml:space"),l=w(u)?u==="default":i;a+=t(d,l)}}return a}return t(n,e)}function rb(n,e){let t=e.extent;if(w(t)){let a=Lu.exec(t);E(a)||(n.size=Number(a[1]))}switch(e.writingMode){case"tb":case"tblr":n.vertical="lr";break;case"tbrl":n.vertical="rl";break;default:break}let i=e.origin;if(w(i)){let a=Lu.exec(i);E(a)}let o=e.align;if(w(o)){n.align=o,o==="center"&&(n.align!=="center"&&(n.align="middle"),n.position="auto");let a=tb[o];n.positionAlign=a===void 0?"":a;let s=eb[o];n.lineAlign=s===void 0?"":s}}function fl(n,e){let t=Qi(n,e),r=[];for(let i of t){let o=cl(i);o!==null&&r.push(o)}return r}var Sm=fl;function ml(n){n.nativeTextTracksParsers.ttml=Sm,n.nativeTextDisplayer=sn}function pl(n,e){if(w(n.vertical)&&(n.vertical==="rl"||n.vertical==="lr")&&(e.vertical=n.vertical),w(n.line)){let r=/^(\d+(\.\d+)?)%(,([a-z]+))?/.exec(n.line);if(Array.isArray(r))e.line=Number(r[1]),e.snapToLines=!1,Q(["start","center","end"],r[4])&&(e.lineAlign=r[4]);else{let o=/^(-?\d+)(,([a-z]+))?/.exec(n.line);Array.isArray(o)&&(e.line=Number(o[1]),e.snapToLines=!0,Q(["start","center","end"],o[3])&&(e.lineAlign=o[3]))}}if(w(n.position)){let r=/^([\d\.]+)%(?:,(line-left|line-right|center))?$/.exec(n.position);if(Array.isArray(r)&&r.length>=2){let i=parseInt(r[1],10);isNaN(i)||(e.position=i,r[2]!==void 0&&(e.positionAlign=r[2]))}}w(n.size)&&(e.size=n.size),typeof n.align=="string"&&Q(["start","center","end","left"],n.align)&&(e.align=n.align)}function gl(n){let{start:e,end:t,payload:r}=n,i=r.join(`
|
|
14
|
+
`);return Bt(e,t,i)}function hl(n,e){let t=n.split(/\r\n|\n|\r/);if(!/^WEBVTT($| |\t)/.test(t[0]))throw new Error("Can't parse WebVTT: Invalid file.");let r=_a(t),i=Zi(t,r),o=[];for(let a of i){let s=Ji(a,e);if(s!==null){let d=gl(s);d!==null&&(no(d)&&pl(s.settings,d),o.push(d))}}return o}var Tm=hl;function yl(n){n.nativeTextTracksParsers.vtt=Tm,n.nativeTextDisplayer=sn}function ir(n){let e=[];n.periods.forEach(t=>{let r=t.id;if(Q(e,r)){m.warn("Two periods with the same ID found. Updating.");let a=r+"-dup";t.id=a,ir(n),e.push(a)}else e.push(r);let{adaptations:i}=t,o=[];Object.keys(i).forEach(a=>{let s=i[a];s!==void 0&&s.forEach(d=>{let u=d.id;if(Q(o,u)){m.warn("Two adaptations with the same ID found. Updating.",u);let c=u+"-dup";d.id=c,ir(n),o.push(c)}else o.push(u);let l=[];d.representations.forEach(c=>{let f=c.id;if(Q(l,f)){m.warn("Two representations with the same ID found. Updating.",f);let g=`${f}-dup`;c.id=g,ir(n),l.push(g)}else l.push(f)})})})})}function _m(n,e){let t;return e==="AACH"?t=5:t=w(n)?(parseInt(n.substring(0,2),16)&248)>>3:2,t===0?"mp4a.40.2":`mp4a.40.${t}`}function Em(n){let e=/00000001\d7([0-9a-fA-F]{6})/.exec(n);return e===null||!w(e[1])?"avc1.4D401E":"avc1."+e[1]}function Il(n){return n.reduce((e,t,r)=>{let i=t.getAttribute("d"),o=t.getAttribute("t"),a=t.getAttribute("r"),s=a!==null?+a-1:0,d=o!==null?+o:void 0,u=i!==null?+i:void 0;if(r===0)d=d===void 0||isNaN(d)?0:d;else{let l=e[r-1];if(d===void 0||isNaN(d)){if(l.duration===void 0||isNaN(l.duration))throw new Error("Smooth: Invalid CNodes. Missing timestamp.");d=l.start+l.duration*(l.repeatCount+1)}}if(u===void 0||isNaN(u)){let l=n[r+1];if(l!==void 0){let c=l.getAttribute("t"),f=w(c)?+c:null;if(f===null)throw new Error("Can't build index timeline from Smooth Manifest.");u=f-d}else return e}return e.push({duration:u,start:d,repeatCount:s}),e},[])}function ib(n){return[{systemId:"edef8ba9-79d6-4ace-a3c8-27dcd51d21ed",privateData:ie([8,1,18,16],n)}]}function bl(n,e=ib){if(n.firstElementChild===null||n.firstElementChild.nodeName!=="ProtectionHeader")throw new Error("Protection should have ProtectionHeader child");let t=n.firstElementChild,r=pt(t.textContent===null?"":t.textContent),i=Nr(r),o=je(i),a=t.getAttribute("SystemID"),s=(a!==null?a:"").toLowerCase().replace(/\{|\}/g,"");return{keyId:o,keySystems:[{systemId:s,privateData:r}].concat(e(o))}}function vm(n,e,t){return n.replace(/\{bitrate\}/g,String(e)).replace(/{CustomAttributes}/g,t.length>0?t[0]:"")}function Rm(n,e){return n.replace(/\{start time\}/g,String(e))}function ob(n,e,t){let r=e-n;return r>0?Math.floor(r/t):0}function ab(n,e,t){let r=n===void 0||n===0?1:n;return{up:e*r,to:(e+t)*r}}function sb(n,e){let t=n.repeatCount;if(n.duration!==void 0&&t<0){let r=e!==void 0?e.start:1/0;t=Math.ceil((r-n.start)/n.duration)-1}return t}var ro=class{constructor(e){let{isLive:t,segmentPrivateInfos:r,media:i,sharedSmoothTimeline:o}=e;if(this._sharedSmoothTimeline=o,this._initSegmentInfos={bitsPerSample:r.bitsPerSample,channels:r.channels,codecPrivateData:r.codecPrivateData,packetSize:r.packetSize,samplingRate:r.samplingRate,timescale:o.timescale,height:r.height,width:r.width,protection:r.protection},this._isLive=t,this._media=i,o.timeline.length!==0&&t){let{timeline:a,validityTime:s}=o,d=a[a.length-1],u=ke(d,null),l=s/1e3*o.timescale;this._scaledLiveGap=l-u}}getInitSegment(){return{id:"init",isInit:!0,privateInfos:{smoothInitSegment:this._initSegmentInfos},url:null,time:0,end:0,duration:0,timescale:1,complete:!0}}getSegments(e,t){this._refreshTimeline();let{timescale:r,timeline:i}=this._sharedSmoothTimeline,{up:o,to:a}=ab(r,e,t),s=this._media,d,u=[],l=i.length,c=this._scaledLiveGap===void 0?void 0:K()/1e3*r-this._scaledLiveGap;for(let f=0;f<l;f++){let g=i[f],{duration:p,start:I}=g,y=sb(g,i[f+1]),b=ob(I,o,p),T=I+b*p,v=p;for(;T<a&&b<=y&&(c===void 0||T+v<=c);){let _=T,R=d!==void 0?d+b:void 0,k={id:String(T),isInit:!1,time:_/r,end:(_+p)/r,duration:p/r,timescale:1,number:R,url:Rm(s,_),complete:!0,privateInfos:{smoothMediaSegment:{time:_,duration:p}}};u.push(k),b++,T=I+b*p}if(T>=a)return u;d!==void 0&&(d+=y+1)}return u}shouldRefresh(e,t){if(this._refreshTimeline(),!this._isLive)return!1;let{timeline:r,timescale:i}=this._sharedSmoothTimeline,o=r[r.length-1];if(o===void 0)return!1;let a=o.repeatCount,s=o.start+(a+1)*o.duration;if(t*i<s)return!1;if(e*i>=s)return!0;let d=o.start+a*o.duration;return e*i>d}getFirstAvailablePosition(){this._refreshTimeline();let{timeline:e,timescale:t}=this._sharedSmoothTimeline;return e.length===0?null:e[0].start/t}getLastAvailablePosition(){this._refreshTimeline();let{timeline:e,timescale:t}=this._sharedSmoothTimeline;if(this._scaledLiveGap===void 0){let r=e[e.length-1];return ke(r,null)/t}for(let r=e.length-1;r>=0;r--){let i=e[r],o=K()/1e3*t,{start:a,duration:s,repeatCount:d}=i;for(let u=d;u>=0;u--){let l=a+s*(u+1);if(l<=o-this._scaledLiveGap)return l/t}}}getEnd(){if(!this._isLive)return this.getLastAvailablePosition()}awaitSegmentBetween(e,t){var i;if(ee(e<=t),this.isStillAwaitingFutureSegments())return!1;let r=this.getLastAvailablePosition();return r!==void 0&&t<r?!1:t>((i=this.getFirstAvailablePosition())!=null?i:0)?void 0:!1}checkDiscontinuity(e){return this._refreshTimeline(),aa(this._sharedSmoothTimeline,e,void 0)}isSegmentStillAvailable(e){if(e.isInit)return!0;this._refreshTimeline();let{timeline:t,timescale:r}=this._sharedSmoothTimeline;for(let i=0;i<t.length;i++){let o=t[i],a=o.start/r;if(a>e.time)return!1;if(a===e.time)return!0;if(o.repeatCount>=0&&o.duration!==void 0){let d=(a-o.start)/o.duration-1;return d%1===0&&d<=o.repeatCount}}return!1}canBeOutOfSyncError(e){return this._isLive?e instanceof it&&(e.isHttpError(404)||e.isHttpError(412)):!1}_replace(e){this._initialScaledLastPosition=e._initialScaledLastPosition,this._scaledLiveGap=e._scaledLiveGap,this._sharedSmoothTimeline.replace(e._sharedSmoothTimeline)}_update(e){this._scaledLiveGap=e._scaledLiveGap,this._sharedSmoothTimeline.update(e._sharedSmoothTimeline)}isStillAwaitingFutureSegments(){return this._isLive}isInitialized(){return!0}initialize(){m.error("A `SmoothRepresentationIndex` does not need to be initialized")}addPredictedSegments(e,t){this._sharedSmoothTimeline.addPredictedSegments(e,t)}_refreshTimeline(){this._sharedSmoothTimeline.refresh()}};function Sl(n,e,t,r){let i=n.length,o=n[i-1],a=t.timescale===e?{time:t.time,duration:t.duration}:{time:t.time/t.timescale*e,duration:t.duration/t.timescale*e};return r.time===a.time?!1:a.time>=ke(o,null)?(o.duration===a.duration?o.repeatCount++:n.push({duration:a.duration,start:a.time,repeatCount:0}),!0):!1}var io=class{constructor(e){let{timeline:t,timescale:r,timeShiftBufferDepth:i,manifestReceivedTime:o}=e;this.timeline=t,this.timescale=r;let a=o!=null?o:K();if(this.validityTime=a,this._timeShiftBufferDepth=i,t.length!==0){let s=t[t.length-1],d=ke(s,null);this._initialScaledLastPosition=d}}refresh(){if(this._initialScaledLastPosition===void 0)return;let e=this._timeShiftBufferDepth,r=(K()-this.validityTime)/1e3+this._initialScaledLastPosition/this.timescale;if(e!==void 0){let i=(r-e)*this.timescale;Mi(this.timeline,i)}}replace(e){let t=this.timeline,r=e.timeline,i=this.timescale,o=e.timescale;if(this._initialScaledLastPosition=e._initialScaledLastPosition,this.validityTime=e.validityTime,t.length===0||r.length===0||i!==o)return;let a=t[t.length-1],s=r[r.length-1],d=ke(s,null);if(!(ke(a,null)<=d))for(let u=0;u<t.length;u++){let l=t[u],c=ke(l,null);if(c===d){this.timeline=this.timeline.concat(t.slice(u+1));return}if(c>d){if(l.duration!==s.duration)return;let f=d-l.start;if(f===0){m.warn("Smooth Parser: a discontinuity detected in the previous manifest has been resolved."),this.timeline=this.timeline.concat(t.slice(u));return}if(f<0||f%l.duration!==0)return;let g=f/l.duration-1,p=l.repeatCount-g;if(p<0)return;s.repeatCount+=p;let I=t.slice(u+1);this.timeline=this.timeline.concat(I);return}}}update(e){Ai(this.timeline,e.timeline),this._initialScaledLastPosition=e._initialScaledLastPosition,this.validityTime=e.validityTime}addPredictedSegments(e,t){var r;if(((r=t.privateInfos)==null?void 0:r.smoothMediaSegment)===void 0){m.warn("Smooth Parser: should only encounter SmoothRepresentationIndex");return}this.refresh();for(let i of e)Sl(this.timeline,this.timescale,i,t.privateInfos.smoothMediaSegment)}};function Tl(n){return typeof n=="boolean"?n:typeof n=="string"?n.toUpperCase()==="TRUE":!1}function or(n,e,t){let r=n.firstElementChild,i=t;for(;r!==null;)i=e(i,r.nodeName,r),r=r.nextElementSibling;return i}var db={audio:"audio/mp4",video:"video/mp4",text:"application/ttml+xml"},oo={AACL:"audio/mp4",AVC1:"video/mp4",H264:"video/mp4",TTML:"application/ttml+xml+mp4",DFXP:"application/ttml+xml+mp4"};function ub(n={}){let e=n.referenceDateTime===void 0?Date.UTC(1970,0,1,0,0,0,0)/1e3:n.referenceDateTime,t=n.minRepresentationBitrate===void 0?0:n.minRepresentationBitrate,{serverSyncInfos:r}=n,i=r!==void 0?r.serverTimestamp-r.clientTime:void 0;function o(d,u){let l=or(d,(f,g,p)=>(g==="CustomAttributes"&&f.push(...or(p,(I,y,b)=>{if(y==="Attribute"){let T=b.getAttribute("Name"),v=b.getAttribute("Value");T!==null&&v!==null&&I.push(T+"="+v)}return I},[])),f),[]);function c(f){let g=d.getAttribute(f);return g===null?void 0:g}switch(u){case"audio":{let f=c("AudioTag"),g=c("BitsPerSample"),p=c("Channels"),I=c("CodecPrivateData"),y=c("FourCC"),b=c("PacketSize"),T=c("SamplingRate"),v=c("Bitrate"),_=v===void 0?0:parseInt(v,10);if(_=isNaN(_)?0:_,y!==void 0&&oo[y]===void 0||I===void 0)return m.warn("Smooth parser: Unsupported audio codec. Ignoring quality level."),null;let R=_m(I,y);return{audiotag:f!==void 0?parseInt(f,10):f,bitrate:_,bitsPerSample:g!==void 0?parseInt(g,10):g,channels:p!==void 0?parseInt(p,10):p,codecPrivateData:I,codecs:R,customAttributes:l,mimeType:y!==void 0?oo[y]:y,packetSize:b!==void 0?parseInt(b,10):b,samplingRate:T!==void 0?parseInt(T,10):T}}case"video":{let f=c("CodecPrivateData"),g=c("FourCC"),p=c("MaxWidth"),I=c("MaxHeight"),y=c("Bitrate"),b=y===void 0?0:parseInt(y,10);if(b=isNaN(b)?0:b,g!==void 0&&oo[g]===void 0||f===void 0)return m.warn("Smooth parser: Unsupported video codec. Ignoring quality level."),null;let T=Em(f);return{bitrate:b,customAttributes:l,mimeType:g!==void 0?oo[g]:g,codecPrivateData:f,codecs:T,width:p!==void 0?parseInt(p,10):void 0,height:I!==void 0?parseInt(I,10):void 0}}case"text":{let f=c("CodecPrivateData"),g=c("FourCC"),p=c("Bitrate"),I=p===void 0?0:parseInt(p,10);return I=isNaN(I)?0:I,{bitrate:I,customAttributes:l,mimeType:g!==void 0?oo[g]:g,codecPrivateData:f!=null?f:""}}default:return m.error("Smooth Parser: Unrecognized StreamIndex type: "+u),null}}function a(d){let{root:u,timescale:l,baseUrl:c,protections:f,timeShiftBufferDepth:g,manifestReceivedTime:p,isLive:I}=d,y=u.getAttribute("Timescale"),b=y===null?l:+y;isNaN(b)&&(b=l);let T=u.getAttribute("Type");if(T===null)throw new Error("StreamIndex without type.");Q(jt,T)||m.warn("Smooth Parser: Unrecognized adaptation type:",T);let v=T,_=u.getAttribute("Subtype"),R=u.getAttribute("Language"),k=u.getAttribute("Url"),x=k===null?"":k;h.CURRENT_ENV===h.DEV&&ee(x!=="");let{qualityLevels:M,cNodes:P}=or(u,(C,D,L)=>{switch(D){case"QualityLevel":{let V=o(L,v);if(V===null)return C;(v!=="video"||V.bitrate>t)&&C.qualityLevels.push(V);break}case"c":C.cNodes.push(L);break}return C},{qualityLevels:[],cNodes:[]}),N=new io({timeline:Il(P),timescale:b,timeShiftBufferDepth:g,manifestReceivedTime:p});ee(M.length!==0,"Adaptation should have at least one playable representation.");let O=v+(w(R)?"_"+R:""),F=M.map(C=>{let D=vm(x,C.bitrate,C.customAttributes),L=w(C.mimeType)?C.mimeType:db[v],V=C.codecs,$=O+"_"+(E(v)?"":v+"-")+(E(L)?"":L+"-")+(E(V)?"":V+"-")+String(C.bitrate),j=[],z;f.length>0&&(z=f[0],f.forEach(ae=>{j.push(ae.keyId)}));let q={bitsPerSample:C.bitsPerSample,channels:C.channels,codecPrivateData:C.codecPrivateData,packetSize:C.packetSize,samplingRate:C.samplingRate,height:C.height,width:C.width,protection:E(z)?void 0:{keyId:z.keyId}},W=new ro({isLive:I,sharedSmoothTimeline:N,media:D,segmentPrivateInfos:q}),se=G({},C,{index:W,cdnMetadata:[{baseUrl:c}],mimeType:L,codecs:V,id:$});if(j.length>0||z!==void 0){let ae=z===void 0?[]:z.keySystems.map(de=>{let{systemId:Se,privateData:Y}=de,ce=Se.replace(/-/g,""),ye=lb(ce,Y);return{systemId:ce,data:ye}});if(ae.length>0){let de=[{type:"cenc",values:ae}];se.contentProtections={keyIds:j,initData:de}}else se.contentProtections={keyIds:j,initData:[]}}return se});if(_==="ADVT")return null;let A={id:O,type:v,representations:F,language:R===null?void 0:R};return v==="text"&&_==="DESC"&&(A.closedCaption=!0),A}function s(d,u,l){let c="";if(u!==void 0){let W=vr(u);c=u.substring(0,W)}let f=d.documentElement;if(E(f)||f.nodeName!=="SmoothStreamingMedia")throw new Error("document root should be SmoothStreamingMedia");let g=f.getAttribute("MajorVersion"),p=f.getAttribute("MinorVersion");if(g===null||p===null||!/^[2]-[0-2]$/.test(g+"-"+p))throw new Error("Version should be 2.0, 2.1 or 2.2");let I=f.getAttribute("Timescale"),y=w(I)?+I:1e7;isNaN(y)&&(y=1e7);let{protections:b,adaptationNodes:T}=or(f,(W,se,ae)=>{switch(se){case"Protection":{W.protections.push(bl(ae,n.keySystems));break}case"StreamIndex":W.adaptationNodes.push(ae);break}return W},{adaptationNodes:[],protections:[]}),v={},_=Tl(f.getAttribute("IsLive")),R;if(_){let W=f.getAttribute("DVRWindowLength");W!==null&&!isNaN(+W)&&+W!=0&&(R=+W/y)}let k=T.reduce((W,se)=>{let ae=a({root:se,baseUrl:c,timescale:y,protections:b,isLive:_,timeShiftBufferDepth:R,manifestReceivedTime:l});if(ae===null)return W;let de=ae.type,Se=W[de];return Se===void 0?W[de]=[ae]:Se.push(ae),W},v),x,M,P,N=null,O,F=k.video!==void 0?k.video[0]:void 0,A=k.audio!==void 0?k.audio[0]:void 0,C,D,L;if(F!==void 0||A!==void 0){let W=[],se=[];if(F!==void 0){let ae=F.representations[0];if(ae!==void 0){let de=ae.index.getFirstAvailablePosition(),Se=ae.index.getLastAvailablePosition();E(de)||W.push(de),E(Se)||se.push(Se)}}if(A!==void 0){let ae=A.representations[0];if(ae!==void 0){let de=ae.index.getFirstAvailablePosition(),Se=ae.index.getLastAvailablePosition();E(de)||W.push(de),E(Se)||se.push(Se)}}W.length>0&&(C=Math.max(...W)),se.length>0&&(D=Math.min(...se),L=Math.max(...se))}let V=f.getAttribute("Duration"),$=V!==null&&+V!=0?+V/y:void 0;if(_){x=n.suggestedPresentationDelay,M=e,P=C!=null?C:M;let W=L;W===void 0&&(W=Date.now()/1e3-M);let se=D;se===void 0&&(se=W),O={isLinear:!0,maximumSafePosition:se,livePosition:W,time:K()},N=R!=null?R:null}else{P=C!=null?C:0;let W=D;W===void 0&&(W=$!==void 0?P+$:1/0),O={isLinear:!1,maximumSafePosition:W,livePosition:void 0,time:K()}}let j=_?0:P,z=_?void 0:O.maximumSafePosition,q={availabilityStartTime:M===void 0?0:M,clockOffset:i,isLive:_,isDynamic:_,isLastPeriodKnown:!0,timeBounds:{minimumSafePosition:P,timeshiftDepth:N,maximumTimeData:O},periods:[{adaptations:k,duration:z!==void 0?z-j:$,end:z,id:"gen-smooth-period-0",start:j}],suggestedPresentationDelay:x,transportType:"smooth",uris:E(u)?[]:[u]};return ir(q),q}return s}function lb(n,e){if(n.length!==32)throw new Error("HSS: wrong system id length");return le("pssh",ie([0,0,0,0],je(n),Ie(e.length),e))}var km=ub;var Cm=km;function Pm(n,e,t,r,i,o,a){return le("avc1",ie(6,fe(1),16,fe(n),fe(e),fe(t),2,fe(r),6,[0,1,i.length],ve(i),31-i.length,fe(o),[255,255],a))}function Mm(n,e,t,r,i,o,a,s){return le("encv",ie(6,fe(1),16,fe(n),fe(e),fe(t),2,fe(r),6,[0,1,i.length],ve(i),31-i.length,fe(o),[255,255],a,s))}function Am(n,e,t,r,i,o){return le("mp4a",ie(6,fe(n),8,fe(e),fe(t),2,fe(r),fe(i),2,o))}function xm(n,e,t,r,i,o,a){return le("enca",ie(6,fe(n),8,fe(e),fe(t),2,fe(r),fe(i),2,o,a))}function wm(n){return le("dref",ie(7,[1],n))}function Om(n,e){let t=ie(...[ve(n),[0,0,0,1]].concat(e.map(ve)));return le("ftyp",t)}function va(n,e){return le("schm",ie(4,ve(n),Ie(e)))}function Dm(n){return le("tfdt",ie([1,0,0,0],Xt(n)))}function Lm(){let n=new Uint8Array(12);return n[3]=1,le("vmhd",n)}function Nm(n){return le("trex",ie(4,Ie(n),[0,0,0,1],12))}function Um(n){return le("free",new Uint8Array(n-8))}function Bm(n,e){return le("esds",ie(4,[3,25],fe(n),[0,4,17,64,21],11,[5,2],je(e),[6,1,2]))}function Ra(n){return le("frma",ve(n))}function Fm(n,e,t){let r;t===2?r=1:t===4?r=3:r=0;let i=n[1],o=n[2],a=n[3];return le("avcC",ie([1,i,o,a,252|r,225],fe(n.length),n,[1],fe(e.length),e))}function Km(n){let e,t;switch(n){case"video":e="vide",t="VideoHandler";break;case"audio":e="soun",t="SoundHandler";break;default:e="hint",t="";break}return le("hdlr",ie(8,ve(e),12,ve(t),1))}function Vm(n){return le("mdhd",ie(12,Ie(n),8))}function zm(n,e){return le("mvhd",ie(12,Ie(n),4,[0,1],2,[1,0],10,[0,1],14,[0,1],14,[64,0,0,0],26,fe(e+1)))}function Hm(n,e,t,r){return le("saio",ie(4,[0,0,0,1],Ie(n.length+e.length+t.length+r.length+8+8+8+8)))}function Wm(n){if(n.length===0)return le("saiz",new Uint8Array(0));let e=ne(n,0),t=ne(n,4),r=new Uint8Array(t+9);r.set(Ie(t),5);let i=9,o=8,a,s;for(;o<n.length;)o+=8,(e&2)===2?(s=2,a=Vo(n,o),o+=a*6+2):(a=0,s=0),r[i]=a*6+8+s,i++;return le("saiz",r)}function Gm(){return le("smhd",new Uint8Array(8))}function ar(n){let e=[7,[n.length]];return le("stsd",ie(...e.concat(n)))}function qm(n,e,t){return le("tkhd",ie(Ie(7),8,Ie(t),20,[1,0,0,0],[0,1,0,0],12,[0,1,0,0],12,[64,0,0,0],fe(n),2,fe(e),2))}function ka(n,e,t){return le("tenc",ie(6,[n,e],t))}function cb(n,e,t){return Ae("moov",[n,e,t])}function ao(n,e,t,r,i,o){let a=Ae("stbl",[t,le("stts",new Uint8Array(8)),le("stsc",new Uint8Array(8)),le("stsz",new Uint8Array(12)),le("stco",new Uint8Array(8))]),s=le("url ",new Uint8Array([0,0,0,1])),d=wm(s),u=Ae("dinf",[d]),l=Ae("minf",[r,u,a]),c=Km(e),f=Vm(n),g=Ae("mdia",[f,c,l]),p=qm(i,o,1),I=Ae("trak",[p,g]),y=Nm(1),b=Ae("mvex",[y]),T=zm(n,1),v=cb(T,b,I),_=Om("isom",["isom","iso2","iso6","avc1","dash"]);return ie(_,v)}var fb=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];function _l(n,e,t){let r=fb.indexOf(e),i;return i=(n&63)<<4,i=(i|r&31)<<4,i=(i|t&31)<<3,Ue(fe(i))}function Ca(n,e,t,r,i,o,a){let s=o.length===0?_l(2,i,e):o,d=Bm(1,s),u=(()=>{if(a===void 0){let y=Am(1,e,t,r,i,d);return ar([y])}let l=ka(1,8,a),c=Ae("schi",[l]),f=va("cenc",65536),g=Ra("mp4a"),p=Ae("sinf",[g,f,c]),I=xm(1,e,t,r,i,d,p);return ar([I])})();return ao(n,"audio",u,Gm(),0,0)}function Pa(n,e,t,r,i,o,a,s){let[,d,u]=a.split("00000001");if(d===void 0||u===void 0)throw new Error("Smooth: unsupported codec private data.");let l=je(d),c=je(u),f=Fm(l,c,o),g;if(s===void 0){let p=Pm(e,t,r,i,"AVC Coding",24,f);g=ar([p])}else{let p=ka(1,8,s),I=Ae("schi",[p]),y=va("cenc",65536),b=Ra("avc1"),T=Ae("sinf",[b,y,I]),v=Mm(e,t,r,i,"AVC Coding",24,f,T);g=ar([v])}return ao(n,"video",g,Lm(),e,t)}function Ma(n){let e=Sn(n,3565190898,3392751253,2387879627,2655430559);if(e===void 0)return[];let t=[],r=e[0],i=e[4];for(let o=0;o<i;o++){let a,s;r===1?(s=Ke(e,o*16+5),a=Ke(e,o*16+5+8)):(s=ne(e,o*8+5),a=ne(e,o*8+5+4)),t.push({time:s,duration:a})}return t}function Aa(n){let e=Sn(n,1830656773,1121273062,2162299933,2952222642);if(e!==void 0)return{duration:Ke(e,12),time:Ke(e,4)}}function El(){return!Wt}function vl(n,e,t,r,i){let o=[n,e,t];return i!==void 0&&o.push(le("senc",i),Wm(i),Hm(r,n,e,t)),Ae("traf",o)}function xa(n,e){let t=Ve(n,1836019558);if(t===null)throw new Error("Smooth: Invalid ISOBMFF given");let r=n.subarray(t[1],t[2]),i=vs(r,1835427940),o=Re(r,1953653094);if(o===null||i===null)throw new Error("Smooth: Invalid ISOBMFF given");let a=Ve(o,1952868452),s=Ve(o,1953658222);if(a===null||s===null)throw new Error("Smooth: Invalid ISOBMFF given");let d=o.subarray(a[0],a[2]),u=o.subarray(s[0],s[2]);d.set([0,0,0,1],a[1]-a[0]+4);let l=Dm(e),c=mb(u,s[1]-s[0]),f=Sn(o,2721664850,1520127764,2722393154,2086964724),g=vl(d,l,c,i,f),p=Ae("moof",[i,g]),I=Ve(p,1836019558),y=Ve(g,1953653094),b=Ve(c,1953658222);if(I===null||y===null||b===null)throw new Error("Smooth: Invalid moof, trun or traf generation");let T=I[1]-I[0]+i.length+(y[1]-y[0])+d.length+l.length+(b[1]-b[0])+8,v=t[2]-t[0],_=p.length-v,R=Ve(n,1835295092);if(R===null)throw new Error("Smooth: Invalid ISOBMFF given");if(El()&&(_===0||_<=-8)){let k=R[1];return p.set(Ie(k),T),n.set(p,t[0]),_<=-8&&n.set(Um(-_),p.length),n}else{let k=R[1]+_;p.set(Ie(k),T);let x=new Uint8Array(n.length+_),M=n.subarray(0,t[0]),P=n.subarray(t[2],n.length);return x.set(M,0),x.set(p,M.length),x.set(P,M.length+p.length),x}}function mb(n,e){if((n[e+3]&1)>0)return n;let r=new Uint8Array(n.length+4);return r.set(n.subarray(0,e+8),0),r[e+3]=r[e+3]|1,r.set([0,0,0,0],e+8),r.set(n.subarray(e+8,n.length),e+12),Ms(r)}function wa(n,e,t,r,i){var g;let o=[],a,s,d;if(i){let p=Dr(n);p!==null?(d=Ma(p),s=Aa(p)):m.warn("smooth: could not find traf atom")}if(d!==void 0)for(let p of d)o.push({time:p.time,duration:p.duration,timescale:t});if(s!==void 0)return a={time:s.time/t,duration:s.duration/t},{nextSegments:o,chunkInfos:a,scaledSegmentTime:s.time};if(e||!r.complete)return{nextSegments:o,chunkInfos:null,scaledSegmentTime:void 0};let u=r.duration*t,l=Math.min(t*.9,u/4),c=Br(n),f=((g=r.privateInfos)==null?void 0:g.smoothMediaSegment)!==void 0?r.privateInfos.smoothMediaSegment.time:Math.round(r.time*t);return c!==void 0&&Math.abs(c-u)<=l?a={time:r.time,duration:c/t}:a={time:r.time,duration:r.duration},{nextSegments:o,chunkInfos:a,scaledSegmentTime:f}}function wn(n){return typeof n=="string"&&n.indexOf("mp4")>=0}async function jm(n,e,t,r,i,o){var g,p;let a=((g=r.cmcdPayload)==null?void 0:g.type)==="headers"?r.cmcdPayload.value:void 0,s=e.segment.range,d;Array.isArray(s)?d=ue(oe({},a),{Range:ut(s)}):a!==void 0&&(d=a);let u=((p=r.cmcdPayload)==null?void 0:p.type)==="query"?$e(n,r.cmcdPayload.value):n,l=await Te({url:u,responseType:"arraybuffer",headers:d,timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i,onProgress:t.onProgress});if(!wn(e.mimeType)||o!==!0)return{resultType:"segment-loaded",resultData:l};let f=new Uint8Array(l.responseData);return nn(f,e.segment.isInit),{resultType:"segment-loaded",resultData:ue(oe({},l),{responseData:f})}}var pb=({checkMediaSegmentIntegrity:n,segmentLoader:e})=>(t,r,i,o,a)=>{let{segment:s}=r;if(s.isInit){if(s.privateInfos===void 0||s.privateInfos.smoothInitSegment===void 0)throw new Error("Smooth: Invalid segment format");let d=s.privateInfos.smoothInitSegment,u,{codecPrivateData:l,timescale:c,height:f,width:g,protection:p={keyId:void 0,keySystems:void 0}}=d;if(l===void 0)throw new Error("Smooth: no codec private data.");switch(r.type){case"video":{u=Pa(c,g!=null?g:0,f!=null?f:0,72,72,4,l,p.keyId);break}case"audio":{let{channels:I=0,bitsPerSample:y=0,packetSize:b=0,samplingRate:T=0}=d;u=Ca(c,I,y,b,T,l,p.keyId);break}default:h.CURRENT_ENV===h.DEV&&ee(!1,"responseData should have been set"),u=new Uint8Array(0)}return Promise.resolve({resultType:"segment-created",resultData:u})}else return t===null?Promise.resolve({resultType:"segment-created",resultData:null}):typeof e!="function"?jm(t,r,a,i,o,n):new Promise((d,u)=>{let l=!1,I={reject:_=>{var M,P;if(l||o.isCancelled())return;l=!0,o.deregister(v);let R=_,k=(M=R==null?void 0:R.message)!=null?M:"Unknown error when fetching a Smooth segment through a custom segmentLoader.",x=new rt(k,(P=R==null?void 0:R.canRetry)!=null?P:!1,R==null?void 0:R.xhr);u(x)},resolve:_=>{if(l||o.isCancelled())return;l=!0,o.deregister(v),(!wn(r.mimeType)||n!==!0)&&d({resultType:"segment-loaded",resultData:{responseData:_.data,size:_.size,requestDuration:_.duration}});let k=_.data instanceof Uint8Array?_.data:new Uint8Array(_.data);nn(k,r.segment.isInit),d({resultType:"segment-loaded",resultData:{responseData:k,size:_.size,requestDuration:_.duration}})},fallback:()=>{l||o.isCancelled()||(l=!0,o.deregister(v),jm(t,r,a,i,o,n).then(d,u))},progress:_=>{l||o.isCancelled()||a.onProgress({duration:_.duration,size:_.size,totalSize:_.totalSize})}},y;r.segment.range!==void 0&&(y=[r.segment.range],r.segment.indexRange!==void 0&&y.push(r.segment.indexRange));let b={isInit:r.segment.isInit,timeout:i.timeout,byteRanges:y,trackType:r.type,url:t,cmcdPayload:i.cmcdPayload},T=e(b,I);o.register(v);function v(_){l||(l=!0,!l&&typeof T=="function"&&T(),u(_))}})},Ym=pb;function Rl(n,e){return n===null?null:e.url===null?n.baseUrl:mn(n.baseUrl,e.url)}function $m(n){let e=Cm(n),t=Ym(n),r={customManifestLoader:n.manifestLoader},o={loadManifest:Bi(r,"text",null),parseManifest(d,u){var b;let l=(b=d.url)!=null?b:u.originalUrl,{receivedTime:c,responseData:f}=d,g=typeof f=="string"?new DOMParser().parseFromString(f,"text/xml"):f,p=e(g,l,c),I=[];return{manifest:new Wn(p,{representationFilter:n.representationFilter},I),url:l,warnings:I}}},a={loadSegment(d,u,l,c,f){let g=Rl(d,u.segment);return t(g,u,l,c,f)},parseSegment(d,u,l){var R,k;let{segment:c}=u,{data:f,isChunked:g}=d;if(f===null)return c.isInit?{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0}:{segmentType:"media",chunkData:null,chunkInfos:null,chunkOffset:0,chunkSize:0,protectionData:[],appendWindow:[void 0,void 0]};let p=f instanceof Uint8Array?f:new Uint8Array(f);if(c.isInit){let x=(k=(R=c.privateInfos)==null?void 0:R.smoothInitSegment)==null?void 0:k.timescale;return{segmentType:"init",initializationData:f,initializationDataSize:f.byteLength,initTimescale:x,protectionData:[]}}let I=l!==void 0?wa(p,g,l,c,u.isLive):null;if(I===null||I.chunkInfos===null||I.scaledSegmentTime===void 0)throw new Error("Smooth Segment without time information");let{nextSegments:y,chunkInfos:b,scaledSegmentTime:T}=I,v=xa(p,T),_=y.length>0?y:void 0;return{segmentType:"media",chunkData:v,chunkInfos:b,chunkOffset:0,chunkSize:v.length,protectionData:[],predictedSegments:_,appendWindow:[void 0,void 0]}}};return{transportName:"smooth",manifest:o,audio:a,video:a,text:{loadSegment(d,u,l,c,f){var y,b,T,v;let{segment:g}=u,p=Rl(d,g);return g.isInit||p===null?Promise.resolve({resultType:"segment-created",resultData:null}):wn(u.mimeType)?Te({url:((T=l.cmcdPayload)==null?void 0:T.type)==="query"?$e(p,l.cmcdPayload.value):p,headers:((v=l.cmcdPayload)==null?void 0:v.type)==="headers"?l.cmcdPayload.value:void 0,responseType:"arraybuffer",timeout:l.timeout,connectionTimeout:l.connectionTimeout,cancelSignal:c,onProgress:f.onProgress}).then(_=>{if(n.checkMediaSegmentIntegrity!==!0)return{resultType:"segment-loaded",resultData:_};let R=new Uint8Array(_.responseData);return nn(R,u.segment.isInit),{resultType:"segment-loaded",resultData:ue(oe({},_),{responseData:R})}}):Te({url:((y=l.cmcdPayload)==null?void 0:y.type)==="query"?$e(p,l.cmcdPayload.value):p,headers:((b=l.cmcdPayload)==null?void 0:b.type)==="headers"?l.cmcdPayload.value:void 0,responseType:"text",timeout:l.timeout,connectionTimeout:l.connectionTimeout,cancelSignal:c,onProgress:f.onProgress}).then(_=>({resultType:"segment-loaded",resultData:_}))},parseSegment(d,u,l){var O;let{segment:c,language:f,mimeType:g="",codecs:p=""}=u,I=wn(u.mimeType),{data:y,isChunked:b}=d,T;if(c.isInit)return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0};if(y===null)return{segmentType:"media",chunkData:null,chunkInfos:null,chunkOffset:0,chunkSize:0,protectionData:[],appendWindow:[void 0,void 0]};let v,_=null,R,k,x,M;if(I){let F;typeof y=="string"?F=ve(y):F=y instanceof Uint8Array?y:new Uint8Array(y),T=F.length;let A=l!==void 0?wa(F,b,l,c,u.isLive):null;v=A==null?void 0:A.nextSegments,_=(O=A==null?void 0:A.chunkInfos)!=null?O:null,_===null?b?m.warn("Smooth: Unavailable time data for current text track."):(R=c.time,k=c.end):(R=_.time,k=_.duration!==void 0?_.time+_.duration:c.end);let C=p.toLowerCase();if(g==="application/ttml+xml+mp4"||C==="stpp"||C==="stpp.ttml"||C==="stpp.ttml.im1t")M="ttml";else if(C==="wvtt")M="vtt";else throw new Error(`could not find a text-track parser for the type ${g}`);let D=Lr(F);x=D===null?"":Ne(D)}else{R=c.time,k=c.end;let F;if(typeof y!="string"){let A=y instanceof Uint8Array?y:new Uint8Array(y);T=A.length,F=Ne(A)}else F=y;switch(g){case"application/x-sami":case"application/smil":M="sami";break;case"application/ttml+xml":M="ttml";break;case"text/vtt":M="vtt";break}if(M===void 0)if(p.toLowerCase()==="srt")M="srt";else throw new Error(`could not find a text-track parser for the type ${g}`);x=F}let P=Array.isArray(v)&&v.length>0?v:void 0,N=R!=null?R:0;return{segmentType:"media",chunkData:{type:M,data:x,start:R,end:k,language:f},chunkSize:T,chunkInfos:_,chunkOffset:N,protectionData:[],predictedSegments:P,appendWindow:[void 0,void 0]}}}}}var Qm=$m;function kl(n){n.transports.smooth===void 0&&(n.transports.smooth=Qm),n.mainThreadMediaSourceInit=vn}function Xm(){if(!ln)return m.warn("Compat: Can't access Firefox version on no firefox browser."),null;let n=navigator.userAgent,e=/Firefox\/([0-9]+)\./.exec(n);if(e===null)return-1;let t=parseInt(e[1],10);return isNaN(t)?-1:t}function Cl(){if(!ln)return!0;let n=Xm();if(n===null||n<67)return!0;let e=HTMLVideoElement==null?void 0:HTMLVideoElement.prototype;return(e==null?void 0:e.requirePictureInPicture)!==void 0}function so(n){let e=n;if(typeof e.getStartDate=="function"){let t=e.getStartDate();if(typeof t=="object"&&t!==null){let r=+t;if(!isNaN(r))return r/1e3}else if(typeof t=="number"&&!isNaN(t))return t}}function Pl(){return Ha&&typeof Worker=="object"||typeof Worker=="function"}var On=class n extends Error{constructor(e,t){super(ct(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="WorkerInitializationError",this.type="WORKER_INITIALIZATION_ERROR",this.code=e}};function Oa(n,e,t){let r=e(n.getReference(),t);return{getCurrentTime(){return n.getCurrentTime()},getReadyState(){return n.getReadyState()},getPlaybackRate(){return n.getPlaybackRate()},getIsPaused(){return n.getIsPaused()},getReference(){return r},listen(i,o){t.isCancelled()||o.clearSignal.isCancelled()||r.onUpdate(i,{clearSignal:o.clearSignal,emitCurrentValue:o.includeLastObservation})},deriveReadOnlyObserver(i){return Oa(this,i,t)}}}var gb=["canplay","ended","play","pause","seeking","seeked","loadedmetadata","ratechange"],uo=class{constructor(e,t){this._internalSeeksIncoming=[],this._mediaElement=e,this._withMediaSource=t.withMediaSource,this._lowLatencyMode=t.lowLatencyMode,this._canceller=new B,this._observationRef=this._createSharedReference(),this._expectedSeekingPosition=null,this._pendingSeek=null;let r=()=>{if(this._pendingSeek!==null){let i=this._pendingSeek;this._pendingSeek=null,this._actuallySetCurrentTime(i)}};e.addEventListener("loadedmetadata",r),this._canceller.signal.register(()=>{e.removeEventListener("loadedmetadata",r)})}stop(){this._canceller.cancel()}getCurrentTime(){return this._mediaElement.currentTime}getPlaybackRate(){return this._mediaElement.playbackRate}getIsPaused(){return this._mediaElement.paused}setCurrentTime(e){this._mediaElement.readyState>=1?this._actuallySetCurrentTime(e):(this._internalSeeksIncoming=[],this._pendingSeek=e,this._generateObservationForEvent("manual"))}setPlaybackRate(e){this._mediaElement.playbackRate=e}getReadyState(){return this._mediaElement.readyState}getReference(){return this._observationRef}listen(e,t){if(this._canceller.isUsed()||t.clearSignal.isCancelled())return X;this._observationRef.onUpdate(e,{clearSignal:t.clearSignal,emitCurrentValue:t.includeLastObservation})}deriveReadOnlyObserver(e){return Oa(this,e,this._canceller.signal)}_actuallySetCurrentTime(e){m.info("API: Seeking internally",e),this._internalSeeksIncoming.push(e),this._mediaElement.currentTime=e}_createSharedReference(){if(this._observationRef!==void 0)return this._observationRef;let{SAMPLING_INTERVAL_MEDIASOURCE:e,SAMPLING_INTERVAL_LOW_LATENCY:t,SAMPLING_INTERVAL_NO_MEDIASOURCE:r}=U.getCurrent(),i=new H(this._getCurrentObservation("init"),this._canceller.signal),o;this._lowLatencyMode?o=t:this._withMediaSource?o=e:o=r;let a=()=>{this._generateObservationForEvent("timeupdate")},s=setInterval(a,o);return gb.map(u=>{let l=()=>{d(),this._generateObservationForEvent(u)};this._mediaElement.addEventListener(u,l),this._canceller.signal.register(()=>{this._mediaElement.removeEventListener(u,l)})}),this._canceller.signal.register(()=>{clearInterval(s),i.finish()}),i;function d(){clearInterval(s),s=setInterval(a,o)}}_getCurrentObservation(e){var T,v;let t=e,r=this._observationRef===void 0?Sb(this._mediaElement):this._observationRef.getValue(),i=!1,o=this._pendingSeek,a=Jm(this._mediaElement),{buffered:s,readyState:d,position:u,seeking:l}=a;if(t==="seeking")if(this._internalSeeksIncoming.length>0){i=!0,t="internal-seeking";let _=this._internalSeeksIncoming.shift();this._expectedSeekingPosition=Xn?Math.max(u,_!=null?_:0):u}else this._expectedSeekingPosition=u;else l?this._expectedSeekingPosition=Math.max(u,(T=this._expectedSeekingPosition)!=null?T:0):Xn&&this._expectedSeekingPosition!==null&&u<this._expectedSeekingPosition?o=this._expectedSeekingPosition:this._expectedSeekingPosition=null;l&&r.seeking===1&&e!=="seeking"&&(i=!0);let c=(v=this._expectedSeekingPosition)!=null?v:u,f,g;!this._withMediaSource&&s.length===0&&d>=3?(f=void 0,g=void 0):(f=$a(s,c),g=f!==null?f.end-c:1/0);let p=yb({previousObservation:r,currentObservation:a,basePosition:c,observationEvent:t,lowLatencyMode:this._lowLatencyMode,withMediaSource:this._withMediaSource,bufferGap:g,currentRange:f}),I=Ib(r,a,t,g),y;i?y=1:l?y=2:y=0;let b=G({},a,{position:new Qn(a.position,o),event:t,seeking:y,rebuffering:p,freezing:I,bufferGap:g,currentRange:f});return m.hasLevel("DEBUG")&&m.debug("API: current media element state tick","event",b.event,"position",b.position.getPolled(),"seeking",b.seeking,"internalSeek",i,"rebuffering",b.rebuffering!==null,"freezing",b.freezing!==null,"ended",b.ended,"paused",b.paused,"playbackRate",b.playbackRate,"readyState",b.readyState,"pendingPosition",o),b}_generateObservationForEvent(e){let t=this._getCurrentObservation(e);m.hasLevel("DEBUG")&&m.debug(`API: current playback timeline:
|
|
15
|
+
`+bb(t.buffered,t.position.getPolled()),`
|
|
16
|
+
${e}`),this._observationRef.setValue(t)}};function Zm(n,e){if(n===null)return 0;let t=e?"LOW_LATENCY":"DEFAULT",{RESUME_GAP_AFTER_SEEKING:r,RESUME_GAP_AFTER_NOT_ENOUGH_DATA:i,RESUME_GAP_AFTER_BUFFERING:o}=U.getCurrent();switch(n.reason){case"seeking":return r[t];case"not-ready":return i[t];case"buffering":return o[t]}}function hb(n,e,t,r,i){let{REBUFFERING_GAP:o}=U.getCurrent(),a=i?"LOW_LATENCY":"DEFAULT";return e===void 0?t&&Math.abs(r-n)<=o[a]:e!==null&&r-e.end<=o[a]}function Jm(n){let{buffered:e,currentTime:t,duration:r,ended:i,paused:o,playbackRate:a,readyState:s,seeking:d}=n;return{buffered:e,position:t,duration:r,ended:i,paused:o,playbackRate:a,readyState:s,seeking:d}}function yb({previousObservation:n,currentObservation:e,basePosition:t,observationEvent:r,withMediaSource:i,lowLatencyMode:o,bufferGap:a,currentRange:s}){let{REBUFFERING_GAP:d}=U.getCurrent(),{position:u,duration:l,paused:c,readyState:f,ended:g}=e,{rebuffering:p,event:I,position:y}=n,b=hb(t,s,g,l,o),T=f>=1&&r!=="loadedmetadata"&&p===null&&!(b||g),v=null,_,R,k=o?d.LOW_LATENCY:d.DEFAULT;if(i){if(T)a===1/0?(_=!0,v=t):a===void 0?f<3&&(_=!0,v=void 0):a<=k&&(_=!0,v=t+a);else if(p!==null){let x=Zm(p,o);_!==!0&&p!==null&&f>1&&(b||g||a!==void 0&&isFinite(a)&&a>x)||a===void 0&&f>=3?R=!0:a===void 0?v=void 0:a===1/0?v=t:a<=x&&(v=t+a)}}else T&&(!c&&r==="timeupdate"&&I==="timeupdate"&&u===y.getPolled()||r==="seeking"&&(a===1/0||a===void 0&&f<3))?_=!0:p!==null&&(r!=="seeking"&&u!==y.getPolled()||r==="canplay"||a===void 0&&f>=3||a!==void 0&&a<1/0&&(a>Zm(p,o)||b||g))&&(R=!0);if(R===!0)return null;if(_===!0||p!==null){let x;return r==="seeking"||p!==null&&p.reason==="seeking"||e.seeking?x="seeking":f===1?x="not-ready":x="buffering",p!==null&&p.reason===x?{reason:p.reason,timestamp:p.timestamp,position:v}:{reason:x,timestamp:K(),position:v}}return null}function Ib(n,e,t,r){let{MINIMUM_BUFFER_AMOUNT_BEFORE_FREEZING:i}=U.getCurrent();return n.freezing!==null?e.ended||e.paused||e.readyState===0||e.playbackRate===0||n.position.getPolled()!==e.position?null:n.freezing:t==="timeupdate"&&r!==void 0&&r>i&&!e.ended&&!e.paused&&e.readyState>=1&&e.playbackRate!==0&&e.position===n.position.getPolled()?{timestamp:K()}:null}function bb(n,e){let t="",r="";for(let i=0;i<n.length;i++){let o=n.start(i),a=n.end(i),s=o.toFixed(2),d=a.toFixed(2),u=(a-o).toFixed(2),l=`${s}|==${u}==|${d}`;if(t+=l,r.length===0&&a>e){let c=t.length-Math.floor(l.length/2);r=" ".repeat(c)+`^${e}`}if(i<n.length-1){let c=n.start(i+1),g=` ~${(c-a).toFixed(2)}~ `;if(t+=g,r.length===0&&e<c){let p=t.length-Math.floor(g.length/2);r=" ".repeat(p)+`^${e}`}}}return r.length===0&&(r=" ".repeat(t.length)+`^${e}`),t+`
|
|
17
|
+
`+r}function Sb(n){let e=Jm(n);return G(e,{rebuffering:null,event:"init",seeking:0,position:new Qn(e.position,null),freezing:null,bufferGap:0,currentRange:null})}var lo=class extends re{constructor(e){super(),this._canceller=new B,this._adaptationRef=e,this._updateToken=!1,this._lastEmitted=void 0,this.refresh=X}hasSetTrack(){return this._adaptationRef.getValue()!==void 0}updateTrack(e){if(this._updateToken=!0,e===null){if(this._lastEmitted===null)return;this._updateToken=!1,this._canceller.cancel(),this._canceller=new B,this._lastEmitted=null,this._adaptationRef.setValue(null);return}let{adaptation:t,switchingMode:r,relativeResumingPosition:i}=e;this._canceller.cancel(),this._canceller=new B;let o=this._constructLockedRepresentationsReference(e);this._updateToken&&(this._lastEmitted={adaptation:t,switchingMode:r,lockedRepresentations:null},this._updateToken=!1,this._adaptationRef.setValue({adaptationId:t.id,switchingMode:r,representations:o,relativeResumingPosition:i}))}_constructLockedRepresentationsReference(e){let t=new H({representationIds:[],switchingMode:"lazy"}),r=this;return this.refresh=i,this._canceller.signal.register(o),e.lockedRepresentations.onUpdate(i,{clearSignal:this._canceller.signal,emitCurrentValue:!1}),i(),t;function i(){let a=e.lockedRepresentations.getValue(),s,d;if(a===null)d=e.adaptation.representations.filter(c=>It(c)===!0),s="lazy";else{let{representationIds:c}=a;if(s=a.switchingMode,d=e.adaptation.representations.filter(g=>Q(c,g.id)).filter(g=>It(g)===!0),d.length===0){r.trigger("noPlayableLockedRepresentation",null);return}}if(d.length<=0){r.trigger("noPlayableRepresentation",null);return}let u=t.getValue(),l=d.map(c=>c.id).slice().sort();if(l.length!==u.representationIds.length){t.setValue({representationIds:l,switchingMode:s});return}for(let c=0;c<l.length;c++)if(u.representationIds[c]!==l[c]){t.setValue({representationIds:l,switchingMode:s});return}}function o(){r.refresh=X}}dispose(){this.removeEventListener(),this._canceller.cancel(),this._adaptationRef.finish()}};var co=class extends re{constructor(e){var t;super(),this._storedPeriodInfo=[],this._isDisposed=!1,this._cachedPeriodInfo=new WeakMap,this._isTrickModeTrackEnabled=e.preferTrickModeTracks,this._defaultAudioTrackSwitchingMode=(t=e.defaultAudioTrackSwitchingMode)!=null?t:U.getCurrent().DEFAULT_AUDIO_TRACK_SWITCHING_MODE}getAvailablePeriods(){return this._storedPeriodInfo.reduce((e,t)=>(t.isPeriodAdvertised&&e.push(Ft(t.period)),e),[])}onManifestCodecSupportUpdate(){this._selectInitialTrackIfNeeded()}onManifestUpdate(e){var a,s,d,u,l,c;let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:t}=U.getCurrent(),{periods:r}=e;if(h.CURRENT_ENV===h.DEV)for(let f=1;f<r.length;f++)ee(r[f-1].start<=r[f].start);let i=[],o=0;for(let f=0;f<this._storedPeriodInfo.length;f++){let g=this._storedPeriodInfo[f].period,p=r[o];if(p===void 0)for(let I=this._storedPeriodInfo.length-1;I>=f;I--)this._storedPeriodInfo[I].inManifest=!1,Ml(this._storedPeriodInfo[I])&&this._removePeriodObject(I);else if(g===p){o++;let I=this._storedPeriodInfo[f].text.storedSettings;if(!E(I)&&!ft(p,"text").some(_=>_.id===I.adaptation.id)){m.warn("TS: Chosen text Adaptation not available anymore");let _=this._storedPeriodInfo[f];if(_.text.storedSettings=null,this.trigger("trackUpdate",{period:Ft(p),trackType:"text",reason:"missing"}),this._isDisposed)return;let R=lt(this._storedPeriodInfo,_.period.id);R!==void 0&&R.isPeriodAdvertised&&R.text.storedSettings===null&&((a=R.text.dispatcher)==null||a.updateTrack(null))}let y=this._storedPeriodInfo[f].video.storedSettings;if(!E(y)){let T=ft(p,"video");if(!T.some(_=>_.id===y.adaptation.id)){m.warn("TS: Chosen video Adaptation not available anymore");let _=this._storedPeriodInfo[f],R;if(T.length===0)R=null;else{let x=T[0],M=Da(x,this._isTrickModeTrackEnabled),P=new H(null);R={adaptationBase:x,adaptation:M,switchingMode:t,lockedRepresentations:P}}if(_.video.storedSettings=R,this.trigger("trackUpdate",{period:Ft(p),trackType:"video",reason:"missing"}),this._isDisposed)return;let k=lt(this._storedPeriodInfo,_.period.id);k!==void 0&&k.isPeriodAdvertised&&k.video.storedSettings===R&&((s=k.video.dispatcher)==null||s.updateTrack(R))}}let b=this._storedPeriodInfo[f].audio.storedSettings;if(!E(b)){let T=ft(p,"audio");if(!T.some(_=>_.id===b.adaptation.id)){m.warn("TS: Chosen audio Adaptation not available anymore");let _=this._storedPeriodInfo[f],R=T.length===0?null:{adaptation:T[0],switchingMode:this._defaultAudioTrackSwitchingMode,lockedRepresentations:new H(null)};if(_.audio.storedSettings=R,this.trigger("trackUpdate",{period:Ft(p),trackType:"audio",reason:"missing"}),this._isDisposed)return;let k=lt(this._storedPeriodInfo,_.period.id);k!==void 0&&k.isPeriodAdvertised&&k.audio.storedSettings===R&&((d=k.audio.dispatcher)==null||d.updateTrack(R))}}}else if(g.start<=p.start)this._storedPeriodInfo[f].inManifest=!1,Ml(this._storedPeriodInfo[f])&&(this._removePeriodObject(f),f--);else{let I=Al(p,!0);this._storedPeriodInfo.splice(f,0,I),i.push(I),o++}}if(o<r.length){let f=r.slice(o).map(g=>Al(g,!0));this._storedPeriodInfo.push(...f),i.push(...f)}for(let f of this._storedPeriodInfo)(u=f.audio.dispatcher)==null||u.refresh(),(l=f.video.dispatcher)==null||l.refresh(),(c=f.text.dispatcher)==null||c.refresh()}onDecipherabilityUpdates(){var e,t,r;for(let i of this._storedPeriodInfo)(e=i.audio.dispatcher)==null||e.refresh(),(t=i.video.dispatcher)==null||t.refresh(),(r=i.text.dispatcher)==null||r.refresh()}addTrackReference(e,t,r){let i=lt(this._storedPeriodInfo,t.id);if(i===void 0){i=Al(t,!1);let s=!1;for(let d=0;d<this._storedPeriodInfo.length;d++)this._storedPeriodInfo[d].period.start>t.start&&(this._storedPeriodInfo.splice(d,0,i),s=!0);s||this._storedPeriodInfo.push(i)}if(i[e].dispatcher!==null){m.error(`TS: Subject already added for ${e} and Period ${t.start}`);return}let o=new lo(r);if(i[e].dispatcher=o,o.addEventListener("noPlayableRepresentation",()=>{var c,f,g,p;let s=Z((c=t.adaptations[e])!=null?c:[],I=>I.supportStatus.hasSupportedCodec===!1||I.supportStatus.isDecipherable===!1?!1:I.representations.filter(b=>It(b)===!0).length>0);if(s===void 0){let I=new te("NO_PLAYABLE_REPRESENTATION",`No ${e} Representation can be played`,{tracks:void 0});this.trigger("error",I),this.dispose();return}let d=(f=lt(this._storedPeriodInfo,t.id))==null?void 0:f[e];if(E(d))return;let u=e==="audio"?this._defaultAudioTrackSwitchingMode:"reload",l={adaptation:s,switchingMode:u,lockedRepresentations:new H(null)};d.storedSettings=l,this.trigger("trackUpdate",{period:Ft(t),trackType:e,reason:"no-playable-representation"}),!this._isDisposed&&(d=(g=lt(this._storedPeriodInfo,t.id))==null?void 0:g[e],!(E(d)||d.storedSettings!==l)&&((p=d.dispatcher)==null||p.updateTrack(l)))}),o.addEventListener("noPlayableLockedRepresentation",()=>{i!==void 0&&(this.unlockVideoRepresentations(i),this.trigger("brokenRepresentationsLock",{period:{id:t.id,start:t.start,end:t.end},trackType:e}))}),this._selectInitialTrackIfNeeded(),this._shouldAdvertisePeriod(i)&&(i.isPeriodAdvertised=!0,this.trigger("newAvailablePeriods",[{id:t.id,start:t.start,end:t.end}]),this._isDisposed))return;let a=["audio","video","text"];for(let s of a){let d=i[s];if(i.isPeriodAdvertised&&d.dispatcher!==null&&!d.dispatcher.hasSetTrack()&&d.storedSettings!==void 0&&d.dispatcher.updateTrack(d.storedSettings),this._isDisposed)return}}removeTrackReference(e,t){let r=Tb(this._storedPeriodInfo,t);if(r===void 0){m.warn(`TS: ${e} not found for period`,t.start);return}let i=this._storedPeriodInfo[r],o=i[e];if((o==null?void 0:o.dispatcher)===null){m.warn(`TS: TrackDispatcher already removed for ${e} and Period ${t.start}`);return}o.dispatcher.dispose(),o.dispatcher=null,Ml(i)&&this._removePeriodObject(r)}getPeriodObjectFromPeriod(e){let t=lt(this._storedPeriodInfo,e.id);return t===void 0&&e!==void 0?this._cachedPeriodInfo.get(e):t}getPeriodObjectFromId(e){return lt(this._storedPeriodInfo,e)}disableVideoTrickModeTracks(){this._isTrickModeTrackEnabled&&(this._isTrickModeTrackEnabled=!1,this._resetVideoTrackChoices("trickmode-disabled"))}enableVideoTrickModeTracks(){this._isTrickModeTrackEnabled||(this._isTrickModeTrackEnabled=!0,this._resetVideoTrackChoices("trickmode-enabled"))}resetPeriodObjects(){var e,t,r;for(let i=this._storedPeriodInfo.length-1;i>=0;i--){let o=this._storedPeriodInfo[i];(e=o.audio.dispatcher)==null||e.dispose(),o.audio.dispatcher=null,(t=o.video.dispatcher)==null||t.dispose(),o.video.dispatcher=null,(r=o.text.dispatcher)==null||r.dispose(),o.text.dispatcher=null,o.inManifest||this._removePeriodObject(i)}}isTrickModeEnabled(){return this._isTrickModeTrackEnabled}setAudioTrack(e){let{periodRef:t,trackId:r,switchingMode:i,lockedRepresentations:o,relativeResumingPosition:a}=e;return this._setAudioOrTextTrack({bufferType:"audio",periodRef:t,trackId:r,switchingMode:i!=null?i:this._defaultAudioTrackSwitchingMode,lockedRepresentations:o,relativeResumingPosition:a})}setTextTrack(e,t){return this._setAudioOrTextTrack({bufferType:"text",periodRef:e,trackId:t,switchingMode:"direct",lockedRepresentations:null,relativeResumingPosition:void 0})}_setAudioOrTextTrack({bufferType:e,periodRef:t,trackId:r,switchingMode:i,lockedRepresentations:o,relativeResumingPosition:a}){var g,p;if(!t.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let s=t.period,d=Z((g=s.adaptations[e])!=null?g:[],({id:I,supportStatus:y})=>y.hasSupportedCodec!==!1&&y.isDecipherable!==!1&&I===r);if(d===void 0)throw new Error(`Wanted ${e} track not found.`);let u=t[e],l;if(o===null)l=new H(null);else{let I=this._getRepresentationsToLock(d,o),y=e==="audio"?this._defaultAudioTrackSwitchingMode:"direct";l=new H({representationIds:I,switchingMode:y})}let c={adaptation:d,switchingMode:i,lockedRepresentations:l,relativeResumingPosition:a};if(u.storedSettings=c,this.trigger("trackUpdate",{period:Ft(s),trackType:e,reason:"manual"}),this._isDisposed)return;let f=lt(this._storedPeriodInfo,s.id);f!==void 0&&f[e].storedSettings===c&&((p=f[e].dispatcher)==null||p.updateTrack(c))}setVideoTrack(e){var I,y;let{periodRef:t,trackId:r,switchingMode:i,lockedRepresentations:o,relativeResumingPosition:a}=e;if(!t.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let s=t.period,d=Z((I=s.adaptations.video)!=null?I:[],({id:b,supportStatus:T})=>T.isDecipherable!==!1&&T.hasSupportedCodec!==!1&&b===r);if(d===void 0)throw new Error("Wanted video track not found.");let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:u}=U.getCurrent(),l=t.video,c=Da(d,this._isTrickModeTrackEnabled),f;if(o===null)f=new H(null);else{let b=this._getRepresentationsToLock(d,o),T=u;f=new H({representationIds:b,switchingMode:T})}let g={adaptationBase:d,switchingMode:i!=null?i:u,adaptation:c,relativeResumingPosition:a,lockedRepresentations:f};if(l.storedSettings=g,this.trigger("trackUpdate",{period:Ft(s),trackType:"video",reason:"manual"}),this._isDisposed)return;let p=lt(this._storedPeriodInfo,s.id);p!==void 0&&p.video.storedSettings===g&&((y=p.video.dispatcher)==null||y.updateTrack(g))}disableTrack(e,t){var o,a;if(!e.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let r=e[t];if(r.storedSettings===null||(t!=="text"&&((o=e[t].storedSettings)==null||o.lockedRepresentations.finish()),r.storedSettings=null,this.trigger("trackUpdate",{period:Ft(e.period),trackType:t,reason:"manual"}),this._isDisposed))return;let i=lt(this._storedPeriodInfo,e.period.id);i!==void 0&&i[t].storedSettings===null&&((a=i[t].dispatcher)==null||a.updateTrack(null))}getChosenAudioTrack(e,t){return E(e.audio.storedSettings)?null:vo(e.audio.storedSettings.adaptation,t)}getChosenTextTrack(e){return E(e.text.storedSettings)?null:Ro(e.text.storedSettings.adaptation)}getChosenVideoTrack(e,t){return E(e.video.storedSettings)?null:ko(e.video.storedSettings.adaptation,t)}getAvailableAudioTracks(e,t){let r=e.audio.storedSettings,i=E(r)?null:r.adaptation.id;return ft(e.period,"audio").map(a=>{let s=i===null?!1:i===a.id;return G(vo(a,t),{active:s})})}getAvailableTextTracks(e){let t=e.text.storedSettings,r=E(t)?null:t.adaptation.id;return ft(e.period,"text").map(o=>{let a=r===null?!1:r===o.id;return G(Ro(o),{active:a})})}getAvailableVideoTracks(e,t){let r=e.video.storedSettings,i=E(r)?void 0:r.adaptation.id;return ft(e.period,"video").map(a=>{let s=i===null?!1:i===a.id,d=ko(a,t),u=d.trickModeTracks!==void 0?d.trickModeTracks.map(c=>{let f=i===null?!1:i===c.id;return G(c,{active:f})}):[],l=G(d,{active:s});return u!==void 0&&(l.trickModeTracks=u),l})}getLockedAudioRepresentations(e){let{storedSettings:t}=e.audio;if(E(t))return null;let r=t.lockedRepresentations.getValue();return r===null?null:r.representationIds}getLockedVideoRepresentations(e){let{storedSettings:t}=e.video;if(E(t))return null;let r=t.lockedRepresentations.getValue();return r===null?null:r.representationIds}lockAudioRepresentations(e,t){var s;let{storedSettings:r}=e.audio;if(E(r))return;let{DEFAULT_AUDIO_REPRESENTATIONS_SWITCHING_MODE:i}=U.getCurrent(),o=this._getRepresentationsToLock(r.adaptation,t.representations),a=(s=t.switchingMode)!=null?s:i;r.lockedRepresentations.setValue({representationIds:o,switchingMode:a})}lockVideoRepresentations(e,t){var s;let{storedSettings:r}=e.video;if(E(r))return;let{DEFAULT_VIDEO_REPRESENTATIONS_SWITCHING_MODE:i}=U.getCurrent(),o=this._getRepresentationsToLock(r.adaptation,t.representations),a=(s=t.switchingMode)!=null?s:i;r.lockedRepresentations.setValue({representationIds:o,switchingMode:a})}unlockAudioRepresentations(e){let{storedSettings:t}=e.audio;E(t)||t.lockedRepresentations.getValue()===null||t.lockedRepresentations.setValue(null)}unlockVideoRepresentations(e){let{storedSettings:t}=e.video;E(t)||t.lockedRepresentations.getValue()===null||t.lockedRepresentations.setValue(null)}dispose(){for(this._isDisposed=!0;;){let e=this._storedPeriodInfo.pop();if(e===void 0)return;e.isRemoved=!0}}_resetVideoTrackChoices(e){var r;for(let i=0;i<this._storedPeriodInfo.length;i++){let o=this._storedPeriodInfo[i];if(!E(o.video.storedSettings)){let a=o.video.storedSettings.adaptationBase;if(a!==null){let s=Da(a,this._isTrickModeTrackEnabled);o.video.storedSettings.adaptationBase=a,o.video.storedSettings.adaptation=s}}}let t=this._storedPeriodInfo.slice();for(let i=0;i<t.length;i++){let o=t[i].period,s=t[i].video.storedSettings;if(s!==void 0){if(this.trigger("trackUpdate",{period:Ft(o),trackType:"video",reason:e}),this._isDisposed)return;let d=lt(this._storedPeriodInfo,o.id);d!==void 0&&d.isPeriodAdvertised&&d.video.storedSettings===s&&((r=d.video.dispatcher)==null||r.updateTrack(s))}}}_removePeriodObject(e){h.CURRENT_ENV===h.DEV&&ee(e<this._storedPeriodInfo.length,"Invalid index for Period removal");let t=this._storedPeriodInfo[e];this._storedPeriodInfo[e].isRemoved=!0,this._storedPeriodInfo.splice(e,1),this._cachedPeriodInfo.set(t.period,t)}_getRepresentationsToLock(e,t){let r=t.reduce((i,o)=>{let a=Z(e.representations,s=>s.id===o);return a===void 0?m.warn("API: Wanted locked Representation not found."):i.push(a.id),i},[]);if(r.length===0)throw new Error("Cannot lock Representations: None of the given Representation id are found");return r}_selectInitialTrackIfNeeded(){var i,o,a,s;let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:e}=U.getCurrent(),t=[],r=[];for(let d of this._storedPeriodInfo){let{period:u}=d;if(d.audio.storedSettings!==void 0&&d.video.storedSettings!==void 0&&d.text.storedSettings!==void 0)continue;let l=[...(i=u.adaptations.audio)!=null?i:[],...(o=u.adaptations.video)!=null?o:[]],c=l.every(b=>b.supportStatus.hasCodecWithUndefinedSupport);if(l.length>0&&c)continue;let f=ft(u,"audio")[0];d.audio.storedSettings=f===void 0?null:{adaptation:f,switchingMode:this._defaultAudioTrackSwitchingMode,lockedRepresentations:new H(null)};let g=ft(u,"video")[0],p=Da(g,this._isTrickModeTrackEnabled);d.video.storedSettings=p===void 0?null:{adaptation:p,adaptationBase:g,switchingMode:e,lockedRepresentations:new H(null)};let I=null,y=((a=u.adaptations.text)!=null?a:[]).filter(b=>b.isForcedSubtitles===!0);if(y.length>0){if(f!=null){let b=Z(y,T=>T.normalizedLanguage===f.normalizedLanguage);b!==void 0&&(I=b)}I===null&&(I=(s=Z(y,b=>b.normalizedLanguage===void 0))!=null?s:null)}d.text.storedSettings=I===null?null:{adaptation:I,switchingMode:"direct",lockedRepresentations:new H(null)},r.push(d),this._shouldAdvertisePeriod(d)&&(d.isPeriodAdvertised=!0,t.push({id:u.id,start:u.start,end:u.end}))}if(!(t.length>0&&(this.trigger("newAvailablePeriods",t),this._isDisposed)))for(let d of r){if(!d.isPeriodAdvertised)continue;let u=["audio","video","text"];for(let l of u){let c=d[l];if(c.dispatcher!==null&&c.storedSettings!==void 0&&!c.dispatcher.hasSetTrack()&&(c.dispatcher.updateTrack(c.storedSettings),this._isDisposed))return}}}_shouldAdvertisePeriod(e){return!e.isPeriodAdvertised&&e.text.dispatcher!==null&&e.video.dispatcher!==null&&e.audio.dispatcher!==null}};function Tb(n,e){for(let t=0;t<n.length;t++)if(n[t].period.id===e.id)return t}function lt(n,e){for(let t=0;t<n.length;t++){let r=n[t];if(r.period.id===e)return r}}function Ml(n){var e,t,r;return!n.inManifest&&((e=n.text)==null?void 0:e.dispatcher)===null&&((t=n.audio)==null?void 0:t.dispatcher)===null&&((r=n.video)==null?void 0:r.dispatcher)===null}function Da(n,e){var t;return e&&((t=n.trickModeTracks)==null?void 0:t[0])!==void 0?n.trickModeTracks[0]:n}function Al(n,e){return{period:n,inManifest:e,isPeriodAdvertised:!1,isRemoved:!1,audio:{storedSettings:void 0,dispatcher:null},video:{storedSettings:void 0,dispatcher:null},text:{storedSettings:void 0,dispatcher:null}}}function Ft(n){return{start:n.start,end:n.end,id:n.id}}var ep=co;function tp(n){let e,t,r,i,o,a,{DEFAULT_BASE_BANDWIDTH:s,DEFAULT_VIDEO_RESOLUTION_LIMIT:d,DEFAULT_MAX_BUFFER_AHEAD:u,DEFAULT_MAX_BUFFER_BEHIND:l,DEFAULT_MAX_VIDEO_BUFFER_SIZE:c,DEFAULT_THROTTLE_VIDEO_BITRATE_WHEN_HIDDEN:f,DEFAULT_WANTED_BUFFER_AHEAD:g}=U.getCurrent();if(E(n.maxBufferAhead))e=u;else if(e=Number(n.maxBufferAhead),isNaN(e))throw new Error("Invalid maxBufferAhead parameter. Should be a number.");if(E(n.maxBufferBehind))t=l;else if(t=Number(n.maxBufferBehind),isNaN(t))throw new Error("Invalid maxBufferBehind parameter. Should be a number.");if(E(n.wantedBufferAhead))r=g;else if(r=Number(n.wantedBufferAhead),isNaN(r))throw new Error("Invalid wantedBufferAhead parameter. Should be a number.");if(E(n.maxVideoBufferSize))i=c;else if(i=Number(n.maxVideoBufferSize),isNaN(i))throw new Error("Invalid maxVideoBufferSize parameter. Should be a number.");let p=E(n.videoResolutionLimit)?d:n.videoResolutionLimit,I=E(n.throttleVideoBitrateWhenHidden)?f:!!n.throttleVideoBitrateWhenHidden;if(E(n.videoElement))o=document.createElement("video");else if(n.videoElement.nodeName.toLowerCase()==="video"||n.videoElement.nodeName.toLowerCase()==="audio")o=n.videoElement;else throw new Error("Invalid videoElement parameter. Should be a HTMLMediaElement.");if(E(n.baseBandwidth))a=s;else if(a=Number(n.baseBandwidth),isNaN(a))throw new Error("Invalid baseBandwidth parameter. Should be a number.");return{maxBufferAhead:e,maxBufferBehind:t,videoResolutionLimit:p,videoElement:o,wantedBufferAhead:r,maxVideoBufferSize:i,throttleVideoBitrateWhenHidden:I,baseBandwidth:a}}function np(n){var e,t,r,i;if(n===null||typeof n!="object"&&n!==void 0)throw new Error("API: reload - Invalid options format.");if((n==null?void 0:n.reloadAt)===null||typeof(n==null?void 0:n.reloadAt)!="object"&&(n==null?void 0:n.reloadAt)!==void 0)throw new Error("API: reload - Invalid 'reloadAt' option format.");if(typeof((e=n==null?void 0:n.reloadAt)==null?void 0:e.position)!="number"&&((t=n==null?void 0:n.reloadAt)==null?void 0:t.position)!==void 0)throw new Error("API: reload - Invalid 'reloadAt.position' option format.");if(typeof((r=n==null?void 0:n.reloadAt)==null?void 0:r.relative)!="number"&&((i=n==null?void 0:n.reloadAt)==null?void 0:i.relative)!==void 0)throw new Error("API: reload - Invalid 'reloadAt.relative' option format.");if(!Array.isArray(n==null?void 0:n.keySystems)&&(n==null?void 0:n.keySystems)!==void 0)throw new Error("API: reload - Invalid 'keySystems' option format.");if((n==null?void 0:n.autoPlay)!==void 0&&typeof n.autoPlay!="boolean")throw new Error("API: reload - Invalid 'autoPlay' option format.")}function rp(n){var _,R,k;let e,t,r,i,o,a,s,{DEFAULT_AUTO_PLAY:d,DEFAULT_CODEC_SWITCHING_BEHAVIOR:u,DEFAULT_ENABLE_FAST_SWITCHING:l,DEFAULT_TEXT_TRACK_MODE:c}=U.getCurrent();if(E(n))throw new Error("No option set on loadVideo");if(!E(n.url))e=String(n.url);else if(E(n.initialManifest)&&E(n.manifestLoader))throw new Error("Unable to load a content: no url set on loadVideo.\nPlease provide at least either an `url` argument, a `initialManifest` option or a `manifestLoader` option so the RxPlayer can load the content.");if(E(n.transport))throw new Error("No transport set on loadVideo");t=String(n.transport);let f=E(n.autoPlay)?d:!!n.autoPlay;if(E(n.keySystems))r=[];else{r=Array.isArray(n.keySystems)?n.keySystems:[n.keySystems];for(let x of r)if(typeof x.type!="string"||typeof x.getLicense!="function")throw new Error("Invalid key system given: Missing type string or getLicense callback")}let g=n.lowLatencyMode===void 0?!1:!!n.lowLatencyMode,p=n.initialManifest,I=(_=n.minimumManifestUpdateInterval)!=null?_:0,y=(R=n.defaultAudioTrackSwitchingMode)!=null?R:void 0;y!==void 0&&!Q(["seamless","direct","reload"],y)&&(m.warn("The `defaultAudioTrackSwitchingMode` loadVideo option must match one of the following strategy name:\n- `seamless`\n- `direct`\n- `reload`"),y=void 0);let b=E(n.onCodecSwitch)?u:n.onCodecSwitch;if(Q(["continue","reload"],b)||(m.warn("The `onCodecSwitch` loadVideo option must match one of the following string:\n- `continue`\n- `reload`\nIf badly set, "+u+" will be used as default"),b=u),E(n.textTrackMode))i=c;else{if(n.textTrackMode!=="native"&&n.textTrackMode!=="html")throw new Error("Invalid textTrackMode.");i=n.textTrackMode}if(i==="html"){if(E(n.textTrackElement))throw new Error('You have to provide a textTrackElement in "html" textTrackMode.');if(n.textTrackElement instanceof HTMLElement)a=n.textTrackElement;else throw new Error("textTrackElement should be an HTMLElement.")}else E(n.textTrackElement)||m.warn('API: You have set a textTrackElement without being in an "html" textTrackMode. It will be ignored.');if(E(n.mode))o="auto";else{if(!Q(["auto","multithread","main"],n.mode))throw new Error("Invalid `mode` option.");o=n.mode}let T=E(n.enableFastSwitching)?l:n.enableFastSwitching;if(!E(n.startAt))if("wallClockTime"in n.startAt&&n.startAt.wallClockTime instanceof Date){let x=n.startAt.wallClockTime.getTime()/1e3;s=G({},n.startAt,{wallClockTime:x})}else s=n.startAt;let v=(k=n.requestConfig)!=null?k:{};return{__priv_patchLastSegmentInSidx:n.__priv_patchLastSegmentInSidx,__priv_manifestUpdateUrl:n.__priv_manifestUpdateUrl,checkMediaSegmentIntegrity:n.checkMediaSegmentIntegrity,checkManifestIntegrity:n.checkManifestIntegrity,autoPlay:f,defaultAudioTrackSwitchingMode:y,enableFastSwitching:T,initialManifest:p,keySystems:r,lowLatencyMode:g,manifestLoader:n.manifestLoader,minimumManifestUpdateInterval:I,requestConfig:v,onCodecSwitch:b,referenceDateTime:n.referenceDateTime,representationFilter:n.representationFilter,segmentLoader:n.segmentLoader,serverSyncInfos:n.serverSyncInfos,startAt:s,textTrackElement:a,textTrackMode:i,transport:t,mode:o,url:e,cmcd:n.cmcd}}function ip(n,e,t,r,i){if(i.isCancelled()||n===null)return;let o=e.getReference().getValue().seeking===2;o&&(t(),i.isCancelled())||e.listen(a=>{a.event==="seeking"?(o=!0,t()):o&&a.event==="seeked"&&(o=!1,r())},{includeLastObservation:!0,clearSignal:i})}function op(n,e,t,r){r.isCancelled()||n===null||(n.addEventListener("play",e),n.addEventListener("pause",t),r.register(()=>{n.removeEventListener("play",e),n.removeEventListener("pause",t)}))}function ap(n,e,t,r){let i=new H("LOADING",r);n.addEventListener("loaded",()=>{if(i.getValue()==="LOADING"){if(i.setValue("LOADED"),!r.isCancelled()){let s=xl(e,null);s!=="PAUSED"&&i.setValue(s)}}else i.getValue()==="RELOADING"?i.setValue(xl(e,null)):a(null)},r),n.addEventListener("reloadingMediaSource",()=>{sr(i.getValue())&&i.setValueIfChanged("RELOADING")},r);let o=null;return n.addEventListener("stalled",s=>{s!==o&&(a(s),o=s)},r),n.addEventListener("unstalled",()=>{o!==null&&(a(null),o=null)},r),t.listen(s=>{Q(["seeking","ended","play","pause"],s.event)&&a(o)},{clearSignal:r}),i;function a(s){if(!sr(i.getValue()))return;let d=xl(e,s);i.getValue()==="LOADED"&&d==="PAUSED"||i.setValueIfChanged(d)}}function xl(n,e){let{FORCED_ENDED_THRESHOLD:t}=U.getCurrent();if(n.ended)return"ENDED";if(e!==null){let r=Math.abs(n.duration-n.currentTime);return!E(t)&&r<t?"ENDED":e==="seeking"?"SEEKING":e==="freezing"?"FREEZING":"BUFFERING"}return n.paused?"PAUSED":"PLAYING"}function sr(n){return n!=="LOADING"&&n!=="RELOADING"&&n!=="STOPPED"}var _b=et(),Eb=["manifestLoader","segmentLoader"],Kt=class Kt extends re{static get ErrorTypes(){return Je}static get ErrorCodes(){return is}static get LogLevel(){return m.getLevel()}static set LogLevel(e){m.setLevel(e,m.getFormat())}static get LogFormat(){return m.getFormat()}static set LogFormat(e){m.setLevel(m.getLevel(),e)}static addFeatures(e){ia(e)}static _priv_registerVideoElement(e){Kt._priv_currentlyUsedVideoElements.has(e)&&console.warn(`The video element is already attached to another RxPlayer instance.
|
|
18
|
+
Make sure to dispose the previous instance with player.dispose() before creating a new player instance attaching that video element.`),Kt._priv_currentlyUsedVideoElements.add(e)}static _priv_deregisterVideoElement(e){Kt._priv_currentlyUsedVideoElements.has(e)&&Kt._priv_currentlyUsedVideoElements.delete(e)}constructor(e={}){super();let{baseBandwidth:t,videoResolutionLimit:r,maxBufferAhead:i,maxBufferBehind:o,throttleVideoBitrateWhenHidden:a,videoElement:s,wantedBufferAhead:d,maxVideoBufferSize:u}=tp(e);s.preload="auto",this.version="4.3.0-dev.2025012900",this.log=m,this.state="STOPPED",this.videoElement=s,Kt._priv_registerVideoElement(this.videoElement);let l=new B;this._destroyCanceller=l,this._priv_pictureInPictureRef=yc(s,l.signal),this._priv_speed=new H(s.playbackRate,this._destroyCanceller.signal),this._priv_preferTrickModeTracks=!1,this._priv_contentLock=new H(!1,this._destroyCanceller.signal),this._priv_bufferOptions={wantedBufferAhead:new H(d,this._destroyCanceller.signal),maxBufferAhead:new H(i,this._destroyCanceller.signal),maxBufferBehind:new H(o,this._destroyCanceller.signal),maxVideoBufferSize:new H(u,this._destroyCanceller.signal)},this._priv_bitrateInfos={lastBitrates:{audio:t,video:t}},this._priv_throttleVideoBitrateWhenHidden=a,this._priv_videoResolutionLimit=r,this._priv_currentError=null,this._priv_contentInfos=null,this._priv_contentEventsMemory={},this._priv_reloadingMetadata={},this._priv_lastAutoPlay=!1,this._priv_worker=null,this._priv_segmentSinkMetricsCallback=null;let c=()=>{this.trigger("volumeChange",{volume:s.volume,muted:s.muted})};s.addEventListener("volumechange",c),l.signal.register(()=>{s.removeEventListener("volumechange",c)})}attachWorker(e){return new Promise((t,r)=>{var a;if(!Pl())return m.warn("API: Cannot rely on a WebWorker: Worker API unavailable"),r(new On("INCOMPATIBLE_ERROR","Worker unavailable"));if(typeof e.workerUrl=="string")this._priv_worker=new Worker(e.workerUrl);else{let s=URL.createObjectURL(e.workerUrl);this._priv_worker=new Worker(s),URL.revokeObjectURL(s)}this._priv_worker.onerror=s=>{this._priv_worker!==null&&(this._priv_worker.terminate(),this._priv_worker=null),m.error("API: Unexpected worker error",s.error instanceof Error?s.error:void 0),r(new On("UNKNOWN_ERROR",'Unexpected Worker "error" event'))};let i=s=>{let d=s.data;d.type==="init-error"?(m.warn("API: Processing InitError worker message: detaching worker"),this._priv_worker!==null&&(this._priv_worker.removeEventListener("message",i),this._priv_worker.terminate(),this._priv_worker=null),r(new On("SETUP_ERROR","Worker parser initialization failed: "+d.value.errorMessage))):d.type==="init-success"&&(m.info("API: InitSuccess received from worker."),this._priv_worker!==null&&this._priv_worker.removeEventListener("message",i),t())};this._priv_worker.addEventListener("message",i),m.debug("---> Sending To Worker:","init"),this._priv_worker.postMessage({type:"init",value:{dashWasmUrl:e.dashWasmUrl,logLevel:m.getLevel(),logFormat:m.getFormat(),sendBackLogs:Dn(),date:Date.now(),timestamp:K(),hasVideo:((a=this.videoElement)==null?void 0:a.nodeName.toLowerCase())==="video",hasMseInWorker:$f}}),m.addEventListener("onLogLevelChange",s=>{this._priv_worker!==null&&(m.debug("---> Sending To Worker:","log-level-update"),this._priv_worker.postMessage({type:"log-level-update",value:{logLevel:s.level,logFormat:s.format,sendBackLogs:Dn()}}))},this._destroyCanceller.signal);let o=s=>{this._priv_worker!==null&&(m.debug("---> Sending To Worker:","config-update"),this._priv_worker.postMessage({type:"config-update",value:s}))};U.updated&&o(U.getCurrent()),U.addEventListener("update",o,this._destroyCanceller.signal)})}getCurrentModeInformation(){return this._priv_contentInfos===null?null:{isDirectFile:this._priv_contentInfos.isDirectFile,useWorker:this._priv_contentInfos.useWorker}}addEventListener(e,t){return super.addEventListener(e,t)}stop(){this._priv_contentInfos!==null&&this._priv_contentInfos.currentContentCanceller.cancel(),this._priv_cleanUpCurrentContentState(),this.state!=="STOPPED"&&this._priv_setPlayerState("STOPPED")}dispose(){this.stop(),this.videoElement!==null&&(Kt._priv_deregisterVideoElement(this.videoElement),Nn(this.videoElement).catch(e=>{let t=e instanceof Error?e.message:"Unknown error";m.error("API: Could not dispose decryption resources: "+t)})),this._destroyCanceller.cancel(),this._priv_reloadingMetadata={},this.videoElement=null,this._priv_worker!==null&&(this._priv_worker.terminate(),this._priv_worker=null)}loadVideo(e){let t=rp(e);m.info("API: Calling loadvideo",t.url,t.transport),this._priv_reloadingMetadata={options:t},this._priv_initializeContentPlayback(t),this._priv_lastAutoPlay=t.autoPlay}reload(e){var l,c,f;let{options:t,manifest:r,reloadPosition:i,reloadInPause:o}=this._priv_reloadingMetadata;if(t===void 0)throw new Error("API: Can't reload without having previously loaded a content.");np(e);let a;if(((l=e==null?void 0:e.reloadAt)==null?void 0:l.position)!==void 0)a={position:e.reloadAt.position};else if(((c=e==null?void 0:e.reloadAt)==null?void 0:c.relative)!==void 0){if(i===void 0)throw new Error("Can't reload to a relative position when previous content was not loaded.");a={position:e.reloadAt.relative+i}}else i!==void 0&&(a={position:i});let s;(e==null?void 0:e.autoPlay)!==void 0?s=e.autoPlay:o!==void 0&&(s=!o);let d;(e==null?void 0:e.keySystems)!==void 0?d=e.keySystems:((f=this._priv_reloadingMetadata.options)==null?void 0:f.keySystems)!==void 0&&(d=this._priv_reloadingMetadata.options.keySystems);let u=ue(oe({},t),{initialManifest:r});a!==void 0&&(u.startAt=a),s!==void 0&&(u.autoPlay=s),d!==void 0&&(u.keySystems=d),this._priv_initializeContentPlayback(u)}createDebugElement(e){if(me.createDebugElement===null)throw new Error("Feature `DEBUG_ELEMENT` not added to the RxPlayer");let t=new B;return me.createDebugElement(e,this,t.signal),{dispose(){t.cancel()}}}_priv_initializeContentPlayback(e){var q,W,se,ae,de,Se;let{autoPlay:t,cmcd:r,defaultAudioTrackSwitchingMode:i,enableFastSwitching:o,initialManifest:a,keySystems:s,lowLatencyMode:d,minimumManifestUpdateInterval:u,requestConfig:l,onCodecSwitch:c,startAt:f,transport:g,checkMediaSegmentIntegrity:p,checkManifestIntegrity:I,manifestLoader:y,referenceDateTime:b,segmentLoader:T,serverSyncInfos:v,mode:_,__priv_manifestUpdateUrl:R,__priv_patchLastSegmentInSidx:k,url:x}=e;if(this.videoElement===null)throw new Error("the attached video element is disposed");let M=g==="directfile",P=new B,N=this.videoElement,O,F=!1,A=null;if(M){if(me.directfile===null)throw this.stop(),this._priv_currentError=null,new Error("DirectFile feature not activated in your build.");if(E(x))throw new Error("No URL for a DirectFile content");if(m.info("API: Initializing DirectFile mode in the main thread"),A=this._priv_initializeMediaElementTracksStore(P.signal),P.isUsed())return;O=new me.directfile.initDirectFile({autoPlay:t,keySystems:s,speed:this._priv_speed,startAt:f,url:x})}else{let Y={lowLatencyMode:d,maxRetry:(q=l.manifest)==null?void 0:q.maxRetry,requestTimeout:(W=l.manifest)==null?void 0:W.timeout,connectionTimeout:(se=l.manifest)==null?void 0:se.connectionTimeout,minimumManifestUpdateInterval:u,initialManifest:a},ce=Cl(),ye={throttleBitrate:{},limitResolution:{}};this._priv_throttleVideoBitrateWhenHidden&&(ce?ye.throttleBitrate={video:dn(Ic(this._priv_pictureInPictureRef,P.signal),De=>De?1/0:0,P.signal)}:m.warn("API: Can't apply throttleVideoBitrateWhenHidden because browser can't be trusted for visibility.")),this._priv_videoResolutionLimit==="videoElement"?ce?ye.limitResolution={video:Sc(N,this._priv_pictureInPictureRef,P.signal)}:m.warn("API: Can't apply videoResolutionLimit because browser can't be trusted for video size."):this._priv_videoResolutionLimit==="screen"&&(ye.limitResolution={video:bc(P.signal)});let Vt={initialBitrates:this._priv_bitrateInfos.lastBitrates,lowLatencyMode:d,throttlers:ye},Qe=e.textTrackMode==="native"?{textTrackMode:"native"}:{textTrackMode:"html",textTrackElement:e.textTrackElement},Be=G({enableFastSwitching:o,onCodecSwitch:c},this._priv_bufferOptions),Et={lowLatencyMode:d,maxRetry:(ae=l.segment)==null?void 0:ae.maxRetry,requestTimeout:(de=l.segment)==null?void 0:de.timeout,connectionTimeout:(Se=l.segment)==null?void 0:Se.connectionTimeout},yt=me.multithread!==null&&this._priv_worker!==null&&g==="dash"&&Eb.every(De=>E(e[De]))&&typeof e.representationFilter!="function";if(_==="main"||_==="auto"&&!yt){if(me.mainThreadMediaSourceInit===null)throw new Error("Cannot load video, neither in a WebWorker nor with the `MEDIA_SOURCE_MAIN` feature");let De=me.transports[g];if(typeof De!="function")throw this.stop(),this._priv_currentError=null,new Error(`transport "${g}" not supported`);let dp=typeof e.representationFilter=="string"?pc(e.representationFilter):e.representationFilter;m.info("API: Initializing MediaSource mode in the main thread");let up=De({lowLatencyMode:d,checkMediaSegmentIntegrity:p,checkManifestIntegrity:I,manifestLoader:y,referenceDateTime:b,representationFilter:dp,segmentLoader:T,serverSyncInfos:v,__priv_manifestUpdateUrl:R,__priv_patchLastSegmentInSidx:k});O=new me.mainThreadMediaSourceInit({adaptiveOptions:Vt,autoPlay:t,bufferOptions:Be,cmcd:r,keySystems:s,lowLatencyMode:d,transport:up,manifestRequestSettings:Y,segmentRequestOptions:Et,speed:this._priv_speed,startAt:f,textTrackOptions:Qe,url:x})}else{if(me.multithread===null)throw new Error("Cannot load video in multithread mode: `MULTI_THREAD` feature not imported.");if(this._priv_worker===null)throw new Error("Cannot load video in multithread mode: `attachWorker` method not called.");ee(typeof e.representationFilter!="function"),F=!0,m.info("API: Initializing MediaSource mode in a WebWorker");let De={lowLatencyMode:d,checkMediaSegmentIntegrity:p,checkManifestIntegrity:I,referenceDateTime:b,serverSyncInfos:v,manifestLoader:void 0,segmentLoader:void 0,representationFilter:e.representationFilter,__priv_manifestUpdateUrl:R,__priv_patchLastSegmentInSidx:k};O=new me.multithread.init({adaptiveOptions:Vt,autoPlay:t,bufferOptions:Be,cmcd:r,keySystems:s,lowLatencyMode:d,transportOptions:De,manifestRequestSettings:Y,segmentRequestOptions:Et,speed:this._priv_speed,startAt:f,textTrackOptions:Qe,worker:this._priv_worker,url:x})}}let C={contentId:_b(),originalUrl:x,currentContentCanceller:P,defaultAudioTrackSwitchingMode:i,initializer:O,isDirectFile:M,manifest:null,currentPeriod:null,activeAdaptations:null,activeRepresentations:null,tracksStore:null,mediaElementTracksStore:A,useWorker:F};O.addEventListener("error",Y=>{this._priv_onFatalError(Y,C)}),O.addEventListener("warning",Y=>{let ce=Oe(Y,{defaultCode:"NONE",defaultReason:"An unknown error happened."});m.warn("API: Sending warning:",ce),this.trigger("warning",ce)}),O.addEventListener("reloadingMediaSource",Y=>{C.tracksStore!==null&&C.tracksStore.resetPeriodObjects(),this._priv_segmentSinkMetricsCallback=null,this._priv_lastAutoPlay=Y.autoPlay}),O.addEventListener("inbandEvents",Y=>this.trigger("inbandEvents",Y)),O.addEventListener("streamEvent",Y=>this.trigger("streamEvent",Y)),O.addEventListener("streamEventSkip",Y=>this.trigger("streamEventSkip",Y)),O.addEventListener("activePeriodChanged",Y=>this._priv_onActivePeriodChanged(C,Y)),O.addEventListener("periodStreamReady",Y=>this._priv_onPeriodStreamReady(C,Y)),O.addEventListener("periodStreamCleared",Y=>this._priv_onPeriodStreamCleared(C,Y)),O.addEventListener("representationChange",Y=>this._priv_onRepresentationChange(C,Y)),O.addEventListener("adaptationChange",Y=>this._priv_onAdaptationChange(C,Y)),O.addEventListener("bitrateEstimateChange",Y=>this._priv_onBitrateEstimateChange(Y)),O.addEventListener("manifestReady",Y=>this._priv_onManifestReady(C,Y)),O.addEventListener("manifestUpdate",Y=>this._priv_onManifestUpdate(C,Y)),O.addEventListener("codecSupportUpdate",()=>this._priv_onCodecSupportUpdate(C)),O.addEventListener("decipherabilityUpdate",Y=>this._priv_onDecipherabilityUpdate(C,Y)),O.addEventListener("loaded",Y=>{this._priv_segmentSinkMetricsCallback=Y.getSegmentSinkMetrics}),O.prepare(),this.stop();let D=new uo(N,{withMediaSource:!M,lowLatencyMode:d});P.signal.register(()=>{D.stop()});let L=ap(O,N,D,P.signal);P.signal.register(()=>{O.dispose()});let V=Y=>{switch(Y){case"STOPPED":case"RELOADING":case"LOADING":break;case"ENDED":this._priv_reloadingMetadata.reloadInPause=!0,this._priv_reloadingMetadata.reloadPosition=D.getReference().getValue().position.getPolled();break;default:{let ce=D.getReference().getValue();this._priv_reloadingMetadata.reloadInPause=ce.paused,this._priv_reloadingMetadata.reloadPosition=ce.position.getWanted();break}}},$=null,j=Y=>{$!==null&&($.cancel(),$=null),L.onUpdate((ce,ye)=>{sr(ce)&&(ye(),$!==null&&$.cancel(),$=new B,$.linkToSignal(P.signal),Y!==!N.paused&&(N.paused?this.trigger("pause",null):this.trigger("play",null)),op(N,()=>this.trigger("play",null),()=>this.trigger("pause",null),P.signal))},{emitCurrentValue:!1,clearSignal:P.signal})};j(t),O.addEventListener("reloadingMediaSource",Y=>{j(Y.autoPlay)}),this._priv_currentError=null,this._priv_contentInfos=C;let z=null;L.onUpdate(Y=>{V(Y),this._priv_setPlayerState(Y),!P.isUsed()&&(z!==null?sr(this.state)||(z.cancel(),z=null):sr(this.state)&&(z=new B,z.linkToSignal(P.signal),ip(N,D,()=>this.trigger("seeking",null),()=>this.trigger("seeked",null),z.signal)))},{emitCurrentValue:!0,clearSignal:P.signal}),D.listen(Y=>{V(this.state),this._priv_triggerPositionUpdate(C,Y)},{clearSignal:P.signal}),P.signal.register(()=>{O.removeEventListener()}),this._priv_contentLock.onUpdate((Y,ce)=>{Y||(ce(),O.start(N,D))},{emitCurrentValue:!0,clearSignal:P.signal})}getError(){return this._priv_currentError}getVideoElement(){return this.videoElement}getPlayerState(){return this.state}isContentLoaded(){return!Q(["LOADING","RELOADING","STOPPED"],this.state)}isBuffering(){return Q(["BUFFERING","SEEKING","LOADING","RELOADING"],this.state)}isPaused(){return this.videoElement!==null?Q(["LOADING","RELOADING"],this.state)?!this._priv_lastAutoPlay:this.videoElement.paused:!0}isLive(){if(this._priv_contentInfos===null)return!1;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;return e||t===null?!1:t.isLive}areTrickModeTracksEnabled(){return this._priv_preferTrickModeTracks}getContentUrls(){if(this._priv_contentInfos===null)return;let{isDirectFile:e,manifest:t,originalUrl:r}=this._priv_contentInfos;if(e)return r===void 0?void 0:[r];if(t!==null)return t.uris}updateContentUrls(e,t){if(this._priv_contentInfos===null)throw new Error("No content loaded");let r=(t==null?void 0:t.refresh)===!0;this._priv_contentInfos.initializer.updateContentUrls(e,r)}getMediaDuration(){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.duration}getCurrentBufferGap(){if(this.videoElement===null)throw new Error("Disposed player");let e=this.videoElement,t=Xl(e.buffered,e.currentTime);return t===1/0?0:t}getWallClockTime(){var r;if(this.videoElement===null)throw new Error("Disposed player");if(this._priv_contentInfos===null)return this.videoElement.currentTime;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;if(e){let i=so(this.videoElement);return(i!=null?i:0)+this.videoElement.currentTime}if(t!==null){let i=this.videoElement.currentTime,o=(r=t.availabilityStartTime)!=null?r:0;return i+o}return 0}getPosition(){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.currentTime}getLastStoredContentPosition(){return this._priv_reloadingMetadata.reloadPosition}getPlaybackRate(){return this._priv_speed.getValue()}setPlaybackRate(e,t){var o;e!==this._priv_speed.getValue()&&this._priv_speed.setValue(e);let r=t==null?void 0:t.preferTrickModeTracks;if(typeof r!="boolean")return;this._priv_preferTrickModeTracks=r;let i=(o=this._priv_contentInfos)==null?void 0:o.tracksStore;E(i)||(r&&!i.isTrickModeEnabled()?i.enableVideoTrickModeTracks():!r&&i.isTrickModeEnabled()&&i.disableVideoTrickModeTracks())}getVideoRepresentation(){let e=this.__priv_getCurrentRepresentations();if(e!==null)return e.video}getAudioRepresentation(){let e=this.__priv_getCurrentRepresentations();if(e!==null)return e.audio}play(){if(this.videoElement===null)throw new Error("Disposed player");let e=this.videoElement.play();return E(e)||typeof e.catch!="function"?Promise.resolve():e.catch(t=>{if(t.name==="NotAllowedError"){let r=new te("MEDIA_ERR_PLAY_NOT_ALLOWED",t.toString());this.trigger("warning",r)}throw t})}pause(){if(this.videoElement===null)throw new Error("Disposed player");this.videoElement.pause()}seekTo(e){var o;if(this.videoElement===null)throw new Error("Disposed player");if(this._priv_contentInfos===null)throw new Error("player: no content loaded");let{isDirectFile:t,manifest:r}=this._priv_contentInfos;if(!t&&r===null)throw new Error("player: the content did not load yet");let i;if(typeof e=="number")i=e;else if(typeof e=="object"){let a=e,s=this.videoElement.currentTime;if(!E(a.relative))i=s+a.relative;else if(!E(a.position))i=a.position;else{if(E(a.wallClockTime))throw new Error('invalid time object. You must set one of the following properties: "relative", "position" or "wallClockTime"');if(r!==null)i=a.wallClockTime-((o=r.availabilityStartTime)!=null?o:0);else if(t&&this.videoElement!==null){let d=so(this.videoElement);d!==void 0&&(i=a.wallClockTime-d)}i===void 0&&(i=a.wallClockTime)}}if(i===void 0)throw new Error("invalid time given");return m.info("API: API Seek to",i),this.videoElement.currentTime=i,i}getVolume(){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.volume}setVolume(e){if(this.videoElement===null)throw new Error("Disposed player");let t=this.videoElement;e!==t.volume&&(t.volume=e)}isMute(){var e;return((e=this.videoElement)==null?void 0:e.muted)===!0}mute(){if(this.videoElement===null)throw new Error("Disposed player");this.videoElement.muted||(this.videoElement.muted=!0)}unMute(){if(this.videoElement===null)throw new Error("Disposed player");this.videoElement.muted&&(this.videoElement.muted=!1)}setMaxBufferBehind(e){this._priv_bufferOptions.maxBufferBehind.setValue(e)}setMaxBufferAhead(e){this._priv_bufferOptions.maxBufferAhead.setValue(e)}setWantedBufferAhead(e){this._priv_bufferOptions.wantedBufferAhead.setValue(e)}setMaxVideoBufferSize(e){this._priv_bufferOptions.maxVideoBufferSize.setValue(e)}getMaxBufferBehind(){return this._priv_bufferOptions.maxBufferBehind.getValue()}getMaxBufferAhead(){return this._priv_bufferOptions.maxBufferAhead.getValue()}getWantedBufferAhead(){return this._priv_bufferOptions.wantedBufferAhead.getValue()}getMaxVideoBufferSize(){return this._priv_bufferOptions.maxVideoBufferSize.getValue()}getCurrentPeriod(){var t;let e=(t=this._priv_contentInfos)==null?void 0:t.currentPeriod;return E(e)?null:{id:e.id,start:e.start,end:e.end}}getKeySystemConfiguration(){if(this.videoElement===null)throw new Error("Disposed player");let e=Hn(this.videoElement);return e===null?null:{keySystem:e[0],configuration:e[1]}}getAvailablePeriods(){if(this._priv_contentInfos===null)return[];let{isDirectFile:e,tracksStore:t}=this._priv_contentInfos;return e?[]:t===null?[]:t.getAvailablePeriods().slice()}getAvailableAudioTracks(e){var a,s;if(this._priv_contentInfos===null)return[];let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return(a=r==null?void 0:r.getAvailableAudioTracks())!=null?a:[];let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(s=e==null?void 0:e.filterPlayableRepresentations)!=null?s:!0),this._priv_callTracksStoreGetterSetter(i,[],(d,u)=>{var l;return(l=d.getAvailableAudioTracks(u,o))!=null?l:[]})}getAvailableTextTracks(e){var i;if(this._priv_contentInfos===null)return[];let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t?(i=r==null?void 0:r.getAvailableTextTracks())!=null?i:[]:this._priv_callTracksStoreGetterSetter(e,[],(o,a)=>{var s;return(s=o.getAvailableTextTracks(a))!=null?s:[]})}getAvailableVideoTracks(e){var a,s;if(this._priv_contentInfos===null)return[];let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return(a=r==null?void 0:r.getAvailableVideoTracks())!=null?a:[];let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(s=e==null?void 0:e.filterPlayableRepresentations)!=null?s:!0),this._priv_callTracksStoreGetterSetter(i,[],(d,u)=>{var l;return(l=d.getAvailableVideoTracks(u,o))!=null?l:[]})}getAudioTrack(e){var a;if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return r===null?void 0:r.getChosenAudioTrack();let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(a=e==null?void 0:e.filterPlayableRepresentations)!=null?a:!0),this._priv_callTracksStoreGetterSetter(i,void 0,(s,d)=>s.getChosenAudioTrack(d,o))}getTextTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t?r===null?void 0:r.getChosenTextTrack():this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.getChosenTextTrack(o))}getVideoTrack(e){var a;if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)return r===null?void 0:r.getChosenVideoTrack();let i,o=!0;return typeof e=="string"?i=e:(i=e==null?void 0:e.periodId,o=(a=e==null?void 0:e.filterPlayableRepresentations)!=null?a:!0),this._priv_callTracksStoreGetterSetter(i,void 0,(s,d)=>s.getChosenVideoTrack(d,o))}setAudioTrack(e){var u;if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)try{let l=typeof e=="string"?e:e.trackId;r==null||r.setAudioTrackById(l);return}catch(l){throw new Error("player: unknown audio track")}let i,o,a,s=null,d;return typeof e=="string"?o=e:(o=e.trackId,i=e.periodId,a=e.switchingMode,s=(u=e.lockedRepresentations)!=null?u:null,d=e.relativeResumingPosition),this._priv_callTracksStoreGetterSetter(i,void 0,(l,c)=>l.setAudioTrack({periodRef:c,trackId:o,switchingMode:a,lockedRepresentations:s,relativeResumingPosition:d}))}setTextTrack(e){if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)try{let a=typeof e=="string"?e:e.trackId;r==null||r.setTextTrackById(a);return}catch(a){throw new Error("player: unknown text track")}let i,o;return typeof e=="string"?o=e:(o=e.trackId,i=e.periodId),this._priv_callTracksStoreGetterSetter(i,void 0,(a,s)=>a.setTextTrack(s,o))}disableTextTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t){r==null||r.disableTextTrack();return}return this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.disableTrack(o,"text"))}setVideoTrack(e){var u;if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;if(t)try{let l=typeof e=="string"?e:e.trackId;r==null||r.setVideoTrackById(l);return}catch(l){throw new Error("player: unknown video track")}let i,o,a,s=null,d;return typeof e=="string"?o=e:(o=e.trackId,i=e.periodId,a=e.switchingMode,s=(u=e.lockedRepresentations)!=null?u:null,d=e.relativeResumingPosition),this._priv_callTracksStoreGetterSetter(i,void 0,(l,c)=>l.setVideoTrack({periodRef:c,trackId:o,switchingMode:a,lockedRepresentations:s,relativeResumingPosition:d}))}disableVideoTrack(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t,mediaElementTracksStore:r}=this._priv_contentInfos;return t&&r!==null?r.disableVideoTrack():this._priv_callTracksStoreGetterSetter(e,void 0,(i,o)=>i.disableTrack(o,"video"))}lockVideoRepresentations(e){if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t}=this._priv_contentInfos;if(t)throw new Error("Cannot lock video Representations in directfile mode.");let r,i,o;return Array.isArray(e)?(r=e,i=void 0):(r=e.representations,i=e.periodId,o=e.switchingMode),this._priv_callTracksStoreGetterSetter(i,void 0,(a,s)=>a.lockVideoRepresentations(s,{representations:r,switchingMode:o}))}lockAudioRepresentations(e){if(this._priv_contentInfos===null)throw new Error("No content loaded");let{isDirectFile:t}=this._priv_contentInfos;if(t)throw new Error("Cannot lock audio Representations in directfile mode.");let r,i,o;return Array.isArray(e)?(r=e,i=void 0):(r=e.representations,i=e.periodId,o=e.switchingMode),this._priv_callTracksStoreGetterSetter(i,void 0,(a,s)=>a.lockAudioRepresentations(s,{representations:r,switchingMode:o}))}getLockedVideoRepresentations(e){if(this._priv_contentInfos===null)return null;let{isDirectFile:t}=this._priv_contentInfos;return t?null:this._priv_callTracksStoreGetterSetter(e,null,(r,i)=>r.getLockedVideoRepresentations(i))}getLockedAudioRepresentations(e){if(this._priv_contentInfos===null)return null;let{isDirectFile:t}=this._priv_contentInfos;return t?null:this._priv_callTracksStoreGetterSetter(e,null,(r,i)=>r.getLockedAudioRepresentations(i))}unlockVideoRepresentations(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t}=this._priv_contentInfos;if(!t)return this._priv_callTracksStoreGetterSetter(e,void 0,(r,i)=>r.unlockVideoRepresentations(i))}unlockAudioRepresentations(e){if(this._priv_contentInfos===null)return;let{isDirectFile:t}=this._priv_contentInfos;if(!t)return this._priv_callTracksStoreGetterSetter(e,void 0,(r,i)=>r.unlockAudioRepresentations(i))}getMinimumPosition(){if(this._priv_contentInfos===null)return null;if(this._priv_contentInfos.isDirectFile)return 0;let{manifest:e}=this._priv_contentInfos;return e!==null?gn(e):null}getLivePosition(){if(this._priv_contentInfos===null)return null;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;if(!e)return(t==null?void 0:t.isLive)!==!0?null:hn(t)}getMaximumPosition(){if(this._priv_contentInfos===null)return null;let{isDirectFile:e,manifest:t}=this._priv_contentInfos;if(e){if(this.videoElement===null)throw new Error("Disposed player");return this.videoElement.duration}return t!==null?!t.isDynamic&&this.videoElement!==null?this.videoElement.duration:bt(t):null}async __priv_getSegmentSinkMetrics(){if(this._priv_segmentSinkMetricsCallback!==null)return this._priv_segmentSinkMetricsCallback()}__priv_getManifest(){return this._priv_contentInfos===null?null:this._priv_contentInfos.manifest}__priv_getCurrentAdaptation(){if(this._priv_contentInfos===null)return null;let{currentPeriod:e,activeAdaptations:t}=this._priv_contentInfos;return e===null||t===null||E(t[e.id])?null:t[e.id]}__priv_getCurrentRepresentations(){if(this._priv_contentInfos===null)return null;let{currentPeriod:e,activeRepresentations:t}=this._priv_contentInfos;return e===null||t===null||E(t[e.id])?null:t[e.id]}_priv_cleanUpCurrentContentState(){var t,r,i,o;m.debug("Locking `contentLock` to clean-up the current content."),this._priv_contentLock.setValue(!0),(r=(t=this._priv_contentInfos)==null?void 0:t.tracksStore)==null||r.dispose(),(o=(i=this._priv_contentInfos)==null?void 0:i.mediaElementTracksStore)==null||o.dispose(),this._priv_contentInfos=null,this._priv_segmentSinkMetricsCallback=null,this._priv_contentEventsMemory={};let e=()=>{this.videoElement!==null&&(m.debug("Unlocking `contentLock`. Next content can begin."),this._priv_contentLock.setValue(!1))};E(this.videoElement)?e():Co(this.videoElement).then(()=>{m.debug("API: DRM session cleaned-up with success!"),e()},a=>{m.error("API: An error arised when trying to clean-up the DRM session:"+(a instanceof Error?a.toString():"Unknown Error")),e()})}_priv_onManifestReady(e,t){var i;if(e.contentId!==((i=this._priv_contentInfos)==null?void 0:i.contentId))return;e.manifest=t,t.manifestFormat===0&&(this._priv_reloadingMetadata.manifest=t);let r=new ep({preferTrickModeTracks:this._priv_preferTrickModeTracks,defaultAudioTrackSwitchingMode:e.defaultAudioTrackSwitchingMode});e.tracksStore=r,r.addEventListener("newAvailablePeriods",o=>{this.trigger("newAvailablePeriods",o)}),r.addEventListener("brokenRepresentationsLock",o=>{this.trigger("brokenRepresentationsLock",o)}),r.addEventListener("trackUpdate",o=>{var s,d;this.trigger("trackUpdate",o);let a=(d=(s=this._priv_contentInfos)==null?void 0:s.currentPeriod)!=null?d:void 0;o.reason==="no-playable-representation"&&o.period.id===(a==null?void 0:a.id)&&this._priv_onAvailableTracksMayHaveChanged(o.trackType)}),e.tracksStore.addEventListener("warning",o=>{this.trigger("warning",o)}),e.tracksStore.addEventListener("error",o=>{this._priv_onFatalError(o,e)}),e.tracksStore.onManifestUpdate(t)}_priv_onManifestUpdate(e,t){var o,a,s;if(this._priv_contentInfos===null||this._priv_contentInfos.manifest===null)return;E(e==null?void 0:e.tracksStore)||e.tracksStore.onManifestUpdate(this._priv_contentInfos.manifest);let r=(a=(o=this._priv_contentInfos)==null?void 0:o.currentPeriod)!=null?a:void 0,i=(s=this._priv_contentInfos)==null?void 0:s.tracksStore;if(!(r===void 0||E(i))){for(let d of t.updatedPeriods)if(d.period.id===r.id&&(d.result.addedAdaptations.length>0||d.result.removedAdaptations.length>0)){if(i.getPeriodObjectFromPeriod(r)===void 0)return;this._priv_onAvailableTracksMayHaveChanged("audio"),this._priv_onAvailableTracksMayHaveChanged("text"),this._priv_onAvailableTracksMayHaveChanged("video")}}}_priv_onCodecSupportUpdate(e){let t=e==null?void 0:e.tracksStore;E(t)||t.onManifestCodecSupportUpdate()}_priv_onDecipherabilityUpdate(e,t){if(e===null||e.manifest===null)return;E(e==null?void 0:e.tracksStore)||e.tracksStore.onDecipherabilityUpdates();let r=t.reduce((i,o)=>{var s,d,u;if(!(Z(i,l=>l[0].id===o.period.id&&l[1]===o.adaptation.type)!==void 0)){let l=e.tracksStore;if(l===null)return i;let c=!1,f=l.getPeriodObjectFromPeriod(o.period);if(f===void 0)return i;switch(o.adaptation.type){case"audio":c=((s=l.getChosenAudioTrack(f,!1))==null?void 0:s.id)===o.adaptation.id;break;case"video":c=((d=l.getChosenVideoTrack(f,!1))==null?void 0:d.id)===o.adaptation.id;break;case"text":c=((u=l.getChosenTextTrack(f))==null?void 0:u.id)===o.adaptation.id;break}c&&i.push([o.period,o.adaptation.type])}return i},[]);for(let[i,o]of r)this._priv_triggerEventIfNotStopped("representationListUpdate",{period:{start:i.start,end:i.end,id:i.id},trackType:o,reason:"decipherability-update"},e.currentContentCanceller.signal)}_priv_onActivePeriodChanged(e,{period:t}){var s,d,u,l,c,f;if(e.contentId!==((s=this._priv_contentInfos)==null?void 0:s.contentId))return;e.currentPeriod=t;let r=e.currentContentCanceller.signal;this._priv_contentEventsMemory.periodChange!==t&&(this._priv_contentEventsMemory.periodChange=t,this._priv_triggerEventIfNotStopped("periodChange",{start:t.start,end:t.end,id:t.id},r)),this._priv_triggerEventIfNotStopped("availableAudioTracksChange",this.getAvailableAudioTracks(),r),this._priv_triggerEventIfNotStopped("availableTextTracksChange",this.getAvailableTextTracks(),r),this._priv_triggerEventIfNotStopped("availableVideoTracksChange",this.getAvailableVideoTracks(),r);let i=(d=this._priv_contentInfos)==null?void 0:d.tracksStore;if(E(i))this._priv_triggerEventIfNotStopped("audioTrackChange",null,r),this._priv_triggerEventIfNotStopped("textTrackChange",null,r),this._priv_triggerEventIfNotStopped("videoTrackChange",null,r);else{let g=i.getPeriodObjectFromPeriod(t);if(g!==void 0){let p=i.getChosenAudioTrack(g,!0);this._priv_triggerEventIfNotStopped("audioTrackChange",p,r);let I=i.getChosenTextTrack(g);this._priv_triggerEventIfNotStopped("textTrackChange",I,r);let y=i.getChosenVideoTrack(g,!0);this._priv_triggerEventIfNotStopped("videoTrackChange",y,r)}}let o=(l=(u=this.__priv_getCurrentRepresentations())==null?void 0:u.audio)!=null?l:null;this._priv_triggerEventIfNotStopped("audioRepresentationChange",o,r);let a=(f=(c=this.__priv_getCurrentRepresentations())==null?void 0:c.video)!=null?f:null;this._priv_triggerEventIfNotStopped("videoRepresentationChange",a,r)}_priv_onPeriodStreamReady(e,t){var s;if(e.contentId!==((s=this._priv_contentInfos)==null?void 0:s.contentId))return;let{type:r,period:i,adaptationRef:o}=t,a=e.tracksStore;switch(r){case"video":case"audio":case"text":E(a)?(m.error(`API: TracksStore not instanciated for a new ${r} period`),o.setValue(null)):a.addTrackReference(r,i,o);break;default:Xe(r)}}_priv_onPeriodStreamCleared(e,t){var d;if(e.contentId!==((d=this._priv_contentInfos)==null?void 0:d.contentId))return;let{type:r,period:i}=t,o=e.tracksStore;switch(r){case"audio":case"text":case"video":E(o)||o.removeTrackReference(r,i);break}let{activeAdaptations:a,activeRepresentations:s}=e;if(!E(a)&&!E(a[i.id])){let u=a[i.id];delete u[r],Object.keys(u).length===0&&delete a[i.id]}if(!E(s)&&!E(s[i.id])){let u=s[i.id];delete u[r],Object.keys(u).length===0&&delete s[i.id]}}_priv_onAdaptationChange(e,{type:t,adaptation:r,period:i}){var l;if(e.contentId!==((l=this._priv_contentInfos)==null?void 0:l.contentId))return;e.activeAdaptations===null&&(e.activeAdaptations={});let{activeAdaptations:o,currentPeriod:a}=e,s=o[i.id];E(s)?o[i.id]={[t]:r}:s[t]=r;let{tracksStore:d}=e,u=e.currentContentCanceller.signal;if(d!==null&&a!==null&&!E(i)&&i.id===a.id){let c=d.getPeriodObjectFromPeriod(i);if(c===void 0)return;switch(t){case"audio":{let f=d.getChosenAudioTrack(c,!0);this._priv_triggerEventIfNotStopped("audioTrackChange",f,u);break}case"text":{let f=d.getChosenTextTrack(c);this._priv_triggerEventIfNotStopped("textTrackChange",f,u);break}case"video":{let f=d.getChosenVideoTrack(c,!0);this._priv_triggerEventIfNotStopped("videoTrackChange",f,u);break}}}}_priv_onRepresentationChange(e,{type:t,period:r,representation:i}){var d;if(e.contentId!==((d=this._priv_contentInfos)==null?void 0:d.contentId))return;e.activeRepresentations===null&&(e.activeRepresentations={});let{activeRepresentations:o,currentPeriod:a}=e,s=o[r.id];if(E(s)?o[r.id]={[t]:i}:s[t]=i,!E(r)&&a!==null&&a.id===r.id){let u=this._priv_contentInfos.currentContentCanceller.signal;t==="video"?this._priv_triggerEventIfNotStopped("videoRepresentationChange",i,u):t==="audio"&&this._priv_triggerEventIfNotStopped("audioRepresentationChange",i,u)}}_priv_onBitrateEstimateChange({type:e,bitrate:t}){t!==void 0&&(this._priv_bitrateInfos.lastBitrates[e]=t),this.trigger("__priv_bitrateEstimateChange",{type:e,bitrate:t})}_priv_setPlayerState(e){this.state!==e&&(this.state=e,m.info("API: playerStateChange event",e),this.trigger("playerStateChange",e))}_priv_triggerPositionUpdate(e,t){var s,d;if(e.contentId!==((s=this._priv_contentInfos)==null?void 0:s.contentId))return;let{isDirectFile:r,manifest:i}=e;if(!r&&i===null||E(t))return;let o=i!==null?bt(i):void 0,a={position:t.position.getPolled(),duration:t.duration,playbackRate:t.playbackRate,maximumPosition:o,bufferGap:t.bufferGap===void 0||!isFinite(t.bufferGap)?0:t.bufferGap};if(i!==null&&i.isLive&&t.position.getPolled()>0){let u=(d=i.availabilityStartTime)!=null?d:0;a.wallClockTime=t.position.getPolled()+u;let l=hn(i);l!==void 0&&(a.liveGap=l-t.position.getPolled())}else if(r&&this.videoElement!==null){let u=so(this.videoElement);u!==void 0&&(a.wallClockTime=u+t.position.getPolled())}this.trigger("positionUpdate",a)}_priv_triggerEventIfNotStopped(e,t,r){r.isCancelled()||this.trigger(e,t)}_priv_initializeMediaElementTracksStore(e){var r,i,o;ee(me.directfile!==null,"Initializing `MediaElementTracksStore` without Directfile feature"),ee(this.videoElement!==null,"Initializing `MediaElementTracksStore` on a disposed RxPlayer");let t=new me.directfile.mediaElementTracksStore(this.videoElement);return this._priv_triggerEventIfNotStopped("availableAudioTracksChange",t.getAvailableAudioTracks(),e),this._priv_triggerEventIfNotStopped("availableVideoTracksChange",t.getAvailableVideoTracks(),e),this._priv_triggerEventIfNotStopped("availableTextTracksChange",t.getAvailableTextTracks(),e),this._priv_triggerEventIfNotStopped("audioTrackChange",(r=t.getChosenAudioTrack())!=null?r:null,e),this._priv_triggerEventIfNotStopped("textTrackChange",(i=t.getChosenTextTrack())!=null?i:null,e),this._priv_triggerEventIfNotStopped("videoTrackChange",(o=t.getChosenVideoTrack())!=null?o:null,e),t.addEventListener("availableVideoTracksChange",a=>this.trigger("availableVideoTracksChange",a)),t.addEventListener("availableAudioTracksChange",a=>this.trigger("availableAudioTracksChange",a)),t.addEventListener("availableTextTracksChange",a=>this.trigger("availableTextTracksChange",a)),t.addEventListener("audioTrackChange",a=>this.trigger("audioTrackChange",a)),t.addEventListener("videoTrackChange",a=>this.trigger("videoTrackChange",a)),t.addEventListener("textTrackChange",a=>this.trigger("textTrackChange",a)),t}_priv_callTracksStoreGetterSetter(e,t,r){var d,u;if(this._priv_contentInfos===null||this._priv_contentInfos.tracksStore===null)return m.warn("API: Trying to call track API too soon"),t;let{tracksStore:i}=this._priv_contentInfos,o=(u=(d=this._priv_contentInfos)==null?void 0:d.currentPeriod)!=null?u:void 0,a=e!=null?e:o==null?void 0:o.id;if(a===void 0)return t;let s=a===(o==null?void 0:o.id)?i.getPeriodObjectFromPeriod(o):i.getPeriodObjectFromId(a);return s===void 0?t:r(i,s)}_priv_onAvailableTracksMayHaveChanged(e,t){let r=this._priv_contentInfos;if(r===null)return;let{currentPeriod:i,tracksStore:o,currentContentCanceller:a}=r,s=a.signal;if(E(i)||o===null)return;let d=t!=null?t:o.getPeriodObjectFromPeriod(i);if(d!==void 0)switch(e){case"video":{let u=o.getAvailableVideoTracks(d,!0);this._priv_triggerEventIfNotStopped("availableVideoTracksChange",u!=null?u:[],s);break}case"audio":{let u=o.getAvailableAudioTracks(d,!0);this._priv_triggerEventIfNotStopped("availableAudioTracksChange",u!=null?u:[],s);break}case"text":{let u=o.getAvailableTextTracks(d);this._priv_triggerEventIfNotStopped("availableTextTracksChange",u!=null?u:[],s);break}default:Xe(e)}}_priv_onFatalError(e,t){let r=Oe(e,{defaultCode:"NONE",defaultReason:"An unknown error stopped content playback."});r.fatal=!0,t.currentContentCanceller.cancel(),this._priv_cleanUpCurrentContentState(),this._priv_currentError=r,m.error("API: The player stopped because of an error",r),this._priv_setPlayerState("STOPPED"),this._priv_currentError===r&&this.trigger("error",r)}};Kt._priv_currentlyUsedVideoElements=new WeakSet;var La=Kt;La.version="4.3.0-dev.2025012900";var sp=La;var Na=sp;Ua();Na.addFeatures([kl,cu,hu,yu,ml,dl,yl,ll,qu,_u,il,Ru]);Dn()?m.setLevel("DEBUG","standard"):h.CURRENT_ENV===h.DEV&&m.setLevel(S.CURRENT_LEVEL,"standard");var Goe=Na;J.RxPlayer=Na;})();
|