rx-player 4.3.0 → 4.3.1-dev.2025040700

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.
@@ -1,18 +1,18 @@
1
- "use strict";(()=>{var kp=Object.defineProperty,Pp=Object.defineProperties;var Cp=Object.getOwnPropertyDescriptors;var Wl=Object.getOwnPropertySymbols;var Mp=Object.prototype.hasOwnProperty,Ap=Object.prototype.propertyIsEnumerable;var ql=(n,e,t)=>e in n?kp(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)&&ql(n,t,e[t]);if(Wl)for(var t of Wl(e))Ap.call(e,t)&&ql(n,t,e[t]);return n},de=(n,e)=>Pp(n,Cp(e));var y={PRODUCTION:0,DEV:1,CURRENT_ENV:0};var S={CURRENT_LEVEL:"NONE"};function Un(){return typeof __RX_PLAYER_DEBUG_MODE__=="boolean"&&__RX_PLAYER_DEBUG_MODE__}function _(n){return n==null}var ae=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(y.CURRENT_ENV===y.DEV)throw o instanceof Error?o:new Error("EventEmitter: listener error");console.error("RxPlayer: EventEmitter error",o instanceof Error?o:null)}})}};var Ht=typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope;var Op=typeof window=="undefined"&&!Ht,Wt=Op;var yo;Ht?yo=self:Wt?yo=global:yo=window;var J=yo;var Rt=typeof queueMicrotask=="function"?queueMicrotask:function(e){Promise.resolve().then(e,()=>e())};function Wa(){if(!Wt&&!_(J.WebKitSourceBuffer)&&J.WebKitSourceBuffer.prototype.addEventListener===void 0){let e=J.WebKitSourceBuffer.prototype;for(let t in ae.prototype)Object.prototype.hasOwnProperty.call(ae.prototype,t)&&(e[t]=ae.prototype[t]);e._listeners=[],e._emitUpdate=function(t,r){Rt(()=>{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 pe(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 Z(){}var Io=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){y.CURRENT_ENV===y.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 Z;let r=()=>{let a=pe(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 ln(n,e,t){let r=new Io(e(n.getValue()),t);return n.onUpdate(function(o){r.setValue(e(o))},{clearSignal:t}),n._onFinished(()=>{r.finish()},t),r}var G=Io;var Gl=new G(0);var Dp=typeof performance!="undefined"?()=>performance.now()+Gl.getValue():()=>Date.now()+Gl.getValue(),V=Dp;var Lp="NONE",mr=class extends ae{constructor(){super(),this.error=Z,this.warn=Z,this.info=Z,this.debug=Z,this._levels={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4},this._currentFormat="standard",this._currentLevel=Lp}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=V();console.log(String(d.toFixed(2)),"[Init]",`Local-Date: ${Date.now()}`)}this._currentFormat=a;let s=this._currentFormat==="full"?(d,u)=>(...c)=>{let l=V();return u(String(l.toFixed(2)),`[${d}]`,...c)}:(d,u)=>u;if(r===void 0)this.error=i>=this._levels.ERROR?s("error",console.error.bind(console)):Z,this.warn=i>=this._levels.WARNING?s("warn",console.warn.bind(console)):Z,this.info=i>=this._levels.INFO?s("info",console.info.bind(console)):Z,this.debug=i>=this._levels.DEBUG?s("log",console.log.bind(console)):Z;else{let d=u=>i>=this._levels[u]?(...c)=>r(u,c):Z;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 Np=new mr,m=Np;var De=J,jl,Yl,$l,Ql,Xl,kt=(Xl=(Ql=($l=(Yl=(jl=De==null?void 0:De.MediaSource)!=null?jl:De==null?void 0:De.MozMediaSource)!=null?Yl:De==null?void 0:De.WebKitMediaSource)!=null?$l:De==null?void 0:De.MSMediaSource)!=null?Ql:De==null?void 0:De.ManagedMediaSource)!=null?Xl:void 0,Zl=kt!==void 0&&kt===(De==null?void 0:De.ManagedMediaSource);var Up=200,bo=new Map;function qa(n){if(_(kt))return Ht&&m.error("Compat: Cannot request codec support in a worker without MSE."),!1;if(typeof kt.isTypeSupported=="function"){let e=bo.get(n);if(e!==void 0)return e;{let t=kt.isTypeSupported(n);return bo.size>=Up&&bo.clear(),bo.set(n,t),t}}return!0}var pr=!1,cn=!1,qt=!1,fn=!1,Ga=!1,mn=!1,ja=!1,gr=!1,hr=!1,Bp=!1,Fp=!1,Ya=!1,$a=!1,Qa=!1,pn=!1,Kp=!1,Xa=!1;(function(){var e,t,r;Wt||(typeof J.MSInputMethodContext!="undefined"&&typeof document.documentMode!="undefined"?(cn=!0,qt=!0):navigator.appName==="Microsoft Internet Explorer"||navigator.appName==="Netscape"&&/(Trident|Edge)\//.test(navigator.userAgent)?qt=!0:navigator.userAgent.toLowerCase().indexOf("edg/")!==-1?pr=!0:navigator.userAgent.toLowerCase().indexOf("firefox")!==-1?fn=!0:typeof navigator.platform=="string"&&/iPad|iPhone|iPod/.test(navigator.platform)?mn=!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))&&(Ga=!0),/SamsungBrowser/.test(navigator.userAgent)&&(ja=!0),navigator.userAgent.indexOf("PlayStation 4")!==-1?Qa=!0:navigator.userAgent.indexOf("PlayStation 5")!==-1?pn=!0:/Tizen/.test(navigator.userAgent)?gr=!0:/[Ww]eb[O0]S/.test(navigator.userAgent)?(hr=!0,/[Ww]eb[O0]S.TV-2022/.test(navigator.userAgent)||/[Cc]hr[o0]me\/87/.test(navigator.userAgent)?Fp=!0:(/[Ww]eb[O0]S.TV-2021/.test(navigator.userAgent)||/[Cc]hr[o0]me\/79/.test(navigator.userAgent))&&(Bp=!0)):navigator.userAgent.indexOf("NETTV")!==-1&&navigator.userAgent.indexOf("Philips")!==-1?$a=!0:/[Pp]anasonic/.test(navigator.userAgent)?Ya=!0:navigator.userAgent.indexOf("Xbox")!==-1?Kp=!0:navigator.userAgent.indexOf("Model/a1-kstb40xx")!==-1&&(Xa=!0))})();var Vp=pn,Jl=Vp;function Za(n){return n===void 0||n.indexOf("widevine")<0}var ec={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,FREEZING_FLUSH_FAILURE_DELAY:{MAXIMUM:2e4,MINIMUM:4e3,POSITION_DELTA:1},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"','audio/mp4;codecs="ec-3"'],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",DEFAULT_MAX_THUMBNAIL_REQUESTS_RETRY_ON_ERROR:1,DEFAULT_THUMBNAIL_REQUEST_TIMEOUT:1e4,DEFAULT_THUMBNAIL_CONNECTION_TIMEOUT:7e3},tc=ec;function zp(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 Y=typeof Object.assign=="function"?Object.assign:zp;function Ja(n){return n!=null&&!Array.isArray(n)&&typeof n=="object"}function yr(n,...e){if(e.length===0)return n;let t=e.shift();if(Ja(n)&&Ja(t))for(let r in t)if(Ja(t[r])){let i=n[r];i===void 0&&(i={},n[r]=i),yr(i,t[r])}else Y(n,{[r]:t[r]});return yr(n,...e)}var es=class extends ae{constructor(){super(...arguments);this.updated=!1;this._config=tc}update(t){let r=yr(this._config,t);this._config=r,this.updated=!0,this.trigger("update",t)}getCurrent(){return this._config}},Hp=new es,L=Hp;var Wp=.016666666666666666;function nc(n,e){return Math.abs(n-e)<Wp}function ic(n,e){let t=Math.min(n.start,e.start),r=Math.max(n.end,e.end);return{start:t,end:r}}function qp(n){for(let e=0;e<n.length;e++){let t=n[e];t.start===t.end&&n.splice(e--,1)}return n}function Gp(n){for(let e=1;e<n.length;e++){let t=n[e-1],r=n[e];if(ac(t,r)){let i=ic(t,r);n.splice(--e,2,i)}}return n}function ts(n,e){return n.end<=e.start}function rc({start:n,end:e},t){return n<=t&&t<e}function oc(n,e){return rc(n,e.start)||n.start<e.end&&e.end<n.end||rc(e,n.start)}function ac(n,e){return nc(e.start,n.end)||nc(e.end,n.start)}function xe(n){let e=[];for(let t=0;t<n.length;t++)e.push({start:n.start(t),end:n.end(t)});return e}function ns(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 jp(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 sc(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 dc(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 uc(n,e){let t=ns(n,e);return t!==null?t.end-e:1/0}function So(n,e){let t=jp(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=oc(t,i),a=ac(t,i);if(o||a)t=ic(t,i),n.splice(r--,1);else if(r===0){if(ts(t,n[0]))break}else if(ts(n[r-1],t)&&ts(t,i))break}return n.splice(r,0,t),Gp(qp(n))}function lc(n,e){let t=[];for(let r=0;r<e.length;r++)oc(n,e[r])&&t.push(e[r]);return t}function cc(n,e){let t=[];for(let r=0;r<n.length;r++){let i=n[r],o=lc(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 To(n,e){let t=[];for(let r=0;r<n.length;r++){let i=n[r],o=[],a=lc(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 _o=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype),this.name="AssertionError"}};function ee(n,e){if(y.DEV===y.CURRENT_ENV&&!n)throw new _o(e===void 0?"invalid assertion":e)}function fc(n,e,t="object"){ee(!_(n),`${t} should be an object`);for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&ee(typeof n[r]===e[r],`${t} should have property ${r} as a ${e[r]}`)}function He(n){throw new _o("Unreachable path taken")}var U=class{constructor(){let[e,t]=Yp();this._isUsed=!1,this._trigger=e,this.signal=new Ir(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 Pe;this._trigger(t)}static isCancellationError(e){return e instanceof Pe}},Ir=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),Z):(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)}},Pe=class n extends Error{constructor(){super("This task was cancelled."),Object.setPrototypeOf(this,n.prototype),this.name="CancellationError"}};function Yp(){let n=Z;return[function(t){n(t)},function(t){n=t}]}function rs(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 rt=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 br=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 rt(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 mc=6e3,$p=15e3,Qp=3e3,Xp=1e3,Zp=9e3,Sr=class{constructor(e){this._levelsMap=rs(e).map(t=>t+4),this._bitrates=e,this._lastUnsuitableQualityTimestamp=void 0,this._blockRaiseDelay=mc,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 g=0;g<r.length;g++){let b=r[g];if(b===o)d=g;else if(b>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 c=isFinite(i)?i:0,l=V();if(c<t[d]||u!==void 0&&u<1&&(a==null?void 0:a.confidenceLevel)===1){if((this._lastUnsuitableQualityTimestamp===void 0?-1:l-this._lastUnsuitableQualityTimestamp)<this._blockRaiseDelay+Zp){let h=this._blockRaiseDelay+Qp;this._blockRaiseDelay=Math.min(h,$p),m.debug("ABR: Incrementing blocking raise in BufferBasedChooser due to unstable quality",this._blockRaiseDelay)}else{let h=this._blockRaiseDelay-Xp;this._blockRaiseDelay=Math.max(mc,h),m.debug("ABR: Lowering quality in BufferBasedChooser",this._blockRaiseDelay)}this._lastUnsuitableQualityTimestamp=l;let b=pe(r,h=>h===o);for(let h=b-1;h>=0;h--)if(c>=t[h]){this._currentEstimate=r[h];return}this._currentEstimate=r[0];return}if(this._lastUnsuitableQualityTimestamp!==void 0&&l-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],p=(()=>{for(let g=d+1;g<t.length;g++)if(t[g]>f)return g})();if(p!==void 0){let g=t[p];if(i>=g){m.debug("ABR: Raising quality in BufferBasedChooser",r[p]),this._currentEstimate=r[p];return}}this._currentEstimate=o}getLastEstimate(){return this._currentEstimate}};function Q(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 Jp(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 Eo(n){if(n.progress.length<5)return;let e=new rt(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 pc(n,e){let t=(n.totalSize-n.size)*8;return Math.max(t/e,0)}function eg(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,c=Jp(n,u);if(c.length!==1)return;let l=c[0],f=V(),p=l.content.segment.duration*1.5;if(p=Math.min(p,3e3),p=Math.max(p,12e3),f-l.requestTimestamp<p)return;let g=l.progress.length>0?l.progress[l.progress.length-1]:void 0,b=Eo(l);if(g!==void 0&&b!==void 0){let v=pc(g,b);if((f-g.timestamp)/1e3<=v&&v-d/a>2500)return b}if(!l.content.segment.complete)return;let h=l.content.segment.duration,I=(f-l.requestTimestamp)/1e3,T=I<=(h*1.5+2)/a;if(_(t)||T)return;let R=h/I,E=t.bitrate*Math.min(.7,R);if(i===void 0||E<i)return E}function tg(n,e,t){if(t)return!0;let r=isFinite(n.bufferGap)?n.bufferGap:0,i=n.position.getWanted()+r,o=Q(e,({content:l})=>l.segment.duration>0&&l.segment.time+l.segment.duration>i);if(o===void 0)return!0;let a=V(),s=o.progress.length>0?o.progress[o.progress.length-1]:void 0,d=Eo(o);if(s===void 0||d===void 0)return!0;let u=pc(s,d);return(a-s.timestamp)/1e3>u*1.2?!0:u-r/n.speed>-1.5}var Tr=class{constructor(e,t){let{ABR_STARVATION_GAP:r,OUT_OF_STARVATION_GAP:i,ABR_STARVATION_FACTOR:o,ABR_REGULAR_FACTOR:a}=L.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:c,duration:l}=e,f=isFinite(u)?u:0,{ABR_STARVATION_DURATION_DELTA:p}=L.getCurrent();return isNaN(l)||f+c.getWanted()<l-p?!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=eg(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:tg(i,r,this._lowLatencyMode)}};var _r=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 Er=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 l=gc(e,r);if(l!==null)return l}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=V()+Math.min(this._consecutiveWrongGuesses*15e3,12e4),ng(e,r);if(u===void 0)return r;if(this._canGuessHigher(a,s,u)){let l=gc(e,r);if(l!==null)return l}return r}_canGuessHigher(e,t,{score:r,confidenceLevel:i}){return isFinite(e)&&e>=2.5&&V()>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=V();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=Eo(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 gc(n,e){let t=n.length,r=pe(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 ng(n,e){let t=pe(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 vr=class{constructor(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=L.getCurrent();this._fastEWMA=new rt(e),this._slowEWMA=new rt(t),this._bytesSampled=0}addSample(e,t){let{ABR_MINIMUM_CHUNK_SIZE:r}=L.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}=L.getCurrent();if(!(this._bytesSampled<e))return Math.min(this._fastEWMA.getEstimate(),this._slowEWMA.getEstimate())}reset(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=L.getCurrent();this._fastEWMA=new rt(e),this._slowEWMA=new rt(t),this._bytesSampled=0}};function is(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=pe(n,o=>o.bitrate>r);return i===-1?n:n.slice(0,i)}function os(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,c;return((u=s.width)!=null?u:0)-((c=d.width)!=null?c:0)}),o=Q(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 Rr(n){return Object.keys(n).map(e=>n[e])}var Bn=typeof Object.values=="function"?Object.values:Rr;var kr=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(y.CURRENT_ENV===y.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(y.CURRENT_ENV===y.DEV)throw new Error("ABR: can't remove unknown request");m.warn("ABR: can't remove unknown request")}delete this._currentRequests[e]}getRequests(){return Bn(this._currentRequests).filter(e=>!_(e)).sort((e,t)=>e.content.segment.time-t.content.segment.time)}};function vo(n,e){let t=pe(n,r=>r.bitrate>e);return t===-1?n[n.length-1]:t===0?n[0]:n[t-1]}var hc=new G(void 0);hc.finish();var yc=new G(1/0);yc.finish();function as(n){let e={},{initialBitrates:t,throttlers:r,lowLatencyMode:i}=n;return function(s,d,u,c,l){var h,I,T;let{type:f}=s.adaptation,p=o(f),g=(h=t[f])!=null?h:0,b={limitResolution:(I=r.limitResolution[f])!=null?I:hc,throttleBitrate:(T=r.throttleBitrate[f])!=null?T:yc};return rg({bandwidthEstimator:p,context:s,currentRepresentation:d,filters:b,initialBitrate:g,playbackObserver:c,representations:u,lowLatencyMode:i},l)};function o(a){let s=e[a];if(_(s)){m.debug("ABR: Creating new BandwidthEstimator for ",a);let d=new vr;return e[a]=d,d}return s}}function rg({bandwidthEstimator:n,context:e,currentRepresentation:t,filters:r,initialBitrate:i,lowLatencyMode:o,playbackObserver:a,representations:s},d){let u=new br,c=new Tr(i!=null?i:0,o),l=new kr,f=Z,p={metrics:T,requestBegin:R,requestProgress:E,requestEnd:v,addedSegment(k){f(k)}},g=new U;g.linkToSignal(d);let b=h(s.getValue(),g.signal);return s.onUpdate(I,{clearSignal:d}),{estimates:b,callbacks:p};function h(k,x){if(k.length<=1)return new G({bitrate:void 0,representation:k[0],urgent:!0,knownStableBitrate:void 0});let P=!1,M=k.sort((K,j)=>K.bitrate-j.bitrate),O=new Sr(M.map(K=>K.bitrate)),B=new _r,D=new Er(u,B),F=a.getReference().getValue(),A=new G(N());return a.listen(K=>{F=K,C()},{includeLastObservation:!1,clearSignal:x}),f=function(K){if(F===null)return;let{position:j,speed:$}=F,z=K.buffered,H=So(z,j.getWanted()),{representation:q}=K.content,ie=u.getEstimate(q),ne=q.bitrate,le={bufferGap:H,currentBitrate:ne,currentScore:ie,speed:$};O.onAddedSegment(le),C()},x.register(()=>{f=Z}),r.throttleBitrate.onUpdate(C,{clearSignal:x}),r.limitResolution.onUpdate(C,{clearSignal:x}),A;function C(){A.setValue(N())}function N(){let{bufferGap:K,position:j,maximumPosition:$}=F,z=r.limitResolution.getValue(),H=r.throttleBitrate.getValue(),q=t.getValue(),ie=ig(M,z,H),ne=l.getRequests(),{bandwidthEstimate:le,bitrateChosen:be}=c.getBandwidthEstimate(F,n,q,ne,B.bandwidth),me=u.getLastStableRepresentation(),W=me===null?void 0:me.bitrate/(F.speed>0?F.speed:1),{ABR_ENTER_BUFFER_BASED_ALGO:Ce,ABR_EXIT_BUFFER_BASED_ALGO:nt}=L.getCurrent();P&&K<=nt?P=!1:!P&&isFinite(K)&&K>=Ce&&(P=!0);let Ae=vo(ie,be),Vt=O.getLastEstimate(),un=Ae.bitrate,mt=null;P&&Vt!==void 0&&Vt>un&&(mt=vo(ie,Vt),un=mt.bitrate);let bt=null;return o&&q!==null&&e.manifest.isDynamic&&$-j.getWanted()<40&&(bt=D.getGuess(M,F,q,un,ne)),bt!==null&&bt.bitrate>un?(m.debug("ABR: Choosing representation with guess-based estimation.",bt.bitrate,bt.id),B.update(bt,le,2),{bitrate:le,representation:bt,urgent:q===null||bt.bitrate<q.bitrate,knownStableBitrate:W}):mt!==null?(m.debug("ABR: Choosing representation with buffer-based estimation.",mt.bitrate,mt.id),B.update(mt,le,0),{bitrate:le,representation:mt,urgent:c.isUrgent(mt.bitrate,q,ne,F),knownStableBitrate:W}):(m.debug("ABR: Choosing representation with bandwidth estimation.",Ae.bitrate,Ae.id),B.update(Ae,le,1),{bitrate:le,representation:Ae,urgent:c.isUrgent(Ae.bitrate,q,ne,F),knownStableBitrate:W})}}function I(){let k=s.getValue();g.cancel(),g=new U,g.linkToSignal(d),h(k,g.signal).onUpdate(function(M){b.setValue(M)},{clearSignal:g.signal,emitCurrentValue:!0})}function T(k){let{requestDuration:x,segmentDuration:P,size:M,content:O}=k;if(n.addSample(x,M),!O.segment.isInit){let{segment:B,representation:D}=O;if(P===void 0&&!B.complete)return;let F=P!=null?P:B.duration;u.addSample(D,x/1e3,F)}}function R(k){l.add(k)}function E(k){l.addProgress(k)}function v(k){l.remove(k.id)}}function ig(n,e,t){let r=n;return t!==void 0&&t<1/0&&(r=is(r,t)),e!==void 0&&(r=os(r,e)),r}var Ic=as;function Ro(){var t;if(typeof((t=J.crypto)==null?void 0:t.randomUUID)=="function")return J.crypto.randomUUID();let n=new Date().getTime(),e=V();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 Xe(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 og=/^(?:[a-z]+:)?\/\//i,ag=/^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/;function Mr(n){let e=n.lastIndexOf("/");if(e<0)return n.length;if(og.test(n)){let r=n.indexOf("/");if(r>=0&&e===r+1)return n.length}let t=n.indexOf("?");return t>=0&&t<e?Mr(n.substring(0,t)):e+1}function bc(n,e){let t=ko(n),r=ko(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=Cr(t.path),o=Cr(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 c=u.join("/");(c.endsWith("../")||c.endsWith("./"))&&(c=c.slice(0,c.length-1)),a=c===""?".":c}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 sg(n,e){let t=ko(n),r=ko(e);if(w(r.scheme))return ss(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=Cr(r.path),ss(i)):(r.path===""?(i.path=t.path,w(r.query)||(i.query=t.query)):Xe(r.path,"/")?i.path=Cr(r.path):i.path=Cr(ug(t,r.path)),ss(i))}var Pr=new Map,dg=200;function ko(n){var r,i,o,a,s;if(Pr.has(n))return Pr.get(n);let e=n.match(ag),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:""},Pr.size>=dg&&Pr.clear(),Pr.set(n,t),t}function ss(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 Cr(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 ug(n,e){if(w(n.authority)&&n.path==="")return"/"+e;let t=n.path;return t.substring(0,t.lastIndexOf("/")+1)+e}function gn(...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=sg(a,s),u=e.slice(2);return gn(d,...u)}}var lg=4,Ar=class{constructor(e){var t,r;this._sessionId=(t=e.sessionId)!=null?t:Ro(),this._contentId=(r=e.contentId)!=null?r:Ro(),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 U,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 c=e.segment.url,l=e.nextSegment.url,f=bc(c,l);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 c=t.buffered[e.adaptation.type];if(!_(c)){let l=(u=(d=(s=this._playbackObserver)==null?void 0:s.getCurrentTime())!=null?d:t.position.getWanted())!=null?u:t.position.getPolled();for(let f of c)if(l>=f.start&&l<f.end){i=(f.end-l)*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 l=e.representation.bitrate*e.segment.duration/1e3/(o/1e3);r.rtp=Math.floor(Math.round(l*lg/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((c,l)=>l.isPlayable()!==!0?c:c===void 0?Math.round(l.bitrate/1e3):Math.max(c,Math.round(l.bitrate/1e3)),void 0),this._producePayload(r)}_producePayload(e){let t={object:"",request:"",session:"",status:""},r="",i=(u,c)=>{this._typePreference===0?t[c]+=u:r+=u},o=(u,c)=>{let l=e[u];if(l!==void 0){let f=`${u}=${String(l)},`;i(f,c)}},a=(u,c)=>{if(e[u]===!0){let l=`${u},`;i(l,c)}},s=(u,c)=>{let l=e[u];if(l!==void 0){let p=`prop=${`"${l.replace("\\","\\\\").replace('"','\\"')}"`},`;i(p,c)}},d=(u,c)=>{let l=e[u];if(l!==void 0){let f=`prop=${l},`;i(f,c)}};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 Sc=Ar;var Fn=class extends ae{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=Tc(this._downgradedCdnList.metadata,e);t>=0&&this._removeIndexFromDowngradeList(t);let{DEFAULT_CDN_DOWNGRADE_TIME:r}=L.getCurrent(),i=r;this._downgradedCdnList.metadata.push(e);let o=setTimeout(()=>{let a=Tc(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 Tc(n,e){return n.length===0?-1:e.id!==void 0?pe(n,t=>t.id===e.id):pe(n,t=>t.baseUrl===e.baseUrl)}var it=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 _e=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 ds=typeof Headers=="function"?Headers:null,us=typeof AbortController=="function"?AbortController:null;function Po(n){var f,p;let e;if(!_(n.headers))if(_(ds))e=n.headers;else{e=new ds;let g=Object.keys(n.headers);for(let b=0;b<g.length;b++){let h=g[b];e.append(h,n.headers[h])}}m.debug("Fetch: Called with URL",n.url);let t=null,r=!1,i=!1,o=V(),a=_(us)?null:new us;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 c=n.cancelSignal.register(function(b){t=b,s()}),l={method:"GET"};if(e!==void 0&&(l.headers=e),l.signal=_(a)?null:a.signal,m.hasLevel("DEBUG")){let g="FETCH: Sending GET "+n.url;n.timeout!==void 0&&(g+=" to="+String(n.timeout/1e3)),n.connectionTimeout!==void 0&&(g+=" cto="+String(n.connectionTimeout/1e3)),((f=n.headers)==null?void 0:f.Range)!==void 0&&(g+=" Range="+((p=n.headers)==null?void 0:p.Range)),m.debug(g)}return fetch(n.url,l).then(g=>{if(u!==void 0&&clearTimeout(u),g.status>=300)throw m.warn("Fetch: Request HTTP Error",g.status,g.url),new _e(g.url,g.status,Fe.ERROR_HTTP_CODE);if(_(g.body))throw new _e(g.url,g.status,Fe.PARSE_ERROR);let b=g.headers.get("Content-Length"),h=!_(b)&&!isNaN(+b)?+b:void 0,I=g.body.getReader(),T=0;return R();async function R(){let E=await I.read();if(!E.done&&!_(E.value)){T+=E.value.byteLength;let v=V(),k={url:g.url,currentTime:v,duration:v-o,sendingTime:o,chunkSize:E.value.byteLength,chunk:E.value.buffer,size:T,totalSize:h};return n.onData(k),R()}else if(E.done){d!==void 0&&clearTimeout(d),c();let v=V();return{requestDuration:v-o,receivedTime:v,sendingTime:o,size:T,status:g.status,url:g.url}}return R()}}).catch(g=>{throw t!==null?t:(c(),r?(m.warn("Fetch: Request timed out."),new _e(n.url,0,Fe.TIMEOUT)):i?(m.warn("Fetch: Request connection timed out."),new _e(n.url,0,Fe.TIMEOUT)):g instanceof _e?g:(m.warn("Fetch: Request Error",g instanceof Error?g.toString():""),new _e(n.url,0,Fe.ERROR_EVENT)))})}function xr(){return typeof J.fetch=="function"&&!_(us)&&!_(ds)}var cg="json";function wr(n){let e={url:n.url,headers:n.headers,responseType:_(n.responseType)?cg: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:c}=e,l=new XMLHttpRequest;l.open("GET",a,!0);let f;u!==void 0&&(l.timeout=u,f=setTimeout(()=>{h(),r(new _e(a,l.status,Fe.TIMEOUT))},u+3e3));let p;if(c!==void 0&&(p=setTimeout(()=>{h(),l.readyState!==XMLHttpRequest.DONE&&l.abort(),r(new _e(a,l.status,Fe.TIMEOUT))},c)),l.responseType=d,l.responseType==="document"&&l.overrideMimeType("text/xml"),!_(s)){let I=s;for(let T in I)Object.prototype.hasOwnProperty.call(I,T)&&l.setRequestHeader(T,I[T])}let g=V(),b=null;if(o!==void 0&&(b=o.register(function(T){h(),l.readyState!==XMLHttpRequest.DONE&&l.abort(),r(T)}),o.isCancelled()))return;if(l.onerror=function(){h(),r(new _e(a,l.status,Fe.ERROR_EVENT))},l.ontimeout=function(){h(),r(new _e(a,l.status,Fe.TIMEOUT))},c!==void 0&&(l.onreadystatechange=function(){l.readyState>=XMLHttpRequest.HEADERS_RECEIVED&&clearTimeout(p)}),i!==void 0&&(l.onprogress=function(T){let R=V();i({url:a,duration:R-g,sendingTime:g,currentTime:R,size:T.loaded,totalSize:T.total})}),l.onload=function(T){if(l.readyState===XMLHttpRequest.DONE)if(h(),l.status>=200&&l.status<300){let R=V(),E=l.response instanceof ArrayBuffer?l.response.byteLength:T.total,v=l.status,k=l.responseType,x=w(l.responseURL)?l.responseURL:a,P;if(k==="json"?P=typeof l.response=="object"?l.response:fg(l.responseText):P=l.response,_(P)){r(new _e(a,l.status,Fe.PARSE_ERROR));return}t({status:v,url:x,responseType:k,sendingTime:g,receivedTime:R,requestDuration:R-g,size:E,responseData:P})}else r(new _e(a,l.status,Fe.ERROR_HTTP_CODE))},m.hasLevel("DEBUG")){let I="XHR: Sending GET "+a;n.responseType!==void 0&&(I+=" type="+n.responseType),u!==void 0&&(I+=" to="+String(u/1e3)),c!==void 0&&(I+=" cto="+String(c/1e3)),(s==null?void 0:s.Range)!==void 0&&(I+=" Range="+(s==null?void 0:s.Range)),m.debug(I)}l.send();function h(){f!==void 0&&clearTimeout(f),p!==void 0&&clearTimeout(p),b!==null&&b()}})}function fg(n){try{return JSON.parse(n)}catch(e){return null}}var Se=wr;var hn=Fe,Ze={NETWORK_ERROR:"NETWORK_ERROR",MEDIA_ERROR:"MEDIA_ERROR",ENCRYPTED_MEDIA_ERROR:"ENCRYPTED_MEDIA_ERROR",OTHER_ERROR:"OTHER_ERROR"},ls={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 Je(n,e){return`${n}: ${e}`}var ge=class n extends Error{constructor(e,t,r){super(Je(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="EncryptedMediaError",this.type=Ze.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(Je(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="MediaError",this.type=Ze.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 ot=class n extends Error{constructor(e,t){super(Je(e,t.message)),Object.setPrototypeOf(this,n.prototype),this.name="NetworkError",this.type=Ze.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===hn.ERROR_HTTP_CODE&&this.status===e}serialize(){return{name:this.name,code:this.code,baseError:this._baseError.serialize()}}};var Ne=class n extends Error{constructor(e,t){super(Je(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="OtherError",this.type=Ze.OTHER_ERROR,this.code=e,this.fatal=!1,this._originalMessage=t}serialize(){return{name:this.name,code:this.code,reason:this._originalMessage}}};function jt(n){return(n instanceof ge||n instanceof te||n instanceof Ne||n instanceof ot)&&Object.keys(Ze).indexOf(n.type)>=0}function Ee(n,{defaultCode:e,defaultReason:t}){if(jt(n))return n;let r=n instanceof Error?n.toString():t;return new Ne(e,r)}var at=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 mg={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"},_c=mg;var pg={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"},Ec=pg;function gg(n){if(_(n)||n==="")return"und";let t=(""+n).toLowerCase().split("-")[0],r=hg(t);return w(r)?r:n}function hg(n){let e;switch(n.length){case 2:e=_c[n];break;case 3:e=Ec[n];break}return e}var vc=gg;var Or=vc;function he(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 Yt=["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=V()-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=V()-e.time;return e.livePosition+t/1e3}function Tt(n){let{maximumTimeData:e}=n.timeBounds;if(!e.isLinear)return e.maximumSafePosition;let t=V()-e.time;return e.maximumSafePosition+t/1e3}function pt(n,e){if(e===void 0)return fs(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 Kn(n,e){let t=null;for(let r of n.periods){if(cs(r,e,t))return r;t=r}}function Co(n,e){let t=e.end;if(t===void 0)return null;let r=Q(n.periods,i=>i.end===void 0||t<i.end);return r===void 0?null:r}function cs(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 fs(n){let e=n.adaptations;return Rr(e).reduce((t,r)=>_(r)?t:t.concat(r),[])}function Mo(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=>St(o)===!0):n.representations).map(yg),label:n.label};return n.isDub===!0&&(t.dub=!0),t}function Ao(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 xo(n,e){let t=n.trickModeTracks!==void 0?n.trickModeTracks.map(i=>{let o=(e?i.representations.filter(s=>St(s)===!0):i.representations).map(Rc),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=>St(i)===!0):n.representations).map(Rc),label:n.label};return n.isSignInterpreted===!0&&(r.signInterpreted=!0),n.isTrickModeTrack===!0&&(r.isTrickModeTrack=!0),t!==void 0&&(r.trickModeTracks=t),r}function yg(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 Rc(n){let{id:e,bitrate:t,frameRate:r,width:i,height:o,codecs:a,hdrInfo:s,isSupported:d,decipherable:u,contentProtections:c}=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:c!==void 0?{keyIds:c.keyIds}:void 0}}function $t(n){switch(n.type){case"audio":return{type:"audio",track:Mo(n,!1)};case"video":return{type:"video",track:xo(n,!1)};case"text":return{type:"text",track:Ao(n)}}}function St(n){return n.decipherable===!1?!1:n.isSupported}function kc(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 Ig=et(),ms=class{constructor(e,t,r){var o,a,s,d,u;this.id=e.id,this.uniqueId=Ig(),this.shouldBeAvoided=!1,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 c=r.isSupported((o=this.mimeType)!=null?o:"",(a=e.supplementalCodecs)!=null?a:"",i);c!==!1&&(this.codecs=[e.supplementalCodecs],this.isSupported=c)}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)he(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],c;for(c=0;c<s.length;c++)if(u.systemId===s[c].systemId){if(he(u.data,s[c].data))break;m.warn("Manifest: different init data for the same system ID")}c===s.length&&(s.push(u),i=!0)}return i}return this.contentProtections.initData.push({type:e,values:r}),!0}isPlayable(){return St(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,isCodecSupportedInWebWorker:this.isCodecSupportedInWebWorker}}},Pc=ms;var Dr=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=Or(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 c=new Pc(s[u],this.type,t),l=!0;if(!_(o)){let f={id:c.id,bitrate:c.bitrate,codecs:c.codecs,height:c.height,width:c.width,frameRate:c.frameRate,hdrInfo:c.hdrInfo};if(c.contentProtections!==void 0&&(f.contentProtections={},c.contentProtections.keyIds!==void 0)){let p=c.contentProtections.keyIds;f.contentProtections.keyIds=p}l=o(f,{trackType:this.type,language:this.language,normalizedLanguage:this.normalizedLanguage,isClosedCaption:this.isClosedCaption,isDub:this.isDub,isAudioDescription:this.isAudioDescription,isSignInterpreted:this.isSignInterpreted})}l?(d.push(c),c.isSupported===void 0?(this.supportStatus.hasCodecWithUndefinedSupport=!0,this.supportStatus.hasSupportedCodec===!1&&(this.supportStatus.hasSupportedCodec=void 0)):c.isSupported&&(this.supportStatus.hasSupportedCodec=!0),c.decipherable===void 0?this.supportStatus.isDecipherable===!1&&(this.supportStatus.isDecipherable=void 0):c.decipherable&&(this.supportStatus.isDecipherable=!0)):m.debug("Filtering Representation due to representationFilter",this.type,`Adaptation: ${this.id}`,`Representation: ${c.id}`,`(${c.bitrate})`)}d.sort((u,c)=>u.bitrate-c.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 Q(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 ps(){return cn}function Sn(n){return new Promise(e=>{setTimeout(e,n)})}function gs(){return hr}function hs(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 gs()?r:Promise.race([r,Sn(1e3)])}var _t=new WeakMap,je={async attach(n,e){let t=_t.get(n),r=bg(n,t,e).then(()=>{_t.set(n,{pendingTask:null,mediaKeysState:e})},()=>{_t.set(n,{pendingTask:null,mediaKeysState:null})});return _t.set(n,{pendingTask:r,mediaKeysState:e}),r},getAwaitedState(n){var t;let e=_t.get(n);return(t=e==null?void 0:e.mediaKeysState)!=null?t:null},async getAttachedMediaKeysState(n){let e=_t.get(n);return e===void 0?null:e.pendingTask!==null?(await e.pendingTask,this.getAttachedMediaKeysState(n)):e.mediaKeysState},clearMediaKeys(n){let e=_t.get(n),t=Sg(n,e).then(()=>{_t.set(n,{pendingTask:null,mediaKeysState:null})},()=>{_t.set(n,{pendingTask:null,mediaKeysState:null})});return _t.set(n,{pendingTask:t,mediaKeysState:null}),t}};async function Cc(n){let e=n.pendingTask;if(!_(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 bg(n,e,t){if(e!==void 0&&(e.pendingTask!==null&&await Cc(e),await(!_(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 hs(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 ge("MEDIA_KEYS_ATTACHMENT_ERROR","Could not attach the MediaKeys to the media element: "+i)}}async function Sg(n,e){if(e===void 0||(e.pendingTask!==null&&await Cc(e),e.mediaKeysState===null))return;m.info("DRM: Disposing of the current MediaKeys");let{loadedSessionsStore:t}=e.mediaKeysState;return await t.closeAllSessions(),hs(e.mediaKeysState.emeImplementation,n,null)}async function Vn(n){return je.clearMediaKeys(n)}async function wo(n){if(m.info("DRM: Clearing-up DRM session."),ps())return m.info("DRM: disposing current MediaKeys."),Vn(n);let e=await je.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 st(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 st(e,t=>{let r=setTimeout(()=>t(),n);return()=>clearTimeout(r)})}function Oo(n){let e=new U;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 Pe)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 _g(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 Eg(n,e){return e.filter(t=>_g(n,t))[0]}function vg(n,e){return n.reduce((t,r)=>t.concat((e===void 0?Tg:e).map(i=>i+r)),[])}function Te(n,e){let t,r=vg(n,e);return(i,o,a)=>{if(!a.isCancelled()){if(typeof HTMLElement!="undefined"&&i instanceof HTMLElement)if(typeof t=="undefined"&&(t=Eg(i,r)),w(t))i.addEventListener(t,o),a.register(()=>{t!==void 0&&i.removeEventListener(t,o)});else{y.CURRENT_ENV===y.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 Rg(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 G(!o,n);return Tn(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 G({isEnabled:i,pipWindow:null},e);return Tn(n,"webkitpresentationmodechanged",()=>{let a=n.webkitPresentationMode==="picture-in-picture";o.setValue({isEnabled:a,pipWindow:null})},e),o}let t=document.pictureInPictureElement===n,r=new G({isEnabled:t,pipWindow:null},e);return Tn(n,"enterpictureinpicture",i=>{var o;r.setValue({isEnabled:!0,pipWindow:(o=i.pictureInPictureWindow)!=null?o:null})},e),Tn(n,"leavepictureinpicture",()=>{r.setValue({isEnabled:!1,pipWindow:null})},e),r}function Ac(n,e){let t=Rg(e),r,i=new G(!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}=L.getCurrent();r=setTimeout(()=>{i.setValueIfChanged(!1)},a)}}}function xc(n){var o,a;let e=_(J.devicePixelRatio)||J.devicePixelRatio===0?1:J.devicePixelRatio,t=new G({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 wc(n,e,t){let r=_(J.devicePixelRatio)||J.devicePixelRatio===0?1:J.devicePixelRatio,i=new G({width:n.clientWidth,height:n.clientHeight,pixelRatio:r},t),o=Z;e.onUpdate(s,{clearSignal:t}),Tn(J,"resize",s,t),Tn(n,"enterpictureinpicture",s,t),Tn(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 l=i.getValue();(l.width!==void 0||l.height!==void 0||l.pixelRatio!==r)&&i.setValue({width:void 0,height:void 0,pixelRatio:r})}else{let l=()=>{c()};u.addEventListener("resize",l),o=()=>{u.removeEventListener("resize",l),o=Z},c()}else{let l=i.getValue();(l.width!==n.clientWidth||l.height!==n.clientHeight||l.pixelRatio!==r)&&i.setValue({width:n.clientWidth,height:n.clientHeight,pixelRatio:r})}function c(){let l=i.getValue();(l.width!==(u==null?void 0:u.width)||l.height!==(u==null?void 0:u.height)||l.pixelRatio!==r)&&i.setValue({width:u==null?void 0:u.width,height:u==null?void 0:u.height,pixelRatio:r})}}}var FP=Te(["loadedmetadata"]),KP=Te(["timeupdate"]),VP=Te(["addtrack"]),zP=Te(["removetrack"]),zn=Te(["sourceopen","webkitsourceopen"]),Do=Te(["sourceclose","webkitsourceclose"]),Lo=Te(["sourceended","webkitsourceended"]),Oc=Te(["update"]),Dc=Te(["removesourcebuffer"]),No=Te(["keymessage","message"]),Lc=Te(["keyadded","ready"]),Uo=Te(["keyerror","error"]),Nc=Te(["keystatuseschange"]),Uc=Te(["seeking"]),Bc=Te(["seeked"]),Fc=Te(["ended"]);function Tn(n,e,t,r){n.addEventListener(e,t),r.register(()=>{n.removeEventListener(e,t)})}var gt,{WebKitMediaKeys:Bo}=J;Bo!==void 0&&typeof Bo.isTypeSupported=="function"&&typeof Bo.prototype.createSession=="function"&&typeof HTMLMediaElement.prototype.webkitSetMediaKeys=="function"&&(gt=Bo);function ys(){return(Ga||mn)&&gt!==void 0}var Lr=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 Mt,{MSMediaKeys:Nr}=J;Nr!==void 0&&Nr.prototype!==void 0&&typeof Nr.isTypeSupported=="function"&&typeof Nr.prototype.createSession=="function"&&(Mt=Nr);var Is=class extends ae{constructor(e){super(),this.expiration=NaN,this.keyStatuses=new Map,this._mk=e,this._sessionClosingCanceller=new U,this.closed=new Promise(t=>{this._sessionClosingCanceller.signal.register(()=>t("closed-by-application"))}),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),No(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"message",o)},this._sessionClosingCanceller.signal),Lc(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"keyadded",o)},this._sessionClosingCanceller.signal),Uo(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:""}},Fo=class{constructor(e){if(Mt===void 0)throw new Error("No MSMediaKeys API.");this._mediaKeys=new Mt(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 Is(this._mediaKeys)}setServerCertificate(){throw new Error("Server certificate is not implemented in your browser")}};function bs(){return{isTypeSupported:(r,i)=>{if(Mt===void 0)throw new Error("No MSMediaKeys API.");return i!==void 0?Mt.isTypeSupported(r,i):Mt.isTypeSupported(r)},createCustomMediaKeys:r=>new Fo(r),setMediaKeys:(r,i)=>{if(i===null)return Promise.resolve(void 0);if(!(i instanceof Fo))throw new Error("Custom setMediaKeys is supposed to be called with IE11 custom MediaKeys.");return i._setVideo(r)}}}var Xt,{MozMediaKeys:Ur}=J;Ur!==void 0&&Ur.prototype!==void 0&&typeof Ur.isTypeSupported=="function"&&typeof Ur.prototype.createSession=="function"&&(Xt=Ur);function Ss(){return{isTypeSupported:(r,i)=>{if(Xt===void 0)throw new Error("No MozMediaKeys API.");return i!==void 0?Xt.isTypeSupported(r,i):Xt.isTypeSupported(r)},createCustomMediaKeys:r=>{if(Xt===void 0)throw new Error("No MozMediaKeys API.");return new Xt(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 At=["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","+","/"],Kc=[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 Ko(n){if(n>=Kc.length)throw new Error("Unable to parse base64 string.");let e=Kc[n];if(e===255)throw new Error("Unable to parse base64 string.");return e}function Vo(n){let e="",t,r=n.length;for(t=2;t<r;t+=3)e+=At[n[t-2]>>2],e+=At[(n[t-2]&3)<<4|n[t-1]>>4],e+=At[(n[t-1]&15)<<2|n[t]>>6],e+=At[n[t]&63];return t===r+1&&(e+=At[n[t-2]>>2],e+=At[(n[t-2]&3)<<4],e+="=="),t===r&&(e+=At[n[t-2]>>2],e+=At[(n[t-2]&3)<<4|n[t-1]>>4],e+=At[(n[t-1]&15)<<2],e+="="),e}function ht(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=Ko(t.charCodeAt(d))<<18|Ko(t.charCodeAt(d+1))<<12|Ko(t.charCodeAt(d+2))<<6|Ko(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 zc=typeof J=="object"&&typeof J.TextDecoder=="function",Pg=typeof J=="object"&&typeof J.TextEncoder=="function";function zo(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 Ho(n){if(zc)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(Pg)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 Cg(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 Vc(n,e){let t=n.toString(16);return t.length>=e?t:new Array(e-t.length+1).join("0")+t}function Ue(n){if(zc)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=Cg(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"+Vc(a,4):"%"+Vc(a,2)}}return decodeURIComponent(r)}function Ye(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 Be(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 Wo(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 Ts(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:Ue(r)}}function Es(n){return typeof(n==null?void 0:n.webkitGenerateKeyRequest)=="function"}var _s=class extends ae{constructor(e,t){super(),this._vid=e,this._key=t,this.sessionId="",this._closeSession=Z,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("closed-by-application")}}),["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(Ue(i)),a=ht(o.keys[0].k),s=ht(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()}},qo=class{constructor(e){this._keySystem=e}_setVideo(e){return Ct(()=>{if(!Es(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 _s(this._videoElement,this._keySystem)}setServerCertificate(){throw new Error("Server certificate is not implemented in your browser")}};function vs(){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 qo(r),setMediaKeys:(r,i)=>{if(i===null)return Promise.resolve(void 0);if(!(i instanceof qo))throw new Error("Custom setMediaKeys is supposed to be called with old webkit custom MediaKeys.");return i._setVideo(r)}}}function se(...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 Go(n,e){return(n[e+0]<<8)+(n[e+1]<<0)}function Rs(n,e){return n[e+0]*65536+n[e+1]*256+n[e+2]}function re(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 ce(n){return new Uint8Array([n>>>8&255,n&255])}function ye(n){return new Uint8Array([n>>>24&255,n>>>16&255,n>>>8&255,n&255])}function Zt(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 Hc(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 qc(n){return new Uint8Array([n&255,n>>>8&255])}function Br(n){return new Uint8Array([n&255,n>>>8&255,n>>>16&255,n>>>24&255])}function ks(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=Ho(t),a=o.indexOf("skd://"),s=a>-1?o.substring(a+6):o,d=zo(s),u=0,c=new Uint8Array(t.byteLength+4+d.byteLength+4+r.byteLength);return c.set(t),u+=t.length,c.set(Br(d.byteLength),u),u+=4,c.set(d,u),u+=d.byteLength,c.set(Br(r.byteLength),u),u+=4,c.set(r,u),c}function Mg(n){return Xe(n,"com.apple.fps")}function Gc(n,e){return Ct(()=>{if(n.webkitSetMediaKeys===void 0)throw new Error("No webKitMediaKeys API.");n.webkitSetMediaKeys(e)})}var Ps=class extends ae{constructor(e,t,r){super(),this._serverCertificate=r,this._videoElement=e,this._keyType=t,this._unbindSession=Z,this._closeSession=Z,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=ks(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("closed-by-application"),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)})}}},jo=class{constructor(e){if(gt===void 0)throw new Error("No WebKitMediaKeys API.");this._keyType=e,this._mediaKeys=new gt(e)}_setVideo(e){if(this._videoElement=e,this._videoElement===void 0)throw new Error("Video not attached to the MediaKeys");return Gc(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 Ps(this._videoElement,this._keyType,this._serverCertificate)}setServerCertificate(e){return this._serverCertificate=e,Promise.resolve(!0)}};function Yo(){if(gt===void 0)throw new Error("No WebKitMediaKeys API.");return{isTypeSupported:gt.isTypeSupported,createCustomMediaKeys:r=>new jo(r),setMediaKeys:(r,i)=>{if(i===null)return Gc(r,i);if(!(i instanceof jo))throw new Error("Custom setMediaKeys is supposed to be called with webkit custom MediaKeys.");return i._setVideo(r)}}}var Ag=xg("auto"),Yc=Ag;function xg(n){var o;let e,t,r=wg,i;if((n==="standard"||n==="auto"&&!ys())&&(Wt||!_(navigator.requestMediaKeySystemAccess)))e=(...a)=>navigator.requestMediaKeySystemAccess(...a),t=Te(["encrypted"]),i="standard";else{let a,s;if(n==="webkit"&&gt!==void 0){let d=Yo();t=jc(),a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="webkit"}else if(Es((o=J.HTMLVideoElement)==null?void 0:o.prototype)){t=Te(["needkey"]);let d=vs();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="older-webkit"}else if(gt!==void 0){t=jc();let d=Yo();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="webkit"}else if(cn&&Mt!==void 0){t=Te(["encrypted","needkey"]);let d=bs();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="ms"}else if(Xt!==void 0){t=Te(["encrypted","needkey"]);let d=Ss();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="moz"}else{t=Te(["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 c="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(c)}};a=c=>(u(),ee(typeof d.isTypeSupported=="function"),d.isTypeSupported(c)),s=c=>(u(),new d(c)),i="unknown"}e=function(d,u){if(!a(d))return Promise.reject(new Error("Unsupported key type"));for(let c=0;c<u.length;c++){let l=u[c],{videoCapabilities:f,audioCapabilities:p,initDataTypes:g,distinctiveIdentifier:b}=l,h=!0;if(h=h&&(_(g)||g.some(I=>I==="cenc")),h=h&&b!=="required",h){let I={initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",persistentState:"required",sessionTypes:["temporary","persistent-license"]};f!==void 0&&(I.videoCapabilities=f),p!==void 0&&(I.audioCapabilities=p);let T=s(d);return Promise.resolve(new Lr(d,T,I))}}return Promise.reject(new Error("Unsupported configuration"))}}return{requestMediaKeySystemAccess:e,onEncrypted:t,setMediaKeys:r,implementation:i}}function jc(){let n=Te(["needkey"],void 0);return(t,r,i)=>{n(t,o=>{let a=Y(o,{forceSessionRecreation:!0});r(a)},i)}}function wg(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 Et(n,e){let t=n.length,r=0;for(;r+8<=t;){let i=re(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(re(n,r+4)===e)return r+i<=t?r:-1;r+=i}return-1}function $o(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=Et(r,1836019558);if(i<0)break;let o=re(n,i+e),a=e+i+o;if(a>n.length)break;let s=Et(r,1835295092);if(s<0)break;let d=re(n,s+e),u=e+s+d;if(u>n.length)break;let c=Math.max(a,u),l=n.subarray(e,c);t.push(l),e=c}return t.length===0?[null,r]:[t,r]}function Og(n,e,t){return new Uint8Array(Array.prototype.slice.call(n,e,t))}function Dg(n,e,t){return n.slice(e,t)}var Cs=typeof Uint8Array.prototype.slice=="function"?Dg:Og;function Ms(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 $c(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 As(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=re(n,a),a+=4,i=re(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 _n(n,e,t,r,i){let o=n.length,a;for(let s=0;s<o;s+=a){let d=s;a=re(n,d),d+=4;let u=re(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&&re(n,d)===e&&re(n,d+4)===t&&re(n,d+8)===r&&re(n,d+12)===i)return d+=16,n.subarray(d,s+a)}}function xs(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=re(n,t);t+=4;let i=re(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 Qo(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=Cs(t,i[0],i[2]),a=Xo(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 Xo(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=Cs(n,t,t+16);return Be(r)}var Fr=Math.pow(2,32)-1;var ws={};function Qc(n){if(ws[n]!==void 0)return ws[n];let e=ve(n);return ws[n]=e,e}function ue(n,e){let t=e.length+8;return t<=Fr?se(ye(t),Qc(n),e):se(ye(1),Qc(n),Zt(t+8),e)}function we(n,e){return ue(n,se(...e))}function Kr(n){let e=Re(n,1836019558);return e===null?null:Re(e,1953653094)}function Xc(n){return $c(n,1836019558).reduce((t,r)=>{let i=Re(r,1953653094);return i!==null&&t.push(i),t},[])}function Vr(n){return Re(n,1835295092)}function Os(n){let e=Re(n,1836019574);if(e===null)return null;let t=Re(e,1953653099);return t===null?null:Re(t,1835297121)}function Zc(n,e=0){return Re(n.subarray(e),1701671783)}function zr(n){let e=Hc(n,8),t=Ho(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=Wo(ht(o));return Be(a).toLowerCase()}function Hr(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=re(n,o);o+=4;let d;if(a===0)d=re(n,o),o+=4,r+=re(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 c=Go(n,o);for(o+=2;--c>=0;){let l=re(n,o);o+=4;let f=(l&2147483648)>>>31,p=l&2147483647;if(f===1)throw new Error("sidx with reference_type `1` not yet implemented");let g=re(n,o);o+=4,o+=4,u.push({time:d,duration:g,timescale:s,range:[r,r+p-1]}),d+=g,r+=p}return u}function Ds(n){let e=Kr(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 re(t,4)}function Lg(n){let e=Re(n,1952868452);if(e===null)return;let t=1,r=Rs(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),re(e,t)):void 0}function Wr(n){let e=Xc(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=Rs(i,o);o+=3;let d=(s&256)>0,u=0;if(!d&&(u=Lg(r),u===void 0))return;let c=(s&1)>0,l=(s&4)>0,f=(s&512)>0,p=(s&1024)>0,g=(s&2048)>0,b=re(i,o);o+=4,c&&(o+=4),l&&(o+=4);let h=b,I=0;for(;h-- >0;)d?(I+=re(i,o),o+=4):I+=u,f&&(o+=4),p&&(o+=4),g&&(o+=4);t+=I}return t}function qr(n){let e=Os(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 re(t,r+16);if(i===0)return re(t,r+8)}function Ls(n){let e=n.length;if(e<4)throw new Error("Cannot update box length: box too short");let t=re(n,0);if(t===0)if(e>Fr){let r=new Uint8Array(e+8);return r.set(ye(1),0),r.set(n.subarray(4,8),4),r.set(Zt(e+8),8),r.set(n.subarray(8,e),16),r}else return n.set(ye(e),0),n;else if(t===1){if(e<16)throw new Error("Cannot update box length: box too short");return n.set(Zt(e),8),n}else{if(e<=Fr)return n.set(ye(e),0),n;{let r=new Uint8Array(e+8);return r.set(ye(1),0),r.set(n.subarray(4,8),4),r.set(Zt(e+8),8),r.set(n.subarray(8,e),16),r}}}function Jc(n){let e=[],t=0;for(;t<n.length;){let r=Zc(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}=Ts(r,a);a=s;let{end:u,string:c}=Ts(r,a);a=u;let l=re(r,a);a+=4;let f=re(r,a);a+=4;let p=re(r,a);a+=4;let g=re(r,a);a+=4;let b=r.subarray(a,i),h={schemeIdUri:d,value:c,timescale:l,presentationTimeDelta:f,eventDuration:p,id:g,messageData:b};e.push(h)}}if(e.length!==0)return e}function ef(n){let e=Ms(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=Ms(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=re(ve("pssh"),0);function Ng(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||re(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=re(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=xs(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=se(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=se(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 se(r,t)}function Gr(n,e,t){m.debug("Compat: Calling generateRequest on the MediaKeySession");let r;try{r=Ng(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 Ug(n){let e=[],t=0;for(;t<n.length;){if(n.length<t+8||re(n,t+4)!==Zo)return m.warn("Compat: Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}];let r=re(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:Xo(i,8),data:i};Bg(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 Bg(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)&&he(e.data,r.data))return!0}return!1}function Jo(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=Ug(i);return{type:t,values:o,forceSessionRecreation:r}}var Fg=100;async function jr(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,Fg);function o(){a(),r(t)}function a(){clearTimeout(i),n.removeEventListener("keystatuseschange",o)}})}var Jt=Yc;function X(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 Yr(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):X(t,"expired")?(m.debug("DRM: isSessionUsable: MediaKeySession given has an expired key",n.sessionId),!1):X(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 Ns(n,e,t,r){let{loadedSessionsStore:i,persistentSessionsStore:o}=n;return t==="temporary"?tf(i,e):o===null?(m.warn("DRM: Cannot create persistent MediaKeySession, PersistentSessionsStore not created."),tf(i,e)):Kg(i,o,e,r)}function tf(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 Kg(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&&Yr(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 Us(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 Bs(n,e,t,r,i){let o=null,{loadedSessionsStore:a,persistentSessionsStore:s}=e,d=a.reuse(n);if(d!==null){if(o=d.mediaKeySession,Yr(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 Us(a,r<=0?r:r-1),i.cancellationError!==null))throw i.cancellationError;let u=await Ns(e,n,t,i);return{type:u.type,value:{mediaKeySession:u.value.mediaKeySession,sessionType:u.value.sessionType,keySessionRecord:u.value.keySessionRecord}}}function Fs(){return!hr&&!$a&&!Ya&&!Xa}function nf(n){return!(pr&&n.indexOf("playready")!==-1)}var rf='<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 of(n){let e=zo(n),t=qc(e.length),r=new Uint8Array([1,0]),i=new Uint8Array([1,0]),o=Br(e.length+6),a=se(o,i,r,t,e),s=Ye("9a04f07998404286ab92e65be0885f95");return Vg(a,s)}function Vg(n,e){let t=ve("pssh"),r=new Uint8Array([0,0,0,0]),i=ye(n.length),o=ye(32+n.length);return se(o,t,r,e,i,n)}function Ks(){return cn}function zg(n,e){let{mimeType:t,codecs:r}=ea(n),{mimeType:i,codecs:o}=ea(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 Hg=7;function ea(n){var i;let[e,...t]=n.split(";"),r=(i=Q(t,o=>Xe(o,"codecs=")))!=null?i:"";return r=r.substring(Hg),r[0]==='"'&&(r=r.substring(1,r.length-1)),{mimeType:e,codecs:r}}var ta=zg;function Hn(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 Wg(n,e){var c,l,f,p,g,b,h,I,T,R;if(n.label!==e.label)return!1;let t=(c=e.distinctiveIdentifier)!=null?c:"optional",r=(l=n.distinctiveIdentifier)!=null?l:"optional";if(t!==r)return!1;let i=(f=e.persistentState)!=null?f:"optional",o=(p=n.persistentState)!=null?p:"optional";if(i!==o)return!1;let a=(g=e.initDataTypes)!=null?g:[],s=(b=n.initDataTypes)!=null?b:[];if(!sf(s,a))return!1;let d=(h=e.sessionTypes)!=null?h:[],u=(I=n.sessionTypes)!=null?I:[];if(!sf(u,d))return!1;for(let E of["audioCapabilities","videoCapabilities"]){let v=(T=n[E])!=null?T:[],k=(R=e[E])!=null?R:[];if(!v.every(P=>{var M,O,B,D,F,A;for(let C=0;C<k.length;C++){let N=k[C];if(((M=N.robustness)!=null?M:"")===((O=P.robustness)!=null?O:"")||((B=N.encryptionScheme)!=null?B:null)===((D=P.encryptionScheme)!=null?D:null)||((F=N.robustness)!=null?F:"")===((A=P.robustness)!=null?A:""))return!0}return!1}))return!1}return!0}function qg(n){let{EME_KEY_SYSTEMS:e}=L.getCurrent();for(let t of Object.keys(e))if(X(e[t],n))return t}function Gg(n){let{keyName:e,keyType:t,keySystemOptions:r}=n,i,o="optional",a="optional";Array.isArray(r.wantedSessionTypes)?(i=r.wantedSessionTypes,X(r.wantedSessionTypes,"persistent-license")&&!_(r.persistentLicenseConfig)&&(o="required")):_(r.persistentLicenseConfig)?i=["temporary"]:(o="required",i=["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:c}=L.getCurrent(),l,f,{audioCapabilitiesConfig:p,videoCapabilitiesConfig:g}=r;if((p==null?void 0:p.type)==="full")l=p.value;else{let h;(p==null?void 0:p.type)==="robustness"?h=p.value:e==="widevine"?h=u:t==="com.microsoft.playready.recommendation"?h=c:h=[],h.length===0&&h.push(void 0);let I=(p==null?void 0:p.type)==="contentType"?p.value:s;l=Hn(h,T=>I.map(R=>T!==void 0?{contentType:R,robustness:T}:{contentType:R}))}if((g==null?void 0:g.type)==="full")f=g.value;else{let h;(g==null?void 0:g.type)==="robustness"?h=g.value:e==="widevine"?h=u:t==="com.microsoft.playready.recommendation"?h=c:h=[],h.length===0&&h.push(void 0);let I=(g==null?void 0:g.type)==="contentType"?g.value:d;f=Hn(h,T=>I.map(R=>T!==void 0?{contentType:R,robustness:T}:{contentType:R}))}let b={initDataTypes:["cenc"],videoCapabilities:f,audioCapabilities:l,distinctiveIdentifier:a,persistentState:o,sessionTypes:i};return p!==void 0?g!==void 0?[b]:[b,de(oe({},b),{videoCapabilities:void 0})]:g!==void 0?[b,de(oe({},b),{audioCapabilities:void 0})]:[b,de(oe({},b),{audioCapabilities:void 0,videoCapabilities:void 0})]}function af(n,e){var u,c,l,f,p,g;let t=(c=(u=n.audioCapabilities)==null?void 0:u.map(b=>b.contentType))!=null?c:[],r=(f=(l=n.videoCapabilities)==null?void 0:l.map(b=>b.contentType))!=null?f:[],i=t.concat(r).filter(b=>b!==void 0),o=(p=e.videoCapabilities)==null?void 0:p.map(b=>b.contentType),a=(g=e.audioCapabilities)==null?void 0:g.map(b=>b.contentType),s=[...o!=null?o:[],...a!=null?a:[]].filter(b=>b!==void 0);return s.length===0?[]:i.map(b=>{let{codecs:h,mimeType:I}=ea(b),T=X(s,b);return{codec:h,mimeType:I,result:T}})}function Vs(n,e,t){m.info("DRM: Searching for compatible MediaKeySystemAccess");let r=e.reduce((o,a)=>{let{EME_KEY_SYSTEMS:s}=L.getCurrent(),d=s[a.type],u;if(!_(d))u=d.map(c=>({keyName:a.type,keyType:c,keySystemOptions:a}));else{let c=qg(a.type),l=a.type;u=[{keyName:c,keyType:l,keySystemOptions:a}]}return o.concat(u)},[]);return i(0);async function i(o){if(o>=r.length)throw new ge("INCOMPATIBLE_KEYSYSTEMS","No key system compatible with your wanted configuration has been found in the current browser.");if(_(Jt.requestMediaKeySystemAccess))throw new Error("requestMediaKeySystemAccess is not implemented in your browser.");let a=r[o],{keyType:s,keySystemOptions:d}=a,u=Gg(a);m.debug(`DRM: Request keysystem access ${s},${o+1} of ${r.length}`);let c,l=await je.getAttachedMediaKeysState(n);for(let f=0;f<u.length;f++){let p=u[f];if(l!==null&&!Ks()&&s===l.mediaKeySystemAccess.keySystem&&Jt.implementation===l.emeImplementation.implementation&&Wg(p,l.askedConfiguration))return m.info("DRM: Found cached compatible keySystem"),Promise.resolve({type:"reuse-media-key-system-access",value:{mediaKeySystemAccess:l.mediaKeySystemAccess,askedConfiguration:l.askedConfiguration,options:d,codecSupport:af(l.askedConfiguration,l.mediaKeySystemAccess.getConfiguration())}});try{return c=await jg(s,[p]),m.info("DRM: Found compatible keysystem",s,o+1),{type:"create-media-key-system-access",value:{options:d,mediaKeySystemAccess:c,askedConfiguration:p,codecSupport:af(p,c.getConfiguration())}}}catch(g){if(m.debug("DRM: Rejected access to keysystem",s,o+1,f),t.cancellationError!==null)throw t.cancellationError}}return i(o+1)}}async function jg(n,e){let t=await Jt.requestMediaKeySystemAccess(n,e);if(!nf(n))try{let i=(await t.createMediaKeys()).createSession(),o=of(rf);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 sf(n,e){for(let t=0;t<n.length;t++)if(!X(e,n[t]))return!1;return!0}function Wn(n,e){for(let t of n)if(!e.some(i=>he(i,t)))return!1;return!0}function df(n,e){for(let t of n)if(e.some(i=>he(i,t)))return!0;return!1}var $r=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(he(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&&Wn(t,this._keyIds))return!0;if(this._initializationData.keyIds!==void 0)return Wn(t,this._initializationData.keyIds)}return this._checkInitializationDataCompatibility(e)}_checkInitializationDataCompatibility(e){return e.keyIds!==void 0&&e.keyIds.length>0&&this._initializationData.keyIds!==void 0?Wn(e.keyIds,this._initializationData.keyIds):this._initializationData.type!==e.type?!1:this._initializationData.values.isCompatibleWith(e.values)}};var Qr=class{constructor(e){this._mediaKeys=e,this._storage=[]}createSession(e,t){let r=new $r(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"),Gr(e,t,r);if(i.isGeneratingRequest=!0,i.closingStatus.type!=="none")throw new Error("The `MediaKeySession` is being closed.");try{await Gr(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"),jr(e,t);if(r.isLoadingPersistentSession=!0,r.closingStatus.type!=="none")throw new Error("The `MediaKeySession` is being closed.");let i;try{i=await jr(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"}),Yg(t).then(()=>{e!==void 0&&(e.closingStatus={type:"done"}),r(!0)}).catch(a=>{e!==void 0&&(e.closingStatus={type:"failed"}),i(a)})}})}};async function Yg(n){m.debug("DRM: Trying to close a MediaKeySession",n.sessionId);try{await Oo(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 en(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 dt=class{constructor(e){this.initData=e}toJSON(){return Vo(this.initData)}static decode(e){return ht(e)}};function qn(n,e){var t,r;return(r=(t=uf(n,e))!=null?t:uf(e,n))!=null?r:!1}function uf(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=dt.decode(t.data):a=t.data.initData;let s;if(o.data instanceof Uint8Array?s=o.data:typeof o.data=="string"?s=dt.decode(o.data):s=o.data.initData,!he(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 c;d.data instanceof Uint8Array?c=d.data:typeof d.data=="string"?c=dt.decode(d.data):c=d.data.initData;let l;if(u.data instanceof Uint8Array?l=u.data:typeof u.data=="string"?l=dt.decode(u.data):l=u.data.initData,!he(c,l))return!1;break}if(r===e.length)return null}return!0}return null}function $g(n){fc(n,{save:"function",load:"function"},"persistentLicenseConfig")}var Xr=class{constructor(e){$g(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=Qg(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 dt(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:en(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=Vo(s);for(let u of o.keyIds)if(typeof u=="string"){if(d===u)return!0}else if(he(u.initData,s))return!0;return!1}))return i}else{let a=e.values.getFormattedValues();if(qn(a,o.values))return i}break;case 3:{let a=e.values.getFormattedValues();if(qn(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"?dt.decode(o.initData):o.initData.initData;if(he(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(he(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 Qg(n){return n.map(({systemId:e,data:t,hash:r})=>({systemId:e,hash:r,data:new dt(t)}))}var na=new WeakMap,En={prepare(n){na.set(n,null)},set(n,e){let t=e instanceof Uint8Array?e:new Uint8Array(e instanceof ArrayBuffer?e:e.buffer),r=en(t);na.set(n,{hash:r,serverCertificate:t})},hasOne(n){let e=na.get(n);if(e===void 0)return!1;if(e!==null)return!0},has(n,e){let t=na.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(en(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 Xr(e))}async function zs(n,e,t){let r=await Vs(n,e,t);if(t.cancellationError!==null)throw t.cancellationError;let{options:i,mediaKeySystemAccess:o,askedConfiguration:a,codecSupport:s}=r.value,d=await je.getAttachedMediaKeysState(n),u=Xg(i);if(r.value.options.reuseMediaKeys!==!1&&Fs()&&d!==null&&r.type==="reuse-media-key-system-access"){m.debug("DRM: Reusing already created MediaKeys");let{mediaKeys:f,loadedSessionsStore:p}=d;if(En.hasOne(f)===!1||!_(i.serverCertificate)&&En.has(f,i.serverCertificate))return{mediaKeys:f,mediaKeySystemAccess:o,askedConfiguration:a,stores:{loadedSessionsStore:p,persistentSessionsStore:u},options:i,codecSupport:s}}let c=await Zg(o);m.info("DRM: MediaKeys created with success");let l=new Qr(c);return{mediaKeys:c,mediaKeySystemAccess:o,askedConfiguration:a,stores:{loadedSessionsStore:l,persistentSessionsStore:u},options:i,codecSupport:s}}async function Zg(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 ge("CREATE_MEDIA_KEYS_ERROR",t)}}async function Hs(n,e,t){let r=await zs(n,e,t),{mediaKeys:i}=r;return n.mediaKeys!==null&&n.mediaKeys!==void 0&&i!==n.mediaKeys&&(m.debug("DRM: Disabling old MediaKeys"),await je.clearMediaKeys(n)),r}function Zr(n){let e=(Math.random()*2-1)*.3;return n*(e+1)}function Ws(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(c){if(t.cancellationError!==null)throw t.cancellationError;if(!_(a)&&!a(c)||d++>=o)throw c;typeof s=="function"&&s(c,d);let l=Jg(r,d,i);return await Sn(l),u()}}}function Jg(n,e,t){let r=n*Math.pow(2,e-1),i=Zr(r);return Math.min(i,t)}function qs(n,e){return n.indexOf("playready")!==-1&&(qt||pr)?Wo(e):e}var Gn=class n extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,n.prototype),this.reason=e}},Gs={EXPIRED:"expired",INTERNAL_ERROR:"internal-error",OUTPUT_RESTRICTED:"output-restricted"};function js(n,e,t){let{onKeyInternalError:r,onKeyOutputRestricted:i,onKeyExpiration:o}=e,a=[],s=[],d=[];n.keyStatuses.forEach((c,l)=>{let[f,p]=typeof c=="string"?[c,l]:[l,c],g=qs(t,new Uint8Array(p)),b={keyId:g.buffer,keyStatus:f};switch(m.hasLevel("DEBUG")&&m.debug(`DRM: key status update (${Be(g)}): ${f}`),f){case Gs.EXPIRED:{let h=new ge("KEY_STATUS_CHANGE_ERROR",`A decryption key expired (${Be(g)})`,{keyStatuses:[b,...d]});if(o==="error"||o===void 0)throw h;switch(o){case"close-session":throw new Gn(h);case"fallback":a.push(g);break;default:o==="continue"||o===void 0?s.push(g):He(o);break}d.push(b);break}case Gs.INTERNAL_ERROR:{let h=new ge("KEY_STATUS_CHANGE_ERROR",`A "${f}" status has been encountered (${Be(g)})`,{keyStatuses:[b,...d]});switch(r){case void 0:case"error":throw h;case"close-session":throw new Gn(h);case"fallback":a.push(g);break;case"continue":s.push(g);break;default:if(r!==void 0)He(r);else throw h}d.push(b);break}case Gs.OUTPUT_RESTRICTED:{let h=new ge("KEY_STATUS_CHANGE_ERROR",`A "${f}" status has been encountered (${Be(g)})`,{keyStatuses:[b,...d]});switch(i){case void 0:case"error":throw h;case"fallback":a.push(g);break;case"continue":s.push(g);break;default:if(i!==void 0)He(i);else throw h}d.push(b);break}default:s.push(g);break}});let u;return d.length>0&&(u=new ge("KEY_STATUS_CHANGE_ERROR","One or several problematic key statuses have been encountered",{keyStatuses:d})),{warning:u,blacklistedKeyIds:a,whitelistedKeyIds:s}}function Ys(n,e,t,r,i){m.info("DRM: Binding session events",n.sessionId);let{getLicenseConfig:o={}}=e,a=new U;a.linkToSignal(i),_(n.closed)||n.closed.then(()=>a.cancel()).catch(c=>{i.isCancelled()||(a.cancel(),r.onError(c))}),Uo(n,c=>{a.cancel(),r.onError(new ge("KEY_ERROR",c.type))},a.signal),Nc(n,()=>{m.info("DRM: keystatuseschange event received",n.sessionId);try{s()}catch(c){if(i.isCancelled()||a.isUsed()&&c instanceof Ir)return;a.cancel(),r.onError(c)}},a.signal),No(n,c=>{let l=c,f=new Uint8Array(l.message),p=w(l.messageType)?l.messageType:"license-request";m.info(`DRM: Received message event, type ${p}`,n.sessionId);let g=u(o.retry);Ws(()=>d(f,p),g,a.signal).then(async b=>{if(!a.isUsed())if(_(b))m.info("DRM: No license given, skipping session.update");else try{await eh(n,b)}catch(h){a.cancel(),r.onError(h)}},b=>{if(a.isUsed())return;a.cancel();let h=lf(b);if(!_(b)){let{fallbackOnLastTry:I}=b;if(I===!0){m.warn("DRM: Last `getLicense` attempt failed. Blacklisting the current session."),r.onError(new jn(h));return}}r.onError(h)})},a.signal),m.info("DRM: transmitting current keystatuses",n.sessionId),s();return;function s(){if(a.isUsed()||n.keyStatuses.size===0)return;let{warning:c,blacklistedKeyIds:l,whitelistedKeyIds:f}=js(n,e,t);c!==void 0&&(r.onWarning(c),a.isUsed())||r.onKeyUpdate({whitelistedKeyIds:f,blacklistedKeyIds:l})}function d(c,l){let f;return new Promise((p,g)=>{try{m.debug("DRM: Calling `getLicense`",l);let I=e.getLicense(c,l),T=_(o.timeout)?10*1e3:o.timeout;T>=0&&(f=setTimeout(()=>{g(new Jr(`"getLicense" timeout exceeded (${T} ms)`))},T)),Promise.resolve(I).then(b,h)}catch(I){h(I)}function b(I){f!==void 0&&clearTimeout(f),p(I)}function h(I){f!==void 0&&clearTimeout(f),g(I)}})}function u(c){return{totalRetry:c!=null?c:2,baseDelay:200,maxDelay:3e3,shouldRetry:l=>l instanceof Jr||_(l)||l.noRetry!==!0,onRetry:l=>r.onWarning(lf(l))}}}function lf(n){if(n instanceof Jr)return new ge("KEY_LOAD_TIMEOUT","The license server took too much time to respond.");let e=new ge("KEY_LOAD_ERROR","An error occured when calling `getLicense`.");return!_(n)&&w(n.message)&&(e.message=n.message),e}async function eh(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 ge("KEY_UPDATE_ERROR",r)}m.info("DRM: MediaKeySession update succeeded.")}var jn=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,jn.prototype),this.message=e}};async function th(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 ge("LICENSE_SERVER_CERTIFICATE_ERROR",r)}}async function $s(n,e){if(En.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"),En.prepare(n);try{let t=await th(n,e);return En.set(n,e),{type:"success",value:t}}catch(t){return{type:"error",value:jt(t)?t:new ge("LICENSE_SERVER_CERTIFICATE_ERROR","Unknown error when setting the server certificate.")}}}function Qs(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 Xs(n){if(Xe(n,"com.microsoft.playready")||n==="com.chromecast.playready"||n==="com.youtube.playready")return"9a04f07998404286ab92e65be0885f95";if(n==="com.widevine.alpha")return"edef8ba979d64acea3c827dcd51d21ed";if(Xe(n,"com.apple.fps"))return"94ce86fb07ff4f43adb893d2fa968ca2";if(Xe(n,"com.nagra."))return"adb41c242dbf4a6d958b4457c0d27b95"}var ei=class n{constructor(e){this._innerValues=e,this._lazyFormattedValues=null}constructRequestData(){return se(...this._innerValues.map(e=>e.data))}isCompatibleWith(e){let t=e instanceof n?e.getFormattedValues():e;return qn(this.getFormattedValues(),t)}getFormattedValues(){return this._lazyFormattedValues===null&&(this._lazyFormattedValues=nh(this._innerValues)),this._lazyFormattedValues}};function nh(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:en(t)}))}function Zs(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(ta(r,d))return s}}var ti=class extends ae{static hasEmeApis(){return!_(Jt.requestMediaKeySystemAccess)}constructor(e,t){super(),m.debug("DRM: Starting ContentDecryptor logic.");let r=new U;this._currentSessions=[],this._canceller=r,this._initDataQueue=[],this._stateData={state:0,isMediaKeysAttached:0,isInitDataQueueLocked:!0,data:null},this._supportedCodecWhenEncrypted=[],this.error=null,Jt.onEncrypted(e,i=>{m.debug("DRM: Encrypted event received from media element.");let o=Jo(i);o!==null&&this.onInitializationData(o)},r.signal),Hs(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=Xs(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:Jt,loadedSessionsStore:a.loadedSessionsStore,mediaKeySystemAccess:o,mediaKeys:i,askedConfiguration:s,keySystemOptions:r};m.debug("DRM: Attaching current MediaKeys"),je.attach(e,u).then(async()=>{if(this._isStopped())return;this._stateData.isMediaKeysAttached=2;let{serverCertificate:c}=r;if(!_(c)){let f=await $s(i,c);f.type==="error"&&this.trigger("warning",f.value)}if(this._isStopped())return;let l=this._stateData.state;this._stateData={state:2,isMediaKeysAttached:2,isInitDataQueueLocked:!1,data:{mediaKeysData:t}},l!==2&&this.trigger("stateChange",2),this._isStopped()||this._processCurrentInitDataQueue()}).catch(c=>{this._onFatalError(c)})}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"),Zs(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=de(oe({},e),{values:new ei(e.values)});this._processInitializationData(r,t).catch(i=>{this._onFatalError(i)})}async _processInitializationData(e,t){var b,h,I;m.hasLevel("DEBUG")&&m.debug("DRM: processing init data",(b=e.content)==null?void 0:b.adaptation.type,(h=e.content)==null?void 0:h.representation.bitrate,((I=e.keyIds)!=null?I:[]).map(T=>Be(T)).join(", "));let{mediaKeySystemAccess:r,stores:i,options:o}=t;if(this._tryToUseAlreadyCreatedSession(e,t)||this._isStopped())return;if(o.singleLicensePer==="content"){let T=Q(this._currentSessions,R=>R.source==="created-session");if(T!==void 0){let R=e.keyIds;if(R===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(R),e.content===void 0)m.warn("DRM: Unable to fallback from a non-decipherable quality.");else{if(m.hasLevel("DEBUG")){let E=R.reduce((v,k)=>`${v}, ${Be(k)}`,"");m.debug("DRM: Blacklisting new key ids",E)}this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:R,delistedKeyIds:[]})}return}}else if(o.singleLicensePer==="periods"&&e.content!==void 0){let{period:T}=e.content,R=this._currentSessions.filter(v=>v.source==="created-session"),E=new Set;ed(E,T);for(let v of R){let k=Array.from(E);for(let x of k)if(v.record.isAssociatedWithKeyId(x)){v.record.associateKeyIds(E.values());for(let P of k)!v.keyStatuses.whitelisted.some(M=>he(M,P))&&!v.keyStatuses.blacklisted.some(M=>he(M,P))&&v.keyStatuses.blacklisted.push(P);m.hasLevel("DEBUG")&&m.debug("DRM: Session already created for",Be(x),'under singleLicensePer "periods" policy'),this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:v.keyStatuses.whitelisted,blacklistedKeyIds:v.keyStatuses.blacklisted,delistedKeyIds:[]});return}}}this._lockInitDataQueue();let a;rh(r)&&(!_(o.persistentLicenseConfig)||!ih(r))?a="persistent-license":a="temporary";let{EME_DEFAULT_MAX_SIMULTANEOUS_MEDIA_KEY_SESSIONS:s,EME_MAX_STORED_PERSISTENT_SESSION_INFORMATION:d}=L.getCurrent(),u=typeof o.maxSessionCacheSize=="number"?o.maxSessionCacheSize:s,c=await Bs(e,i,a,u,this._canceller.signal);if(this._isStopped())return;let l={record:c.value.keySessionRecord,source:c.type,keyStatuses:{whitelisted:[],blacklisted:[]},blacklistedSessionError:null};this._currentSessions.push(l);let{mediaKeySession:f,sessionType:p}=c.value,g=!1;if(Ys(f,o,r.keySystem,{onKeyUpdate:T=>{let R=sh(e,l.record,o.singleLicensePer,l.source==="created-session",T.whitelistedKeyIds,T.blacklistedKeyIds);if(l.record.associateKeyIds(R.whitelisted),l.record.associateKeyIds(R.blacklisted),l.keyStatuses={whitelisted:R.whitelisted,blacklisted:R.blacklisted},l.record.getAssociatedKeyIds().length!==0&&p==="persistent-license"&&i.persistentSessionsStore!==null&&!g){let{persistentSessionsStore:E}=i;Qs(E,d-1),E.add(e,l.record.getAssociatedKeyIds(),f),g=!0}e.content!==void 0&&this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:R.whitelisted,blacklistedKeyIds:R.blacklisted,delistedKeyIds:[]}),this._unlockInitDataQueue()},onWarning:T=>{this.trigger("warning",T)},onError:T=>{var R;if(T instanceof Gn){m.warn("DRM: A session's closing condition has been triggered"),this._lockInitDataQueue();let E=this._currentSessions.indexOf(l);E>=0&&this._currentSessions.splice(E),e.content!==void 0&&this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:[],delistedKeyIds:l.record.getAssociatedKeyIds()}),(R=i.persistentSessionsStore)==null||R.delete(f.sessionId),i.loadedSessionsStore.closeSession(f).catch(v=>{let k=v instanceof Error?v:"unknown error";m.warn("DRM: failed to close expired session",k)}).then(()=>this._unlockInitDataQueue()).catch(v=>this._onFatalError(v)),this._isStopped()||this.trigger("warning",T.reason);return}if(!(T instanceof jn)){this._onFatalError(T);return}l.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(),c.type==="created-session"){let T=e.values.constructRequestData();try{await i.loadedSessionsStore.generateLicenseRequest(f,e.type,T)}catch(R){let E=i.loadedSessionsStore.getEntryForSession(f);if(E===null||E.closingStatus.type!=="none"){let v=this._currentSessions.indexOf(l);return v>=0&&this._currentSessions.splice(v,1),Promise.resolve()}throw new ge("KEY_GENERATE_REQUEST_ERROR",R instanceof Error?R.toString():"Unknown error")}}return Promise.resolve()}_tryToUseAlreadyCreatedSession(e,t){let{stores:r,options:i}=t,o=Q(this._currentSessions,c=>c.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 c;if(i.singleLicensePer===void 0||i.singleLicensePer==="init-data"){let{blacklisted:l}=o.keyStatuses;c=df(e.keyIds,l)}else{let{whitelisted:l}=o.keyStatuses;c=!Wn(e.keyIds,l)}if(c)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=Q(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 Ne("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 rh(n){let{sessionTypes:e}=n.getConfiguration();return e!==void 0&&X(e,"persistent-license")}function ih(n){let{sessionTypes:e}=n.getConfiguration();return e!==void 0&&X(e,"temporary")}function cf(n,e){return n.filter(t=>!e.some(r=>he(r,t)))}function oh(n,e){let t=n.getAssociatedKeyIds(),r=cf(t,e);return r.length>0&&m.hasLevel("DEBUG")&&m.debug("DRM: KeySessionRecord's keys missing in the license, blacklisting them",r.map(i=>Be(i)).join(", ")),r}function ah(n,e){let t=[],{keyIds:r}=n;return r!==void 0&&(t=cf(r,e)),t.length>0&&m.hasLevel("DEBUG")&&m.debug("DRM: init data keys missing in the license, blacklisting them",t.map(i=>Be(i)).join(", ")),t}function sh(n,e,t,r,i,o){var u;let a=[...i,...o],s=oh(e,a),d=a.concat(s);if(t!==void 0&&t!=="init-data"){let c=ah(n,d);d.push(...c);let{content:l}=n;if(r&&l!==void 0){if(t==="content"){let f=new Set,{manifest:p}=l;for(let g of p.periods)ed(f,g);Js(f,d)}else if(t==="periods"){let{manifest:f}=l;for(let p of f.periods){let g=new Set;if(ed(g,p),((u=n.content)==null?void 0:u.period.id)===p.id)Js(g,d);else{let b=Array.from(g);for(let h of b)if(d.some(T=>he(T,h))){Js(g,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=>he(o,r))||e.push(r)}function ed(n,e){let t=e.adaptations,r=Rr(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 Yn(n){let e=je.getAwaitedState(n);return e===null?null:[e.mediaKeySystemAccess.keySystem,e.mediaKeySystemAccess.getConfiguration()]}var ff=ti;function mf(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 c of u.representations)c.isSupported===void 0&&e.push({mimeType:(i=c.mimeType)!=null?i:"",codec:(a=(o=c.codecs)==null?void 0:o[0])!=null?a:""})}return e}var pf=[];function xt(n){X(pf,n)||(console.warn(n),pf.push(n))}var ni=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 ri=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 c=new Dr(u,r,{representationFilter:i});return c.representations.length>0&&c.supportStatus.hasSupportedCodec===!1&&t.push(c),c}).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.thumbnailTracks=e.thumbnailTracks.map(o=>({id:o.id,mimeType:o.mimeType,index:o.index,cdnMetadata:o.cdnMetadata,height:o.height,width:o.width,horizontalTiles:o.horizontalTiles,verticalTiles:o.verticalTiles,start:o.start,end:o.end,tileDuration:o.tileDuration})),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 fs(this)}getAdaptationsForType(e){let t=this.adaptations[e];return t!=null?t:[]}getAdaptation(e){return Q(this.getAdaptations(),({id:t})=>e===t)}getSupportedAdaptations(e){return pt(this,e)}containsTime(e,t){return cs(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,thumbnailTracks:this.thumbnailTracks.map(r=>({id:r.id,mimeType:r.mimeType,height:r.height,width:r.width,horizontalTiles:r.horizontalTiles,verticalTiles:r.verticalTiles,start:r.start,end:r.end,tileDuration:r.tileDuration}))}}};function ii(n,e,t){let r={updatedAdaptations:[],removedAdaptations:[],addedAdaptations:[],updatedThumbnailTracks:[],removedThumbnailTracks:[],addedThumbnailTracks:[]};n.start=e.start,n.end=e.end,n.duration=e.duration,n.streamEvents=e.streamEvents;let i=n.thumbnailTracks,o=e.thumbnailTracks;for(let d=0;d<i.length;d++){let u=i[d],c=pe(o,l=>l.id===u.id);if(c===-1){m.warn('Manifest: ThumbnailTrack "'+i[d].id+'" not found when merging.');let[l]=i.splice(d,1);d--,r.removedThumbnailTracks.push({id:l.id})}else{let[l]=o.splice(c,1);u.mimeType=l.mimeType,u.height=l.height,u.width=l.width,u.horizontalTiles=l.horizontalTiles,u.verticalTiles=l.verticalTiles,u.start=l.start,u.end=l.end,u.tileDuration=l.tileDuration,u.cdnMetadata=l.cdnMetadata,t===0?u.index._replace(l.index):u.index._update(l.index),r.updatedThumbnailTracks.push({id:u.id,mimeType:u.mimeType,height:u.height,width:u.width,horizontalTiles:u.horizontalTiles,verticalTiles:u.verticalTiles,start:u.start,end:u.end,tileDuration:u.tileDuration})}}o.length>0&&(m.warn(`Manifest: ${o.length} new Thumbnail tracks found when merging.`),r.addedThumbnailTracks.push(...o.map(d=>({id:d.id,mimeType:d.mimeType,height:d.height,width:d.width,horizontalTiles:d.horizontalTiles,verticalTiles:d.verticalTiles,start:d.start,end:d.end,tileDuration:d.tileDuration}))),n.thumbnailTracks.push(...o));let a=n.getAdaptations(),s=e.getAdaptations();for(let d=0;d<a.length;d++){let u=a[d],c=pe(s,l=>l.id===u.id);if(c===-1){m.warn('Manifest: Adaptation "'+a[d].id+'" not found when merging.');let[l]=a.splice(d,1);d--,r.removedAdaptations.push({id:l.id,trackType:l.type})}else{let[l]=s.splice(c,1),f=[],p=[],g=[];r.updatedAdaptations.push({adaptation:u.id,trackType:u.type,updatedRepresentations:f,addedRepresentations:p,removedRepresentations:g});let b=u.representations,h=l.representations.slice();for(let I=0;I<b.length;I++){let T=b[I],R=pe(h,E=>E.id===T.id);if(R===-1){m.warn(`Manifest: Representation "${b[I].id}" not found when merging.`);let[E]=b.splice(I,1);I--,g.push(E.id)}else{let[E]=h.splice(R,1);f.push(T.getMetadataSnapshot()),T.cdnMetadata=E.cdnMetadata,t===0?T.index._replace(E.index):T.index._update(E.index)}}h.length>0&&(m.warn(`Manifest: ${h.length} new Representations found when merging.`),u.representations.push(...h),p.push(...h.map(I=>I.getMetadataSnapshot())))}}if(s.length>0){m.warn(`Manifest: ${s.length} new Adaptations found when merging.`);for(let d of s){let u=n.adaptations[d.type];u===void 0?n.adaptations[d.type]=[d]:u.push(d),r.addedAdaptations.push(d.getMetadataSnapshot())}}return r}function gf(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=ii(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 c=e.slice(r,o),l=s-r,f=n.splice(r,l,...c);t.removedPeriods.push(...f.map(p=>({id:p.id,start:p.start,end:p.end}))),t.addedPeriods.push(...c.map(p=>p.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 hf(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=pe(n,({id:s})=>s===e[0].id);if(i<0)throw new te("MANIFEST_UPDATE_ERROR","Cannot perform partial update: incoherent data");let o=ii(n[i],e[0],1);t.updatedPeriods.push({period:Y(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 c=a;c<n.length;c++)if(d.id===n[c].id){u=c;break}if(u<0){let c=-1;for(let p=a;p<n.length;p++)if(d.start<n[p].start){c=p;break}let l=c-a,f=n.splice(a,l,d);t.addedPeriods.push(d.getMetadataSnapshot()),t.removedPeriods.push(...f.map(p=>({id:p.id,start:p.start,end:p.end})))}else{if(u>a){m.warn("Manifest: old Periods not found in new when updating, removing");let l=n.splice(a,u-a);t.removedPeriods.push(...l.map(f=>({id:f.id,start:f.start,end:f.end}))),u=a}let c=ii(n[u],d,0);t.updatedPeriods.push({period:Y(n[u].getMetadataSnapshot(),{adaptations:void 0}),result:c})}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 dh=et(),oi=class extends ae{constructor(e,t,r){var s;super();let{representationFilter:i,manifestUpdateUrl:o}=t;this.manifestFormat=0,this.id=dh(),this.expired=(s=e.expired)!=null?s:null,this.transport=e.transportType,this.clockOffset=e.clockOffset,this._cachedCodecSupport=new ni([]);let a=[];if(this.periods=e.periods.map(d=>new ri(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($t)});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($t)}):null}getPeriod(e){return Q(this.periods,t=>e===t.id)}getPeriodForTime(e){return Kn(this,e)}getNextPeriod(e){return Q(this.periods,t=>t.start>e)}getPeriodAfter(e){return Co(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 Tt(this)}updateCodecSupportList(e){this._cachedCodecSupport=e}updateRepresentationsDeciperability(e){let t=uh(this,e);t.length>0&&this.trigger("decipherabilityUpdate",t)}addRepresentationsToAvoid(e){let t=[];for(let r of e){let i=this.getPeriod(r.period.id);if(i===void 0)continue;let o=i.getAdaptation(r.adaptation.id);if(o===void 0)continue;let a=o.getRepresentation(r.representation.id);a!==void 0&&(a.shouldBeAvoided=!0,t.push({manifest:this,period:i,adaptation:o,representation:a}))}t.length>0&&this.trigger("representationAvoidanceUpdate",t)}getAdaptations(){xt("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(Object.prototype.hasOwnProperty.call(t,i)){let o=t[i];r.push(...o)}return r}getAdaptationsForType(e){xt("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 xt("manifest.getAdaptation(id) is deprecated. Please use manifest.period[].getAdaptation(id) instead"),Q(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 mf(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=gf(this.periods,e.periods);else{this.timeBounds.maximumTimeData=e.timeBounds.maximumTimeData,this.updateUrl=e.uris[0],r=hf(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 uh(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 Pt(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 $n=oi;function ut(n){return n instanceof _e?new ot("PIPELINE_LOAD_ERROR",n):Ee(n,{defaultCode:"PIPELINE_LOAD_ERROR",defaultReason:"Unknown error when fetching the Manifest"})}function lh(n){return n instanceof _e?n.type===hn.ERROR_HTTP_CODE?n.status>=500||n.status===404||n.status===415||n.status===412:n.type===hn.TIMEOUT||n.type===hn.ERROR_EVENT:n instanceof it?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:jt(n)&&n.code==="INTEGRITY_ERROR"}async function ai(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,c=l();if(c===void 0)throw new Error("No CDN to request");return f(c);function l(){if(n===null){let h=u.get(null);return h!==void 0&&h.isBlacklisted?void 0:null}else{if(e===null)return b(n);{let h=e.getCdnPreferenceForResource(n);return b(h)}}}async function f(h){try{return await t(h,i)}catch(I){if(U.isCancellationError(I))throw I;h!==null&&e!==null&&e.downgradeCdn(h);let T=u.get(h);if(T===void 0?(T={errorCounter:1,blockedUntil:void 0,isBlacklisted:!1},u.set(h,T)):T.errorCounter++,!lh(I))return T.blockedUntil=void 0,T.isBlacklisted=!0,p(I);if(T.errorCounter>s)T.blockedUntil=void 0,T.isBlacklisted=!0;else{let R=T.errorCounter,E=Math.min(o*Math.pow(2,R-1),a),v=Zr(E);T.blockedUntil=V()+v}return p(I)}}async function p(h){let I=l();if(i.isCancelled())throw i.cancellationError;if(I===void 0)throw h;if(d(h),i.isCancelled())throw i.cancellationError;return g(I,h)}function g(h,I){let T=u.get(h);if(T===void 0||T.blockedUntil===void 0)return f(h);let R=V(),E=T.blockedUntil-R;if(E<=0)return f(h);let v=new U,k=v.linkToSignal(i);return new Promise((x,P)=>{e==null||e.addEventListener("priorityChange",()=>{let B=l();if(i.isCancelled())throw i.cancellationError;if(B===void 0)return O(I);B!==h&&(v.cancel(),g(B,I).then(M,O))},v.signal),Qt(E,v.signal).then(()=>f(h).then(M,O),Z);function M(B){k(),x(B)}function O(B){k(),P(B)}})}function b(h){var T;if(u.size===0)return h[0];let I=V();return(T=h.filter(R=>{var E;return((E=u.get(R))==null?void 0:E.isBlacklisted)!==!0}).reduce((R,E)=>{var k;let v=(k=u.get(E))==null?void 0:k.blockedUntil;return v!==void 0&&v<=I&&(v=void 0),R===void 0?[E,v]:R[1]===void 0?R:v===void 0?[E,void 0]:v<R[1]?[E,v]:R},void 0))==null?void 0:T[0]}}function td(n,e,t){return ai(null,null,n,e,t)}var si=class extends ae{constructor(e,t,r){super(),this.scheduleManualRefresh=Z,this._manifestUrls=e,this._pipelines=t.manifest,this._transportName=t.transportName,this._settings=r,this._canceller=new U,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 $n?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(c=>{this.trigger("warning",ut(c))});try{let c=await d(a);return{parse:l=>this._parseLoadedManifest(c,l,a)}}catch(c){throw ut(c)}function d(c){var h;let{loadManifest:l}=o,f=r.requestTimeout===void 0?L.getCurrent().DEFAULT_REQUEST_TIMEOUT:r.requestTimeout,p=r.connectionTimeout===void 0?L.getCurrent().DEFAULT_CONNECTION_TIMEOUT:r.connectionTimeout;f<0&&(f=void 0),p<0&&(p=void 0);let g={timeout:f,connectionTimeout:p,cmcdPayload:(h=r.cmcdDataBuilder)==null?void 0:h.getCmcdDataForManifest(i)};return td(()=>l(c,g,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 b;let i=V(),o=this._canceller.signal,a=this.trigger.bind(this),{sendingTime:s,receivedTime:d}=e,u=this._getBackoffSetting(h=>{this.trigger("warning",ut(h))}),c=r!=null?r:(b=this._manifestUrls)==null?void 0:b[0],l={externalClockOffset:t.externalClockOffset,unsafeMode:t.unsafeMode,previousManifest:t.previousManifest,originalUrl:c};try{let h=this._pipelines.parseManifest(e,l,p,o,f);if(ch(h)){let{manifest:I,warnings:T}=await h;return g(I,T)}else return g(h.manifest,h.warnings)}catch(h){throw Ee(h,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"})}async function f(h){try{return await td(h,u,o)}catch(I){throw ut(I)}}function p(h){for(let I of h){if(o.isCancelled())return;let T=Ee(I,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"});a("warning",T)}}function g(h,I){p(I);let T=V()-i;return m.info(`MF: Manifest parsed in ${T}ms`),{manifest:h,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}=L.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}=L.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:V()-t,c=Math.max(this._settings.minimumManifestUpdateInterval-u,0),l=new U;if(l.linkToSignal(this._canceller.signal),this.scheduleManualRefresh=f=>{let{enablePartialRefresh:p,delay:g,canUseUnsafeMode:b}=f,h=b&&d,I=t===void 0?0:V()-t,T=Math.max(this._settings.minimumManifestUpdateInterval-I,0),R=setTimeout(()=>{l.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:p,unsafeMode:h})},Math.max((g!=null?g:0)-I,T));l.signal.register(()=>{clearTimeout(R)})},e.expired!==null){let f=setTimeout(()=>{var p;(p=e.expired)==null||p.then(()=>{l.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},Z)},c);l.signal.register(()=>{clearTimeout(f)})}if(e.lifetime!==void 0&&e.lifetime>=0){let f=e.lifetime*1e3-u,p;s===void 0?p=f:e.lifetime<3&&s>=100?(p=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,p)):s>=e.lifetime*1e3/10?(p=Math.min(Math.max(f,0)+s,f*6),m.info("MUS: Manifest took too long to parse. Postponing next request",p,p)):p=f;let g=setTimeout(()=>{l.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},Math.max(p,c));l.signal.register(()=>{clearTimeout(g)})}}_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:c,parsingTime:l}=d,f=V();if(o)e.replace(u);else try{e.update(u)}catch(g){let b=g instanceof Error?g.message:"unknown error";m.warn(`MUS: Attempt to update Manifest failed: ${b}`,"Re-downloading the Manifest fully");let{FAILED_PARTIAL_UPDATE_MANIFEST_REFRESH_DELAY:h}=L.getCurrent(),I=c===void 0?0:V()-c,T=Math.max(this._settings.minimumManifestUpdateInterval-I,0),R=Z,E=setTimeout(()=>{R(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:!1})},Math.max(h-I,T));R=this._canceller.signal.register(()=>{clearTimeout(E)});return}let p=V()-f;this._recursivelyRefreshManifest(e,{sendingTime:c,parsingTime:l,updatingTime:p})}).catch(d=>{this._isRefreshPending=!1,this._onFatalError(d)}))}_onFatalError(e){this._canceller.isUsed()||(this.trigger("error",e),this.dispose())}};function ch(n){return n instanceof Promise}var nd=si;function rd(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 id=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}},yf=id;var fh=et();function od({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=X(["audio","video"],n)?new yf:void 0,{loadSegment:u,parseSegment:c}=e;return async function(f,p,g){var j,$,z;let{segment:b,adaptation:h,representation:I,manifest:T,period:R}=f,E=bn(f),v=fh(),k,x=[],P=0,M=!1,O={segment:b,type:h.type,language:h.language,isLive:T.isLive,periodStart:R.start,periodEnd:R.end,mimeType:I.mimeType,codecs:I.codecs[0],manifestPublishTime:T.publishTime},B={onProgress(H){var q;k===void 0&&H.totalSize!==void 0&&H.size<H.totalSize&&((q=i.onProgress)==null||q.call(i,{duration:H.duration,size:H.size,totalSize:H.totalSize,timestamp:V(),id:v}))},onNewChunk(H){p.onChunk(C(H,!0))}},D=d!==void 0?d.get(f):null;if(D!==null)return m.debug("SF: Found wanted segment in cache",E),p.onChunk(C(D,!1)),Promise.resolve();m.debug("SF: Beginning request",E),(j=i.onRequestBegin)==null||j.call(i,{requestTimestamp:V(),id:v,content:f}),g.register(F);try{let H=await ai(f.representation.cdnMetadata,t,A,Y({onRetry:N},o),g);if(H.resultType==="segment-loaded"){let q=H.resultData.responseData;d!==void 0&&d.add(f,H.resultData.responseData),p.onChunk(C(q,!1))}else H.resultType==="segment-created"&&p.onChunk(C(H.resultData,!1));m.debug("SF: Segment request ended with success",E),p.onAllChunksReceived(),H.resultType!=="segment-created"?(k=H.resultData,K()):k=null,g.isCancelled()||($=i.onRequestEnd)==null||$.call(i,{id:v}),g.deregister(F)}catch(H){throw g.deregister(F),k=null,H instanceof Pe?(m.debug("SF: Segment request aborted",E),H):(m.debug("SF: Segment request failed",E),(z=i.onRequestEnd)==null||z.call(i,{id:v}),ut(H))}function F(){var H;k===void 0&&(m.debug("SF: Segment request cancelled",E),k=null,(H=i.onRequestEnd)==null||H.call(i,{id:v}))}function A(H){return s.cmcdPayload=r==null?void 0:r.getCmcdDataForSegmentRequest(f),u(H,O,s,g,B)}function C(H,q){x.push(!1);let ie=x.length-1;return function(le){let be={data:H,isChunked:q};try{let me=c(be,O,le);return x[ie]||(P=P!==void 0&&me.segmentType==="media"&&me.chunkInfos!==null&&me.chunkInfos.duration!==void 0?P+me.chunkInfos.duration:void 0,x[ie]=!0,K()),me}catch(me){throw Ee(me,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}}}function N(H){p.onRetry(ut(H))}function K(){var H;M||!_(k)&&k.size!==void 0&&k.requestDuration!==void 0&&x.length>0&&x.every(q=>q)&&(M=!0,(H=i.onMetrics)==null||H.call(i,{size:k.size,requestDuration:k.requestDuration,content:f,segmentDuration:P}))}}}function If({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}=L.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 di=class extends ae{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 G({initSegment:null,segmentQueue:[]}),i=new U;i.signal.register(()=>{r.finish()});let o={content:e,downloadQueue:r,initSegmentInfoRef:t?new G(void 0):new G(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 c=d[0];if(u.segment.id!==c.segment.id){m.debug("SQ: Next media segment changed, cancelling previous",e.adaptation.type),this._restartMediaSegmentDownloadingQueue(o);return}u.priority!==c.priority&&(m.debug("SQ: Priority of next media segment changed, updating",e.adaptation.type,u.priority,c.priority),this._segmentFetcher.updatePriority(u.request,c.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 R;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 U,c=o===null?Z:u.linkToSignal(o.signal),{segment:l,priority:f}=d,p=Y({segment:l,nextSegment:(R=s[1])==null?void 0:R.segment},r),g=!1,b=!1;u.signal.register(()=>{e.mediaSegmentRequest=null,!g&&(e.mediaSegmentAwaitingInitMetadata===l.id&&(e.mediaSegmentAwaitingInitMetadata=null),g=!0,b=!1)});let h=E=>{ee(E.segmentType==="media","Should have loaded a media segment."),this.trigger("parsedMediaSegment",Y({},E,{segment:l}))},I=()=>{let E=t.getValue().segmentQueue;if(E.length===0){g=!0,this.trigger("emptyQueue",null);return}else E[0].segment.id===l.id&&E.shift();g=!0,a()},T=this._segmentFetcher.createRequest(p,f,{onRetry:E=>{this.trigger("requestRetry",{segment:l,error:E})},beforeInterrupted(){m.info("SQ: segment request interrupted temporarly.",l.id,l.time)},onChunk:E=>{let v=i.getValue();v!==void 0?h(E(v!=null?v:void 0)):(b=!0,i.waitUntilDefined(k=>{h(E(k!=null?k:void 0))},{clearSignal:u.signal}))},onAllChunksReceived:()=>{b?(e.mediaSegmentAwaitingInitMetadata=l.id,i.waitUntilDefined(()=>{e.mediaSegmentAwaitingInitMetadata=null,b=!1,this.trigger("fullyLoadedSegment",l)},{clearSignal:u.signal})):this.trigger("fullyLoadedSegment",l)},beforeEnded:()=>{c(),e.mediaSegmentRequest=null,b?i.waitUntilDefined(I,{clearSignal:u.signal}):I()}},u.signal);T.catch(E=>{c(),g||(g=!0,this.stop(),this.trigger("error",E))}),e.mediaSegmentRequest={segment:l,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 U,a=e.currentCanceller===null?Z:o.linkToSignal(e.currentCanceller.signal),{segment:s,priority:d}=t,u=Y({segment:s,nextSegment:void 0},r),c=!1,l=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,c=!0},onChunk:f=>{var g;let p=f(void 0);ee(p.segmentType==="init","Should have loaded an init segment."),this.trigger("parsedInitSegment",Y({},p,{segment:s})),p.segmentType==="init"&&i.setValue((g=p.initTimescale)!=null?g:null)},onAllChunksReceived:()=>{this.trigger("fullyLoadedSegment",s)}},o.signal);l.catch(f=>{a(),c||(c=!0,this.stop(),this.trigger("error",f))}),o.signal.register(()=>{e.initSegmentRequest=null,!c&&(c=!0)}),e.initSegmentRequest={segment:s,priority:d,request:l,canceller:o}}};var li=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 st(i,(a,s)=>(o={hasEnded:!1,priority:t,trigger:()=>{if(o.hasEnded)return;let u=()=>{p(),this._endTask(o)},c=g=>{r.beforeEnded(),u(),a(g)},l=g=>{u(),s(g)},f=new U,p=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(c).catch(g=>{!i.isCancelled()&&f.isUsed()&&g instanceof Pe||l(g)})},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=ui(e.taskFn,this._waitingQueue);if(t>=0)this._waitingQueue.splice(t,1);else{let r=ui(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=ui(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=ui(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=ui(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 ui(n,e){return pe(e,t=>t.taskFn===n)}var ci=class{constructor(e,t,r,i){let{MIN_CANCELABLE_PRIORITY:o,MAX_HIGH_PRIORITY_LEVEL:a}=L.getCurrent();this._transport=e,this._prioritizer=new li({prioritySteps:{high:a,low:o}}),this._cdnPrioritizer=t,this._backoffOptions=i,this._cmcdDataBuilder=r}createSegmentQueue(e,t,r){let i=If(this._backoffOptions),o=this._transport[e],a=od({bufferType:e,pipeline:o,cdnPrioritizer:this._cdnPrioritizer,cmcdDataBuilder:this._cmcdDataBuilder,eventListeners:t,requestOptions:i}),s=rd(this._prioritizer,a);return new di(s,r)}};var ad=ci;function sd(n,e){let{loadThumbnail:t}=n;return async function(i,o,a,s){let d;a.connectionTimeout===void 0||a.connectionTimeout<0?d=void 0:d=a.connectionTimeout;let u={timeout:a.requestTimeout<0?void 0:a.requestTimeout,connectionTimeout:d,cmcdPayload:void 0};m.debug("TF: Beginning thumbnail request",i.time),s.register(l);let c;try{if(c=await ai(o.cdnMetadata,e,f,Y({onRetry:p},a),s),s.isCancelled())return Promise.reject(s.cancellationError);m.debug("TF: Thumbnail request ended with success",i.time),s.deregister(l)}catch(g){throw s.deregister(l),g instanceof Pe?(m.debug("TF: Thumbnail request aborted",i.time),g):(m.debug("TF: Thumbnail request failed",i.time),ut(g))}try{return n.parseThumbnail(c.responseData,{thumbnail:i,thumbnailTrack:o})}catch(g){throw Ee(g,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}function l(){m.debug("TF: Thumbnail request cancelled",i.time)}function f(g){return t(g,i,u,s)}function p(g){let b=ut(g);m.warn("TF: Thumbnail request retry ",i.time,b)}}}function ra({maxRetry:n,requestTimeout:e,connectionTimeout:t}){let{DEFAULT_MAX_THUMBNAIL_REQUESTS_RETRY_ON_ERROR:r,DEFAULT_THUMBNAIL_REQUEST_TIMEOUT:i,DEFAULT_THUMBNAIL_CONNECTION_TIMEOUT:o,INITIAL_BACKOFF_DELAY_BASE:a,MAX_BACKOFF_DELAY_BASE:s}=L.getCurrent();return{maxRetry:n!=null?n:r,baseDelay:a.REGULAR,maxDelay:s.REGULAR,requestTimeout:e===void 0?i:e,connectionTimeout:t===void 0?o:t}}var dd=sd;var vn=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 Q(this._array,e)}has(e){return X(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 fi=class extends ae{constructor(e,t,r){super(),this._canceller=new U,this._manifest=e,this._activeStreams=new Map,this._allBufferTypes=r,this._lastCurrentPeriodId=null;let i=new ud(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 vn((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)}},ud=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=ia(this._lastVideoAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}}else if(this._lastVideoAdaptation===null){let e=ia(this._lastAudioAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}else{let e=ia(this._lastAudioAdaptation),t=ia(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=oa(this._lastVideoAdaptation))!=null?e:void 0;if(this._lastVideoAdaptation===null)return(t=oa(this._lastAudioAdaptation))!=null?t:void 0;{let r=oa(this._lastAudioAdaptation),i=oa(this._lastVideoAdaptation);return typeof r!="number"||typeof i!="number"?void 0:Math.min(r,i)}}}};function ia(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 oa(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 ld(n,e,t,r,i,o){o.register(()=>{e.interruptDurationSetting()});let a=new fi(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 bf=6,cd=4e3,aa=6e3,mh=6e4,mi=class{constructor(e){this._segmentSinksStore=e,this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=null,this._lastFlushAttempt=null,this._lastSegmentInfo={audio:[],video:[]}}onNewObservation(e){var h,I;let t=V();if(this._addPositionToHistory(e,t),this._ignoreFreezeUntil!==null&&t<this._ignoreFreezeUntil)return null;this._ignoreFreezeUntil=null;let{UNFREEZING_SEEK_DELAY:r,UNFREEZING_DELTA_POSITION:i,FREEZING_FLUSH_FAILURE_DELAY:o}=L.getCurrent(),{readyState:a,rebuffering:s,freezing:d,fullyLoaded:u}=e,c=e.position.getPolled(),l=Sf(e.bufferGap);if(!(d!==null||s!==null&&a===1&&(l>=bf||u)))return this._decipherabilityFreezeStartingTimestamp=null,null;let p=(I=(h=d==null?void 0:d.timestamp)!=null?h:s==null?void 0:s.timestamp)!=null?I:null;if(m.info("FR: Freeze detected",p,t-(p!=null?p:t)),this._lastFlushAttempt!==null&&t-this._lastFlushAttempt.timestamp<o.MAXIMUM&&t-this._lastFlushAttempt.timestamp>=o.MINIMUM&&Math.abs(c-this._lastFlushAttempt.position)<o.POSITION_DELTA){let T=this._getStrategyIfFlushingFails(c);return this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+aa,T}let b=this._checkForDecipherabilityRelatedFreeze(e,t);return b!==null?b:p!==null&&t-p>r?(this._lastFlushAttempt={timestamp:t,position:c+i},m.debug("FR: trying to flush to un-freeze"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+aa,{type:"flush",value:{relativeSeek:i}}):null}_checkForDecipherabilityRelatedFreeze(e,t){let{readyState:r,rebuffering:i,freezing:o,fullyLoaded:a}=e,s=Sf(e.bufferGap),d=i!==null&&t-i.timestamp>cd,u=o!==null&&t-o.timestamp>cd;(d||u)&&(s>=bf||a)&&r<=1?this._decipherabilityFreezeStartingTimestamp===null&&(m.debug("FR: Start of a potential decipherability freeze detected"),this._decipherabilityFreezeStartingTimestamp=t):this._decipherabilityFreezeStartingTimestamp=null;let l=this._decipherabilityFreezeStartingTimestamp!==null&&V()-this._decipherabilityFreezeStartingTimestamp>cd,f=!0,p=!0;for(let g of["audio","video"]){let b=this._segmentSinksStore.getStatus(g);if(b.type==="initialized")for(let h of b.value.getLastKnownInventory()){let{representation:I}=h.infos;if(I.decipherable===!1)return m.warn("FR: we have undecipherable segments left in the buffer, reloading"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+aa,{type:"reload",value:null};I.contentProtections!==void 0&&(p=!1,I.decipherable!==!0&&(f=!1))}}return l&&!p&&f?(m.warn("FR: we are frozen despite only having decipherable segments left in the buffer, reloading"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+aa,{type:"reload",value:null}):null}_getStrategyIfFlushingFails(e){m.warn("FR: A recent flush seemed to have no effect on freeze, checking for transitions");let t=[];for(let r of["audio","video"]){let i=this._lastSegmentInfo[r];if(i.length===0)continue;let o=i[i.length-1];if(o.segment===null)continue;let a=o.segment,s;for(let d=i.length-2;d>=0;d--){let u=i[d];if(u.segment===null){s=u;break}else if(u.segment.infos.representation.uniqueId!==a.infos.representation.uniqueId&&o.timestamp-u.timestamp<5e3){s=u;break}else u.segment.start===a.start&&e-u.position<3e3&&(o=u)}if(s===void 0||s.segment===null)m.debug("FR: Freeze when beginning to play a content, try avoiding this quality"),t.push({adaptation:a.infos.adaptation,period:a.infos.period,representation:a.infos.representation});else{if(a.infos.period.id!==s.segment.infos.period.id)return m.debug("FR: Freeze when switching Period, reloading"),{type:"reload",value:null};a.infos.representation.uniqueId!==s.segment.infos.representation.uniqueId&&(m.warn("FR: Freeze when switching Representation, avoiding",a.infos.representation.bitrate),t.push({adaptation:a.infos.adaptation,period:a.infos.period,representation:a.infos.representation}))}}return t.length>0?{type:"avoid-representations",value:t}:(m.debug("FR: Reloading because flush doesn't work"),{type:"reload",value:null})}_addPositionToHistory(e,t){var i,o;let r=e.position.getPolled();for(let a of["audio","video"]){let s=this._segmentSinksStore.getStatus(a);if(s.type==="initialized")for(let c of s.value.getLastKnownInventory())((i=c.bufferedStart)!=null?i:c.start)<=r&&((o=c.bufferedEnd)!=null?o:c.end)>r&&this._lastSegmentInfo[a].push({segment:c,position:r,timestamp:t});else this._lastSegmentInfo[a].push({segment:null,position:r,timestamp:t});if(this._lastSegmentInfo[a].length>100){let c=this._lastSegmentInfo[a].length-100;this._lastSegmentInfo[a].splice(0,c)}let d=t-mh,u;for(u=0;u<this._lastSegmentInfo[a].length&&!(this._lastSegmentInfo[a][u].timestamp>d);u++);u>0&&this._lastSegmentInfo[a].splice(0,u)}}};function Sf(n){return n!==void 0&&isFinite(n)?n:0}async function fd(n,e,t,r,i){let o=e.getPeriod(t);if(o===void 0)throw new Error("Wanted Period not found.");let a=Q(o.thumbnailTracks,d=>d.id===r);if(a===void 0)throw new Error("Wanted Period has no thumbnail track.");let s=a.index.getSegments(i,1)[0];if(s===void 0)throw new Error("No thumbnail for the given timestamp");return n(s,a,ra({}),new U().signal)}function md(n,e){["video","audio","text"].forEach(t=>{var i;let r=e.getStatus(t);r.type==="initialized"&&r.value.synchronizeInventory((i=n.buffered[t])!=null?i:[])})}function sa({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&&ph(n,o,a,t.getValue(),r.getValue(),i).catch(d=>{if(i.isCancelled()&&U.isCancellationError(d))return;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 ph(n,e,t,r,i,o){if(!isFinite(r)&&!isFinite(i))return Promise.resolve();let a=[],{innerRange:s,outerRanges:d}=dc(t,e),u=()=>{if(isFinite(r)){for(let l of d)e-r>=l.end?a.push(l):e>=l.end&&e-r>l.start&&e-r<l.end&&a.push({start:l.start,end:e-r});_(s)||e-r>s.start&&a.push({start:s.start,end:e-r})}},c=()=>{if(isFinite(i)){for(let l of d)e+i<=l.start?a.push(l):e<=l.start&&e+i<l.end&&e+i>l.start&&a.push({start:e+i,end:l.end});_(s)||e+i<s.end&&a.push({start:e+i,end:s.end})}};u(),c();for(let l of a)if(l.start<l.end){if(m.debug("GC: cleaning range from SegmentSink",l.start,l.end),o.cancellationError!==null)throw o.cancellationError;await n.removeBuffer(l.start,l.end)}}var pi=class{constructor(e,t){this._history=[],this._lifetime=e,this._maxHistoryLength=t}addBufferedSegment(e,t){let r=V();this._history.push({date:r,buffered:t,context:e}),this._cleanHistory(r)}getHistoryFor(e){return this._history.filter(t=>Pt(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 gi=class{constructor(){let{BUFFERED_HISTORY_RETENTION_TIME:e,BUFFERED_HISTORY_MAXIMUM_ENTRIES:t}=L.getCurrent();this._inventory=[],this._bufferedHistory=new pi(e,t)}reset(){this._inventory.length=0}synchronizeBuffered(e){var d,u,c,l,f,p,g;let t=this._inventory,r=0,i=t[0],{MINIMUM_SEGMENT_SIZE:o}=L.getCurrent(),a=i==null?void 0:i.infos.adaptation.type;if(m.hasLevel("DEBUG")){let b=e.map(h=>`${h.start}-${h.end}`).join(",");m.debug(`SI: synchronizing ${a!=null?a:"unknown"} buffered ranges:`,b)}let s=e.length;for(let b=0;b<s;b++){if(i===void 0)return;let h=e[b].start,I=e[b].end;if(I-h<o){m.warn("SI: skipped range when synchronizing because it was too small",a,h,I);continue}let T=r;for(;i!==void 0&&((d=i.bufferedEnd)!=null?d:i.end)-h<o;)i=t[++r];let R=null,E=r-T;if(E>0){let k=t[T+E-1];R={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 P of x)P.bufferedStart===void 0&&P.bufferedEnd===void 0&&P.status!==2&&this._bufferedHistory.addBufferedSegment(P.infos,null);r=T}if(i===void 0)return;if(I-((c=i.bufferedStart)!=null?c:i.start)>=o){if(gh(i,h,R,a),r===t.length-1){_f(i,I,a);return}i=t[++r];let k=(l=i.bufferedStart)!=null?l:i.start,x=(f=i.bufferedEnd)!=null?f:i.end,P=b<s-1?e[b+1].start:void 0;for(;i!==void 0&&!(I<k||I-k<o&&x-I>=o||P!==void 0&&I-k<x-P);){let M=t[r-1];M.bufferedEnd===void 0&&(i.precizeStart?M.bufferedEnd=i.start:M.infos.segment.complete?M.bufferedEnd=M.end:M.bufferedEnd=i.start,m.debug("SI: calculating buffered end of contiguous segment",a,M.bufferedEnd,M.end)),i.bufferedStart=M.bufferedEnd,i=t[++r],i!==void 0&&(k=(p=i.bufferedStart)!=null?p:i.start,x=(g=i.bufferedEnd)!=null?g:i.end)}}let v=t[r-1];v!==void 0&&_f(v,I,a)}if(!_(i)){let{SEGMENT_SYNCHRONIZATION_DELAY:b}=L.getCurrent(),h=V();for(let I=r;I<t.length;I++){let T=t[I];h-T.insertionTs>=b&&(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(I,1),I--)}}a!==void 0&&m.hasLevel("DEBUG")&&m.debug(`SI: current ${a} inventory timeline:
2
- `+hh(this._inventory))}insertChunk({period:e,adaptation:t,representation:r,segment:i,chunkSize:o,start:a,end:s},d,u){if(i.isInit)return;let c=t.type;if(a>=s){m.warn("SI: Invalid chunked inserted: starts before it ends",c,a,s);return}let l=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 g=l.length-1;g>=0;g--){let b=l[g];if(b.start<=a)if(b.end<=a){for(m.debug("SI: Pushing segment strictly after previous one.",c,a,b.end),this._inventory.splice(g+1,0,f),g+=2;g<l.length&&l[g].start<f.end;){if(l[g].end>f.end){m.debug("SI: Segment pushed updates the start of the next one",c,f.end,l[g].start),l[g].start=f.end,l[g].bufferedStart=void 0,l[g].precizeStart=l[g].precizeStart&&f.precizeEnd;return}m.debug("SI: Segment pushed removes the next one",c,a,s,l[g].start,l[g].end),l.splice(g,1)}return}else if(b.start===a)if(b.end<=s){for(m.debug("SI: Segment pushed replace another one",c,a,s,b.end),this._inventory.splice(g,1,f),g+=1;g<l.length&&l[g].start<f.end;){if(l[g].end>f.end){m.debug("SI: Segment pushed updates the start of the next one",c,f.end,l[g].start),l[g].start=f.end,l[g].bufferedStart=void 0,l[g].precizeStart=l[g].precizeStart&&f.precizeEnd;return}m.debug("SI: Segment pushed removes the next one",c,a,s,l[g].start,l[g].end),l.splice(g,1)}return}else{m.debug("SI: Segment pushed ends before another with the same start",c,a,s,b.end),l.splice(g,0,f),b.start=f.end,b.bufferedStart=void 0,b.precizeStart=b.precizeStart&&f.precizeEnd;return}else if(b.end<=f.end){for(m.debug("SI: Segment pushed updates end of previous one",c,a,s,b.start,b.end),this._inventory.splice(g+1,0,f),b.end=f.start,b.bufferedEnd=void 0,b.precizeEnd=b.precizeEnd&&f.precizeStart,g+=2;g<l.length&&l[g].start<f.end;){if(l[g].end>f.end){m.debug("SI: Segment pushed updates the start of the next one",c,f.end,l[g].start),l[g].start=f.end,l[g].bufferedStart=void 0,l[g].precizeStart=l[g].precizeStart&&f.precizeEnd;return}m.debug("SI: Segment pushed removes the next one",c,a,s,l[g].start,l[g].end),l.splice(g,1)}return}else{m.warn("SI: Segment pushed is contained in a previous one",c,a,s,b.start,b.end);let h={status:b.status,insertionTs:b.insertionTs,chunkSize:b.chunkSize,splitted:!0,start:f.end,end:b.end,precizeStart:b.precizeStart&&b.precizeEnd&&f.precizeEnd,precizeEnd:b.precizeEnd,bufferedStart:void 0,bufferedEnd:b.end,infos:b.infos};b.end=f.start,b.splitted=!0,b.bufferedEnd=void 0,b.precizeEnd=b.precizeEnd&&f.precizeStart,l.splice(g+1,0,f),l.splice(g+2,0,h);return}}let p=this._inventory[0];if(p===void 0){m.debug("SI: first segment pushed",c,a,s),this._inventory.push(f);return}if(p.start>=s)m.debug("SI: Segment pushed comes before all previous ones",c,a,s,p.start),this._inventory.splice(0,0,f);else if(p.end<=s){for(m.debug("SI: Segment pushed starts before and completely recovers the previous first one",c,a,s,p.start,p.end),this._inventory.splice(0,1,f);l.length>1&&l[1].start<f.end;){if(l[1].end>f.end){m.debug("SI: Segment pushed updates the start of the next one",c,f.end,l[1].start),l[1].start=f.end,l[1].bufferedStart=void 0,l[1].precizeStart=f.precizeEnd;return}m.debug("SI: Segment pushed removes the next one",c,a,s,l[1].start,l[1].end),l.splice(1,1)}return}else{m.debug("SI: Segment pushed start of the next one",c,a,s,p.start,p.end),p.start=s,p.bufferedStart=void 0,p.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(Pt(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&&Pt(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,c=t[d].end,l=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=c,this._inventory[a].bufferedEnd=l,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 pd(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}=L.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 Tf(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}=L.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 gh(n,e,t,r){let{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:i,MISSING_DATA_TRIGGER_SYNC_DELAY:o,SEGMENT_SYNCHRONIZATION_DELAY:a}=L.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&&pd(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,pd(n)&&(n.start=t.end,n.precizeStart=!0);else if(n.start-e<=i){let s=V();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,pd(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=V();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 _f(n,e,t){let{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:r,MISSING_DATA_TRIGGER_SYNC_DELAY:i,SEGMENT_SYNCHRONIZATION_DELAY:o}=L.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&&Tf(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=V();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,Tf(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=V();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 hh(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,c=d.infos.representation.id,l=t[u],f;if(l===void 0)f=a(d.infos),t[u]={[c]:f};else{let p=l[c];p===void 0?(f=a(d.infos),l[c]=f):f=p}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 Qn(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 Xn(n,e){for(let t of n)if(t.infos.period.start>e.start)return t;return null}var Ef=gi;var Zn=class{constructor(){this._segmentInventory=new Ef}synchronizeInventory(e){this._segmentInventory.synchronizeBuffered(e)}getLastKnownInventory(){return this._segmentInventory.getInventory()}getSegmentHistory(e){return this._segmentInventory.getHistoryFor(e)}};var hi=class extends Zn{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){vf(t),this._initSegmentsMap.set(e,t)}freeInitSegment(e){this._initSegmentsMap.delete(e)}async pushChunk(e){vf(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,V()),a}e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,V());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 vf(n){if(y.CURRENT_ENV!==y.PRODUCTION&&(typeof n!="object"||n!==null&&!(n instanceof ArrayBuffer)&&!(n.buffer instanceof ArrayBuffer)))throw new Error("Invalid data given to the AudioVideoSegmentSink")}var ua=hi;var yi=class extends Zn{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;Ih(t.chunk);let r=this._sender.pushTextData(de(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,V()),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 Ih(n){if(y.CURRENT_ENV!==y.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")}y.CURRENT_ENV===y.DEV&&(bh=function(e){function t(r){}});var bh;var Rf=yi;var Sh=["audio","video","text"],Ii=class n{static isNative(e){return kf(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():st(e,t=>{let r=Z,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(kf(e)){if(!_(r))return r instanceof ua&&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 ua(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 Rf(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(){Sh.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=>de(oe({},a),{infos:Th(a.infos)}))}}getSegmentSinksMetrics(){return{segmentSinks:{audio:this.createSegmentSinkMetricsForType("audio"),video:this.createSegmentSinkMetricsForType("video"),text:this.createSegmentSinkMetricsForType("text")}}}};function kf(n){return n==="audio"||n==="video"}function Th(n){return{adaptation:n.adaptation.getMetadataSnapshot(),period:n.period.getMetadataSnapshot(),representation:n.representation.getMetadataSnapshot()}}var tn=Ii;var bi=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 gd(n,e,t,r,i){let{period:o,adaptation:a,representation:s}=n,d=_h(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 l=s.index.checkDiscontinuity(e.start);if(l!==null)return{start:void 0,end:l}}return null}let u=i[d];if(u.bufferedStart!==void 0&&u.bufferedStart>e.start&&(t===null||u.infos.segment.end<=t)){let l=u.bufferedStart;return!r&&s.index.awaitSegmentBetween(e.start,l)!==!1?null:(m.debug("RS: current discontinuity encountered",a.type,u.bufferedStart),{start:void 0,end:l})}let c=Eh(i,e,d+1);if(c!==null){let l=i[c-1],f=i[c];if(t===null||f.infos.segment.end<=t){if(!r&&s.index.awaitSegmentBetween(l.infos.segment.end,f.infos.segment.time)!==!1)return null;let p=l.bufferedEnd,g=f.bufferedStart;return m.debug("RS: future discontinuity encountered",a.type,p,g),{start:p,end:g}}}if(t===null){if(r&&o.end!==void 0){if(e.end<o.end)return null;let l=vh(i,o.end);if(l!==null){let f=i[l];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 l=i.length-1;l>=0;l--){let f=i[l];if(f.bufferedStart===void 0)break;if(f.bufferedStart<e.end){if(f.bufferedEnd!==void 0&&f.bufferedEnd<e.end){let p=s.index.checkDiscontinuity(e.end);if(p!==null)return{start:f.bufferedEnd,end:p}}return null}}}return null}function _h(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 Eh(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 vh(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 hd({bufferedSegments:n,content:e,currentPlaybackTime:t,fastSwitchThreshold:r,getBufferedHistory:i,neededRange:o,segmentsBeingPushed:a,maxBufferSize:s}){let{adaptation:d,representation:u}=e,c=Rh(n,a,s),l=u.index.getSegments(o.start,o.end-o.start),f=n.filter(v=>!Pf(v.infos,e,t,r)),p=wh(f,o,i),{MINIMUM_SEGMENT_SIZE:g,MIN_BUFFER_AHEAD:b}=L.getCurrent(),h=!1,I=Math.min(1/60,g),T=!1,R=[];return{segmentsToLoad:l.filter(v=>{let k=Y({segment:v},e);if(a.length>0&&a.some(F=>Pt(k,F)))return!1;let{duration:x,time:P,end:M}=v;if(v.isInit)return!0;if(h)return R.push(v),!1;if(v.complete&&x<g||a.length>0&&a.some(F=>{if(F.period.id!==e.period.id||F.adaptation.id!==e.adaptation.id)return!1;let{segment:A}=F;if(A.time-I>P)return!1;if(A.complete){if(A.end+I<M)return!1}else if(Math.abs(P-A.time)>P)return!1;return!Pf(F,k,t,r)}))return!1;for(let D of p){let F=D.infos.period.id===e.period.id;if(D.status===1&&F){let A=D.infos.segment;if(P-A.time>-I){if(A.complete){if(A.end-M>-I)return!1}else if(Math.abs(P-A.time)<I)return!1}}}let O=x*e.representation.bitrate;if(c-O<0&&(T=!0,P>o.start+b))return h=!0,R.push(v),!1;let B=i(k);if(B.length>1){let D=B[B.length-1],F=B[B.length-2];if(D.buffered===null&&F.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,v.time),!1}for(let D=0;D<p.length;D++){let F=p[D];if(F.end+I>P){let A=F.start>P+I||kh(p,D).end<M-I;return A&&(c-=O),A}}return c-=O,!0}),segmentsOnHold:R,isBufferFull:T}}function Rh(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 kh(n,e){let t=e+1,{MINIMUM_SEGMENT_SIZE:r}=L.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}=L.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:Ph(n.representation,e.representation,r)}function Ph(n,e,t){let r=n.bitrate,{BITRATE_REBUFFERING_RATIO:i}=L.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}=L.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 Mh(n,e,t){let{MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:r}=L.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 Ah(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 xh(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 wh(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),Ah(d,r.bufferedStart))return!1;m.debug("Stream: skipping segment gc-ed at the start",r.start,r.bufferedStart)}if(Mh(r,s,e.end)){if(d=d!=null?d:t(r.infos),xh(d,r.bufferedEnd))return!1;m.debug("Stream: skipping segment gc-ed at the end",r.end,r.bufferedEnd)}return!0})}function Si(n,e){let t=n-e,{SEGMENT_PRIORITIES_STEPS:r}=L.getCurrent();for(let i=0;i<r.length;i++)if(t<r[i])return i;return r.length}function yd(n,e,t,r,i,o,a){var P,M,O;let{representation:s}=n,d=(M=(P=t.getIsPaused())!=null?P:t.getReference().getValue().paused.pending)!=null?M:t.getReference().getValue().paused.last,u=(O=t.getPlaybackRate())!=null?O:t.getReference().getValue().speed,c=e;(d===void 0||u===void 0||d||u<=0)&&(c-=.1);let l=Oh(n,c,i),f=s.index.shouldRefresh(l.start,l.end),p=a.getPendingOperations().filter(B=>B.type===2).map(B=>B.value),g=a.getLastKnownInventory(),b=t.getCurrentTime();b===void 0&&(b=t.getReference().getValue().position.getWanted());let h=a.getSegmentHistory.bind(a),{segmentsToLoad:I,segmentsOnHold:T,isBufferFull:R}=hd({content:n,bufferedSegments:g,currentPlaybackTime:b,fastSwitchThreshold:r,getBufferedHistory:h,neededRange:l,segmentsBeingPushed:p,maxBufferSize:o}),E=I.map(B=>({priority:Si(B.time,c),segment:B})),v=s.index.isInitialized()&&!s.index.isStillAwaitingFutureSegments()&&l.hasReachedPeriodEnd&&E.length===0&&T.length===0,k=null;return p.length>0&&(k=Math.min(...p.map(B=>B.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:gd(n,l,k,v,g),hasFinishedLoading:v,neededSegments:E,isBufferFull:R,shouldRefreshManifest:f}}function Oh(n,e,t){var l;let r,{manifest:i,period:o,representation:a}=n,s=a.index.getLastAvailablePosition(),d=a.index;!_(s)&&tn.isNative(n.adaptation.type)&&e>=s&&d.isInitialized()&&!d.isStillAwaitingFutureSegments()&&Dh(i,o,e)?r=s-1:r=e-.1;let u=r+t,c;return!a.index.isInitialized()||a.index.isStillAwaitingFutureSegments()||o.end===void 0?c=!1:s===void 0?c=u>=o.end:s===null?c=!0:c=u>=s,{start:Math.max(r,o.start),end:Math.min(u,(l=o.end)!=null?l:1/0),hasReachedPeriodEnd:c}}function Dh(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 Ti(n,e,t,r,i){try{return await e.pushChunk(t)}catch(o){if(i.isCancelled()&&o instanceof Pe)throw o;if(!(o instanceof at)||!o.isBufferFull){let d=o instanceof Error?o.toString():"An unknown error happened when pushing content";throw new te("BUFFER_APPEND_ERROR",d,{tracks:[$t(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 Sn(200),i.cancellationError!==null)throw i.cancellationError;return await e.pushChunk(t)}catch(d){if(d instanceof Pe)throw d;let u=d instanceof Error?d.toString():"Could not clean the buffer";throw new te("BUFFER_FULL_ERROR",u,{tracks:[$t(t.inventoryInfos.adaptation)]})}}}async function Id({playbackObserver:n,content:e,initSegmentUniqueId:t,segment:r,segmentSink:i,bufferGoal:o},a){let s=e.representation.getMimeTypeString(),d={initSegmentUniqueId:t,chunk:null,timestampOffset:0,appendWindow:[void 0,void 0],codec:s},u=Y({segment:r,chunkSize:void 0,start:0,end:0},e),c=await Ti(n,i,{data:d,inventoryInfos:u},o,a);return{content:e,segment:r,buffered:c}}async function bd({playbackObserver:n,bufferGoal:e,content:t,initSegmentUniqueId:r,parsedSegment:i,segment:o,segmentSink:a},s){var k,x;if(i.chunkData===null)return null;let{chunkData:d,chunkInfos:u,chunkOffset:c,chunkSize:l,appendWindow:f}=i,p=t.representation.getMimeTypeString(),{APPEND_WINDOW_SECURITIES:g}=L.getCurrent(),b=[f[0]!==void 0?Math.max(0,f[0]-g.START):void 0,f[1]!==void 0?f[1]+g.END:void 0],h={initSegmentUniqueId:r,chunk:d,timestampOffset:c,appendWindow:b,codec:p},I=(k=u==null?void 0:u.time)!=null?k:o.time,T=(x=u==null?void 0:u.duration)!=null?x:o.duration,R=I+T;b[0]!==void 0&&(I=Math.max(I,b[0])),b[1]!==void 0&&(R=Math.min(R,b[1]));let E=Y({segment:o,chunkSize:l,start:I,end:R},t),v=await Ti(n,a,{data:h,inventoryInfos:E},e,s);return{content:t,segment:o,buffered:v}}function Sd({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:c}=n,{bufferGoal:l,maxBufferSize:f,drmSystemId:p,fastSwitchThreshold:g}=e,b=u.type,h=new U;h.linkToSignal(s);let I={segment:c.index.getInitSegment(),uniqueId:null,isLoaded:!1};h.signal.register(()=>{I.uniqueId!==null&&r.freeInitSegment(I.uniqueId)});let T=I.segment!==null;T||(I.isLoaded=!0);let R=!1;if(p!==void 0){let P=c.getEncryptionData(p);if(P.length>0&&P.every(M=>M.keyIds!==void 0)&&(R=!0,a.encryptionDataEncountered(P.map(M=>Y({content:n},M))),h.isUsed()))return}i.addEventListener("error",P=>{h.signal.isCancelled()||(h.cancel(),a.error(P))}),i.addEventListener("parsedInitSegment",k,h.signal),i.addEventListener("parsedMediaSegment",k,h.signal),i.addEventListener("emptyQueue",v,h.signal),i.addEventListener("requestRetry",P=>{if(a.warning(P.error),h.signal.isCancelled())return;let M=P.segment,{index:O}=c;O.isSegmentStillAvailable(M)===!1?v():O.canBeOutOfSyncError(P.error,M)&&a.manifestMightBeOufOfSync()},h.signal),i.addEventListener("fullyLoadedSegment",P=>{r.signalSegmentComplete(Y({segment:P},n)).catch(x)},h.signal);let E=i.resetForContent(n,T);h.signal.register(()=>{i.stop()}),t.listen(v,{includeLastObservation:!1,clearSignal:h.signal}),n.manifest.addEventListener("manifestUpdate",v,h.signal),l.onUpdate(v,{emitCurrentValue:!1,clearSignal:h.signal}),f.onUpdate(v,{emitCurrentValue:!1,clearSignal:h.signal}),o.onUpdate(v,{emitCurrentValue:!1,clearSignal:h.signal}),v();return;function v(){if(h.isUsed())return;let P=t.getReference().getValue(),M=P.position.getWanted(),O=yd(n,M,t,g.getValue(),l.getValue(),f.getValue(),r),{neededSegments:B}=O,D=null;if(c.index.isInitialized()){if(B.length>0&&!I.isLoaded&&I.segment!==null){let C=B[0].priority;D={segment:I.segment,priority:C}}}else if(I.segment===null)m.warn("Stream: Uninitialized index without an initialization segment");else if(I.isLoaded)m.warn("Stream: Uninitialized index with an already loaded initialization segment");else{let C=P.position.getWanted();D={segment:I.segment,priority:Si(d.start,C)}}let F=o.getValue();if(F===null)E.setValue({initSegment:D,segmentQueue:B});else if(F.urgent){m.debug("Stream: Urgent switch, terminate now.",b),E.setValue({initSegment:null,segmentQueue:[]}),E.finish(),h.cancel(),a.terminating();return}else{let C=B[0],N=i.getRequestedInitSegment(),K=i.getRequestedMediaSegment(),j=K===null||C===void 0||K.id!==C.segment.id?[]:[C],$=N===null?null:D;if(E.setValue({initSegment:$,segmentQueue:j}),j.length===0&&$===null){m.debug("Stream: No request left, terminate",b),E.finish(),h.cancel(),a.terminating();return}}if(a.streamStatusUpdate({period:d,position:P.position.getWanted(),bufferType:b,imminentDiscontinuity:O.imminentDiscontinuity,isEmptyStream:!1,hasFinishedLoading:O.hasFinishedLoading,neededSegments:O.neededSegments}),h.signal.isCancelled())return;let{UPTO_CURRENT_POSITION_CLEANUP:A}=L.getCurrent();if(O.isBufferFull){let C=Math.max(0,M-A);C>0&&r.removeBuffer(0,C).catch(x)}O.shouldRefreshManifest&&a.needsManifestRefresh()}function k(P){for(let M of P.protectionData)c.addProtectionData(M.initDataType,M.keyId,M.initData);if(!R){let M=c.getAllEncryptionData();M.length>0&&(a.encryptionDataEncountered(M.map(O=>Y({content:n},O))),R=!0)}if(P.segmentType==="init"){if(!c.index.isInitialized()&&P.segmentList!==void 0&&c.index.initialize(P.segmentList),I.isLoaded=!0,P.initializationData!==null){let M=c.uniqueId;I.uniqueId=M,r.declareInitSegment(M,P.initializationData),Id({playbackObserver:t,bufferGoal:l,content:n,initSegmentUniqueId:M,segment:P.segment,segmentData:P.initializationData,segmentSink:r},h.signal).then(O=>{O!==null&&a.addedSegment(O)}).catch(x)}v();return}else{let{inbandEvents:M,predictedSegments:O,needsManifestRefresh:B}=P;if(O!==void 0&&c.index.addPredictedSegments(O,P.segment),B===!0&&(a.needsManifestRefresh(),h.isUsed())||M!==void 0&&M.length>0&&(a.inbandEvent(M),h.isUsed()))return;let D=I.uniqueId;bd({playbackObserver:t,bufferGoal:l,content:n,initSegmentUniqueId:D,parsedSegment:P,segment:P.segment,segmentSink:r},h.signal).then(F=>{F!==null&&a.addedSegment(F)}).catch(x)}}function x(P){h.isUsed()&&P instanceof Pe||(m.warn("Stream: Received fatal buffer error",u.type,c.bitrate,P instanceof Error?P:null),h.cancel(),a.error(P))}}var Cf=Sd;function Td(n,e,t,r,i){var f,p,g,b;if(t.switchingMode==="lazy")return{type:"continue",value:void 0};let o=r.getLastKnownInventory(),a=[];for(let h of o)h.infos.period.id===n.id&&(h.infos.adaptation.id!==e.id||!X(t.representationIds,h.infos.representation.id))&&Gt(a,{start:(f=h.bufferedStart)!=null?f:h.start,end:(p=h.bufferedEnd)!=null?p:h.end});let s=r.getPendingOperations();for(let h of s)if(h.type===0){let I=h.value.inventoryInfos;if(I.period.id===n.id&&(I.adaptation.id!==e.id||!X(t.representationIds,I.representation.id))){let T=I.segment.time,R=T+I.segment.duration;Gt(a,{start:T,end:R})}}if(a.length===0)return{type:"continue",value:void 0};if(t.switchingMode==="reload"){let h=i.getReadyState();if(h===void 0||h>1)return{type:"needs-reload",value:void 0}}let d=t.switchingMode==="direct",u=[],c=Qn(o,n);if(c!==null&&(c.bufferedEnd===void 0||n.start-c.bufferedEnd<1)&&u.push({start:0,end:n.start+1}),!d){let{ADAP_REP_SWITCH_BUFFER_PADDINGS:h}=L.getCurrent(),I=e.type,T=(g=h[I].before)!=null?g:0,R=(b=h[I].after)!=null?b:0,E=i.getCurrentTime();E===void 0&&(E=i.getReference().getValue().position.getPolled()),u.push({start:E-T,end:E+R})}if(n.end!==void 0){let h=Xn(o,n);h!==null&&(h.bufferedStart===void 0||h.bufferedStart-n.end<1)&&u.push({start:n.end-1,end:Number.MAX_VALUE})}let l=To(a,u);return l.length===0?{type:"continue",value:void 0}:d?{type:"flush-buffer",value:l}:{type:"clean-buffer",value:l}}function _d({playbackObserver:n,content:e,options:t,representationEstimator:r,segmentSink:i,segmentQueueCreator:o,wantedBufferAhead:a,maxVideoBufferSize:s},d,u){let{manifest:c,period:l,adaptation:f}=e,p=new U;p.linkToSignal(u);let g=new Map,b=new G(null,p.signal),h,I=e.representations.getValue().representationIds,T=Mf(e.adaptation.representations,I),R=new G(T,p.signal),{estimates:E,callbacks:v}=r({manifest:c,period:l,adaptation:f},b,R,n,p.signal),k=new G(!1);n.listen(A=>{var N;let C=(N=A.canStream)!=null?N:!0;k.getValue()===C&&(m.debug("Stream: isMediaSegmentQueueInterrupted updated to",!C),k.setValue(!C))},{clearSignal:p.signal});let x=o.createSegmentQueue(f.type,{onRequestBegin:v.requestBegin,onRequestEnd:v.requestEnd,onProgress:v.requestProgress,onMetrics:v.metrics},k),P=new G(0);E.onUpdate(({bitrate:A,knownStableBitrate:C})=>{t.enableFastSwitching&&P.setValueIfChanged(C),!(A===void 0||A===h)&&(h=A,m.debug(`Stream: new ${f.type} bitrate estimate`,A),d.bitrateEstimateChange({type:f.type,bitrate:A}))},{emitCurrentValue:!0,clearSignal:p.signal});let M;e.representations.onUpdate(A=>{M!==void 0&&M.cancel();let C=e.representations.getValue().representationIds,N=Mf(e.adaptation.representations,C);R.setValueIfChanged(N),M=new U,M.linkToSignal(p.signal),O(A,M.signal).catch(K=>{(M==null?void 0:M.isUsed())===!0&&U.isCancellationError(K)||(p.cancel(),d.error(K))})},{clearSignal:p.signal,emitCurrentValue:!0});return;async function O(A,C){let N=Td(l,f,A,i,n);switch(N.type){case"continue":break;case"needs-reload":return Rt(()=>{n.listen(()=>{if(C.isCancelled())return;let{DELTA_POSITION_AFTER_RELOAD:K}=L.getCurrent(),j=K.bitrateSwitch;return d.waitingMediaSourceReload({bufferType:f.type,period:l,timeOffset:j,stayInPeriod:!0})},{includeLastObservation:!0,clearSignal:C})});case"flush-buffer":case"clean-buffer":for(let K of N.value)if(await i.removeBuffer(K.start,K.end),C.isCancelled())return;if(N.type==="flush-buffer"&&(d.needsBufferFlush(),C.isCancelled()))return;break;default:He(N)}B(C)}function B(A){let C=new U;C.linkToSignal(A);let{representation:N}=E.getValue();if(N===null)return;let K=new G(null,C.signal);E.onUpdate(z=>{if(!(z.representation===null||z.representation.id===N.id))return z.urgent?(m.info("Stream: urgent Representation switch",f.type),K.setValue({urgent:!0})):(m.info("Stream: slow Representation switch",f.type),K.setValue({urgent:!1}))},{clearSignal:C.signal,emitCurrentValue:!0});let j={type:f.type,adaptation:f,period:l,representation:N};if(b.setValue(N),A.isCancelled()||(d.representationChange(j),A.isCancelled()))return;let $={streamStatusUpdate:d.streamStatusUpdate,encryptionDataEncountered:d.encryptionDataEncountered,manifestMightBeOufOfSync:d.manifestMightBeOufOfSync,needsManifestRefresh:d.needsManifestRefresh,inbandEvent:d.inbandEvent,warning:d.warning,error(z){p.cancel(),d.error(z)},addedSegment(z){v.addedSegment(z)},terminating(){if(!C.isUsed())return C.cancel(),B(A)}};D(N,K,$,A)}function D(A,C,N,K){let j=!1,$=new U;$.linkToSignal(K);let z=ln(a,ie=>F(A,ie),$.signal),H=f.type==="video"?s:new G(1/0);m.info("Stream: changing representation",f.type,A.id,A.bitrate);let q=Y({},N,{error(ie){var le;if(j){m.warn("Stream: Ignoring RepresentationStream error",ie);return}j=!0;let ne=Ee(ie,{defaultCode:"NONE",defaultReason:"Unknown `RepresentationStream` error"});if(ne.code!=="BUFFER_FULL_ERROR")N.error(ie);else{m.warn("Stream: received BUFFER_FULL_ERROR",f.type,A.bitrate);let be=a.getValue(),W=((le=g.get(A.id))!=null?le:1)*.7;if(g.set(A.id,W),W<=.05||F(A,be)<=2){N.error(ne);return}Qt(4e3,K).then(()=>D(A,C,N,K)).catch(Z)}},terminating(){$.cancel(),N.terminating()}});Cf({playbackObserver:n,content:{representation:A,adaptation:f,period:l,manifest:c},segmentSink:i,segmentQueue:x,terminate:C,options:{bufferGoal:z,maxBufferSize:H,drmSystemId:t.drmSystemId,fastSwitchThreshold:P}},q,K),c.addEventListener("manifestUpdate",ie=>{for(let ne of ie.updatedPeriods)if(ne.period.id===l.id){for(let le of ne.result.updatedAdaptations)if(le.adaptation===f.id){for(let be of le.removedRepresentations)if(be===A.id)return K.isCancelled()?void 0:d.waitingMediaSourceReload({bufferType:f.type,period:l,timeOffset:0,stayInPeriod:!0})}}else if(ne.period.start>l.start)break},K)}function F(A,C){let N=g.get(A.id),K=N!==void 0?N:1;return N===void 0&&g.set(A.id,K),K<1&&C===1/0?5*60*1e3*K:C*K}}function Mf(n,e){let t=n.filter(r=>X(e,r.id)&&!r.shouldBeAvoided&&r.isPlayable()!==!1);return t.length>0?t:n.filter(r=>X(e,r.id)&&r.isPlayable()!==!1)}var Af=_d;function Ed(n,e,t,r,i,o){var p,g,b,h;if(n.codec!==void 0&&o.onCodecSwitch==="reload"&&!Lh(t,n.codec))return{type:"needs-reload",value:void 0};let a=n.getLastKnownInventory(),s=[];for(let I of a)I.infos.period.id===e.id&&I.infos.adaptation.id!==t.id&&Gt(s,{start:(p=I.bufferedStart)!=null?p:I.start,end:(g=I.bufferedEnd)!=null?g:I.end});let d=n.getPendingOperations();for(let I of d)if(I.type===0){let T=I.value.inventoryInfos;if(T.period.id===e.id&&T.adaptation.id!==t.id){let R=T.segment.time,E=R+T.segment.duration;Gt(s,{start:R,end:E})}}if(s.length===0)return{type:"continue",value:void 0};if(r==="reload"){let I=i.getReadyState();if(I===void 0||I>1)return{type:"needs-reload",value:void 0}}let u=r==="direct",c=[],l=Qn(a,e);if(l!==null&&(l.bufferedEnd===void 0||e.start-l.bufferedEnd<1)&&c.push({start:0,end:e.start+1}),!u){let I=t.type,{ADAP_REP_SWITCH_BUFFER_PADDINGS:T}=L.getCurrent(),R=(b=T[I].before)!=null?b:0,E=(h=T[I].after)!=null?h:0,v=i.getCurrentTime();v===void 0&&(v=i.getReference().getValue().position.getPolled()),c.push({start:v-R,end:v+E})}if(e.end!==void 0){let I=Xn(a,e);I!==null&&(I.bufferedStart===void 0||I.bufferedStart-e.end<1)&&c.push({start:e.end-1,end:Number.MAX_VALUE})}let f=To(s,c);return f.length===0?{type:"continue",value:void 0}:u&&t.type!=="text"?{type:"flush-buffer",value:f}:{type:"clean-buffer",value:f}}function Lh(n,e){return n.representations.some(t=>t.isPlayable()===!0&&ta(t.getMimeTypeString(),e))}function vd({bufferType:n,content:e,garbageCollectors:t,playbackObserver:r,representationEstimator:i,segmentQueueCreator:o,segmentSinksStore:a,options:s,wantedBufferAhead:d,maxVideoBufferSize:u},c,l){let{manifest:f,period:p}=e,g=new G(void 0,l);if(c.periodStreamReady({type:n,manifest:f,period:p,adaptationRef:g}),l.isCancelled())return;let b,h=!0;g.onUpdate(R=>{(async()=>{var F;if(R===void 0)return;let E=new U;if(E.linkToSignal(l),b==null||b.cancel(),b=E,R===null){m.info(`Stream: Set no ${n} Adaptation. P:`,p.start);let A=a.getStatus(n);if(A.type==="initialized"){if(m.info(`Stream: Clearing previous ${n} SegmentSink`),tn.isNative(n))return T(0,!0,E.signal);{let C=(F=p.end)!=null?F:1/0;if(p.start>C)m.warn("Stream: Can't free buffer: period's start is after its end");else if(await A.value.removeBuffer(p.start,C),E.isUsed())return}}else if(A.type==="uninitialized"&&(a.disableSegmentSink(n),E.isUsed()))return;return c.adaptationChange({type:n,adaptation:null,period:p}),E.isUsed()?void 0:xf(r,d,n,{period:p},c,E.signal)}let v=p.adaptations[n],k=Q(v!=null?v:[],A=>A.id===R.adaptationId);if(k===void 0){b.cancel(),m.warn("Stream: Unfound chosen Adaptation choice",R.adaptationId);return}let{DELTA_POSITION_AFTER_RELOAD:x}=L.getCurrent(),P=!1,M;if(h)M=0;else if(R.relativeResumingPosition!==void 0)M=R.relativeResumingPosition;else switch(P=!0,n){case"audio":M=x.trackSwitch.audio;break;case"video":M=x.trackSwitch.video;break;default:M=x.trackSwitch.other;break}if(h=!1,tn.isNative(n)&&a.getStatus(n).type==="disabled")return T(M,!0,E.signal);f.addEventListener("manifestUpdate",A=>{for(let C of A.updatedPeriods)if(C.period.id===p.id){for(let N of C.result.removedAdaptations)if(N.id===k.id)return T(M,!0,E.signal)}else if(C.period.start>p.start)break},b.signal);let{representations:O}=R;if(m.info(`Stream: Updating ${n} adaptation`,`A: ${k.id}`,`P: ${p.start}`),c.adaptationChange({type:n,adaptation:k,period:p}),E.isUsed())return;let B=Nh(a,n,k),D=Ed(B,p,k,R.switchingMode,r,s);if(D.type==="needs-reload")return T(M,!0,E.signal);if(await a.waitForUsableBuffers(E.signal),!E.isUsed()){if(D.type==="flush-buffer"||D.type==="clean-buffer"){for(let{start:A,end:C}of D.value)if(await B.removeBuffer(A,C),E.isUsed())return;if(D.type==="flush-buffer"&&(c.needsBufferFlush({relativeResumingPosition:M,relativePosHasBeenDefaulted:P}),E.isUsed()))return}t.get(B)(E.signal),I(k,O,B,E.signal)}})().catch(E=>{E instanceof Pe||(b==null||b.cancel(),c.error(E))})},{clearSignal:l,emitCurrentValue:!0});function I(R,E,v,k){let x=Bh(r,R.type);Af({content:{manifest:f,period:p,adaptation:R,representations:E},options:s,playbackObserver:x,representationEstimator:i,segmentSink:v,segmentQueueCreator:o,wantedBufferAhead:d,maxVideoBufferSize:u},de(oe({},c),{error:P}),k);function P(M){if(!tn.isNative(n)){m.error(`Stream: ${n} Stream crashed. Aborting it.`,M instanceof Error?M:""),a.disposeSegmentSink(n);let O=Ee(M,{defaultCode:"NONE",defaultReason:"Unknown `AdaptationStream` error"});return c.warning(O),k.isCancelled()?void 0:xf(r,d,n,{period:p},c,k)}m.error(`Stream: ${n} Stream crashed. Stopping playback.`,M instanceof Error?M:""),c.error(M)}}function T(R,E,v){Rt(()=>{r.listen(()=>{v.isCancelled()||c.waitingMediaSourceReload({bufferType:n,period:p,timeOffset:R,stayInPeriod:E})},{includeLastObservation:!0,clearSignal:v})})}}function Nh(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=Uh(t);return n.createSegmentSink(e,i)}function Uh(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:[$t(n)]});return e[0].getMimeTypeString()}function Bh(n,e){return n.deriveReadOnlyObserver(function(r,i){let o=new G(a(),i);return r.onUpdate(s,{clearSignal:i,emitCurrentValue:!1}),o;function a(){let d=r.getValue(),u=d.buffered[e],c=u!==null?So(u,d.position.getWanted()):0;return Y({},d,{bufferGap:c,buffered:u})}function s(){o.setValue(a())}})}function xf(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(),c=e.getValue(),l=u.position.getWanted();a.end!==void 0&&l+c>=a.end&&(m.debug('Stream: full "empty" AdaptationStream',t),s=!0),i.streamStatusUpdate({period:a,bufferType:t,imminentDiscontinuity:null,position:l,isEmptyStream:!0,hasFinishedLoading:s,neededSegments:[]})}}var wf=vd;function la(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 Rd(n,e,t,r,i,o,a,s){let{manifest:d,initialPeriod:u}=n,{maxBufferAhead:c,maxBufferBehind:l,wantedBufferAhead:f,maxVideoBufferSize:p}=o,{MINIMUM_MAX_BUFFER_AHEAD:g,MAXIMUM_MAX_BUFFER_AHEAD:b,MAXIMUM_MAX_BUFFER_BEHIND:h}=L.getCurrent(),I=new bi(E=>{var P,M;let{bufferType:v}=E,k=(P=h[v])!=null?P:1/0,x=(M=b[v])!=null?M:1/0;return O=>{sa({segmentSink:E,playbackObserver:e,maxBufferBehind:ln(l,B=>Math.min(B,k),O),maxBufferAhead:ln(c,B=>{var F;let D=Math.max(B,(F=g[v])!=null?F:0);return Math.min(D,x)},O)},O)}});for(let E of r.getBufferTypes())T(E,u);function T(E,v){let k=new vn((D,F)=>D.start-F.start),x=!1,P=new U;return P.linkToSignal(s),e.listen(({position:D})=>{var C;let F=D.getWanted();if(!x||!O(F))return;for(m.info("Stream: Destroying all PeriodStreams due to out of bounds situation",E,F),x=!1;k.length()>0;){let N=k.get(k.length()-1);k.removeElement(N),a.periodStreamCleared({type:E,manifest:d,period:N})}P.cancel(),P=new U,P.linkToSignal(s);let A=(C=d.getPeriodForTime(F))!=null?C:d.getNextPeriod(F);if(A===void 0){m.warn("Stream: The wanted position is not found in the Manifest."),x=!0;return}M(A)},{clearSignal:s,includeLastObservation:!0}),d.addEventListener("decipherabilityUpdate",D=>{s.isCancelled()||B(D).catch(F=>{s.isCancelled()||(P.cancel(),a.error(F))})},s),M(v);function M(D){let F=de(oe({},a),{waitingMediaSourceReload(A){let C=k.head();C===void 0||C.id!==A.period.id?a.lockedStream({bufferType:A.bufferType,period:A.period}):a.needsMediaSourceReload({timeOffset:A.timeOffset,minimumPosition:A.stayInPeriod?A.period.start:void 0,maximumPosition:A.stayInPeriod?A.period.end:void 0})},periodStreamReady(A){x=!0,k.add(A.period),a.periodStreamReady(A)},periodStreamCleared(A){k.removeElement(A.period),a.periodStreamCleared(A)},error(A){P.cancel(),a.error(A)}});R(E,D,F,P.signal)}function O(D){let F=k.head(),A=k.last();return F===void 0||A===void 0?!0:F.start>D||(_(A.end)?1/0:A.end)<D}async function B(D){let F=r.getStatus(E),A=D.filter(z=>z.adaptation.type===E);if(A.length===0||F.type!=="initialized"||A.every(z=>z.representation.decipherable===!0))return;let C=F.value,N=A.filter(z=>z.representation.decipherable===void 0),K=A.filter(z=>z.representation.decipherable===!1),j=la(C,K),$=la(C,N);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})}P.cancel(),P=new U,P.linkToSignal(s);for(let{start:z,end:H}of[...j,...$]){if(s.isCancelled())return;if(z<H){if(s.isCancelled())return;await C.removeBuffer(z,H)}}Rt(()=>{if(s.isCancelled())return;let z=e.getReference().getValue();if(Of(z,j)){if(a.needsDecipherabilityFlush(),s.isCancelled())return}else if(Of(z,$)&&(a.needsBufferFlush(),s.isCancelled()))return;let H=z.position.getWanted(),q=d.getPeriodForTime(H);if(q===void 0){a.error(new te("MEDIA_TIME_NOT_FOUND","The wanted position is not found in the Manifest."));return}M(q)})}}function R(E,v,k,x){m.info("Stream: Creating new Stream for",E,v.start);let P=null,M=new U;M.linkToSignal(x),e.listen(({position:A},C)=>{if(v.end!==void 0&&A.getWanted()>=v.end){let N=d.getPeriodAfter(v);if(v.containsTime(A.getWanted(),N))return;m.info("Stream: Destroying PeriodStream as the current playhead moved above it",E,v.start,A.getWanted(),v.end),C(),k.periodStreamCleared({type:E,manifest:d,period:v}),M.cancel()}},{clearSignal:x,includeLastObservation:!0});let O={bufferType:E,content:{manifest:d,period:v},garbageCollectors:I,maxVideoBufferSize:p,segmentQueueCreator:i,segmentSinksStore:r,options:o,playbackObserver:e,representationEstimator:t,wantedBufferAhead:f},B=de(oe({},k),{streamStatusUpdate(A){if(A.hasFinishedLoading){let C=d.getPeriodAfter(v);C!==null&&D(C)}else P!==null&&(m.info("Stream: Destroying next PeriodStream due to current one being active",E,P.period.start),k.periodStreamCleared({type:E,manifest:d,period:P.period}),P.canceller.cancel(),P=null);k.streamStatusUpdate(A)},error(A){P!==null&&(P.canceller.cancel(),P=null),M.cancel(),k.error(A)}});wf(O,B,M.signal),F(M.signal);function D(A){if(P!==null){if(P.period.id===A.id)return;m.warn("Stream: Creating next `PeriodStream` while one was already created.",E,A.id,P.period.id),k.periodStreamCleared({type:E,manifest:d,period:P.period}),P.canceller.cancel()}let C=new U;C.linkToSignal(x),P={canceller:C,period:A},R(E,A,k,P.canceller.signal)}function F(A){d.addEventListener("manifestUpdate",C=>{for(let N of C.removedPeriods)if(N.id===v.id){if(d.periods.length>0&&d.periods[0].start<=N.start)return Rt(()=>{if(!A.isCancelled())return a.needsMediaSourceReload({timeOffset:0,minimumPosition:void 0,maximumPosition:void 0})})}else if(N.start>v.start)break;if(C.addedPeriods.length>0&&P!==null){let N=d.getPeriodAfter(v);(N===null||P.period.id!==N.id)&&(m.warn("Stream: Destroying next PeriodStream due to new one being added",E,P.period.start),k.periodStreamCleared({type:E,manifest:d,period:P.period}),P.canceller.cancel(),P=null)}},A)}}}function Of(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 Df=Rd;var Lf=Df;var Fh={dashParsers:{wasm:null,native:null,fastJs:null},createDebugElement:null,directfile:null,decrypt:null,htmlTextDisplayer:null,htmlTextTracksParsers:{},mainThreadMediaSourceInit:null,multithread:null,nativeTextDisplayer:null,nativeTextTracksParsers:{},transports:{}},_i=Fh;function ca(n){for(let e of n)if(typeof e=="function")e(_i);else if(!_(e)&&typeof e._addFeature=="function")e._addFeature(_i);else throw new Error("Unrecognized feature")}var fe=_i;var Kh={createSync(n){return{syncValue:n,getValueAsAsync(){return Promise.resolve(n)}}},createAsync(n){let e=null;return n.then(t=>{e=t},Z),{get syncValue(){return e},getValueAsAsync(){return n}}}},Nf=Kh;var Jn=class extends ae{};function kd(n,e){let t={audio:null,video:null,text:null};if(e!==null&&(t.text=e.getBufferedRanges()),n===null)return t;let r=Q(n.sourceBuffers,s=>s.type==="audio"),i=Q(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 Pd(n,{autoPlay:e,initialPlayPerformed:t,manifest:r,mediaSource:i,speed:o,textDisplayer:a},s){return n.deriveReadOnlyObserver(function(u,c){let l=new U;l.linkToSignal(c),l.linkToSignal(s);let f=new G(p(),l.signal);return o.onUpdate(g,{clearSignal:l.signal,emitCurrentValue:!1}),u.onUpdate(g,{clearSignal:l.signal,emitCurrentValue:!1}),i==null||i.addEventListener("streamingChanged",()=>{g()},l.signal),f;function p(){var I;let b=u.getValue(),h=o.getValue();return Vh(b,r),{maximumPosition:Tt(r),bufferGap:b.bufferGap,position:b.position,buffered:kd(i,a),duration:b.duration,rebuffering:b.rebuffering,freezing:b.freezing,paused:{last:b.paused,pending:zh(t,e)},readyState:b.readyState,speed:h,canStream:(I=i==null?void 0:i.streaming)!=null?I:!0,fullyLoaded:b.fullyLoaded}}function g(){f.setValue(p())}})}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 zh(n,e){return n.getValue()?void 0:!e}function er(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 Cd(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 Hh(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t];r.updating&&e.push(r)}return e}function Ei(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=Hh(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 U;i.linkToSignal(e);for(let o of r)Oc(o,()=>{i.cancel(),Ei(n,e)},i.signal);Dc(t,()=>{i.cancel(),Ei(n,e)},i.signal)}function Uf(n,e){let t=new U;t.linkToSignal(e),zn(n,()=>{m.debug("Init: MediaSource re-opened while end-of-stream is active"),t.cancel(),t=new U,t.linkToSignal(e),Ei(n,t.signal)},e),Ei(n,t.signal)}function Md(){return pn}var Wh=365*24*3600,vi=class{constructor(e){this._mediaSource=e,this._currentMediaSourceDurationUpdateCanceller=null}updateDuration(e,t){this._currentMediaSourceDurationUpdateCanceller!==null&&this._currentMediaSourceDurationUpdateCanceller.cancel(),this._currentMediaSourceDurationUpdateCanceller=new U;let r=this._mediaSource,i=this._currentMediaSourceDurationUpdateCanceller.signal,o=jh(r,i),a=new U;a.linkToSignal(i),o.onUpdate(s,{emitCurrentValue:!0,clearSignal:i});function s(){if(a.cancel(),!o.getValue())return;a=new U,a.linkToSignal(i);let d=Gh(r.sourceBuffers,a.signal),u=new U;return u.linkToSignal(a.signal),d.onUpdate(c=>{u.cancel(),u=new U,u.linkToSignal(a.signal),!c&&Ff(r,e,t,u.signal)},{clearSignal:a.signal,emitCurrentValue:!0})}}stopUpdating(){this._currentMediaSourceDurationUpdateCanceller!==null&&(this._currentMediaSourceDurationUpdateCanceller.cancel(),this._currentMediaSourceDurationUpdateCanceller=null)}};function qh(n,e,t){let r=e;t||(r=Md()?1/0:Bf(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=Bf(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 Gh(n,e){if(n.length===0){let i=new G(!1);return i.finish(),i}let t=new G(!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 jh(n,e){let t=new G(n.readyState==="open",e);return zn(n,()=>{m.debug("Init: Reacting to MediaSource open in duration updater"),t.setValueIfChanged(!0)},e),Lo(n,()=>{m.debug("Init: Reacting to MediaSource ended in duration updater"),t.setValueIfChanged(!1)},e),Do(n,()=>{m.debug("Init: Reacting to MediaSource close in duration updater"),t.setValueIfChanged(!1)},e),t}function Ff(n,e,t,r){if(qh(n,e,t)==="success")return;let o=setTimeout(()=>{a(),Ff(n,e,t,r)},2e3),a=r.register(()=>{clearTimeout(o)})}function Bf(n){return Math.max(Math.pow(2,32),n+Wh)}var Ri=class extends ae{constructor(e){if(super(),this.id=e,this.sourceBuffers=[],this._canceller=new U,_(kt))throw new te("MEDIA_SOURCE_NOT_SUPPORTED","No MediaSource Object was found in the current browser.");m.info("Init: Creating MediaSource");let t=new kt,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 vi(t),this._endOfStreamCanceller=null,zn(t,()=>{this.readyState=t.readyState,this.trigger("mediaSourceOpen",null)},this._canceller.signal),Lo(t,()=>{this.readyState=t.readyState,this.trigger("mediaSourceEnded",null)},this._canceller.signal),Do(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 Ad(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 U,this._endOfStreamCanceller.linkToSignal(this._canceller.signal),m.debug("Init: end-of-stream order received."),Uf(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(),Yh(this._mediaSource)}},Ad=class{constructor(e,t,r){this.type=e,this.codec=t,this._canceller=new U,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 xe(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 at(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(xe(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 Pe;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=Y({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 c;s instanceof ArrayBuffer?c=new Uint8Array(s):s instanceof Uint8Array?c=s:c=new Uint8Array(s.buffer);let l=[c];for(;((t=this._operationQueue[0])==null?void 0:t.operationName)===0;){let f=this._operationQueue[0],p=(r=d.appendWindow)!=null?r:[void 0,void 0],g=(i=f.params[1].appendWindow)!=null?i:[void 0,void 0],b=(o=d.timestampOffset)!=null?o:0,h=(a=f.params[1].timestampOffset)!=null?a:0;if(p[0]===g[0]&&p[1]===g[1]&&d.codec===f.params[1].codec&&b===h){let I=f.params[0],T;I instanceof ArrayBuffer?T=new Uint8Array(I):I instanceof Uint8Array?T=I:T=new Uint8Array(I.buffer),l.push(T),this._operationQueue.splice(0,1),this._currentOperations.push({operationName:0,resolve:f.resolve,reject:f.reject})}else break}l.length>1&&(m.info(`MMSI: Merging ${l.length} segments together for perf`,this.type),u=se(...l))}try{this._appendBufferNow(u,d)}catch(c){let l=c instanceof Error?new at(c.name,c.message,c.name==="QuotaExceededError"):new at("Error","Unknown SourceBuffer Error during appendBuffer",!1);this._currentOperations.forEach(f=>{f.reject(l)}),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 c=u instanceof Error?new at(u.name,u.message,!1):new at("Error","Unknown SourceBuffer Error during remove",!1);e.reject(c),this._currentOperations.forEach(l=>{l.reject(c)}),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),Cd(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 Yh(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 $h=et();function xd(n,e){if(e!==null&&n.src===e&&(m.info("Init: Clearing HTMLMediaElement's src"),er(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 Qh(n,e){if(Zl&&"disableRemotePlayback"in n){let t=n.disableRemotePlayback;e.register(()=>{n.disableRemotePlayback=t}),n.disableRemotePlayback=!0}}function Xh(n,e){let t=w(n.src)?n.src:null;xd(n,t);let r=new Ri($h());return Qh(n,e),e.register(()=>{r.dispose()}),r}function fa(n,e){return st(e,t=>{let r=Xh(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(()=>{xd(n,null)});else{let i=URL.createObjectURL(r.handle.value);n.src=i,e.register(()=>{xd(n,i)})}})}function wd(n,e,t){var i;if(!_(t)){let o=yn(n),a=Tt(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=Tt(n),d,{DEFAULT_LIVE_GAP:u}=L.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 l=n.availabilityStartTime===void 0?0:n.availabilityStartTime,f=(V()+a)/1e3-l;d=Math.min(s,f)}let c=o!=null?o:e?u.LOW_LATENCY:u.DEFAULT;return m.debug(`Init: ${d} defined as the live time, applying a live gap of ${c}`),Math.max(d-c,r)}return m.info("Init: starting at the minimum available position:",r),r}function ki(){return ja}function Od(n){return!(n&&mn)}function Dd(){return pn}function Pi(n,e,t){let r=new U;r.linkToSignal(t);let i=new G(!1,r.signal);return n.listen(o=>{if(o.rebuffering!==null||o.freezing!==null||o.readyState===0)return;if(!Od(e)){if(isNaN(o.duration))return;if(o.duration>0){i.setValue(!0),r.cancel();return}}let a=Dd()?4:3;if(o.readyState>=a&&(o.currentRange!==null||o.ended)&&(!ki()||o.duration>0)){i.setValue(!0),r.cancel();return}},{includeLastObservation:!0,clearSignal:r.signal}),i}var Zh=!mn,Kf=Zh;var tr=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 Ci({mediaElement:n,playbackObserver:e,startTime:t,mustAutoPlay:r,isDirectfile:i,onWarning:o},a){let s=new G(!1,a);return{autoPlayResult:new Promise((u,c)=>{let l=a.register(I=>{c(I)});if(a.isCancelled())return;let f=!1,p=I=>{e.setCurrentTime(I),f=!0};if(!i||typeof t=="number"){let I=typeof t=="number"?t:t();I!==0&&I!==void 0&&p(I),g()}else e.listen((I,T)=>{let R=typeof t=="number"?t:t();R===void 0&&I.readyState<HTMLMediaElement.HAVE_CURRENT_DATA||I.readyState>=1&&(T(),R!==0&&R!==void 0&&(Kf?p(R):setTimeout(()=>{p(R)},0)),g())},{includeLastObservation:!0,clearSignal:a});function g(){let I=!1;e.listen((T,R)=>{if(!I&&(T.seeking!==0||T.event==="seeking"||T.event==="internal-seeking")&&(I=!0),!(f&&!I||T.readyState===0)){if(R(),ki()&&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()||b()}},{includeLastObservation:!0,clearSignal:a})}function b(){e.listen((I,T)=>{I.seeking===0&&I.rebuffering===null&&I.readyState>=1&&(T(),h())},{includeLastObservation:!0,clearSignal:a})}function h(){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(),l(),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(),l(),u({type:"skipped"});let I;try{I=(T=n.play())!=null?T:Promise.resolve()}catch(R){return l(),c(R)}I.then(()=>{if(!a.isCancelled())return s.setValue(!0),s.finish(),l(),u({type:"autoplay"})}).catch(R=>{if(l(),!a.isCancelled())if(R instanceof Error&&R.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 c(R)})}}),initialPlayPerformed:s}}function Mi(n,e,t,r){if(e.length===0)return u("No `keySystems` option given.");if(fe.decrypt===null)return u("EME feature not activated.");let i=new U;i.linkToSignal(r);let o=new G({initializationState:{type:"uninitialized",value:null},drmSystemId:void 0},r),a=fe.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=c=>{var l;c>0&&((l=t.onCodecSupportUpdate)==null||l.call(t),s.removeEventListener("stateChange",d))};return s.addEventListener("stateChange",d),s.addEventListener("stateChange",c=>{if(c===1){let l=new G(!1);l.onUpdate((f,p)=>{f&&(p(),c===1&&s.attach())},{clearSignal:i.signal}),o.setValue({initializationState:{type:"awaiting-media-link",value:{isMediaLinked:l}},drmSystemId:s.systemId})}else c===2&&(o.setValue({initializationState:{type:"initialized",value:null},drmSystemId:s.systemId}),s.removeEventListener("stateChange"))}),s.addEventListener("error",c=>{i.cancel(),t.onError(c)}),s.addEventListener("warning",c=>{t.onWarning(c)}),s.addEventListener("blackListProtectionData",c=>{t.onBlackListProtectionData(c)}),s.addEventListener("keyIdsCompatibilityUpdate",c=>{t.onKeyIdsCompatibilityUpdate(c)}),i.signal.register(()=>{s.dispose()}),{statusRef:o,contentDecryptor:{enabled:!0,value:s}};function u(c){let l=new ge("MEDIA_IS_ENCRYPTED_ERROR",c),f=new G({initializationState:{type:"initialized",value:null},drmSystemId:void 0});return f.finish(),{statusRef:f,contentDecryptor:{enabled:!1,value:l}}}}var Ai=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 Jh=gr,nr=Jh;var xi=1/60,Rn=class extends ae{constructor(e,t,r){super(),this._playbackObserver=e,this._manifest=t,this._speed=r,this._discontinuitiesStore=[],this._isStarted=!1,this._canceller=new U}start(){if(this._isStarted)return;this._isStarted=!0;let e=new Ud(this._playbackObserver,this._speed);this._canceller.signal.register(()=>{e.dispose()}),this._playbackObserver.listen(t=>{let r=this._discontinuitiesStore,{buffered:i,position:o,readyState:a,rebuffering:s,freezing:d}=t,{BUFFER_DISCONTINUITY_THRESHOLD:u,FREEZING_STALLED_DELAY:c}=L.getCurrent();if(d!==null&&V()-d.timestamp>c){s===null?e.stopRebuffering():e.startRebuffering(),this.trigger("stalled","freezing");return}if(s===null){if(e.stopRebuffering(),a===1){let h;t.seeking!==0?h=t.seeking===1?"internal-seek":"seeking":h="not-ready",this.trigger("stalled",h);return}this.trigger("unstalled",null);return}let l=s.reason==="seeking"&&t.seeking===1?"internal-seek":s.reason;if(o.isAwaitingFuturePosition()?(e.stopRebuffering(),m.debug("Init: let rebuffering happen as we're awaiting a future position")):e.startRebuffering(),this._manifest===null||nr&&V()-s.timestamp<=1e3){this.trigger("stalled",l);return}let{position:f}=s,p=t.position.isAwaitingFuturePosition()?t.position.getWanted():this._playbackObserver.getCurrentTime();if(f!=null&&this._speed.getValue()>0){let h=ey(r,this._manifest,f);if(h!==null){let I=h+.001;if(I<=p)m.info("Init: position to seek already reached, no seeking",p,I);else{m.warn("SA: skippable discontinuity found in the stream",o.getPolled(),I),this._playbackObserver.setCurrentTime(I),this.trigger("warning",Nd(f,I));return}}}let g=f!=null?f:o.getPolled(),b=sc(i,g);if((!nr||V()-s.timestamp>1e3)&&this._speed.getValue()>0&&b<u){let h=g+b+xi;if(p<h){m.warn("Init: discontinuity encountered inferior to the threshold",g,h,u),this._playbackObserver.setCurrentTime(h),this.trigger("warning",Nd(g,h));return}}for(let h=this._manifest.periods.length-2;h>=0;h--){let I=this._manifest.periods[h];if(I.end!==void 0&&I.end<=g){if(this._manifest.periods[h+1].start>g&&this._manifest.periods[h+1].start>p){let T=this._manifest.periods[h+1];this._playbackObserver.setCurrentTime(T.start),this.trigger("warning",Nd(g,T.start));return}break}}this.trigger("stalled",l)},{includeLastObservation:!0,clearSignal:this._canceller.signal})}updateDiscontinuityInfo(e){this._isStarted||this.start();let t=this._playbackObserver.getReference().getValue();ty(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 ey(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:c}=s,l=u!=null?u:d;if(t>=l-xi)if(c===null){let f=Co(e,o);f!==null?a=f.start+xi:m.warn("Init: discontinuity at Period's end but no next Period")}else t<c+xi&&(a=c+xi);a!==void 0&&(m.info("Init: discontinuity found",t,a),r=r!==null&&r>a?r:a)}}return r}function Ld(n){return n.discontinuity!==null}function ty(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){Ld(e)?n[a]=e:n.splice(a,1);return}}else if(n[a].period.start>i.start){Ld(e)&&n.splice(a,0,e);return}Ld(e)&&n.push(e)}}function Nd(n,e){return new te("DISCONTINUITY_ENCOUNTERED","A discontinuity has been encountered at position "+String(n)+", seeking at position "+String(e))}var Ud=class{constructor(e,t){this._speedUpdateCanceller=new U,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 U,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 ny(n,e){return n.id===e.id&&n.start===e.start&&n.end===e.end}var Vf=ny;function ry(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(Vf(f,{id:d,start:a,end:s})){t.push(f);return}let c;if(u.value.element!==void 0)c=u.value.element;else if(u.value.xmlData!==void 0){let f=u.value.xmlData.namespaces.reduce((g,b)=>g+"xmlns:"+b.key+'="'+b.value+'" ',"<toremove ");f+=">";let p=new DOMParser().parseFromString(f+u.value.xmlData.data+"</toremove>","application/xml").documentElement;c=p.children.length>0?p.children[0]:p.childNodes[0]}else return;let l={type:u.type,value:de(oe({},u.value),{element:c})};if(s===void 0){let f={start:a,id:d,data:l,publicEvent:{start:a,data:l}};t.push(f)}else{let f={start:a,end:s,id:d,data:l,publicEvent:{start:a,end:s,data:l}};t.push(f)}})}return t}var Bd=ry;var wi=class extends ae{constructor(e,t){super(),this._manifest=e,this._playbackObserver=t,this._canceller=null,this._scheduledEventsRef=new G([]),this._eventsBeingPlayed=new WeakMap}start(){if(this._canceller!==null)return;this._canceller=new U;let e=this._canceller.signal,t=this._playbackObserver,r=!1,i=new U;i.linkToSignal(e),this._scheduledEventsRef.setValue(Bd([],this._manifest)),this._scheduledEventsRef.onUpdate(({length:o})=>{if(o===0){r&&(i.cancel(),i=new U,i.linkToSignal(e),r=!1);return}else if(r)return;r=!0;let a=c(),s=()=>{let l=c();this._emitStreamEvents(this._scheduledEventsRef.getValue(),a,l,i.signal),a=l},{STREAM_EVENT_EMITTER_POLL_INTERVAL:d}=L.getCurrent(),u=setInterval(s,d);t.listen(s,{includeLastObservation:!1,clearSignal:i.signal}),i.signal.register(()=>{clearInterval(u)});function c(){var g;let l=t.getReference().getValue(),f=(g=t.getCurrentTime())!=null?g:t.getReference().getValue().position.getPolled(),p=l.seeking!==0;return{currentTime:f,isSeeking:p}}},{emitCurrentValue:!0,clearSignal:e})}onManifestUpdate(e){let t=this._scheduledEventsRef.getValue();this._scheduledEventsRef.setValue(Bd(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 c=0;c<e.length;c++){let l=e[c],f=l.start,p=Fd(l)?l.end:void 0;this._eventsBeingPlayed.has(l)?(f>s||p!==void 0&&s>=p)&&(Fd(l)&&u.push(l.publicEvent),this._eventsBeingPlayed.delete(l)):f<=s&&p!==void 0&&s<p?(d.push({type:"stream-event",value:l.publicEvent}),this._eventsBeingPlayed.set(l,!0)):o<f&&s>=(p!=null?p:f)&&(a?d.push({type:"stream-event-skip",value:l.publicEvent}):(d.push({type:"stream-event",value:l.publicEvent}),Fd(l)&&u.push(l.publicEvent)))}if(d.length>0){for(let c of d)if(c.type==="stream-event"?this.trigger("event",c.value):this.trigger("eventSkip",c.value),i.isCancelled())return}if(u.length>0){for(let c of u)if(typeof c.onExit=="function"&&c.onExit(),i.isCancelled())return}}};function Fd(n){return n.end!==void 0}var zf=wi;function Oi(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 kn=class extends Jn{constructor(e){super(),this._initSettings=e,this._initCanceller=new U,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 Sc(e.cmcd),this._manifestFetcher=new nd(t,e.transport,de(oe({},e.manifestRequestSettings),{lowLatencyMode:e.lowLatencyMode,cmcdDataBuilder:this._cmcdDataBuilder}))}prepare(){this._manifest===null&&(this._manifest=Nf.createAsync(st(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(),Oi(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 st(t.signal,r=>{let{keySystems:i}=this._initSettings,{statusRef:o,contentDecryptor:a}=Mi(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();ay(d,s)})().catch(Z)},onKeyIdsCompatibilityUpdate:s=>{(async()=>{var u;if(this._manifest===null)return;let d=(u=this._manifest.syncValue)!=null?u:await this._manifest.getValueAsAsync();oy(d,s.whitelistedKeyIds,s.blacklistedKeyIds,s.delistedKeyIds)})().catch(Z)},onCodecSupportUpdate:()=>{var d,u;let s=(d=this._manifest)==null?void 0:d.syncValue;_(s)?(u=this._manifest)==null||u.getValueAsAsync().then(c=>{this._initCanceller.isUsed()||this._refreshManifestCodecSupport(c)},Z):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 U;u.linkToSignal(t.signal),fa(e,u.signal).then(c=>{let l=o.getValue();if(l.initializationState.type==="awaiting-media-link")l.initializationState.value.isMediaLinked.setValue(!0),o.onUpdate((f,p)=>{if(f.initializationState.type==="initialized"){p(),r({mediaSource:c,drmSystemId:f.drmSystemId,unlinkMediaSource:u});return}},{emitCurrentValue:!0,clearSignal:t.signal});else if(s.initializationState.type==="initialized"){r({mediaSource:c,drmSystemId:s.drmSystemId,unlinkMediaSource:u});return}}).catch(c=>{u.isUsed()||this._onFatalError(c)})},{emitCurrentValue:!0,clearSignal:t.signal})})}async _onInitialMediaSourceReady(e,t,r,i,o){var k;let{adaptiveOptions:a,autoPlay:s,bufferOptions:d,lowLatencyMode:u,segmentRequestOptions:c,speed:l,startAt:f,textTrackOptions:p,transport:g}=this._initSettings,b=this._initCanceller;ee(this._manifest!==null);let h;try{h=(k=this._manifest.syncValue)!=null?k:await this._manifest.getValueAsAsync()}catch(x){return}h.addEventListener("manifestUpdate",x=>{this.trigger("manifestUpdate",x),this._refreshManifestCodecSupport(h)},b.signal),h.addEventListener("decipherabilityUpdate",x=>{this.trigger("decipherabilityUpdate",x)},b.signal),h.addEventListener("supportUpdate",()=>{this.trigger("codecSupportUpdate",null)},b.signal),m.debug("Init: Calculating initial time");let I=wd(h,u,f);m.debug("Init: Initial time calculated:",I);let T=Ic(a),R=Y({textTrackOptions:p,drmSystemId:i},d),E=new Fn(b.signal),v=new ad(g,E,this._cmcdDataBuilder,c);this._refreshManifestCodecSupport(h),this.trigger("manifestReady",h),!b.isUsed()&&this._setupContentWithNewMediaSource({mediaElement:e,playbackObserver:r,mediaSource:t,initialTime:I,autoPlay:s,manifest:h,representationEstimator:T,cdnPrioritizer:E,segmentQueueCreator:v,speed:l,bufferOptions:R},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 U;o.linkToSignal(r.signal),fa(e.mediaElement,o.signal).then(a=>{this._setupContentWithNewMediaSource(de(oe({},e),{mediaSource:a,initialTime:i.position,autoPlay:i.autoPlay}),o)}).catch(a=>{o.isUsed()||this._onFatalError(a)})}}_startLoadingContentOnMediaSource(e,t,r){var F,A;let{autoPlay:i,bufferOptions:o,initialTime:a,manifest:s,mediaElement:d,mediaSource:u,playbackObserver:c,representationEstimator:l,cdnPrioritizer:f,segmentQueueCreator:p,speed:g}=e,{transport:b}=this._initSettings,h=(F=s.getPeriodForTime(a))!=null?F:s.getNextPeriod(a);if(h===void 0){let C=new te("MEDIA_STARTING_TIME_NOT_FOUND","Wanted starting time not found in the Manifest.");return this._onFatalError(C)}let I=null,T=iy(d,this._initSettings.textTrackOptions);if(T!==null){let C=new Ai(T);I=C,r.register(()=>{C.stop(),T==null||T.stop()})}let R=new tn(u,d.nodeName==="VIDEO",I);r.register(()=>{R.disposeAll()});let{autoPlayResult:E,initialPlayPerformed:v}=Ci({mediaElement:d,playbackObserver:c,startTime:a,mustAutoPlay:i,onWarning:C=>{this.trigger("warning",C)},isDirectfile:!1},r);if(r.isCancelled())return;v.onUpdate((C,N)=>{if(C){N();let K=new zf(s,c);s.addEventListener("manifestUpdate",()=>{K.onManifestUpdate(s)},r),K.addEventListener("event",j=>{this.trigger("streamEvent",j)},r),K.addEventListener("eventSkip",j=>{this.trigger("streamEventSkip",j)},r),K.start(),r.register(()=>{K.stop()})}},{clearSignal:r,emitCurrentValue:!0});let k=Pd(c,{autoPlay:i,manifest:s,mediaSource:u,textDisplayer:T,initialPlayPerformed:v,speed:g},r);(A=this._cmcdDataBuilder)==null||A.startMonitoringPlayback(k),r.register(()=>{var C;(C=this._cmcdDataBuilder)==null||C.stopMonitoringPlayback()});let x=this._createRebufferingController(c,s,g,r),P=new mi(R);Jl&&s.addEventListener("decipherabilityUpdate",C=>{C.some(N=>N.representation.decipherable!==!0)&&D(0,void 0,void 0)},r),k.listen(C=>{md(C,R);let N=P.onNewObservation(C);if(N===null)return;let K=()=>{var H;let j=c.getReference().getValue(),$=j.position.isAwaitingFuturePosition()?j.position.getWanted():(H=k.getCurrentTime())!=null?H:j.position.getPolled(),z=v.getValue()?!c.getIsPaused():i;t({position:$,autoPlay:z})};sy(N,{enableRepresentationAvoidance:this._initSettings.enableRepresentationAvoidance,manifest:s,triggerReload:K,playbackObserver:c})},{clearSignal:r});let M=ld(s,u,k,R,{onWarning:C=>this.trigger("warning",C),onPeriodChanged:C=>this.trigger("activePeriodChanged",{period:C})},r);E.then(()=>{Pi(c,!1,r).onUpdate((C,N)=>{C&&(N(),this.trigger("loaded",{getSegmentSinkMetrics:async()=>new Promise(K=>K(R.getSegmentSinksMetrics())),getThumbnailData:async(K,j,$)=>{let z=dd(b.thumbnails,f);return fd(z,s,K,j,$)}}))},{emitCurrentValue:!0,clearSignal:r})}).catch(C=>{r.isCancelled()||this._onFatalError(C)});let O=this;Lf({manifest:s,initialPeriod:h},k,l,R,p,o,B(),r);function B(){return{needsBufferFlush:C=>{var H;let N,K=c.getReference().getValue(),j=K.position.isAwaitingFuturePosition()?K.position.getWanted():d.currentTime,$=(H=C==null?void 0:C.relativeResumingPosition)!=null?H:0,z=!!(C!=null&&C.relativePosHasBeenDefaulted);$===0&&z?N=j+.001:N=j+$,c.setCurrentTime(N),c.listen((q,ie)=>{(q.currentRange!==null||q.position.getPolled()>N+.1)&&(ie(),c.setCurrentTime(q.position.getWanted()+.001))},{includeLastObservation:!1,clearSignal:r})},streamStatusUpdate(C){let{period:N,bufferType:K,imminentDiscontinuity:j,position:$}=C;x.updateDiscontinuityInfo({period:N,bufferType:K,discontinuity:j,position:$}),!r.isCancelled()&&s.isLastPeriodKnown&&C.period.id===s.periods[s.periods.length-1].id&&(C.hasFinishedLoading||C.isEmptyStream?M.onLastSegmentFinishedLoading(C.bufferType):M.onLastSegmentLoadingResume(C.bufferType))},needsManifestRefresh:()=>O._manifestFetcher.scheduleManualRefresh({enablePartialRefresh:!0,canUseUnsafeMode:!0}),manifestMightBeOufOfSync:()=>{let{OUT_OF_SYNC_MANIFEST_REFRESH_DELAY:C}=L.getCurrent();O._manifestFetcher.scheduleManualRefresh({enablePartialRefresh:!1,canUseUnsafeMode:!1,delay:C})},lockedStream:C=>x.onLockedStream(C.bufferType,C.period),adaptationChange:C=>{O.trigger("adaptationChange",C),!r.isCancelled()&&M.onAdaptationChange(C.type,C.period,C.adaptation)},representationChange:C=>{O.trigger("representationChange",C),!r.isCancelled()&&M.onRepresentationChange(C.type,C.period)},inbandEvent:C=>O.trigger("inbandEvents",C),warning:C=>O.trigger("warning",C),periodStreamReady:C=>O.trigger("periodStreamReady",C),periodStreamCleared:C=>{M.onPeriodCleared(C.type,C.period),!r.isCancelled()&&O.trigger("periodStreamCleared",{type:C.type,periodId:C.period.id})},bitrateEstimateChange:C=>{var N;(N=O._cmcdDataBuilder)==null||N.updateThroughput(C.type,C.bitrate),O.trigger("bitrateEstimateChange",C)},needsMediaSourceReload:C=>{D(C.timeOffset,C.minimumPosition,C.maximumPosition)},needsDecipherabilityFlush(){var N,K,j,$;let C=Yn(d);if(Za(C==null?void 0:C[0])){let z=k.getReference().getValue(),H=z.position.isAwaitingFuturePosition()?z.position.getWanted():(N=k.getCurrentTime())!=null?N:z.position.getPolled(),q=(j=(K=z.paused.pending)!=null?K:k.getIsPaused())!=null?j:z.paused.last;t({position:H,autoPlay:!q})}else{let z=k.getReference().getValue(),H=z.position.isAwaitingFuturePosition()?z.position.getWanted():($=k.getCurrentTime())!=null?$:z.position.getPolled();H+.001<z.duration?c.setCurrentTime(d.currentTime+.001):c.setCurrentTime(H)}},encryptionDataEncountered:C=>{if(O._decryptionCapabilities.status==="disabled"){O._onFatalError(O._decryptionCapabilities.value);return}else if(O._decryptionCapabilities.status==="uninitialized"){m.error("Init: received encryption data without known decryption capabilities");return}for(let N of C)if(O._decryptionCapabilities.value.onInitializationData(N),r.isCancelled())return},error:C=>O._onFatalError(C)}}function D(C,N,K){var q,ie,ne;let j=k.getReference().getValue(),$=j.position.isAwaitingFuturePosition()?j.position.getWanted():(q=k.getCurrentTime())!=null?q:j.position.getPolled(),z=(ne=(ie=j.paused.pending)!=null?ie:k.getIsPaused())!=null?ne:j.paused.last,H=$+C;N!==void 0&&(H=Math.max(N,H)),K!==void 0&&(H=Math.min(K,H)),t({position:H,autoPlay:!z})}}_createRebufferingController(e,t,r,i){let o=new Rn(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=qa(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 iy(n,e){return e.textTrackMode==="html"&&fe.htmlTextDisplayer!==null?new fe.htmlTextDisplayer(n,e.textTrackElement):fe.nativeTextDisplayer!==null?new fe.nativeTextDisplayer(n):null}function oy(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(he(d,s))return!1;for(let d of e)if(he(d,s))return!0;for(let d of r)if(he(d,s))return}return o.decipherable})}function ay(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(c=>(u.systemId===void 0||c.systemId===u.systemId)&&he(c.data,u.data))))return!1;return r.decipherable})}function sy(n,{playbackObserver:e,enableRepresentationAvoidance:t,manifest:r,triggerReload:i}){switch(n.type){case"reload":{m.info("Init: Planning reload due to freeze"),i();break}case"flush":{m.info("Init: Flushing buffer due to freeze");let o=e.getReference().getValue(),a=o.position.isAwaitingFuturePosition()?o.position.getWanted():e.getCurrentTime(),s=n.value.relativeSeek,d=a+s;e.setCurrentTime(d);break}case"avoid-representations":{let o=n.value;t&&r.addRepresentationsToAvoid(o),i();break}default:He(n)}}function Kd(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=Kd(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 vt(n,e){var t;return(n-((t=e.indexTimeOffset)!=null?t:0))/e.timescale}function Hf(n,e,t){return[n*t,(n+e)*t]}function dy(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 ma(n,e,t){let{timeline:r}=n,i=We(e,n);if(i<0)return null;let o=dy(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?vt(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:_(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 uy(n,e){let t=n.toString();return t.length>=e?t:(new Array(e+1).join("0")+t).slice(-e)}function Vd(n){return(e,t,r)=>{let i=w(r)?parseInt(r,10):1;return uy(String(n),i)}}function lt(n,e,t){return ly(n,e,t)}function ly(n,e,t){return n.indexOf("$")===-1?n:n.replace(/\$\$/g,"$").replace(/\$RepresentationID\$/g,String(e)).replace(/\$Bandwidth(%0(\d+)d)?\$/g,Vd(t===void 0?0:t))}function pa(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 Vd(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 Vd(n)(i,o,a)})}}function cy(n,e,t){let r=t-n;return r>0?Math.floor(r/e):0}function Di(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:c,timescale:l,segmentUrlTemplate:f,startNumber:p,endNumber:g}=n,b=p!=null?p:1,h=[],I=c.length;for(let R=0;R<I;R++){let E=c[R],{duration:v,start:k,range:x}=E,P;a===void 0?P=i:P=Math.min(a*l,i!=null?i:1/0);let M=Kd(E,c[R+1],P),O=n.availabilityTimeComplete!==!1||R!==I-1&&M!==0,B=cy(k,v,d),D=k+B*v;for(;D<u&&B<=M;){let F=b+B;if(g!==void 0&&F>g)break;let A=f===null?null:pa(D,F)(f),C=D-n.indexTimeOffset,N=v;C<0&&(N=v+C,C=0);let K={id:String(D),time:C/l,end:(C+N)/l,duration:N/l,isInit:!1,range:x,timescale:1,url:A,number:F,timestampOffset:-(n.indexTimeOffset/l),complete:O,privateInfos:{isEMSGWhitelisted:o}};h.push(K),B++,D=k+B*v}if(D>=u||(b+=M+1,g!==void 0&&b>g))return h}return h}function fy(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 Pn=class{constructor(e,t){var g,b,h,I;let{periodStart:r,periodEnd:i,representationId:o,representationBitrate:a,isEMSGWhitelisted:s}=t,d=(g=e.timescale)!=null?g:1,c=((b=e.presentationTimeOffset)!=null?b:0)-r*d,l=((h=e.initialization)==null?void 0:h.media)===void 0?null:lt(e.initialization.media,o,a),f=e.media===void 0?null:lt(e.media,o,a),p;e.initialization!==void 0?p=e.initialization.range:e.indexRange!==void 0&&(p=[0,e.indexRange[0]-1]),this._index={indexRange:e.indexRange,indexTimeOffset:c,initialization:{url:l,range:p},segmentUrlTemplate:f,startNumber:e.startNumber,endNumber:e.endNumber,timeline:(I=e.timeline)!=null?I:[],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 wt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){return Di(this._index,e,t,this._manifestBoundsCalculator,this._scaledPeriodEnd,this._isEMSGWhitelisted)}shouldRefresh(){return!1}getFirstAvailablePosition(){let e=this._index;return e.timeline.length===0?null:vt(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 vt(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++)fy(this._index,e[t]);this._isInitialized=!0}}addPredictedSegments(){m.warn("Cannot add predicted segments to a `BaseRepresentationIndex`")}getTargetSegmentDuration(){let{timeline:e,timescale:t}=this._index,r=e[0];if(r!==void 0)return{duration:r.duration/t,isPrecize:!1}}_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 Cn=class{constructor(e,t){var p,g,b;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=(p=e.presentationTimeOffset)!=null?p:0,u=(g=e.timescale)!=null?g:1,c=d-r*u,l=((b=e.initialization)==null?void 0:b.media)===void 0?null:lt(e.initialization.media,o,a),f=e.list.map(h=>({url:h.media===void 0?null:lt(h.media,o,a),mediaRange:h.mediaRange}));this._index={list:f,timescale:u,duration:e.duration,indexTimeOffset:c,indexRange:e.indexRange,initialization:_(e.initialization)?void 0:{url:l,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,c]=Hf(d,t,a),l=Math.min(o.length-1,Math.floor(c/i)),f=[],p=Math.floor(u/i);for(;p<=l;){let g=o[p].mediaRange,b=o[p].url,h=p*s+this._periodStart,I={id:String(p),time:h,isInit:!1,range:g,duration:s,timescale:1,end:h+s,url:b,timestampOffset:-(r.indexTimeOffset/a),complete:!0,privateInfos:{isEMSGWhitelisted:this._isEMSGWhitelisted}};f.push(I),p++}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`")}getTargetSegmentDuration(){let{duration:e,timescale:t}=this._index;return{duration:e/t,isPrecize:!0}}_replace(e){this._index=e._index}_update(){m.error("A `ListRepresentationIndex` cannot be updated")}};function rr(n){return L.getCurrent().DEFAULT_MAXIMUM_TIME_ROUNDING_ERROR*n}var Mn=class{constructor(e,t){var I,T,R;let{availabilityTimeOffset:r,manifestBoundsCalculator:i,isDynamic:o,periodEnd:a,periodStart:s,representationId:d,representationBitrate:u,isEMSGWhitelisted:c}=t,l=(I=e.timescale)!=null?I:1;this._availabilityTimeOffset=r,this._manifestBoundsCalculator=i;let f=(T=e.presentationTimeOffset)!=null?T:0,p=s*l,g=f-p;if(e.duration===void 0)throw new Error("Invalid SegmentTemplate: no duration");let b=((R=e.initialization)==null?void 0:R.media)===void 0?null:lt(e.initialization.media,d,u),h=e.media===void 0?null:lt(e.media,d,u);this._index={duration:e.duration,timescale:l,indexRange:e.indexRange,indexTimeOffset:g,initialization:_(e.initialization)?void 0:{url:b,range:e.initialization.range},url:h,presentationTimeOffset:f,startNumber:e.startNumber,endNumber:e.endNumber},this._isDynamic=o,this._periodStart=s,this._scaledRelativePeriodEnd=a===void 0?void 0:(a-s)*l,this._isEMSGWhitelisted=c}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,c=this._scaledRelativePeriodEnd,l=e*s-u,f=(e+t)*s-u,p=this._getFirstSegmentStart(),g=this._getLastSegmentStart();if(_(p)||_(g))return[];let b=Math.max(p,l),h=Math.min(g,f);if(h+i<=b)return[];let I=[],T=o!=null?o:1,R=Math.floor(b/i);for(let E=R*i;E<=h;E+=i){let v=R+T;if(a!==void 0&&v>a)return I;let k=!_(c)&&E+i>c?c-E:i,x=E+u,P=E+this._index.presentationTimeOffset,M=d===null?null:pa(P,v)(d),O={id:String(v),number:v,time:x/s,end:(x+k)/s,duration:k/s,timescale:1,isInit:!1,scaledDuration:k/s,url:M,timestampOffset:-(r.indexTimeOffset/s),complete:!0,privateInfos:{isEMSGWhitelisted:this._isEMSGWhitelisted}};I.push(O),R++}return I}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=rr(r),o=this._periodStart*r,a=e*r-o,s=t*r-o,d=this._getLastSegmentStart();if(_(d)){let l=this._estimateRelativeScaledEnd();return l===void 0?s+i>=0:s+i>=0&&a<l-i}let u=d+this._index.duration,c=this._estimateRelativeScaledEnd();return c===void 0?s>u-i:s>u-i&&a<c-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=rr(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`")}getTargetSegmentDuration(){return{duration:this._index.duration/this._index.timescale,isPrecize:!0}}_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 l=Math.ceil(this._scaledRelativePeriodEnd/e);return r!==void 0&&r-i+1<l&&(l=r-i+1),(l-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 c=Math.floor(u/e);return r!==void 0&&r-i+1<c&&(c=r-i+1),c<=0?null:(c-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,c=L.getCurrent().MINIMUM_SEGMENT_SIZE*t;return r!==void 0||s-u>c||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 Li(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 Ni(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 c=t-1;c>=0;c--){let l=n[c].start;if(l===r){let f=t-c;return n.splice(c,f,...e),!1}else if(l<r){let f=n[c];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(c+1,t-(c+1),...e),!1;if(f.start+f.duration*(f.repeatCount+1)<=r)return n.splice(c+1,t-(c+1),...e),!1;let g=(r-f.start)/f.duration-1;if(g%1===0&&f.duration===e[0].duration){let b=e[0].repeatCount<0?-1:e[0].repeatCount+g+1;return n.splice(c,t-c,...e),n[c].start=f.start,n[c].repeatCount=b,!1}return m.warn("RepresentationIndex: Manifest update removed previous segments"),n[c].repeatCount=Math.floor(g),n.splice(c+1,t-(c+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 Ui(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 Bi(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 Fi(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 nn(n){let e=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)e.push(Bi(n[r]));else for(let r=0;r<n.length;r++)e.push(Fi(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=Ui(i,o,a);s!==null&&t.push(s)}return t}function zd(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"),c=_(u)?null:parseInt(u,10);if(c===null||Number.isNaN(c))return null;let l=a!==null?a.attributes.r:s==null?void 0:s.getAttribute("r"),f=_(l)?null:parseInt(l,10);if(f!==null){if(Number.isNaN(f)||f<0)return null;if(f>0){let b=t-d;if(b%c===0&&b/c<=f)return{repeatNumberInPrevSegments:0,repeatNumberInNewElements:b/c,prevSegmentsIdx:0,newElementsIdx:o}}d+=c*(f+1)}else d+=c;if(o++,o>=e.length)return null;Array.isArray(e)?a=e[o]:s=e[o];let p=a!==null?a.attributes.t:s==null?void 0:s.getAttribute("t"),g=_(p)?null:parseInt(p,10);if(g!==null){if(Number.isNaN(g))return null;d=g}if(d===t)return{newElementsIdx:o,prevSegmentsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(d>i)return null}}}function Hd(n,e){var b;let t=zd(e,n);if(t===null)return m.warn('DASH: Cannot perform "based" update. Common segment not found.'),nn(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'),nn(n);let u=e.slice(r);if(o>0){let h=u[0];h.start+=h.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.'),nn(n);let c=u[u.length-1],l=Array.isArray(n)?Bi(n[d]):Fi(n[d]),f=((b=l.repeatCount)!=null?b:0)-a;if(l.duration!==c.duration||c.repeatCount>f)return m.info('DASH: Cannot perform "based" update. The new timeline has a different form at the beginning.'),nn(n);l.repeatCount!==void 0&&l.repeatCount>c.repeatCount&&(c.repeatCount=l.repeatCount);let p=[],g=[];if(Array.isArray(n))for(let h=d+1;h<n.length;h++)g.push(Bi(n[h]));else for(let h=d+1;h<n.length;h++)g.push(Fi(n[h]));for(let h=0;h<g.length;h++){let I=g[h],T=p[p.length-1]===void 0?c:p[p.length-1],R=g[h+1]===void 0?null:g[h+1],E=Ui(I,T,R);E!==null&&p.push(E)}return u.concat(p)}var Ki=class n{constructor(e,t){var E,v,k,x,P;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:c,periodEnd:l,isEMSGWhitelisted:f}=t,p=(E=e.timescale)!=null?E:1,g=(v=e.presentationTimeOffset)!=null?v:0,b=c*p,h=g-b;this._manifestBoundsCalculator=o,this._isEMSGWhitelisted=f,this._isLastPeriod=s,this._lastUpdate=(k=t.receivedTime)!=null?k:V(),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 I=((P=e.initialization)==null?void 0:P.media)===void 0?null:lt(e.initialization.media,d,u),T=e.media===void 0?null:lt(e.media,d,u),R;i===void 0&&r===void 0?R=1/0:R=i!=null?i:0,this._index={availabilityTimeComplete:r!=null?r:!0,availabilityTimeOffset:R,indexRange:e.indexRange,indexTimeOffset:h,initialization:_(e.initialization)?void 0:{url:I,range:e.initialization.range},segmentUrlTemplate:T,startNumber:e.startNumber,endNumber:e.endNumber,timeline:e.timeline===void 0?null:Wd(e.timeline,e.startNumber,e.endNumber),timescale:p},this._scaledPeriodStart=We(c,this._index),this._scaledPeriodEnd=l===void 0?void 0:We(l,this._index)}getInitSegment(){return wt(this._index,this._isEMSGWhitelisted)}getSegments(e,t){return this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),Di(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:vt(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=ga(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 vt(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 vt(t,this._index)}awaitSegmentBetween(e,t){var u,c;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=rr(r),a=We(t,this._index),s=ga(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(s!==null&&Math.min(s.end,(u=this._scaledPeriodEnd)!=null?u:1/0)+o>=Math.min(a,(c=this._scaledPeriodEnd)!=null?c:1/0))return!1;let d=We(e,this._index);if(i.length>0&&s!==null&&!s.isLastOfTimeline){let l=i[i.length-1],p=ke(l,null,this._scaledPeriodEnd)+o;if(d<p+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()),my(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),ma({timeline:t,timescale:this._index.timescale,indexTimeOffset:this._index.indexTimeOffset},e,this._scaledPeriodEnd)}canBeOutOfSyncError(e){return this._isDynamic?e instanceof ot&&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()),Ni(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=rr(this._index.timescale),r=ga(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`")}getTargetSegmentDuration(){this._refreshTimeline();let{timeline:e,timescale:t}=this._index;if(e===null)return;let r=e[0];if(r!==void 0)return{duration:r.duration/t,isPrecize:!1}}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=Li(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}=L.getCurrent();if(this._unsafelyBaseOnPreviousIndex===null||e.length<t)return Wd(nn(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,Wd(Hd(e,r),this._index.startNumber,this._index.endNumber)}};function Wd(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 my(n,e,t,r){let i=ga(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 ga(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(vt(a,n)<=r){let s=ke(o,n.timeline[i+1],t);if(vt(s,n)<=r)return{isLastOfTimeline:i===n.timeline.length-1,timelineIdx:i,newRepeatCount:o.repeatCount,end:a};{let u=We(r,n)-o.start,c=Math.floor(u/o.duration);return ee(c>=1),{isLastOfTimeline:!1,timelineIdx:i,newRepeatCount:c-1,end:o.start+c*o.duration}}}}return null}var ha=Ki;var Vi=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 qd(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"),qd(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),qd(e,t),!0)}_getReferenced(e){return this._refs.get(e)}};function qd(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=Q(n.contentProtections.initData,a=>a.type==="cenc");o===void 0?n.contentProtections.initData.push({type:"cenc",values:i}):o.values.push(...i)}function ya(n){let e=Date.parse(n)-V();if(isNaN(e)){m.warn("DASH Parser: Invalid clock received: ",n);return}return e}function Gd(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 Ia(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 jd(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=Ia(r);if(s===void 0)return{safe:void 0,unsafe:void 0};o=s}if(i!==void 0){let s=Ia(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 ba(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 Yd(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=ba(r);if(s===void 0)return;o=s}if(i!==void 0){let s=ba(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 $d(n){if(n.length===0)throw new Error("DASH Parser: no period available for a dynamic content");let e=Yd(n),t=jd(n);return{minimumSafePosition:e,maximumSafePosition:t.safe,maximumUnsafePosition:t.unsafe}}var zi=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(V()+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+V()/1e3,0):this._lastPosition}};function Qd(n,e){return n.type!=="dynamic"?0:_(n.availabilityStartTime)?e!=null?e:0:n.availabilityStartTime}function Xd(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 py(n,e){for(let t of e){let{adaptation:r,trickModeAttachedAdaptationIds:i}=t;for(let o of i)for(let a of Yt){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 Wf=py;var gy=["subtitle","caption"];function Jd(n,e){var s,d,u,c;let t=(c=Q((s=n.children.essentialProperties)!=null?s:[],l=>l.schemeIdUri==="http://dashif.org/guidelines/thumbnail_tile"||l.schemeIdUri==="http://dashif.org/thumbnail_tile"))!=null?c:Q((u=(d=e!=null?e:n.children.representations[0])==null?void 0:d.children.essentialProperties)!=null?u:[],l=>l.schemeIdUri==="http://dashif.org/guidelines/thumbnail_tile"||l.schemeIdUri==="http://dashif.org/thumbnail_tile");if(t===void 0)return null;let r=/(\d+)x(\d+)/;if(t===void 0||t.value===void 0||!r.test(t.value))return m.warn("DASH: Invalid thumbnails Representation, no tile-related information"),null;let i=t.value.match(r),o=parseInt(i[1],10),a=parseInt(i[2],10);return{horizontalTiles:o,verticalTiles:a}}function eu(n,e){if(n.attributes.contentType==="image")return Jd(n)!==null?"thumbnails":void 0;let t=w(n.attributes.mimeType)?n.attributes.mimeType:null,r=w(n.attributes.codecs)?n.attributes.codecs:null,i=_(n.children.roles)?null:n.children.roles;function o(s,d){let u=s.split("/")[0];if(X(Yt,u))return u;if(s==="application/ttml+xml")return"text";if(s==="application/mp4")return d!==null&&Q(d,c=>c.schemeIdUri==="urn:mpeg:dash:role:2011"&&X(gy,c.value))!==void 0?"text":void 0}function a(s){switch(s.substring(0,3)){case"avc":case"hev":case"hvc":case"vp8":case"vp9":case"av1":return"video";case"vtt":return"text"}switch(s.substring(0,4)){case"mp4a":return"audio";case"wvtt":case"stpp":return"text"}}if(t!==null){let s=o(t,i);if(s!==void 0)return s}if(r!==null){let s=a(r);if(s!==void 0)return s}for(let s=0;s<e.length;s++){let d=e[s],{mimeType:u,codecs:c}=d.attributes;if(u!==void 0){let l=o(u,i);if(l!==void 0)return l}if(c!==void 0){let l=a(c);if(l!==void 0)return l}}}var hy=/[, ]+/g;function qf(n){return w(n)?n.trim().replace(hy,", "):""}function Gf(n){let[e,t,r,i,o,a,s,d]=n.split(".");if(e!=="vp08"&&e!=="vp09"&&e!=="vp10")return;let u,c,l;if((i!==void 0&&i==="10"||i==="12")&&(u=parseInt(i,10)),s!==void 0&&(s==="16"?c="pq":s==="18"&&(c="hlg")),a!==void 0&&d!==void 0&&a==="09"&&d==="09"&&(l="rec2020"),!(u===void 0||c===void 0))return{colorDepth:u,eotf:c,colorSpace:l}}function tu(n,e){var g,b,h;let{availabilityTimeOffset:t,manifestBoundsCalculator:r,isDynamic:i,end:o,start:a,receivedTime:s,unsafelyBaseOnPreviousRepresentation:d,inbandEventStreams:u,isLastPeriod:c}=e,f={availabilityTimeComplete:void 0,availabilityTimeOffset:t,unsafelyBaseOnPreviousRepresentation:d,isEMSGWhitelisted:I=>u===void 0?!1:u.some(({schemeIdUri:T})=>T===I.schemeIdUri),isLastPeriod:c,manifestBoundsCalculator:r,isDynamic:i,periodEnd:o,periodStart:a,receivedTime:s,representationBitrate:n.attributes.bitrate,representationId:n.attributes.id},p;if(n.children.segmentBase!==void 0){let{segmentBase:I}=n.children;p=new Pn(I,f)}else if(n.children.segmentList!==void 0){let{segmentList:I}=n.children;p=new Cn(I,f)}else if(n.children.segmentTemplate!==void 0||e.parentSegmentTemplates.length>0){let I=e.parentSegmentTemplates.slice(),T=n.children.segmentTemplate;T!==void 0&&I.push(T);let R=Y({},...I);(R.availabilityTimeOffset!==void 0||e.availabilityTimeOffset!==void 0)&&(f.availabilityTimeOffset=((g=R.availabilityTimeOffset)!=null?g:0)+((b=e.availabilityTimeOffset)!=null?b:0)),(R.availabilityTimeComplete!==void 0||e.availabilityTimeComplete!==void 0)&&(f.availabilityTimeComplete=(h=R.availabilityTimeComplete)!=null?h:e.availabilityTimeComplete),p=ha.isTimelineIndexArgument(R)?new ha(R,f):new Mn(R,f)}else{let I=e.adaptation.children;if(I.segmentBase!==void 0){let{segmentBase:T}=I;p=new Pn(T,f)}else if(I.segmentList!==void 0){let{segmentList:T}=I;p=new Cn(T,f)}else p=new Mn({duration:Number.MAX_VALUE,timescale:1,startNumber:0,media:""},f)}return p}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=gn(a.url,d.url);r.push({url:u,serviceLocation:(i=d.serviceLocation)!=null?i:a.serviceLocation})}}return r}function yy(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 Iy({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=Q([...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 Gf(i)}function nu(n,e,t){var i,o,a,s,d,u,c;let r=[];for(let l of n){let f=l.attributes.id!==void 0?l.attributes.id:String(l.attributes.bitrate)+(l.attributes.height!==void 0?`-${l.attributes.height}`:"")+(l.attributes.width!==void 0?`-${l.attributes.width}`:"")+(l.attributes.mimeType!==void 0?`-${l.attributes.mimeType}`:"")+(l.attributes.codecs!==void 0?`-${l.attributes.codecs}`:"");for(;r.some(M=>M.id===f);)f+="-dup";let p=(o=(i=t.unsafelyBaseOnPreviousAdaptation)==null?void 0:i.getRepresentation(f))!=null?o:null,g=yy(l,e),b=(a=l.attributes.availabilityTimeComplete)!=null?a:t.availabilityTimeComplete,h;(l.attributes.availabilityTimeOffset!==void 0||t.availabilityTimeOffset!==void 0)&&(h=((s=l.attributes.availabilityTimeOffset)!=null?s:0)+((d=t.availabilityTimeOffset)!=null?d:0));let I=Y({},t,{availabilityTimeOffset:h,availabilityTimeComplete:b,unsafelyBaseOnPreviousRepresentation:p,adaptation:e,inbandEventStreams:g}),T=tu(l,I),R;l.attributes.bitrate===void 0?(m.warn("DASH: No usable bitrate found in the Representation."),R=0):R=l.attributes.bitrate;let E=Ot(t.baseURLs,l.children.baseURLs),v=E.length===0?[{baseUrl:"",id:void 0}]:E.map(M=>({baseUrl:M.url,id:M.serviceLocation})),k={bitrate:R,cdnMetadata:v,index:T,id:f};l.children.supplementalProperties!==void 0&&Q(l.children.supplementalProperties,M=>M.schemeIdUri==="tag:dolby.com,2018:dash:EC3_ExtensionType:2018"&&M.value==="JOC")!==void 0&&(k.isSpatialAudio=!0);let x;l.attributes.codecs!==void 0?x=l.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 P;l.attributes.supplementalCodecs!==void 0?P=l.attributes.supplementalCodecs:e.attributes.supplementalCodecs!==void 0&&(P=e.attributes.supplementalCodecs),P!==void 0&&(k.supplementalCodecs=qf(P)),l.attributes.frameRate!==void 0?k.frameRate=l.attributes.frameRate:e.attributes.frameRate!==void 0&&(k.frameRate=e.attributes.frameRate),l.attributes.height!==void 0?k.height=l.attributes.height:e.attributes.height!==void 0&&(k.height=e.attributes.height),l.attributes.mimeType!==void 0?k.mimeType=l.attributes.mimeType:e.attributes.mimeType!==void 0&&(k.mimeType=e.attributes.mimeType),l.attributes.width!==void 0?k.width=l.attributes.width:e.attributes.width!==void 0&&(k.width=e.attributes.width);{let M=[...(u=e.children.contentProtections)!=null?u:[],...(c=l.children.contentProtections)!=null?c:[]];for(let O of M)t.contentProtectionParser.add(k,O)}k.hdrInfo=Iy({adaptationProfiles:e.attributes.profiles,supplementalProperties:e.children.supplementalProperties,essentialProperties:e.children.essentialProperties,manifestProfiles:t.manifestProfiles,codecs:x}),r.push(k)}return r}function by(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 Sy(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 Ty(n){return n===void 0?!1:n.schemeIdUri==="urn:mpeg:dash:role:2011"&&n.value==="sign"}function _y(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 Ey(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=>w(r))}return[]}function ru(n,e){var d,u,c,l,f,p,g;let t={video:[],audio:[],text:[]},r=[],i=[],o={},a=[];for(let b=0;b<n.length;b++){let h=n[b],I=h.children,{essentialProperties:T,roles:R,label:E}=I,v=Array.isArray(R)&&R.some(W=>W.value==="main")&&R.some(W=>W.schemeIdUri==="urn:mpeg:dash:role:2011"),k=h.children.representations,x=(d=h.attributes.availabilityTimeComplete)!=null?d:e.availabilityTimeComplete,P;(h.attributes.availabilityTimeOffset!==void 0||e.availabilityTimeOffset!==void 0)&&(P=((u=h.attributes.availabilityTimeOffset)!=null?u:0)+((c=e.availabilityTimeOffset)!=null?c:0));let M=eu(h,k);if(M===void 0)continue;let O=(l=h.attributes.selectionPriority)!=null?l:1,B=h.attributes.id,D=Ey(h),F=[];e.segmentTemplate!==void 0&&F.push(e.segmentTemplate),h.children.segmentTemplate!==void 0&&F.push(h.children.segmentTemplate);let A={availabilityTimeComplete:x,availabilityTimeOffset:P,baseURLs:Ot(e.baseURLs,I.baseURLs),contentProtectionParser:e.contentProtectionParser,manifestBoundsCalculator:e.manifestBoundsCalculator,end:e.end,isDynamic:e.isDynamic,isLastPeriod:e.isLastPeriod,manifestProfiles:e.manifestProfiles,parentSegmentTemplates:F,receivedTime:e.receivedTime,start:e.start,unsafelyBaseOnPreviousAdaptation:null},C=Array.isArray(T)?Q(T,W=>W.schemeIdUri==="http://dashif.org/guidelines/trickmode"):void 0,N=(f=C==null?void 0:C.value)==null?void 0:f.split(" "),K=N!==void 0,{accessibilities:j}=I,$;R!==void 0&&R.some(W=>W.value==="dub")&&($=!0);let z;M!=="text"?z=!1:z=Sy(j,R);let H;M==="text"&&R!==void 0&&R.some(W=>W.value==="forced-subtitle"||W.value==="forced_subtitle")&&(H=!0);let q;M!=="audio"?q=!1:j!==void 0&&(q=j.some(by));let ie;M!=="video"?ie=!1:j!==void 0&&(ie=j.some(Ty));let ne=_y(h,{isAudioDescription:q,isForcedSubtitle:H,isClosedCaption:z,isSignInterpreted:ie,isTrickModeTrack:K,type:M});for(;X(a,ne);)ne+="-dup";let le=ne;a.push(ne),A.unsafelyBaseOnPreviousAdaptation=(g=(p=e.unsafelyBaseOnPreviousPeriod)==null?void 0:p.getAdaptation(ne))!=null?g:null;let be=nu(k,h,A);if(M==="thumbnails"){let W=vy(h,be);W!==null&&r.push(...W);continue}let me={id:ne,representations:be,type:M,isTrickModeTrack:K};if(_(h.attributes.language)||(me.language=h.attributes.language),_(z)||(me.closedCaption=z),_(q)||(me.audioDescription=q),$===!0&&(me.isDub=!0),H!==void 0&&(me.forcedSubtitles=H),ie===!0&&(me.isSignInterpreted=!0),E!==void 0&&(me.label=E),N!==void 0)i.push({adaptation:me,trickModeAttachedAdaptationIds:N});else{let W=-1;for(let Ce of D){let nt=o[Ce];if(nt!==void 0&&nt.newID!==le&&X(nt.adaptationSetSwitchingIDs,B)){W=pe(t[M],Vt=>Vt[0].id===Ce);let Ae=t[M][W];if(Ae!==void 0&&Ae[0].audioDescription===me.audioDescription&&Ae[0].closedCaption===me.closedCaption&&Ae[0].language===me.language){m.info('DASH Parser: merging "switchable" AdaptationSets',B,Ce),Ae[0].representations.push(...me.representations),Ae[1]={priority:Math.max(O,Ae[1].priority),isMainAdaptation:v||Ae[1].isMainAdaptation,indexInMpd:Math.min(b,Ae[1].indexInMpd)};break}}}W<0&&t[M].push([me,{priority:O,isMainAdaptation:v,indexInMpd:b}])}!_(B)&&_(o[B])&&(o[B]={newID:le,adaptationSetSwitchingIDs:D})}let s=Yt.reduce((b,h)=>{let I=t[h];return I.length>0&&(I.sort(jf),b[h]=I.map(([T])=>T)),b},{});return t.video.sort(jf),Wf(s,i),{adaptations:s,thumbnailTracks:r}}function vy(n,e){var r,i;let t=[];for(let o=0;o<e.length;o++){let a=e[o];if(a!==void 0){if(a.mimeType===void 0){m.warn("DASH: Invalid thumbnails Representation, no mime-type");continue}let s=Jd(n,n.children.representations[o]);if(s===null)continue;if(a.height===void 0){m.warn("DASH: Invalid thumbnails Representation, no height information");continue}if(a.width===void 0){m.warn("DASH: Invalid thumbnails Representation, no width information");continue}let d=(r=a.index.getFirstAvailablePosition())!=null?r:void 0,u=(i=a.index.getEnd())!=null?i:void 0,c,l=a.index.getTargetSegmentDuration();l!==void 0&&l.isPrecize?c=l.duration:m.warn("DASH: Cannot produce duration estimate for thumbnail track"),t.push({id:a.id,cdnMetadata:a.cdnMetadata,index:a.index,mimeType:a.mimeType,height:a.height,width:a.width,horizontalTiles:s.horizontalTiles,verticalTiles:s.verticalTiles,start:d,end:u,tileDuration:c===void 0?void 0:c/(s.horizontalTiles*s.verticalTiles)})}}return t}function jf(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 Ry=et();function iu(n,e){var a,s,d,u,c;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 l=n.length-1;l>=0;l--){let f=l===n.length-1,p=n[l],g=e.xlinkInfos.get(p),b=Ot(e.baseURLs,p.children.baseURLs),{periodStart:h,periodDuration:I,periodEnd:T}=r[l],R;for(_(p.attributes.id)?(m.warn("DASH: No usable id found in the Period. Generating one."),R="gen-dash-period-"+Ry()):R=p.attributes.id;t.some(K=>K.id===R);)R+="-dup";let E=g!==void 0?g.receivedTime:e.receivedTime,v=(s=(a=e.unsafelyBaseOnPreviousManifest)==null?void 0:a.getPeriod(R))!=null?s:null,k=p.attributes.availabilityTimeComplete,x=p.attributes.availabilityTimeOffset,{manifestProfiles:P,contentProtectionParser:M}=e,{segmentTemplate:O}=p.children;M.addReferences((d=p.children.contentProtections)!=null?d:[]);let B={availabilityTimeComplete:k,availabilityTimeOffset:x,baseURLs:b,contentProtectionParser:M,manifestBoundsCalculator:o,end:T,isDynamic:i,isLastPeriod:f,manifestProfiles:P,receivedTime:E,segmentTemplate:O,start:h,unsafelyBaseOnPreviousPeriod:v},{adaptations:D,thumbnailTracks:F}=ru(p.children.adaptations,B),A=((u=e.xmlNamespaces)!=null?u:[]).concat((c=p.attributes.namespaces)!=null?c:[]),C=Py(p.children.eventStreams,h,A),N={id:R,start:h,end:T,duration:I,thumbnailTracks:F,adaptations:D,streamEvents:C};if(t.unshift(N),!o.lastPositionIsKnown()){let K=ky(D);if(!i)typeof K=="number"&&o.setLastPosition(K);else if(typeof K=="number"){let j=V()/1e3;o.setLastPosition(K,j)}else{let j=Yf(e,h);if(j!==void 0){let[$,z]=j;o.setLastPosition($,z)}}}}if(e.isDynamic&&!o.lastPositionIsKnown()){let l=Yf(e,0);if(l!==void 0){let[f,p]=l;o.setLastPosition(f,p)}}return Xd(t)}function Yf(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=V()/1e3;return[r,i]}}else{let t=n.clockOffset/1e3-n.availabilityStartTime,r=V()/1e3,i=r+t;if(i>=e)return[i,r]}}function ky(n){let e=null,t=!0,r=Bn(n).filter(o=>!_(o)),i=Hn(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 Py(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 c of a.children.events)if(c.eventStreamData!==void 0){let l=((o=c.presentationTime)!=null?o:0)/d+e,f=c.duration===void 0?void 0:l+c.duration/d,p,g;if(!Ht&&c.eventStreamData instanceof Element)p=c.eventStreamData;else try{g={namespaces:u,data:typeof c.eventStreamData=="string"?c.eventStreamData:Ue(new Uint8Array(c.eventStreamData))}}catch(b){m.error("DASH: Error while parsing event-stream:",b instanceof Error?b.message:"Unknown error")}r.push({start:l,end:f,id:c.id,data:{type:"dash-event-stream",value:{schemeIdUri:s,timescale:d,element:p,xmlData:g}}})}}return r}function ir(n,e,t,r,i=new WeakMap){let{children:o,attributes:a}=n;if(_(e.externalClockOffset)){let d=a.type==="dynamic",u=Q(o.utcTimings,f=>f.schemeIdUri==="urn:mpeg:dash:utc:direct:2014"&&!_(f.value)),c=!_(u)&&!_(u.value)?ya(u.value):void 0,l=!_(c)&&!isNaN(c)?c:void 0;if(!_(l)&&r!==!0)e.externalClockOffset=l;else if(d&&r!==!0){let f=Gd(n);if(!_(f)&&f.length>0)return{type:"needs-clock",value:{url:f,continue:function(g){return g.success?(e.externalClockOffset=ya(g.data),ir(n,e,t,!0)):(t.push(g.error),m.warn("DASH Parser: Error on fetching the clock ressource",g.error),ir(n,e,t,!0))}}}}}let s=[];for(let d=0;d<o.periods.length;d++){let{xlinkHref:u,xlinkActuate:c}=o.periods[d].attributes;!_(u)&&c==="onLoad"&&s.push({index:d,ressource:u})}return s.length===0?Cy(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 c=u.length-1;c>=0;c--){let l=s[c].index,{parsed:f,warnings:p,receivedTime:g,sendingTime:b,url:h}=u[c];p.length>0&&t.push(...p);for(let I of f)i.set(I,{receivedTime:g,sendingTime:b,url:h});o.periods.splice(l,1,...f)}return ir(n,e,t,r,i)}}}}function Cy(n,e,t,r){var A,C,N,K,j;let{children:i,attributes:o}=n,a=o.type==="dynamic",s=e.url!==void 0?[{url:e.url.substring(0,Mr(e.url))}]:[],d=Ot(s,i.baseURLs),u=Qd(o,e.referenceDateTime),c=o.timeShiftBufferDepth,l=o.maxSegmentDuration,{externalClockOffset:f,unsafelyBaseOnPreviousManifest:p}=e,{externalClockOffset:g}=e,b=new zi({availabilityStartTime:u,isDynamic:a,timeShiftBufferDepth:c,serverTimestampOffset:g}),h=new Vi;h.addReferences((A=i.contentProtections)!=null?A:[]);let I={availabilityStartTime:u,baseURLs:d,clockOffset:f,contentProtectionParser:h,duration:o.duration,isDynamic:a,manifestBoundsCalculator:b,manifestProfiles:n.attributes.profiles,receivedTime:e.manifestReceivedTime,unsafelyBaseOnPreviousManifest:p,xlinkInfos:r,xmlNamespaces:n.attributes.namespaces},T=iu(i.periods,I);h.finalize();let R=o.duration,E,v,k=null,x;o.minimumUpdatePeriod!==void 0&&o.minimumUpdatePeriod>=0&&(E=o.minimumUpdatePeriod===0?L.getCurrent().DASH_FALLBACK_LIFETIME_WHEN_MINIMUM_UPDATE_PERIOD_EQUAL_0:o.minimumUpdatePeriod);let{minimumSafePosition:P,maximumSafePosition:M,maximumUnsafePosition:O}=$d(T),B=V();if(a){let $;M!==void 0?$=M:g===void 0?(m.warn("DASH Parser: use system clock to define maximum position"),$=Date.now()/1e3-u):$=(V()+g)/1e3-u;let z=b.getEstimatedLiveEdge();z===void 0&&(O!==void 0?z=O:z=$),x={isLinear:!0,maximumSafePosition:$,livePosition:z,time:B},v=P,k=c!=null?c:null,k!==null&&(k+=l!=null?l:0),k!==null&&v!==void 0&&z-v>k&&(k=z-v)}else{v=P,v===void 0&&(v=(N=(C=T[0])==null?void 0:C.start)!=null?N:0);let $=R!=null?R:1/0;if(T[T.length-1]!==void 0){let z=T[T.length-1],H=(K=z.end)!=null?K:z.duration!==void 0?z.start+z.duration:void 0;H!==void 0&&H<$&&($=H)}M!==void 0&&M<$&&($=M),x={isLinear:!1,maximumSafePosition:$,livePosition:void 0,time:B}}let D=!a||n.attributes.minimumUpdatePeriod===void 0&&(((j=T[T.length-1])==null?void 0:j.end)!==void 0||n.attributes.duration!==void 0);return{type:"done",value:{parsed:{availabilityStartTime:u,clockOffset:e.externalClockOffset,isDynamic:a,isLive:a,isLastPeriodKnown:D,periods:T,publishTime:o.publishTime,suggestedPresentationDelay:o.suggestedPresentationDelay,transportType:"dash",timeBounds:{minimumSafePosition:v,timeshiftDepth:k,maximumTimeData:x},lifetime:E,uris:_(e.url)?i.locations:[e.url,...i.locations]},warnings:t}}}var $f=ir;function Dt(n){let e=n.textContent,t=[];return e===null||e.length===0?[void 0,t]:[{value:e},t]}var My=/^P(([\d.]*)Y)?(([\d.]*)M)?(([\d.]*)D)?T?(([\d.]*)H)?(([\d.]*)M)?(([\d.]*)S)?/,Ay=/([0-9]+)-([0-9]+)/;function qe(n,e){return n==="true"?[!0,null]:n==="false"?[!1,null]:[!1,new tt(`\`${e}\` property is not a boolean value but "${n}"`)]}function Ie(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 $e(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 ou(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 Sa(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 yt(n,e){if(!w(n))return[0,new tt(`\`${e}\` property is empty`)];let t=My.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 An(n,e){let t=Ay.exec(n);return t===null?[null,new tt(`\`${e}\` property has an unrecognized format "${n}"`)]:[[+t[1],+t[2]],null]}function Qf(n,e){try{return[ht(n),null]}catch(t){return[null,new tt(`\`${e}\` is not a valid base64 string: "${n}"`)]}}function or(n,e){let t=/^(\d+)\/(\d+)$/.exec(n);return t!==null?[+t[1]/+t[2],null]:$e(n,e)}function Le(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 Oe(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 xy(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]=Qf(o,"cenc:pssh");s!==null&&(m.warn(s.message),e.push(s)),a!==null&&t.push(a)}}}return[{cencPssh:t},e]}function wy(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=Ye(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]=xy(n.childNodes),r=wy(n);return[{children:e,attributes:r},t]}function au(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 su(n){let e={},t=[],r=Oe(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:An,dashName:"range"});break;case"sourceURL":e.media=o.value;break}}return[e,t]}function Nt(n){let e={},t=[],r=Oe(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]=su(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:Ie,dashName:"timescale"});break;case"presentationTimeOffset":r(a.value,{asKey:"presentationTimeOffset",parser:$e,dashName:"presentationTimeOffset"});break;case"indexRange":r(a.value,{asKey:"indexRange",parser:An,dashName:"indexRange"});break;case"indexRangeExact":r(a.value,{asKey:"indexRangeExact",parser:qe,dashName:"indexRangeExact"});break;case"availabilityTimeOffset":r(a.value,{asKey:"availabilityTimeOffset",parser:$e,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(a.value,{asKey:"availabilityTimeComplete",parser:qe,dashName:"availabilityTimeComplete"});break;case"duration":r(a.value,{asKey:"duration",parser:Ie,dashName:"duration"});break;case"startNumber":r(a.value,{asKey:"startNumber",parser:Ie,dashName:"startNumber"});break;case"endNumber":r(a.value,{asKey:"endNumber",parser:Ie,dashName:"endNumber"});break}}return[e,t]}function du(n){let e={},t=[],r=Oe(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:An,dashName:"indexRange"});break;case"index":e.index=o.value;break;case"mediaRange":r(o.value,{asKey:"mediaRange",parser:An,dashName:"mediaRange"});break}}return[e,t]}function Hi(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,c]=du(d);i.push(u),r=r.concat(c)}}return[Y(e,{list:i}),r]}function uu(n){let e=null;return function(){if(e===null){let t=n.getElementsByTagName("S");return e=t,t}return e}}function xn(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=uu(d))}let o=Y({},e,{duration:e.duration,timelineParser:i}),a=Oe(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:$e,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":a(d.value,{asKey:"availabilityTimeComplete",parser:qe,dashName:"availabilityTimeComplete"});break;case"media":o.media=d.value;break;case"bitstreamSwitching":a(d.value,{asKey:"bitstreamSwitching",parser:qe,dashName:"bitstreamSwitching"});break}}return[o,r]}function Oy(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(Le(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]=Hi(o);r=r.concat(s),e.segmentList=a;break}case"SegmentTemplate":{let[a,s]=xn(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"EssentialProperty":_(e.essentialProperties)?e.essentialProperties=[Le(o)]:e.essentialProperties.push(Le(o));break;case"SupplementalProperty":_(e.supplementalProperties)?e.supplementalProperties=[Le(o)]:e.supplementalProperties.push(Le(o));break}}return t.length>0&&(e.contentProtections=t),[e,r]}function Dy(n){let e={},t=[],r=Oe(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:Ie,dashName:"bandwidth"});break;case"codecs":e.codecs=o.value;break;case"codingDependency":r(o.value,{asKey:"codingDependency",parser:qe,dashName:"codingDependency"});break;case"frameRate":r(o.value,{asKey:"frameRate",parser:or,dashName:"frameRate"});break;case"height":r(o.value,{asKey:"height",parser:Ie,dashName:"height"});break;case"id":e.id=o.value;break;case"maxPlayoutRate":r(o.value,{asKey:"maxPlayoutRate",parser:$e,dashName:"maxPlayoutRate"});break;case"maximumSAPPeriod":r(o.value,{asKey:"maximumSAPPeriod",parser:$e,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:Ie,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:Ie,dashName:"width"});break;case"availabilityTimeOffset":r(o.value,{asKey:"availabilityTimeOffset",parser:$e,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(o.value,{asKey:"availabilityTimeComplete",parser:qe,dashName:"availabilityTimeComplete"});break}}return e.bitrate===void 0&&t.push(new tt("No bitrate found on a Representation")),[e,t]}function Xf(n){let[e,t]=Oy(n.childNodes),[r,i]=Dy(n),o=t.concat(i);return[{children:e,attributes:r},o]}function Ly(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=[Le(o)]:e.accessibilities.push(Le(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=au(o);break;case"EssentialProperty":_(e.essentialProperties)?e.essentialProperties=[Le(o)]:e.essentialProperties.push(Le(o));break;case"InbandEventStream":e.inbandEventStreams===void 0&&(e.inbandEventStreams=[]),e.inbandEventStreams.push(Le(o));break;case"Label":{let a=o.textContent;a!=null&&(e.label=a);break}case"Representation":{let[a,s]=Xf(o);e.representations.push(a),s.length>0&&(r=r.concat(s));break}case"Role":_(e.roles)?e.roles=[Le(o)]:e.roles.push(Le(o));break;case"SupplementalProperty":_(e.supplementalProperties)?e.supplementalProperties=[Le(o)]:e.supplementalProperties.push(Le(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]=Hi(o);e.segmentList=a,s.length>0&&(r=r.concat(s));break}case"SegmentTemplate":{let[a,s]=xn(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 Ny(n){let e={},t=[],r=Oe(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:Ie,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:Ie,dashName:"minBandwidth"});break;case"maxBandwidth":r(o.value,{asKey:"maxBitrate",parser:Ie,dashName:"maxBandwidth"});break;case"minWidth":r(o.value,{asKey:"minWidth",parser:Ie,dashName:"minWidth"});break;case"maxWidth":r(o.value,{asKey:"maxWidth",parser:Ie,dashName:"maxWidth"});break;case"minHeight":r(o.value,{asKey:"minHeight",parser:Ie,dashName:"minHeight"});break;case"maxHeight":r(o.value,{asKey:"maxHeight",parser:Ie,dashName:"maxHeight"});break;case"minFrameRate":r(o.value,{asKey:"minFrameRate",parser:or,dashName:"minFrameRate"});break;case"maxFrameRate":r(o.value,{asKey:"maxFrameRate",parser:or,dashName:"maxFrameRate"});break;case"selectionPriority":r(o.value,{asKey:"selectionPriority",parser:Ie,dashName:"selectionPriority"});break;case"segmentAlignment":r(o.value,{asKey:"segmentAlignment",parser:ou,dashName:"segmentAlignment"});break;case"subsegmentAlignment":r(o.value,{asKey:"subsegmentAlignment",parser:ou,dashName:"subsegmentAlignment"});break;case"bitstreamSwitching":r(o.value,{asKey:"bitstreamSwitching",parser:qe,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:qe,dashName:"codingDependency"});break;case"frameRate":r(o.value,{asKey:"frameRate",parser:or,dashName:"frameRate"});break;case"height":r(o.value,{asKey:"height",parser:Ie,dashName:"height"});break;case"maxPlayoutRate":r(o.value,{asKey:"maxPlayoutRate",parser:$e,dashName:"maxPlayoutRate"});break;case"maximumSAPPeriod":r(o.value,{asKey:"maximumSAPPeriod",parser:$e,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:Ie,dashName:"width"});break;case"availabilityTimeOffset":r(o.value,{asKey:"availabilityTimeOffset",parser:$e,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(o.value,{asKey:"availabilityTimeComplete",parser:qe,dashName:"availabilityTimeComplete"});break}}return[e,t]}function Zf(n){let e=n.childNodes,[t,r]=Ly(e),[i,o]=Ny(n),a=r.concat(o);return[{children:t,attributes:i},a]}function lu(n){let e={children:{events:[]},attributes:{}},t=[],r=Oe(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:Ie,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]=Uy(o);e.children.events.push(a),s.length>0&&(t=t.concat(s));break}}}return[e,t]}function Uy(n){let e={eventStreamData:n},t=[],r=Oe(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:Ie,dashName:"presentationTime"});break;case"duration":r(o.value,{asKey:"duration",parser:Ie,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,c]=Dt(d);u!==void 0&&e.push(u),o=o.concat(c);break}case"AdaptationSet":{let[u,c]=Zf(d);t.push(u),o=o.concat(c);break}case"EventStream":{let[u,c]=lu(d);a.push(u),o=o.concat(c);break}case"SegmentTemplate":{let[u,c]=xn(d);r=u,c.length>0&&(o=o.concat(c));break}case"ContentProtection":{let[u,c]=Lt(d);c.length>0&&(o=o.concat(c)),u!==void 0&&i.push(u);break}}}return[{baseURLs:e,adaptations:t,eventStreams:a,segmentTemplate:r,contentProtections:i},o]}function Fy(n){let e={},t=[],r=Oe(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:yt,dashName:"start"});break;case"duration":r(o.value,{asKey:"duration",parser:yt,dashName:"duration"});break;case"bitstreamSwitching":r(o.value,{asKey:"bitstreamSwitching",parser:qe,dashName:"bitstreamSwitching"});break;case"xlink:href":e.xlinkHref=o.value;break;case"xlink:actuate":e.xlinkActuate=o.value;break}}return[e,t]}function Ta(n){let[e,t]=By(n.childNodes),[r,i]=Fy(n),o=t.concat(i);return[{children:e,attributes:r},o]}function Ky(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,c]=Dt(d);u!==void 0&&e.push(u),a=a.concat(c);break}case"Location":t.push(d.textContent===null?"":d.textContent);break;case"Period":{let[u,c]=Ta(d);r.push(u),a=a.concat(c);break}case"UTCTiming":{let u=Le(d);i.push(u);break}case"ContentProtection":{let[u,c]=Lt(d);c.length>0&&(a=a.concat(c)),u!==void 0&&o.push(u);break}}}return[{baseURLs:e,locations:t,periods:r,utcTimings:i,contentProtections:o},a]}function Vy(n){let e={},t=[],r=Oe(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:Sa,dashName:"availabilityStartTime"});break;case"availabilityEndTime":r(o.value,{asKey:"availabilityEndTime",parser:Sa,dashName:"availabilityEndTime"});break;case"publishTime":r(o.value,{asKey:"publishTime",parser:Sa,dashName:"publishTime"});break;case"mediaPresentationDuration":r(o.value,{asKey:"duration",parser:yt,dashName:"mediaPresentationDuration"});break;case"minimumUpdatePeriod":r(o.value,{asKey:"minimumUpdatePeriod",parser:yt,dashName:"minimumUpdatePeriod"});break;case"minBufferTime":r(o.value,{asKey:"minBufferTime",parser:yt,dashName:"minBufferTime"});break;case"timeShiftBufferDepth":r(o.value,{asKey:"timeShiftBufferDepth",parser:yt,dashName:"timeShiftBufferDepth"});break;case"suggestedPresentationDelay":r(o.value,{asKey:"suggestedPresentationDelay",parser:yt,dashName:"suggestedPresentationDelay"});break;case"maxSegmentDuration":r(o.value,{asKey:"maxSegmentDuration",parser:yt,dashName:"maxSegmentDuration"});break;case"maxSubsegmentDuration":r(o.value,{asKey:"maxSubsegmentDuration",parser:yt,dashName:"maxSubsegmentDuration"});break}}return[e,t]}function Jf(n){let[e,t]=Ky(n.childNodes),[r,i]=Vy(n),o=t.concat(i);return[{children:e,attributes:r},o]}function cu(n,e){let t=n.documentElement;if(_(t)||t.nodeName!=="MPD")throw new Error("DASH Parser: document root should be MPD");let[r,i]=Jf(t),o=$f(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 l=0;l<d.length;l++){let{responseData:f,receivedTime:p,sendingTime:g,url:b}=d[l];if(!f.success)throw f.error;let h="<root>"+f.data+"</root>",I=new DOMParser().parseFromString(h,"text/xml");if(_(I)||I.children.length===0)throw new Error("DASH parser: Invalid external ressources");let T=I.children[0].children,R=[],E=[];for(let v=0;v<T.length;v++)if(T[v].nodeType===Node.ELEMENT_NODE){let[k,x]=Ta(T[v]);E.push(...x),R.push(k)}u.push({url:b,receivedTime:p,sendingTime:g,parsed:R,warnings:E})}let c=s.value.continue(u);return a(c)}}};He(s)}}var em=cu;function ze(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 fu(n,e){return(t,r,i)=>new Promise((o,a)=>{let s=Date.now()-V(),d=!1,f={reject:b=>{var R,E;if(d||i.isCancelled())return;d=!0,i.deregister(g);let h=b,I=(R=h==null?void 0:h.message)!=null?R:"Unknown error when fetching the Manifest through a custom manifestLoader.",T=new it(I,(E=h==null?void 0:h.canRetry)!=null?E:!1,h==null?void 0:h.xhr);a(T)},resolve:b=>{if(d||i.isCancelled())return;d=!0,i.deregister(g);let h=b.receivingTime!==void 0?b.receivingTime-s:void 0,I=b.sendingTime!==void 0?b.sendingTime-s:void 0;o({responseData:b.data,size:b.size,requestDuration:b.duration,url:b.url,receivedTime:h,sendingTime:I})},fallback:()=>{d||i.isCancelled()||(d=!0,i.deregister(g),e(t,r,i).then(o,a))}},p=n({url:t,timeout:r.timeout,cmcdPayload:r.cmcdPayload},f);i.register(g);function g(b){d||(d=!0,typeof p=="function"&&p(),a(b))}})}function zy(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"?ze(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 Se({url:o,headers:a,responseType:"arraybuffer",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});case"text":return Se({url:o,headers:a,responseType:"text",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});case"document":return Se({url:o,headers:a,responseType:"document",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});default:He(n)}}}function Wi({customManifestLoader:n},e,t){let r=zy(e),i=typeof n!="function"?r:fu(n,r);return t!==null?t(i):i}function rn(n,e){if(e){if(Et(n,1718909296)<0)throw new Ne("INTEGRITY_ERROR","Incomplete `ftyp` box");if(Et(n,1836019574)<0)throw new Ne("INTEGRITY_ERROR","Incomplete `moov` box")}else{if(Et(n,1836019558)<0)throw new Ne("INTEGRITY_ERROR","Incomplete `moof` box");if(Et(n,1835295092)<0)throw new Ne("INTEGRITY_ERROR","Incomplete `mdat` box")}}function It(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 _a(n){return(e,t,r,i,o)=>{return new Promise((s,d)=>{let u=new U,c=u.linkToSignal(i);u.signal.register(d),n(e,t,r,u.signal,de(oe({},o),{onNewChunk(f){try{a(f),o.onNewChunk(f)}catch(p){l(),u.cancel(),d(p)}}})).then(f=>{if(l(),!u.isUsed()){if(f.resultType==="segment-loaded")try{a(f.resultData.responseData)}catch(p){d(p);return}s(f)}},f=>{l(),d(f)});function l(){u.signal.deregister(d),c()}});function a(s){!(s instanceof ArrayBuffer)&&!(s instanceof Uint8Array)||It(t.type,t.mimeType)!=="mp4"||rn(new Uint8Array(s),t.segment.isInit)}}}function tm(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 c=d[u];for(;Hy(a[s]);)s--;for(let l=c.length-1;l>=0;l--){if(a[s]!==c[l])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 c=u.length-1;c>=0;c--){let l=u[c];for(;Wy(d.getUint8(s));)s--;for(let f=l.length-1;f>=0;f--){if(d.getUint8(s)!==l[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 Ne("INTEGRITY_ERROR","MPD does not end with </MPD>")}}}function Hy(n){return n===" "||n===" "||n==="\r"||n===`
5
- `}function Wy(n){return n===32||n===9||n===13||n===10}function mu(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,c=o.externalClockOffset,l=(T=i.url)!=null?T:o.originalUrl,f=t!=null?t:c,g={unsafelyBaseOnPreviousManifest:o.unsafeMode?o.previousManifest:null,url:l,referenceDateTime:e,externalClockOffset:f},b=fe.dashParsers;if(b.wasm===null||b.wasm.status==="uninitialized"||b.wasm.status==="failure")return m.debug("DASH: WASM MPD Parser not initialized. Running JS one."),h();{let R=$y(u);if(!Qy(R))return m.info("DASH: MPD doesn't seem to be UTF-8-encoded. Running JS parser instead of the WASM one."),h();if(b.wasm.status==="initialized"){m.debug("DASH: Running WASM MPD Parser.");let E=b.wasm.runWasmParser(R,g);return I(E)}else return m.debug("DASH: Awaiting WASM initialization before parsing the MPD."),b.wasm.waitForInitialization().catch(()=>{}).then(()=>{if(b.wasm===null||b.wasm.status!=="initialized")return m.warn("DASH: WASM MPD parser initialization failed. Running JS parser instead"),h();m.debug("DASH: Running WASM MPD Parser.");let v=b.wasm.runWasmParser(R,g);return I(v)})}function h(){if(b.fastJs!==null){let R=jy(u),E=b.fastJs(R,g);return I(E)}else if(b.native!==null){let R=Yy(u),E=b.native(R,g);return I(E)}else throw new Error("No MPD parser is imported")}function I(R){if(R.type==="done"){if(R.value.warnings.length>0&&a(R.value.warnings),s.isCancelled())return Promise.reject(s.cancellationError);let k=[];return{manifest:new $n(R.value.parsed,n,k),url:l,warnings:k}}let{value:E}=R,v=E.urls.map(k=>d(()=>{let x=L.getCurrent().DEFAULT_REQUEST_TIMEOUT,P=L.getCurrent().DEFAULT_CONNECTION_TIMEOUT;return E.format==="string"?Se({url:k,responseType:"text",timeout:x,connectionTimeout:P,cancelSignal:s}):Se({url:k,responseType:"arraybuffer",timeout:x,connectionTimeout:P,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 Y(x,{responseData:{success:!0,data:x.responseData}})}else{if(!(x.responseData instanceof ArrayBuffer))throw new Error("External DASH resources should have been ArrayBuffers");return Y(x,{responseData:{success:!0,data:x.responseData}})}},x=>{let P=Ee(x,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"An unknown error occured when parsing ressources."});return Y({},{size:void 0,requestDuration:void 0,responseData:{success:!1,error:P}})}));return Promise.all(v).then(k=>E.format==="string"?(qy(k),I(E.continue(k))):(Gy(k),I(E.continue(k))))}}}function qy(n){y.CURRENT_ENV!==y.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 Gy(n){y.CURRENT_ENV!==y.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 jy(n){if(n instanceof ArrayBuffer)return Ue(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 Yy(n){if(n instanceof ArrayBuffer)return new DOMParser().parseFromString(Ue(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 $y(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 Qy(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 Qe([n,e]){return e===1/0?`bytes=${n}-`:`bytes=${n}-${e}`}function wn(n,e){return n===null?null:e.url===null?n.baseUrl:gn(n.baseUrl,e.url)}function qi(n,e,t,r,i){var u,c;let o=n;((u=t.cmcdPayload)==null?void 0:u.type)==="query"&&(o=ze(o,t.cmcdPayload.value));let a=((c=t.cmcdPayload)==null?void 0:c.type)==="headers"?t.cmcdPayload.value:void 0;if(e.range===void 0)return Se({url:o,responseType:"arraybuffer",headers:a,timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(l=>({resultType:"segment-loaded",resultData:l}));if(e.indexRange===void 0)return Se({url:o,headers:de(oe({},a),{Range:Qe(e.range)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(l=>({resultType:"segment-loaded",resultData:l}));if(e.range[1]+1===e.indexRange[0])return Se({url:o,headers:de(oe({},a),{Range:Qe([e.range[0],e.indexRange[1]])}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(l=>({resultType:"segment-loaded",resultData:l}));let s=Se({url:o,headers:de(oe({},a),{Range:Qe(e.range)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}),d=Se({url:o,headers:de(oe({},a),{Range:Qe(e.indexRange)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress});return Promise.all([s,d]).then(([l,f])=>{let p=se(new Uint8Array(l.responseData),new Uint8Array(f.responseData)),g=Math.min(l.sendingTime,f.sendingTime),b=Math.max(l.receivedTime,f.receivedTime);return{resultType:"segment-loaded",resultData:{url:o,responseData:p,size:l.size+f.size,requestDuration:b-g,sendingTime:g,receivedTime:b}}})}async function Gi(n,e,t,r){let i=null;function o(s){let d=new Uint8Array(s.chunk),u=i!==null?se(i,d):d,c=$o(u),l=c[0];i=c[1],!(l!==null&&(l.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 Po({url:n,headers:e.headers,onData:o,timeout:e.timeout,connectionTimeout:e.connectionTimeout,cancelSignal:r})}}async function nm(n,e,t,r,i,o){var f,p;if(e.segment.isInit)return qi(n,e.segment,r,o,i);let a=((f=r.cmcdPayload)==null?void 0:f.type)==="query"?ze(n,r.cmcdPayload.value):n,s=((p=r.cmcdPayload)==null?void 0:p.type)==="headers"?r.cmcdPayload.value:void 0,{segment:d}=e,u;d.range!==void 0?u=de(oe({},s),{Range:Qe(d.range)}):s!==void 0&&(u=s);let c=It(e.type,e.mimeType);if(t&&(c==="mp4"||c===void 0)){if(xr())return Gi(a,{headers:u,timeout:r.timeout,connectionTimeout:r.connectionTimeout},i,o);xt("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 Se({url:a,responseType:"arraybuffer",headers:u,timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:o,onProgress:i.onProgress})}}function pu({lowLatencyMode:n,segmentLoader:e,checkMediaSegmentIntegrity:t}){return t!==!0?r:_a(r);function r(i,o,a,s,d){let u=wn(i,o.segment);return u===null?Promise.resolve({resultType:"segment-created",resultData:null}):n||e===void 0?nm(u,o,n,a,d,s):new Promise((c,l)=>{let f=!1,I={reject:k=>{var O,B;if(f||s.isCancelled())return;f=!0,s.deregister(v);let x=k,P=(O=x==null?void 0:x.message)!=null?O:"Unknown error when fetching a DASH segment through a custom segmentLoader.",M=new it(P,(B=x==null?void 0:x.canRetry)!=null?B:!1,x==null?void 0:x.xhr);l(M)},resolve:k=>{f||s.isCancelled()||(f=!0,s.deregister(v),c({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(v),nm(u,o,n,a,d,s).then(c,l))}},T;o.segment.range!==void 0&&(T=[o.segment.range],o.segment.indexRange!==void 0&&T.push(o.segment.indexRange));let R={isInit:o.segment.isInit,timeout:a.timeout,byteRanges:T,trackType:o.type,url:u,cmcdPayload:a.cmcdPayload},E=e(R,I);s.register(v);function v(k){f||(f=!0,typeof E=="function"&&E(),l(k))}})}}var hu=408125543,rm=357149030,Xy=2807729,Zy=17545,Jy=475249515,eI=187,tI=179,nI=183,rI=241;function on(n,e,t,[r,i]){let o=r;for(;o<i;){let a=oI(t,o);if(a===null)return null;let{value:s,length:d}=a,u=o+d,c=aI(t,u);if(c===null)return null;let{length:l,value:f}=c,p=u+l,g=p+f;if(s===n)return[p,g];if(e.length>0){for(let b=0;b<e.length;b++)if(s===e[b]){let h=e.slice(b+1,e.length);return on(n,h,t,[p,g])}}o=g}return null}function Ea(n,e){let t=on(Xy,[hu,rm],n,[e,n.length]);if(t===null)return null;let r=t[1]-t[0];return 1e9/gu(n,t[0],r)}function iI(n,e){let t=on(Zy,[hu,rm],n,[e,n.length]);if(t===null)return null;let r=t[1]-t[0];return r===4?sI(n,t[0]):r===8?dI(n,t[0]):null}function yu(n,e){let t=on(hu,[],n,[e,n.length]);if(t===null)return null;let[r,i]=t,o=Ea(n,r);if(o===null)return null;let a=iI(n,r);if(a===null)return null;let s=on(Jy,[],n,[r,i]);if(s===null)return null;let d=[],u=s[0];for(;u<s[1];){let l=on(eI,[],n,[u,s[1]]);if(l===null)break;let f=on(tI,[],n,[l[0],l[1]]);if(f===null)return null;let p=gu(n,f[0],f[1]-f[0]),g=on(rI,[nI],n,[l[0],l[1]]);if(g===null)return null;let b=gu(n,g[0],g[1]-g[0])+r;d.push({time:p,rangeStart:b}),u=l[1]}let c=[];for(let l=0;l<d.length;l++){let f=d[l];l===d.length-1?c.push({time:f.time,timescale:o,duration:l===0?a:a-f.time,range:[f.rangeStart,1/0]}):c.push({time:f.time,timescale:o,duration:d[l+1].time-f.time,range:[f.rangeStart,d[l+1].rangeStart-1]})}return c}function im(n,e){for(let t=1;t<=8;t++)if(n[e]>=Math.pow(2,8-t))return t}function oI(n,e){let t=im(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 aI(n,e){let t=im(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 sI(n,e){return new DataView(n.buffer).getFloat32(e)}function dI(n,e){return new DataView(n.buffer).getFloat64(e)}function gu(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 ji(n,e,t,r){let i=Ds(n);if(i===void 0||r===void 0)return null;let o=t.timestampOffset!==void 0?i+t.timestampOffset*r:i,a=Wr(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 uI(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=Ue(a),d=Date.parse(s);if(o===void 0||d===void 0||isNaN(d)||d>=o)return!0}return!1}function Iu(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:uI(t,e);return{inbandEvents:i,needsManifestRefresh:o}}function bu({__priv_patchLastSegmentInSidx:n}){return function(t,r,i){var R,E;let{segment:o,periodStart:a,periodEnd:s}=r,{data:d,isChunked:u}=t,c=[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:c};let l=d instanceof Uint8Array?d:new Uint8Array(d),f=It(r.type,r.mimeType),p=f==="mp4"||f===void 0,g=[];if(p){let v=Qo(l),k;o.isInit&&(k=(R=ef(l))!=null?R:void 0),(v.length>0||k!==void 0)&&g.push({initDataType:"cenc",keyId:k,initData:v})}if(!o.isInit){let v=p?ji(l,u,o,i):null,k=(E=o.timestampOffset)!=null?E:0;if(p){let x=Jc(l);if(x!==void 0){let P=x.filter(O=>o.privateInfos===void 0||o.privateInfos.isEMSGWhitelisted===void 0?!1:o.privateInfos.isEMSGWhitelisted(O)),M=Iu(P,r.manifestPublishTime);if(M!==void 0){let{needsManifestRefresh:O,inbandEvents:B}=M;return{segmentType:"media",chunkData:l,chunkSize:l.length,chunkInfos:v,chunkOffset:k,appendWindow:c,inbandEvents:B,protectionData:g,needsManifestRefresh:O}}}}return{segmentType:"media",chunkData:l,chunkSize:l.length,chunkInfos:v,chunkOffset:k,protectionData:g,appendWindow:c}}let{indexRange:b}=o,h;if(f==="webm")h=yu(l,0);else if(p&&(h=Hr(l,Array.isArray(b)?b[0]:0),n===!0&&h!==null&&h.length>0)){let v=h[h.length-1];Array.isArray(v.range)&&(v.range[1]=1/0)}let I;p?I=qr(l):f==="webm"&&(I=Ea(l,0));let T=_(I)?void 0:I;return{segmentType:"init",initializationData:l,initializationDataSize:l.length,protectionData:g,initTimescale:T,segmentList:h!=null?h:void 0}}}function Su({lowLatencyMode:n,checkMediaSegmentIntegrity:e}){return e!==!0?t:_a(t);async function t(r,i,o,a,s){var h,I;let{segment:d}=i,u=wn(r,d);if(u===null)return Promise.resolve({resultType:"segment-created",resultData:null});if(d.isInit)return qi(u,d,o,a,s);let c=((h=o.cmcdPayload)==null?void 0:h.type)==="query"?ze(u,o.cmcdPayload.value):u,l=((I=o.cmcdPayload)==null?void 0:I.type)==="headers"?o.cmcdPayload.value:void 0,f;d.range!==void 0?f=de(oe({},l),{Range:Qe(d.range)}):l!==void 0&&(f=l);let p=It(i.type,i.mimeType),g=p==="mp4"||p===void 0;if(n&&g){if(xr())return Gi(c,{headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout},s,a);xt("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 b;return g?b=await Se({url:c,responseType:"arraybuffer",headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout,onProgress:s.onProgress,cancelSignal:a}):b=await Se({url:c,responseType:"text",headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout,onProgress:s.onProgress,cancelSignal:a}),{resultType:"segment-loaded",resultData:b}}}function lI(n){let e=Vr(n);return e===null?"":Ue(e)}function cI(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 fI(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 om({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=cI(t);return{data:lI(r),type:d,language:e,start:a,end:s}}function am(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=fI(n.codecs,n.mimeType);return{data:e,type:a,language:n.language,start:i,end:o}}function mI(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 p=Hr(d,Array.isArray(s)?s[0]:0);if(i===!0&&p!==null&&p.length>0){let b=p[p.length-1];Array.isArray(b.range)&&(b.range[1]=1/0)}let g=qr(d);return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:g,segmentList:p!=null?p:void 0}}let u=ji(d,e,o,r),c=om(t,d,u,e),l=(f=o.timestampOffset)!=null?f:0;return{segmentType:"media",chunkData:c,chunkSize:d.length,chunkInfos:u,chunkOffset:l,protectionData:[],appendWindow:[t.periodStart,t.periodEnd]}}function pI(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 c=n instanceof Uint8Array?n:new Uint8Array(n);s=Ue(c),d=c.length}else s=n;return{segmentType:"media",chunkData:am(t,s,e),chunkSize:d,chunkInfos:null,chunkOffset:a,protectionData:[],appendWindow:[r,i]}}function Tu({__priv_patchLastSegmentInSidx:n}){return function(t,r,i){var l;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:(l=s.timestampOffset)!=null?l:0,protectionData:[],appendWindow:[o,a]};let c=It(r.type,r.mimeType);if(c==="webm")throw new Error("Text tracks with a WEBM container are not yet handled.");return c==="mp4"?mI(d,u,r,i,n):pI(d,u,r)}}async function sm(n,e,t,r){var d,u;let i=wn(n,e);if(i===null)return Promise.reject(new Error("Cannot load thumbnail: no URL"));let o=((d=t.cmcdPayload)==null?void 0:d.type)==="query"?ze(i,t.cmcdPayload.value):i,a=((u=t.cmcdPayload)==null?void 0:u.type)==="headers"?t.cmcdPayload.value:void 0,s;return e.range!==void 0?s=de(oe({},a),{Range:Qe(e.range)}):a!==void 0&&(s=a),wr({url:o,responseType:"arraybuffer",headers:s,timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r})}function dm(n,e){var u;let{thumbnailTrack:t,thumbnail:r}=e,i=t.height/t.verticalTiles,o=t.width/t.horizontalTiles,a=[],s=(u=t.tileDuration)!=null?u:(r.end-r.time)/(t.horizontalTiles*t.verticalTiles),d=r.time;for(let c=0;c<t.verticalTiles;c++)for(let l=0;l<t.horizontalTiles;l++)a.push({start:d,end:d+s,offsetX:Math.round(l*o),offsetY:Math.round(c*i),height:Math.floor(i),width:Math.floor(o)}),d+=s;return{mimeType:t.mimeType,data:n,thumbnails:a}}function um(n){let e=Wi({customManifestLoader:n.manifestLoader},gI()?"text":"arraybuffer",n.checkManifestIntegrity===!0?tm:null),t=mu(n),r=pu(n),i=bu(n),o=Su(n),a=Tu(n);return{transportName:"dash",manifest:{loadManifest:e,parseManifest:t},audio:{loadSegment:r,parseSegment:i},video:{loadSegment:r,parseSegment:i},text:{loadSegment:o,parseSegment:a},thumbnails:{loadThumbnail:sm,parseThumbnail:dm}}}function gI(){return fe.dashParsers.wasm!==null&&(fe.dashParsers.wasm.status==="initialized"||fe.dashParsers.wasm.status==="initializing")}var lm=um;function _u(n){n.transports.dash===void 0&&(n.transports.dash=lm),n.dashParsers.native=em,n.mainThreadMediaSourceInit=kn}var hI=typeof MediaSource=="function"&&MediaSource.canConstructInDedicatedWorker===!0,cm=hI;var Yi=class extends Jn{constructor(e){super(),this._settings=e,this._initCanceller=new U}prepare(){}start(e,t){let r=this._initCanceller.signal,{keySystems:i,speed:o,url:a}=this._settings;er(e);let{statusRef:s}=Mi(e,i,{onError:u=>this._onFatalError(u),onWarning:u=>this.trigger("warning",u),onBlackListProtectionData:Z,onKeyIdsCompatibilityUpdate:Z},r);Oi(e,u=>this._onFatalError(u),r);let d=new Rn(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,c)=>{u.initializationState.type!=="uninitialized"&&(c(),m.info("Setting URL to HTMLMediaElement",a),e.src=a,r.register(()=>{m.info("Init: Removing directfile src from media element",e.src),er(e)}),u.initializationState.type==="awaiting-media-link"?(u.initializationState.value.isMediaLinked.setValue(!0),s.onUpdate((l,f)=>{l.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;Ci({mediaElement:e,playbackObserver:t,startTime:()=>{m.debug("Init: Calculating initial time");let s=yI(e,o);return m.debug("Init: Initial time calculated:",s),s},mustAutoPlay:i,onWarning:s=>this.trigger("warning",s),isDirectfile:!0},r).autoPlayResult.then(()=>Pi(t,!0,r).onUpdate((s,d)=>{s&&(d(),this.trigger("loaded",{getSegmentSinkMetrics:null,getThumbnailData:()=>Promise.reject(new Error("Thumbnail data not available with directfile contents"))}))},{emitCurrentValue:!0,clearSignal:r})).catch(s=>{r.isCancelled()||this._onFatalError(s)})}};function yI(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 Eu(n,e){for(let t=0;t<n.length;t++)(!gr||t!==e)&&(n[t].enabled=!1);return e<0||e>=n.length?!1:(n[e].enabled=!0,!0)}function ar(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 vu(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:Or(o.language),audioDescription:o.kind==="descriptions"||o.kind==="description",representations:[]};e.push({track:u,nativeTrack:o})}return e}function Ru(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,c={language:o.language,forced:u,label:o.label,id:d,normalized:Or(o.language),closedCaption:o.kind==="captions"};e.push({track:c,nativeTrack:o})}return e}function ku(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 $i=class extends ae{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?vu(this._nativeAudioTracks):[],this._videoTracks=this._nativeVideoTracks!==void 0?ku(this._nativeVideoTracks):[],this._textTracks=this._nativeTextTracks!==void 0?Ru(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(){fm(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(){mm(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){fm(this._textTracks);return}else for(let e=0;e<this._textTracks.length;e++){let{nativeTrack:t}=this._textTracks[e];if(t===this._textTrackLockedOn){II(this._textTracks,t),t.mode!=="showing"&&(t.mode="showing");return}}}_setPreviouslyLockedVideoTrack(){if(this._videoTrackLockedOn!==void 0)if(this._videoTrackLockedOn===null){mm(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=vu(this._nativeAudioTracks);if(ar(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=vu(this._nativeAudioTracks);if(ar(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=Ru(this._nativeTextTracks);if(ar(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=Ru(this._nativeTextTracks);if(ar(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=ku(this._nativeVideoTracks);if(ar(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=ku(this._nativeVideoTracks);if(ar(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){Eu(this._audioTracks.map(({nativeTrack:t})=>t),e)}};function fm(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.mode="disabled"}}function II(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 mm(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.selected=!1}}function Pu(n){n.directfile={initDirectFile:Yi,mediaElementTracksStore:$i}}function Cu(n){n.decrypt=ff}var pm=J.ResizeObserver;function Mu(n,e,t){let{height:r,width:i}=n.getBoundingClientRect(),o=new G({height:r,width:i},t),a=r,s=i;if(pm!==void 0){let d=new pm(u=>{if(u.length===0){m.error("Compat: Resized but no observed element.");return}let c=u[0],{height:l,width:f}=c.contentRect;(l!==a||f!==s)&&(a=l,s=f,o.setValue({height:l,width:f}))});d.observe(n),t.register(()=>{d.disconnect()})}else{let d=setInterval(()=>{let{height:u,width:c}=n.getBoundingClientRect();(u!==a||c!==s)&&(a=u,s=c,o.setValue({height:u,width:c}))},e);t.register(()=>{clearInterval(d)})}return o}var On=class{constructor(){this._ranges=[],this.length=0}insert(e,t){y.CURRENT_ENV===y.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){y.CURRENT_ENV===y.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=cc(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 Au(n,e,t,r){m.debug("HTSB: Finding parser for html text tracks:",n);let i=fe.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 bI=.05;function gm(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<=bI}function Qi(n,e){for(let t=n.length-1;t>=0;t--)if(n[t].start<e)return n.slice(0,t+1);return[]}function sr(n,e){for(let t=0;t<n.length;t++)if(n[t].end>e)return n.slice(t,n.length);return[]}function xu(n,e,t){let r=Math.max(n.start,e),i=Qi(n.cues,e),o={start:n.start,end:r,cues:i},a=Math.min(t,n.end),s=sr(n.cues,t),d={start:a,end:n.end,cues:s};return[o,d]}var hm=.001,SI=5,Xi=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,hm)||Ut(e,s.end,hm))&&r.push(s.element);return r}}return[]}remove(e,t){y.CURRENT_ENV===y.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=sr(a.cues,r),a.start=r;else{let[s,d]=xu(a,e,r);this._cuesBuffer[o]=s,i.splice(o+1,0,d)}return}a.start>=e?(i.splice(o,1),o--):(a.cues=Qi(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)/SI;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=sr(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(gm(o,u)){if(Ut(r,u.end,a)){i[d]=o;return}else if(r<u.end){u.cues=sr(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=sr(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=Qi(u.cues,t),u.end=t,i.splice(d+1,0,o);return}else if(u.end>r){let[c,l]=xu(u,t,r);this._cuesBuffer[d]=c,i.splice(d+1,0,o),i.splice(d+2,0,l);return}else{u.cues=Qi(u.cues,t),u.end=t;let c=d+1;for(u=i[c];u!==void 0&&r>u.end;)i.splice(c,1),u=i[c];s(c);return}}}if(i.length>0){let d=i[i.length-1];Ut(d.end,t,a)&&(d.end=t)}i.push(o)}};function wu(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 c=s.getAttribute("data-proportional-height");c!==null&&!isNaN(+c)&&(s.style.height=String(+c*i[1])+"px");let l=s.getAttribute("data-proportional-line-height");l!==null&&!isNaN(+l)&&(s.style.lineHeight=String(+l*i[1])+"px");let f=s.getAttribute("data-proportional-left");f!==null&&!isNaN(+f)&&(s.style.left=String(+f*i[0])+"px");let p=s.getAttribute("data-proportional-top");p!==null&&!isNaN(+p)&&(s.style.top=String(+p*i[1])+"px");let g=s.getAttribute("data-proportional-padding-top");g!==null&&!isNaN(+g)&&(s.style.paddingTop=String(+g*i[1])+"px");let b=s.getAttribute("data-proportional-padding-bottom");b!==null&&!isNaN(+b)&&(s.style.paddingBottom=String(+b*i[1])+"px");let h=s.getAttribute("data-proportional-padding-left");h!==null&&!isNaN(+h)&&(s.style.paddingLeft=String(+h*i[0])+"px");let I=s.getAttribute("data-proportional-padding-right");I!==null&&!isNaN(+I)&&(s.style.paddingRight=String(+I*i[0])+"px")}}return o.length>0}function ym(n,e){try{n.removeChild(e)}catch(t){m.warn("HTD: Can't remove text track: not in the element.")}}function TI(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 Zi=class{constructor(e,t){m.debug("HTD: Creating HTMLTextDisplayer"),this._buffered=new On,this._videoElement=e,this._textTrackElement=t,this._sizeUpdateCanceller=new U,this._subtitlesIntervalCanceller=new U,this._buffer=new Xi,this._currentCues=[],this._isAutoRefreshing=!1}pushTextData(e){var b,h;m.debug("HTD: Appending new html text tracks");let{timestampOffset:t,appendWindow:r,chunk:i}=e;if(i===null)return xe(this._buffered);let{start:o,end:a,data:s,type:d,language:u}=i,c=(b=r[0])!=null?b:0,l=(h=r[1])!=null?h:1/0,f=Au(d,s,t,u);if(c!==0&&l!==1/0){let I=0;for(;I<f.length&&f[I].end<=c;)I++;for(f.splice(0,I),I=0;I<f.length&&f[I].start<c;)f[I].start=c,I++;for(I=f.length-1;I>=0&&f[I].start>=l;)I--;for(f.splice(I,f.length),I=f.length-1;I>=0&&f[I].end>l;)f[I].end=l,I--}let p;if(o!==void 0)p=Math.max(c,o);else{if(f.length<=0)return m.warn("HTD: Current text tracks have no cues nor start time. Aborting"),xe(this._buffered);m.warn("HTD: No start time given. Guessing from cues."),p=f[0].start}let g;if(a!==void 0)g=Math.min(l,a);else{if(f.length<=0)return m.warn("HTD: Current text tracks have no cues nor end time. Aborting"),xe(this._buffered);m.warn("HTD: No end time given. Guessing from cues."),g=f[f.length-1].end}return g<=p?(m.warn("HTD: Invalid text track appended: ","the start time is inferior or equal to the end time."),xe(this._buffered)):(this._buffer.insert(f,p,g),this._buffered.insert(p,g),!this._isAutoRefreshing&&!this._buffer.isEmpty()&&this.autoRefreshSubtitles(this._subtitlesIntervalCanceller.signal),xe(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 U),xe(this._buffered)}getBufferedRanges(){return xe(this._buffered)}reset(){m.debug("HTD: Resetting HTMLTextDisplayer"),this.stop(),this._subtitlesIntervalCanceller=new U}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)ym(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)ym(this._textTrackElement,i.element);this._currentCues=[];for(let i of e){let o=TI(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 U,this._sizeUpdateCanceller.linkToSignal(this._subtitlesIntervalCanceller.signal);let{TEXT_TRACK_SIZE_CHECKS_INTERVAL:i}=L.getCurrent();Mu(this._textTrackElement,i,this._sizeUpdateCanceller.signal).onUpdate(({height:a,width:s})=>{for(let d of r){let{resolution:u,element:c}=d;wu(a,s,u,c)}},{clearSignal:this._sizeUpdateCanceller.signal,emitCurrentValue:!0})}}autoRefreshSubtitles(e){if(this._isAutoRefreshing||e.isCancelled())return;let t=null,{MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:r}=L.getCurrent(),i=()=>{this._isAutoRefreshing=!1,t!==null&&(t.cancel(),t=null)},o=()=>{i(),this._isAutoRefreshing=!0,t=new U,t.linkToSignal(e);let a=setInterval(()=>this.refreshSubtitles(),r);t.signal.register(()=>{clearInterval(a)}),this.refreshSubtitles()};Uc(this._videoElement,()=>{i(),this._disableCurrentCues()},e),Bc(this._videoElement,o,e),Fc(this._videoElement,o,e),o()}refreshSubtitles(){let{MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:e}=L.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)}};y.CURRENT_ENV===y.DEV&&(_I=function(e){function t(r){}});var _I;var an=Zi;var EI=/&#([0-9]+);/g,vI=/<br>/gi,RI=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,kI=/\s*<p (?:class=([^>]+))?>(.*)/i,PI=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i;function CI(n){let e=/\.(\S+)\s*{([^}]*)}/gi,t={},r=e.exec(n);for(;r!==null;){let i=r[1],o=AI(r[2],"lang");!_(i)&&!_(o)&&(t[o]=i),r=e.exec(n)}return t}function MI(n){let t=/p\s*{([^}]*)}/gi.exec(n);return t===null?"":t[1]}function AI(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(EI,(e,t)=>String.fromCharCode(Number(t)))}function wI(n,e,t){let r=/<sync[ >]/gi,i=/<sync[ >]|<\/body>/gi,o=[],a=RI.exec(n),s=Array.isArray(a)?a[1]:"",d,u;i.exec(n);let c=CI(s),l=MI(s),f;if(w(t)&&(f=c[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 g=n.slice(d.index,u.index),b=PI.exec(g);if(!Array.isArray(b))throw new Error("parse error (sync time attribute)");let h=+b[1];if(isNaN(h))throw new Error("parse error (sync time attribute NaN)");p(g.split(`
6
- `),h/1e3)}return o;function p(g,b){let h=g.length;for(;--h>=0;){let I=kI.exec(g[h]);if(!Array.isArray(I))continue;let[,T,R]=I;if(f===T)if(R==="&nbsp;")o[o.length-1].end=b;else{let E=document.createElement("DIV");E.className="rxp-texttrack-region";let v=document.createElement("DIV");v.className="rxp-texttrack-div",v.style.position="absolute",v.style.bottom="0",v.style.width="100%",v.style.color="#fff",v.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(l)&&(k.style.cssText=l);let x=R.split(vI);for(let P=0;P<x.length;P++){P!==0&&k.appendChild(document.createElement("BR"));let M=document.createElement("SPAN");M.className="rxp-texttrack-span",M.textContent=xI(x[P]),k.appendChild(M)}v.appendChild(k),E.appendChild(v),o.push({element:E,start:b+e,end:-1})}}}}var Im=wI;function Ou(n){n.htmlTextTracksParsers.sami=Im,n.htmlTextDisplayer=an}function Du(n,e){let t=e+1;for(;w(n[t]);)t++;return t}function Ji(n){let e=[];for(let t=0;t<n.length;t++)if(w(n[t])){let r=Du(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 va(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 eo(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=va(t),a=va(r);return o===void 0||a===void 0?null:{start:o+e,end:a+e,payload:i}}function Lu(n,e){let t=n.split(/\r\n|\n|\r/),r=Ji(t),i=[];for(let o of r){let a=eo(o,e);if(a!==null){let s=OI(a);s!==null&&i.push(s)}}return i}function OI(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=DI(r[o]);i.appendChild(a)}return{start:e,end:t,element:i}}function DI(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 c=document.createTextNode(d[u]);o.appendChild(c)}}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(LI(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 LI(n){return n.nodeName==="FONT"&&"color"in n}function Nu(n){n.htmlTextTracksParsers.srt=Lu,n.htmlTextDisplayer=an}var NI=/(\d+) (\d+)/;function Uu(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 b=NI.exec(a);if(b===null||b.length<3)m.warn("TTML Parser: Invalid cellResolution");else{let h=parseInt(b[1],10),I=parseInt(b[2],10);isNaN(h)||isNaN(I)?m.warn("TTML Parser: Invalid cellResolution"):s={columns:h,rows:I}}}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 c=Number(r);(isNaN(c)||c<=0)&&(c=void 0);let l=d,f=u!=null?u:1,p=o!=null?o:"default",g=c!=null?c:d*u;if(i!==null){let b=/^(\d+) (\d+)$/g.exec(i);if(b!==null){let h=Number(b[1]),I=Number(b[2]),T=h/I;l=d*T}}return{cellResolution:s,tickRate:g,frameRate:l,subFrameRate:f,spaceStyle:p}}function Dn(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 c=s;for(let l=0;l<=c.attributes.length-1;l++){let f=c.attributes[l],p=f.name;if(p==="style")d=f.value;else if(p==="region")u=f.value;else{let g=p.substring(4);if(X(o,g)&&(i[g]=f.value,o.splice(l,1),o.length===0))return i}}}if(w(d)){let c=Q(t,l=>l.id===d);if(c!==void 0)for(let l=0;l<=o.length-1;l++){let f=o[l];if(!w(i[f])&&w(c.style[f])){if(i[f]=c.style[f],o.splice(l,1),o.length===0)return i;l--}}}if(w(u)){let c=Q(r,l=>l.id===u);if(c!==void 0)for(let l=0;l<=o.length-1;l++){let f=o[l];if(!w(i[f])&&w(c.style[f])){if(i[f]=c.style[f],o.splice(l,1),o.length===0)return i;l--}}}}}return i}function Bu(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(Xe(i.name,"tts")){let o=i.name.substring(4);t[o]=i.value}}return t}function Fu(n){let e=[];function t(r,i){e.push(i);for(let o of r.extendsStyles){let a=pe(n,s=>s.id===o);if(a<0)m.warn("TTML Parser: unknown style inheritance: "+o);else{let s=n[a];X(e,a)?m.warn("TTML Parser: infinite style inheritance loop avoided"):t(s,a),r.style=Y({},s.style,r.style)}}r.extendsStyles.length=0}for(let r=0;r<n.length;r++)t(n[r],r),e.length=0}function bm(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 Ra(n){let e=bm(n,"div");if(e.length===0){let t=bm(n,"tt:div");t.length>0&&(e=t)}return e}function Sm(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 Tm(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 _m(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 Em(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 ka(n){return n.nodeName==="br"||n.nodeName==="tt:br"}function Pa(n){return n.nodeName==="span"||n.nodeName==="tt:span"}var vm=["align","backgroundColor","color","direction","display","displayAlign","extent","fontFamily","fontSize","fontStyle","fontWeight","lineHeight","opacity","origin","overflow","padding","textAlign","textDecoration","textOutline","unicodeBidi","visibility","wrapOption","writingMode"];function to(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=Sm(o),s=Tm(o),d=_m(o),u=Em(o),c=Uu(o),l=[];for(let h=0;h<=s.length-1;h++){let I=s[h];if(I instanceof Element){let T=I.getAttribute("xml:id");if(T!==null){let R=I.getAttribute("style"),E=R===null?[]:R.split(" ");l.push({id:T,style:Bu(I),extendsStyles:E})}}}Fu(l);let f=[];for(let h=0;h<=d.length-1;h++){let I=d[h];if(I instanceof Element){let T=I.getAttribute("xml:id");if(T!==null){let R=Bu(I),E=I.getAttribute("style");if(w(E)){let v=Q(l,k=>k.id===E);v!==void 0&&(R=Y({},v.style,R))}f.push({id:T,style:R,extendsStyles:[]})}}}let p=Dn(vm,a!==null?[a]:[],l,f),b=(a!==null?a.getAttribute("xml:space"):void 0)==="default"||c.spaceStyle==="default";for(let h=0;h<u.length;h++){let I=u[h];if(I instanceof Element){let T=Ra(I),R=Y({},p,Dn(vm,[I,...T],l,f)),E=I.getAttribute("xml:space"),v=w(E)?E==="default":b,k={paragraph:I,timeOffset:e,idStyles:l,regionStyles:f,body:a,paragraphStyle:R,ttParams:c,shouldTrimWhiteSpace:v};k!==null&&t.push(k)}}}return t}function Rm(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 km(n){n.extent="70% 20%",n.fontSize="1c",n.origin="15% 80%",n.displayAlign="before",n.textAlign="center"}var Ku=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Vu=/^(?:(\d{2,}):)?(\d{2}):(\d{2})$/,zu=/^(?:(\d{2,}):)?(\d{2}):(\d{2}\.\d{2,})$/,Hu=/^(\d*\.?\d*)f$/,Wu=/^(\d*\.?\d*)t$/,qu=/^(?:(\d*\.?\d*)h)?(?:(\d*\.?\d*)m)?(?:(\d*\.?\d*)s)?(?:(\d*\.?\d*)ms)?$/,Gu=/^(\d{1,2}|100)% (\d{1,2}|100)%$/,Ge=/^((?:\+|-)?\d*(?:\.\d+)?)(px|em|c|%|rh|rw)$/,Pm=/^#([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])$/,Mm=/^rgb\( *(\d+) *, *(\d+) *, *(\d+) *\)/,Am=/^rgba\( *(\d+) *, *(\d+) *, *(\d+) *, *(\d+) *\)/;function UI(n,e){if(Ku.test(n))return KI(e,n);if(Vu.test(n))return ju(Vu,n);if(zu.test(n))return ju(zu,n);if(Hu.test(n))return BI(e,n);if(Wu.test(n))return FI(e,n);if(qu.test(n))return ju(qu,n)}function BI(n,e){let t=Hu.exec(e);return Number(t[1])/n.frameRate}function FI(n,e){let t=Wu.exec(e);return Number(t[1])/n.tickRate}function KI(n,e){let t=Ku.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 ju(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 Ca=UI;function no(n,e){let t=n.getAttribute("begin"),r=n.getAttribute("dur"),i=n.getAttribute("end"),o=w(t)?Ca(t,e):null,a=w(r)?Ca(r,e):null,s=w(i)?Ca(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 Yu;function Me(n,e){Yu===void 0&&(Yu=n.classList!==void 0&&typeof n.classList.add=="function"),Yu?n.classList.add(e):(" "+n.className+" ").indexOf(" "+e+" ")<0&&(n.className+=" "+e)}function $u(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"?(Me(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"?(Me(n,"proportional-style"),n.setAttribute("data-proportional-height",o[1])):m.warn("TTML Parser: unhandled extent unit:",o[2]))}function Qu(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",Me(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",Me(n,"proportional-style"),n.setAttribute("data-proportional-font-size",String(o/100)))}else m.warn("TTML Parser: unhandled fontSize unit:",i[2])}function Xu(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"?(Me(n,"proportional-style"),n.setAttribute("data-proportional-line-height",i[1])):m.warn("TTML Parser: unhandled lineHeight unit:",i[2]))}function Zu(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"?(Me(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"?(Me(n,"proportional-style"),n.setAttribute("data-proportional-top",o[1])):m.warn("TTML Parser: unhandled origin unit:",o[2]))}function Ju(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"?(Me(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"?(Me(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"?(Me(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"?(Me(n,"proportional-style"),n.setAttribute("data-proportional-padding-left",s[1])):m.warn("TTML Parser: unhandled padding unit:",s[2])}function dr(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 sn(n){let e;return e=Pm.exec(n),_(e)?(e=Cm.exec(n),_(e)?(e=Mm.exec(n),_(e)?(e=Am.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 VI=["color","direction","display","fontFamily","fontSize","fontStyle","fontWeight","textDecoration","textOutline","unicodeBidi","visibility","wrapOption"];function zI(n,e,t){let r=e.color;w(r)&&(n.style.color=sn(r));let i=e.backgroundColor;w(i)&&(n.style.backgroundColor=sn(i));let o=e.textOutline;if(w(o)){let h=o.trim().replace(/\s+/g," ").split(" "),I=h.length;if(I===3){let T=sn(h[0]),R=h[1];n.style.textShadow=dr(T,R)}else if(w(r)&&I===1){let T=h[0];n.style.textShadow=dr(r,T)}else if(I===2){let T=/^[#A-Z]/i.test(h[0]),R=/^[0-9]/.test(h[0]);if(T!==R){if(T){let E=sn(h[0]),v=h[1];n.style.textShadow=dr(E,v)}else if(w(r)){let E=h[0];n.style.textShadow=dr(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 c=e.fontSize;w(c)?Qu(n,c):(Me(n,"proportional-style"),n.setAttribute("data-proportional-font-size","1"));let l=e.direction;w(l)&&(n.style.direction=l);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 p=e.visibility;w(p)&&(n.style.visibility=p),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 HI(n,e){n.style.color="white",n.style.position="absolute";let t=e.extent;w(t)&&$u(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)&&Ju(n,o);let a=e.origin;w(a)&&Zu(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 WI(n,e){n.style.margin="0px",Me(n,"proportional-style"),n.setAttribute("data-proportional-font-size","1");let t=e.backgroundColor;w(t)&&(n.style.backgroundColor=sn(t));let r=e.lineHeight;w(r)&&Xu(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 qI(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",zI(r,e,t),r}function GI(n,e,t,r,i){function o(a,s,d,u){let c=a.childNodes,l=[];for(let f=0;f<c.length;f++){let p=c[f];if(p.nodeName==="#text"){let{backgroundColor:g}=Dn(["backgroundColor"],d,t,e);w(g)?s.backgroundColor=g:s.backgroundColor="";let b=qI(p,s,u);l.push(b)}else if(ka(p)){let g=document.createElement("BR");l.push(g)}else if(Pa(p)&&p.nodeType===Node.ELEMENT_NODE&&p.childNodes.length>0){let g=p.getAttribute("xml:space"),b=w(g)?g==="default":u,h=Y({},s,Dn(VI,[p],t,e));l.push(...o(p,h,[p,...d],b))}}return l}return o(n,Y({},r),[],i)}function el(n,e,t,r,i,{cellResolution:o,shouldTrimWhiteSpace:a}){let s=Ra(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)),HI(d,i),e!==null){let{bodyBackgroundColor:l}=Dn(["backgroundColor"],[...s,e],r,t);w(l)&&(d.style.backgroundColor=sn(l))}let u=document.createElement("p");u.className="rxp-texttrack-p",WI(u,i);let c=GI(n,t,r,i,a);for(let l=0;l<c.length;l++)u.appendChild(c[l]);return d.appendChild(u),d}function tl(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:c,end:l}=no(e,t),f=el(e,r,i,o,a,{cellResolution:u,shouldTrimWhiteSpace:d});return{start:c+s,end:l+s,element:f}}function nl(n,e){let t=to(n,e),r=[];for(let i of t){let{paragraphStyle:o}=i;Rm(o)&&km(o);let a=tl(i);a!==null&&r.push(a)}return r}var xm=nl;function rl(n){n.htmlTextTracksParsers.ttml=xm,n.htmlTextDisplayer=an}function Ma(n){let e=0;for(;e<n.length;){if(n[e]==="")return e+1;e++}return e}function il(n,e){return typeof n[e]=="string"&&/^STYLE( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function jI(n,e){return typeof n[e]=="string"&&/^NOTE( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function YI(n,e){return typeof n[e]=="string"&&/^REGION( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function wm(n,e){let t=n[e];if(t===void 0||t===""||il(n,e)||YI(n,e)||jI(n,e))return!1;if(t.indexOf("-->")>=0)return!0;let r=n[e+1];return r!==void 0&&r.indexOf("-->")>=0}function Om(n,e){let t=e+1;for(;w(n[t]);)t++;return t}function ro(n,e){let t=[];for(let r=e;r<n.length;r++)if(wm(n,r)){let i=Om(n,r);t.push(n.slice(r,i)),r=i}else if(w(n[r]))for(;w(n[r]);)r++;return t}function ol(n,e){let t=[];for(let r=e;r<n.length;r++)if(il(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 Aa(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 $I(n){return n.split(/ |\t/).reduce((t,r)=>{let i=r.split(":");return i.length===2&&(t[i[0]]=i[1]),t},{})}function QI(n){let t=/^([\d:.]+)[ |\t]+-->[ |\t]+([\d:.]+)[ |\t]*(.*)$/.exec(n);if(t===null)return null;let r=Aa(t[1]),i=Aa(t[2]);if(r===void 0||i===void 0)return null;let o=$I(t[3]);return{start:r,end:i,settings:o}}function io(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=QI(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 al={white:"#ffffff",lime:"#00ff00",cyan:"#00ffff",red:"#ff0000",yellow:"#ffff00",magenta:"#ff00ff",blue:"#0000ff",black:"#000000"};function sl(){return Object.keys(al).reduce((n,e)=>(n[e]=`color: ${al[e]};`,n[`bg_${e}`]=`background-color: ${al[e]};`,n),{})}function dl(n){let e=sl(),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 oo(n,e){let t=["u","i","b"],r=["u","i","b","c","#text"],i=n.nodeName.toLowerCase().split(".")[0],o;if(X(r,i))if(i==="#text"){let a=n.wholeText.split(`
1
+ "use strict";(()=>{var kp=Object.defineProperty,Pp=Object.defineProperties;var Cp=Object.getOwnPropertyDescriptors;var Wl=Object.getOwnPropertySymbols;var Mp=Object.prototype.hasOwnProperty,Ap=Object.prototype.propertyIsEnumerable;var ql=(n,e,t)=>e in n?kp(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)&&ql(n,t,e[t]);if(Wl)for(var t of Wl(e))Ap.call(e,t)&&ql(n,t,e[t]);return n},de=(n,e)=>Pp(n,Cp(e));var y={PRODUCTION:0,DEV:1,CURRENT_ENV:0};var S={CURRENT_LEVEL:"NONE"};function Un(){return typeof __RX_PLAYER_DEBUG_MODE__=="boolean"&&__RX_PLAYER_DEBUG_MODE__}function _(n){return n==null}var ae=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(y.CURRENT_ENV===y.DEV)throw o instanceof Error?o:new Error("EventEmitter: listener error");console.error("RxPlayer: EventEmitter error",o instanceof Error?o:null)}})}};var Wt=typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope;var Op=typeof window=="undefined"&&!Wt,qt=Op;var yo;Wt?yo=self:qt?yo=global:yo=window;var J=yo;var Rt=typeof queueMicrotask=="function"?queueMicrotask:function(e){Promise.resolve().then(e,()=>e())};function Wa(){if(!qt&&!_(J.WebKitSourceBuffer)&&J.WebKitSourceBuffer.prototype.addEventListener===void 0){let e=J.WebKitSourceBuffer.prototype;for(let t in ae.prototype)Object.prototype.hasOwnProperty.call(ae.prototype,t)&&(e[t]=ae.prototype[t]);e._listeners=[],e._emitUpdate=function(t,r){Rt(()=>{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 pe(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 Z(){}var Io=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){y.CURRENT_ENV===y.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 Z;let r=()=>{let a=pe(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 cn(n,e,t){let r=new Io(e(n.getValue()),t);return n.onUpdate(function(o){r.setValue(e(o))},{clearSignal:t}),n._onFinished(()=>{r.finish()},t),r}var G=Io;var Gl=new G(0);var Dp=typeof performance!="undefined"?()=>performance.now()+Gl.getValue():()=>Date.now()+Gl.getValue(),V=Dp;var Lp="NONE",mr=class extends ae{constructor(){super(),this.error=Z,this.warn=Z,this.info=Z,this.debug=Z,this._levels={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4},this._currentFormat="standard",this._currentLevel=Lp}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=V();console.log(String(d.toFixed(2)),"[Init]",`Local-Date: ${Date.now()}`)}this._currentFormat=a;let s=this._currentFormat==="full"?(d,u)=>(...c)=>{let l=V();return u(String(l.toFixed(2)),`[${d}]`,...c)}:(d,u)=>u;if(r===void 0)this.error=i>=this._levels.ERROR?s("error",console.error.bind(console)):Z,this.warn=i>=this._levels.WARNING?s("warn",console.warn.bind(console)):Z,this.info=i>=this._levels.INFO?s("info",console.info.bind(console)):Z,this.debug=i>=this._levels.DEBUG?s("log",console.log.bind(console)):Z;else{let d=u=>i>=this._levels[u]?(...c)=>r(u,c):Z;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 Np=new mr,m=Np;var De=J,jl,Yl,$l,Ql,Xl,kt=(Xl=(Ql=($l=(Yl=(jl=De==null?void 0:De.MediaSource)!=null?jl:De==null?void 0:De.MozMediaSource)!=null?Yl:De==null?void 0:De.WebKitMediaSource)!=null?$l:De==null?void 0:De.MSMediaSource)!=null?Ql:De==null?void 0:De.ManagedMediaSource)!=null?Xl:void 0,Zl=kt!==void 0&&kt===(De==null?void 0:De.ManagedMediaSource);var Up=200,bo=new Map;function qa(n){if(_(kt))return Wt&&m.error("Compat: Cannot request codec support in a worker without MSE."),!1;if(typeof kt.isTypeSupported=="function"){let e=bo.get(n);if(e!==void 0)return e;{let t=kt.isTypeSupported(n);return bo.size>=Up&&bo.clear(),bo.set(n,t),t}}return!0}var pr=!1,fn=!1,Gt=!1,Pt=!1,Ga=!1,mn=!1,ja=!1,gr=!1,hr=!1,Bp=!1,Fp=!1,Ya=!1,$a=!1,Qa=!1,pn=!1,Kp=!1,Xa=!1;(function(){var e,t,r;qt||(typeof J.MSInputMethodContext!="undefined"&&typeof document.documentMode!="undefined"?(fn=!0,Gt=!0):navigator.appName==="Microsoft Internet Explorer"||navigator.appName==="Netscape"&&/(Trident|Edge)\//.test(navigator.userAgent)?Gt=!0:navigator.userAgent.toLowerCase().indexOf("edg/")!==-1?pr=!0:navigator.userAgent.toLowerCase().indexOf("firefox")!==-1?Pt=!0:typeof navigator.platform=="string"&&/iPad|iPhone|iPod/.test(navigator.platform)?mn=!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))&&(Ga=!0),/SamsungBrowser/.test(navigator.userAgent)&&(ja=!0),navigator.userAgent.indexOf("PlayStation 4")!==-1?Qa=!0:navigator.userAgent.indexOf("PlayStation 5")!==-1?pn=!0:/Tizen/.test(navigator.userAgent)?gr=!0:/[Ww]eb[O0]S/.test(navigator.userAgent)?(hr=!0,/[Ww]eb[O0]S.TV-2022/.test(navigator.userAgent)||/[Cc]hr[o0]me\/87/.test(navigator.userAgent)?Fp=!0:(/[Ww]eb[O0]S.TV-2021/.test(navigator.userAgent)||/[Cc]hr[o0]me\/79/.test(navigator.userAgent))&&(Bp=!0)):navigator.userAgent.indexOf("NETTV")!==-1&&navigator.userAgent.indexOf("Philips")!==-1?$a=!0:/[Pp]anasonic/.test(navigator.userAgent)?Ya=!0:navigator.userAgent.indexOf("Xbox")!==-1?Kp=!0:navigator.userAgent.indexOf("Model/a1-kstb40xx")!==-1&&(Xa=!0))})();var Vp=pn,Jl=Vp;function Za(n){return n===void 0||n.indexOf("widevine")<0}var ec={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,FREEZING_FLUSH_FAILURE_DELAY:{MAXIMUM:2e4,MINIMUM:4e3,POSITION_DELTA:1},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"','audio/mp4;codecs="ec-3"'],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",DEFAULT_MAX_THUMBNAIL_REQUESTS_RETRY_ON_ERROR:1,DEFAULT_THUMBNAIL_REQUEST_TIMEOUT:1e4,DEFAULT_THUMBNAIL_CONNECTION_TIMEOUT:7e3},tc=ec;function zp(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 Y=typeof Object.assign=="function"?Object.assign:zp;function Ja(n){return n!=null&&!Array.isArray(n)&&typeof n=="object"}function yr(n,...e){if(e.length===0)return n;let t=e.shift();if(Ja(n)&&Ja(t))for(let r in t)if(Ja(t[r])){let i=n[r];i===void 0&&(i={},n[r]=i),yr(i,t[r])}else Y(n,{[r]:t[r]});return yr(n,...e)}var es=class extends ae{constructor(){super(...arguments);this.updated=!1;this._config=tc}update(t){let r=yr(this._config,t);this._config=r,this.updated=!0,this.trigger("update",t)}getCurrent(){return this._config}},Hp=new es,L=Hp;var Wp=.016666666666666666;function nc(n,e){return Math.abs(n-e)<Wp}function ic(n,e){let t=Math.min(n.start,e.start),r=Math.max(n.end,e.end);return{start:t,end:r}}function qp(n){for(let e=0;e<n.length;e++){let t=n[e];t.start===t.end&&n.splice(e--,1)}return n}function Gp(n){for(let e=1;e<n.length;e++){let t=n[e-1],r=n[e];if(ac(t,r)){let i=ic(t,r);n.splice(--e,2,i)}}return n}function ts(n,e){return n.end<=e.start}function rc({start:n,end:e},t){return n<=t&&t<e}function oc(n,e){return rc(n,e.start)||n.start<e.end&&e.end<n.end||rc(e,n.start)}function ac(n,e){return nc(e.start,n.end)||nc(e.end,n.start)}function xe(n){let e=[];for(let t=0;t<n.length;t++)e.push({start:n.start(t),end:n.end(t)});return e}function ns(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 jp(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 sc(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 dc(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 uc(n,e){let t=ns(n,e);return t!==null?t.end-e:1/0}function So(n,e){let t=jp(n,e);return t!==null?t.end-e:1/0}function jt(n,e){if(e.start===e.end)return n;let t=e,r=0;for(;r<n.length;r++){let i=n[r],o=oc(t,i),a=ac(t,i);if(o||a)t=ic(t,i),n.splice(r--,1);else if(r===0){if(ts(t,n[0]))break}else if(ts(n[r-1],t)&&ts(t,i))break}return n.splice(r,0,t),Gp(qp(n))}function lc(n,e){let t=[];for(let r=0;r<e.length;r++)oc(n,e[r])&&t.push(e[r]);return t}function cc(n,e){let t=[];for(let r=0;r<n.length;r++){let i=n[r],o=lc(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 To(n,e){let t=[];for(let r=0;r<n.length;r++){let i=n[r],o=[],a=lc(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 _o=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype),this.name="AssertionError"}};function ee(n,e){if(y.DEV===y.CURRENT_ENV&&!n)throw new _o(e===void 0?"invalid assertion":e)}function fc(n,e,t="object"){ee(!_(n),`${t} should be an object`);for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&ee(typeof n[r]===e[r],`${t} should have property ${r} as a ${e[r]}`)}function He(n){throw new _o("Unreachable path taken")}var U=class{constructor(){let[e,t]=Yp();this._isUsed=!1,this._trigger=e,this.signal=new Ir(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 Pe;this._trigger(t)}static isCancellationError(e){return e instanceof Pe}},Ir=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),Z):(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)}},Pe=class n extends Error{constructor(){super("This task was cancelled."),Object.setPrototypeOf(this,n.prototype),this.name="CancellationError"}};function Yp(){let n=Z;return[function(t){n(t)},function(t){n=t}]}function rs(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 rt=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 br=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 rt(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 mc=6e3,$p=15e3,Qp=3e3,Xp=1e3,Zp=9e3,Sr=class{constructor(e){this._levelsMap=rs(e).map(t=>t+4),this._bitrates=e,this._lastUnsuitableQualityTimestamp=void 0,this._blockRaiseDelay=mc,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 g=0;g<r.length;g++){let b=r[g];if(b===o)d=g;else if(b>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 c=isFinite(i)?i:0,l=V();if(c<t[d]||u!==void 0&&u<1&&(a==null?void 0:a.confidenceLevel)===1){if((this._lastUnsuitableQualityTimestamp===void 0?-1:l-this._lastUnsuitableQualityTimestamp)<this._blockRaiseDelay+Zp){let h=this._blockRaiseDelay+Qp;this._blockRaiseDelay=Math.min(h,$p),m.debug("ABR: Incrementing blocking raise in BufferBasedChooser due to unstable quality",this._blockRaiseDelay)}else{let h=this._blockRaiseDelay-Xp;this._blockRaiseDelay=Math.max(mc,h),m.debug("ABR: Lowering quality in BufferBasedChooser",this._blockRaiseDelay)}this._lastUnsuitableQualityTimestamp=l;let b=pe(r,h=>h===o);for(let h=b-1;h>=0;h--)if(c>=t[h]){this._currentEstimate=r[h];return}this._currentEstimate=r[0];return}if(this._lastUnsuitableQualityTimestamp!==void 0&&l-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],p=(()=>{for(let g=d+1;g<t.length;g++)if(t[g]>f)return g})();if(p!==void 0){let g=t[p];if(i>=g){m.debug("ABR: Raising quality in BufferBasedChooser",r[p]),this._currentEstimate=r[p];return}}this._currentEstimate=o}getLastEstimate(){return this._currentEstimate}};function Q(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 Jp(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 Eo(n){if(n.progress.length<5)return;let e=new rt(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 pc(n,e){let t=(n.totalSize-n.size)*8;return Math.max(t/e,0)}function eg(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,c=Jp(n,u);if(c.length!==1)return;let l=c[0],f=V(),p=l.content.segment.duration*1.5;if(p=Math.min(p,3e3),p=Math.max(p,12e3),f-l.requestTimestamp<p)return;let g=l.progress.length>0?l.progress[l.progress.length-1]:void 0,b=Eo(l);if(g!==void 0&&b!==void 0){let v=pc(g,b);if((f-g.timestamp)/1e3<=v&&v-d/a>2500)return b}if(!l.content.segment.complete)return;let h=l.content.segment.duration,I=(f-l.requestTimestamp)/1e3,T=I<=(h*1.5+2)/a;if(_(t)||T)return;let R=h/I,E=t.bitrate*Math.min(.7,R);if(i===void 0||E<i)return E}function tg(n,e,t){if(t)return!0;let r=isFinite(n.bufferGap)?n.bufferGap:0,i=n.position.getWanted()+r,o=Q(e,({content:l})=>l.segment.duration>0&&l.segment.time+l.segment.duration>i);if(o===void 0)return!0;let a=V(),s=o.progress.length>0?o.progress[o.progress.length-1]:void 0,d=Eo(o);if(s===void 0||d===void 0)return!0;let u=pc(s,d);return(a-s.timestamp)/1e3>u*1.2?!0:u-r/n.speed>-1.5}var Tr=class{constructor(e,t){let{ABR_STARVATION_GAP:r,OUT_OF_STARVATION_GAP:i,ABR_STARVATION_FACTOR:o,ABR_REGULAR_FACTOR:a}=L.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:c,duration:l}=e,f=isFinite(u)?u:0,{ABR_STARVATION_DURATION_DELTA:p}=L.getCurrent();return isNaN(l)||f+c.getWanted()<l-p?!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=eg(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:tg(i,r,this._lowLatencyMode)}};var _r=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 Er=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 l=gc(e,r);if(l!==null)return l}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=V()+Math.min(this._consecutiveWrongGuesses*15e3,12e4),ng(e,r);if(u===void 0)return r;if(this._canGuessHigher(a,s,u)){let l=gc(e,r);if(l!==null)return l}return r}_canGuessHigher(e,t,{score:r,confidenceLevel:i}){return isFinite(e)&&e>=2.5&&V()>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=V();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=Eo(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 gc(n,e){let t=n.length,r=pe(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 ng(n,e){let t=pe(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 vr=class{constructor(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=L.getCurrent();this._fastEWMA=new rt(e),this._slowEWMA=new rt(t),this._bytesSampled=0}addSample(e,t){let{ABR_MINIMUM_CHUNK_SIZE:r}=L.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}=L.getCurrent();if(!(this._bytesSampled<e))return Math.min(this._fastEWMA.getEstimate(),this._slowEWMA.getEstimate())}reset(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=L.getCurrent();this._fastEWMA=new rt(e),this._slowEWMA=new rt(t),this._bytesSampled=0}};function is(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=pe(n,o=>o.bitrate>r);return i===-1?n:n.slice(0,i)}function os(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,c;return((u=s.width)!=null?u:0)-((c=d.width)!=null?c:0)}),o=Q(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 Rr(n){return Object.keys(n).map(e=>n[e])}var Bn=typeof Object.values=="function"?Object.values:Rr;var kr=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(y.CURRENT_ENV===y.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(y.CURRENT_ENV===y.DEV)throw new Error("ABR: can't remove unknown request");m.warn("ABR: can't remove unknown request")}delete this._currentRequests[e]}getRequests(){return Bn(this._currentRequests).filter(e=>!_(e)).sort((e,t)=>e.content.segment.time-t.content.segment.time)}};function vo(n,e){let t=pe(n,r=>r.bitrate>e);return t===-1?n[n.length-1]:t===0?n[0]:n[t-1]}var hc=new G(void 0);hc.finish();var yc=new G(1/0);yc.finish();function as(n){let e={},{initialBitrates:t,throttlers:r,lowLatencyMode:i}=n;return function(s,d,u,c,l){var h,I,T;let{type:f}=s.adaptation,p=o(f),g=(h=t[f])!=null?h:0,b={limitResolution:(I=r.limitResolution[f])!=null?I:hc,throttleBitrate:(T=r.throttleBitrate[f])!=null?T:yc};return rg({bandwidthEstimator:p,context:s,currentRepresentation:d,filters:b,initialBitrate:g,playbackObserver:c,representations:u,lowLatencyMode:i},l)};function o(a){let s=e[a];if(_(s)){m.debug("ABR: Creating new BandwidthEstimator for ",a);let d=new vr;return e[a]=d,d}return s}}function rg({bandwidthEstimator:n,context:e,currentRepresentation:t,filters:r,initialBitrate:i,lowLatencyMode:o,playbackObserver:a,representations:s},d){let u=new br,c=new Tr(i!=null?i:0,o),l=new kr,f=Z,p={metrics:T,requestBegin:R,requestProgress:E,requestEnd:v,addedSegment(k){f(k)}},g=new U;g.linkToSignal(d);let b=h(s.getValue(),g.signal);return s.onUpdate(I,{clearSignal:d}),{estimates:b,callbacks:p};function h(k,x){if(k.length<=1)return new G({bitrate:void 0,representation:k[0],urgent:!0,knownStableBitrate:void 0});let P=!1,M=k.sort((K,j)=>K.bitrate-j.bitrate),O=new Sr(M.map(K=>K.bitrate)),B=new _r,D=new Er(u,B),F=a.getReference().getValue(),A=new G(N());return a.listen(K=>{F=K,C()},{includeLastObservation:!1,clearSignal:x}),f=function(K){if(F===null)return;let{position:j,speed:$}=F,z=K.buffered,H=So(z,j.getWanted()),{representation:q}=K.content,ie=u.getEstimate(q),ne=q.bitrate,le={bufferGap:H,currentBitrate:ne,currentScore:ie,speed:$};O.onAddedSegment(le),C()},x.register(()=>{f=Z}),r.throttleBitrate.onUpdate(C,{clearSignal:x}),r.limitResolution.onUpdate(C,{clearSignal:x}),A;function C(){A.setValue(N())}function N(){let{bufferGap:K,position:j,maximumPosition:$}=F,z=r.limitResolution.getValue(),H=r.throttleBitrate.getValue(),q=t.getValue(),ie=ig(M,z,H),ne=l.getRequests(),{bandwidthEstimate:le,bitrateChosen:be}=c.getBandwidthEstimate(F,n,q,ne,B.bandwidth),me=u.getLastStableRepresentation(),W=me===null?void 0:me.bitrate/(F.speed>0?F.speed:1),{ABR_ENTER_BUFFER_BASED_ALGO:Ce,ABR_EXIT_BUFFER_BASED_ALGO:nt}=L.getCurrent();P&&K<=nt?P=!1:!P&&isFinite(K)&&K>=Ce&&(P=!0);let Ae=vo(ie,be),zt=O.getLastEstimate(),ln=Ae.bitrate,mt=null;P&&zt!==void 0&&zt>ln&&(mt=vo(ie,zt),ln=mt.bitrate);let bt=null;return o&&q!==null&&e.manifest.isDynamic&&$-j.getWanted()<40&&(bt=D.getGuess(M,F,q,ln,ne)),bt!==null&&bt.bitrate>ln?(m.debug("ABR: Choosing representation with guess-based estimation.",bt.bitrate,bt.id),B.update(bt,le,2),{bitrate:le,representation:bt,urgent:q===null||bt.bitrate<q.bitrate,knownStableBitrate:W}):mt!==null?(m.debug("ABR: Choosing representation with buffer-based estimation.",mt.bitrate,mt.id),B.update(mt,le,0),{bitrate:le,representation:mt,urgent:c.isUrgent(mt.bitrate,q,ne,F),knownStableBitrate:W}):(m.debug("ABR: Choosing representation with bandwidth estimation.",Ae.bitrate,Ae.id),B.update(Ae,le,1),{bitrate:le,representation:Ae,urgent:c.isUrgent(Ae.bitrate,q,ne,F),knownStableBitrate:W})}}function I(){let k=s.getValue();g.cancel(),g=new U,g.linkToSignal(d),h(k,g.signal).onUpdate(function(M){b.setValue(M)},{clearSignal:g.signal,emitCurrentValue:!0})}function T(k){let{requestDuration:x,segmentDuration:P,size:M,content:O}=k;if(n.addSample(x,M),!O.segment.isInit){let{segment:B,representation:D}=O;if(P===void 0&&!B.complete)return;let F=P!=null?P:B.duration;u.addSample(D,x/1e3,F)}}function R(k){l.add(k)}function E(k){l.addProgress(k)}function v(k){l.remove(k.id)}}function ig(n,e,t){let r=n;return t!==void 0&&t<1/0&&(r=is(r,t)),e!==void 0&&(r=os(r,e)),r}var Ic=as;function Ro(){var t;if(typeof((t=J.crypto)==null?void 0:t.randomUUID)=="function")return J.crypto.randomUUID();let n=new Date().getTime(),e=V();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 Xe(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 og=/^(?:[a-z]+:)?\/\//i,ag=/^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/;function Mr(n){let e=n.lastIndexOf("/");if(e<0)return n.length;if(og.test(n)){let r=n.indexOf("/");if(r>=0&&e===r+1)return n.length}let t=n.indexOf("?");return t>=0&&t<e?Mr(n.substring(0,t)):e+1}function bc(n,e){let t=ko(n),r=ko(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=Cr(t.path),o=Cr(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 c=u.join("/");(c.endsWith("../")||c.endsWith("./"))&&(c=c.slice(0,c.length-1)),a=c===""?".":c}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 sg(n,e){let t=ko(n),r=ko(e);if(w(r.scheme))return ss(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=Cr(r.path),ss(i)):(r.path===""?(i.path=t.path,w(r.query)||(i.query=t.query)):Xe(r.path,"/")?i.path=Cr(r.path):i.path=Cr(ug(t,r.path)),ss(i))}var Pr=new Map,dg=200;function ko(n){var r,i,o,a,s;if(Pr.has(n))return Pr.get(n);let e=n.match(ag),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:""},Pr.size>=dg&&Pr.clear(),Pr.set(n,t),t}function ss(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 Cr(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 ug(n,e){if(w(n.authority)&&n.path==="")return"/"+e;let t=n.path;return t.substring(0,t.lastIndexOf("/")+1)+e}function gn(...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=sg(a,s),u=e.slice(2);return gn(d,...u)}}var lg=4,Ar=class{constructor(e){var t,r;this._sessionId=(t=e.sessionId)!=null?t:Ro(),this._contentId=(r=e.contentId)!=null?r:Ro(),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 U,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 c=e.segment.url,l=e.nextSegment.url,f=bc(c,l);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 c=t.buffered[e.adaptation.type];if(!_(c)){let l=(u=(d=(s=this._playbackObserver)==null?void 0:s.getCurrentTime())!=null?d:t.position.getWanted())!=null?u:t.position.getPolled();for(let f of c)if(l>=f.start&&l<f.end){i=(f.end-l)*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 l=e.representation.bitrate*e.segment.duration/1e3/(o/1e3);r.rtp=Math.floor(Math.round(l*lg/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((c,l)=>l.isPlayable()!==!0?c:c===void 0?Math.round(l.bitrate/1e3):Math.max(c,Math.round(l.bitrate/1e3)),void 0),this._producePayload(r)}_producePayload(e){let t={object:"",request:"",session:"",status:""},r="",i=(u,c)=>{this._typePreference===0?t[c]+=u:r+=u},o=(u,c)=>{let l=e[u];if(l!==void 0){let f=`${u}=${String(l)},`;i(f,c)}},a=(u,c)=>{if(e[u]===!0){let l=`${u},`;i(l,c)}},s=(u,c)=>{let l=e[u];if(l!==void 0){let p=`prop=${`"${l.replace("\\","\\\\").replace('"','\\"')}"`},`;i(p,c)}},d=(u,c)=>{let l=e[u];if(l!==void 0){let f=`prop=${l},`;i(f,c)}};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 Sc=Ar;var Fn=class extends ae{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=Tc(this._downgradedCdnList.metadata,e);t>=0&&this._removeIndexFromDowngradeList(t);let{DEFAULT_CDN_DOWNGRADE_TIME:r}=L.getCurrent(),i=r;this._downgradedCdnList.metadata.push(e);let o=setTimeout(()=>{let a=Tc(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 Tc(n,e){return n.length===0?-1:e.id!==void 0?pe(n,t=>t.id===e.id):pe(n,t=>t.baseUrl===e.baseUrl)}var it=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 _e=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 ds=typeof Headers=="function"?Headers:null,us=typeof AbortController=="function"?AbortController:null;function Po(n){var f,p;let e;if(!_(n.headers))if(_(ds))e=n.headers;else{e=new ds;let g=Object.keys(n.headers);for(let b=0;b<g.length;b++){let h=g[b];e.append(h,n.headers[h])}}m.debug("Fetch: Called with URL",n.url);let t=null,r=!1,i=!1,o=V(),a=_(us)?null:new us;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 c=n.cancelSignal.register(function(b){t=b,s()}),l={method:"GET"};if(e!==void 0&&(l.headers=e),l.signal=_(a)?null:a.signal,m.hasLevel("DEBUG")){let g="FETCH: Sending GET "+n.url;n.timeout!==void 0&&(g+=" to="+String(n.timeout/1e3)),n.connectionTimeout!==void 0&&(g+=" cto="+String(n.connectionTimeout/1e3)),((f=n.headers)==null?void 0:f.Range)!==void 0&&(g+=" Range="+((p=n.headers)==null?void 0:p.Range)),m.debug(g)}return fetch(n.url,l).then(g=>{if(u!==void 0&&clearTimeout(u),g.status>=300)throw m.warn("Fetch: Request HTTP Error",g.status,g.url),new _e(g.url,g.status,Fe.ERROR_HTTP_CODE);if(_(g.body))throw new _e(g.url,g.status,Fe.PARSE_ERROR);let b=g.headers.get("Content-Length"),h=!_(b)&&!isNaN(+b)?+b:void 0,I=g.body.getReader(),T=0;return R();async function R(){let E=await I.read();if(!E.done&&!_(E.value)){T+=E.value.byteLength;let v=V(),k={url:g.url,currentTime:v,duration:v-o,sendingTime:o,chunkSize:E.value.byteLength,chunk:E.value.buffer,size:T,totalSize:h};return n.onData(k),R()}else if(E.done){d!==void 0&&clearTimeout(d),c();let v=V();return{requestDuration:v-o,receivedTime:v,sendingTime:o,size:T,status:g.status,url:g.url}}return R()}}).catch(g=>{throw t!==null?t:(c(),r?(m.warn("Fetch: Request timed out."),new _e(n.url,0,Fe.TIMEOUT)):i?(m.warn("Fetch: Request connection timed out."),new _e(n.url,0,Fe.TIMEOUT)):g instanceof _e?g:(m.warn("Fetch: Request Error",g instanceof Error?g.toString():""),new _e(n.url,0,Fe.ERROR_EVENT)))})}function xr(){return typeof J.fetch=="function"&&!_(us)&&!_(ds)}var cg="json";function wr(n){let e={url:n.url,headers:n.headers,responseType:_(n.responseType)?cg: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:c}=e,l=new XMLHttpRequest;l.open("GET",a,!0);let f;u!==void 0&&(l.timeout=u,f=setTimeout(()=>{h(),r(new _e(a,l.status,Fe.TIMEOUT))},u+3e3));let p;if(c!==void 0&&(p=setTimeout(()=>{h(),l.readyState!==XMLHttpRequest.DONE&&l.abort(),r(new _e(a,l.status,Fe.TIMEOUT))},c)),l.responseType=d,l.responseType==="document"&&l.overrideMimeType("text/xml"),!_(s)){let I=s;for(let T in I)Object.prototype.hasOwnProperty.call(I,T)&&l.setRequestHeader(T,I[T])}let g=V(),b=null;if(o!==void 0&&(b=o.register(function(T){h(),l.readyState!==XMLHttpRequest.DONE&&l.abort(),r(T)}),o.isCancelled()))return;if(l.onerror=function(){h(),r(new _e(a,l.status,Fe.ERROR_EVENT))},l.ontimeout=function(){h(),r(new _e(a,l.status,Fe.TIMEOUT))},c!==void 0&&(l.onreadystatechange=function(){l.readyState>=XMLHttpRequest.HEADERS_RECEIVED&&clearTimeout(p)}),i!==void 0&&(l.onprogress=function(T){let R=V();i({url:a,duration:R-g,sendingTime:g,currentTime:R,size:T.loaded,totalSize:T.total})}),l.onload=function(T){if(l.readyState===XMLHttpRequest.DONE)if(h(),l.status>=200&&l.status<300){let R=V(),E=l.response instanceof ArrayBuffer?l.response.byteLength:T.total,v=l.status,k=l.responseType,x=w(l.responseURL)?l.responseURL:a,P;if(k==="json"?P=typeof l.response=="object"?l.response:fg(l.responseText):P=l.response,_(P)){r(new _e(a,l.status,Fe.PARSE_ERROR));return}t({status:v,url:x,responseType:k,sendingTime:g,receivedTime:R,requestDuration:R-g,size:E,responseData:P})}else r(new _e(a,l.status,Fe.ERROR_HTTP_CODE))},m.hasLevel("DEBUG")){let I="XHR: Sending GET "+a;n.responseType!==void 0&&(I+=" type="+n.responseType),u!==void 0&&(I+=" to="+String(u/1e3)),c!==void 0&&(I+=" cto="+String(c/1e3)),(s==null?void 0:s.Range)!==void 0&&(I+=" Range="+(s==null?void 0:s.Range)),m.debug(I)}l.send();function h(){f!==void 0&&clearTimeout(f),p!==void 0&&clearTimeout(p),b!==null&&b()}})}function fg(n){try{return JSON.parse(n)}catch(e){return null}}var Se=wr;var hn=Fe,Ze={NETWORK_ERROR:"NETWORK_ERROR",MEDIA_ERROR:"MEDIA_ERROR",ENCRYPTED_MEDIA_ERROR:"ENCRYPTED_MEDIA_ERROR",OTHER_ERROR:"OTHER_ERROR"},ls={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 Je(n,e){return`${n}: ${e}`}var ge=class n extends Error{constructor(e,t,r){super(Je(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="EncryptedMediaError",this.type=Ze.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(Je(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="MediaError",this.type=Ze.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 ot=class n extends Error{constructor(e,t){super(Je(e,t.message)),Object.setPrototypeOf(this,n.prototype),this.name="NetworkError",this.type=Ze.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===hn.ERROR_HTTP_CODE&&this.status===e}serialize(){return{name:this.name,code:this.code,baseError:this._baseError.serialize()}}};var Ne=class n extends Error{constructor(e,t){super(Je(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="OtherError",this.type=Ze.OTHER_ERROR,this.code=e,this.fatal=!1,this._originalMessage=t}serialize(){return{name:this.name,code:this.code,reason:this._originalMessage}}};function Yt(n){return(n instanceof ge||n instanceof te||n instanceof Ne||n instanceof ot)&&Object.keys(Ze).indexOf(n.type)>=0}function Ee(n,{defaultCode:e,defaultReason:t}){if(Yt(n))return n;let r=n instanceof Error?n.toString():t;return new Ne(e,r)}var at=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 mg={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"},_c=mg;var pg={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"},Ec=pg;function gg(n){if(_(n)||n==="")return"und";let t=(""+n).toLowerCase().split("-")[0],r=hg(t);return w(r)?r:n}function hg(n){let e;switch(n.length){case 2:e=_c[n];break;case 3:e=Ec[n];break}return e}var vc=gg;var Or=vc;function he(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 $t=["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=V()-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=V()-e.time;return e.livePosition+t/1e3}function Tt(n){let{maximumTimeData:e}=n.timeBounds;if(!e.isLinear)return e.maximumSafePosition;let t=V()-e.time;return e.maximumSafePosition+t/1e3}function pt(n,e){if(e===void 0)return fs(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 Kn(n,e){let t=null;for(let r of n.periods){if(cs(r,e,t))return r;t=r}}function Co(n,e){let t=e.end;if(t===void 0)return null;let r=Q(n.periods,i=>i.end===void 0||t<i.end);return r===void 0?null:r}function cs(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 fs(n){let e=n.adaptations;return Rr(e).reduce((t,r)=>_(r)?t:t.concat(r),[])}function Mo(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=>St(o)===!0):n.representations).map(yg),label:n.label};return n.isDub===!0&&(t.dub=!0),t}function Ao(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 xo(n,e){let t=n.trickModeTracks!==void 0?n.trickModeTracks.map(i=>{let o=(e?i.representations.filter(s=>St(s)===!0):i.representations).map(Rc),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=>St(i)===!0):n.representations).map(Rc),label:n.label};return n.isSignInterpreted===!0&&(r.signInterpreted=!0),n.isTrickModeTrack===!0&&(r.isTrickModeTrack=!0),t!==void 0&&(r.trickModeTracks=t),r}function yg(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 Rc(n){let{id:e,bitrate:t,frameRate:r,width:i,height:o,codecs:a,hdrInfo:s,isSupported:d,decipherable:u,contentProtections:c}=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:c!==void 0?{keyIds:c.keyIds}:void 0}}function Qt(n){switch(n.type){case"audio":return{type:"audio",track:Mo(n,!1)};case"video":return{type:"video",track:xo(n,!1)};case"text":return{type:"text",track:Ao(n)}}}function St(n){return n.decipherable===!1?!1:n.isSupported}function kc(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 Ig=et(),ms=class{constructor(e,t,r){var o,a,s,d,u;this.id=e.id,this.uniqueId=Ig(),this.shouldBeAvoided=!1,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 c=r.isSupported((o=this.mimeType)!=null?o:"",(a=e.supplementalCodecs)!=null?a:"",i);c!==!1&&(this.codecs=[e.supplementalCodecs],this.isSupported=c)}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)he(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],c;for(c=0;c<s.length;c++)if(u.systemId===s[c].systemId){if(he(u.data,s[c].data))break;m.warn("Manifest: different init data for the same system ID")}c===s.length&&(s.push(u),i=!0)}return i}return this.contentProtections.initData.push({type:e,values:r}),!0}isPlayable(){return St(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,isCodecSupportedInWebWorker:this.isCodecSupportedInWebWorker}}},Pc=ms;var Dr=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=Or(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 c=new Pc(s[u],this.type,t),l=!0;if(!_(o)){let f={id:c.id,bitrate:c.bitrate,codecs:c.codecs,height:c.height,width:c.width,frameRate:c.frameRate,hdrInfo:c.hdrInfo};if(c.contentProtections!==void 0&&(f.contentProtections={},c.contentProtections.keyIds!==void 0)){let p=c.contentProtections.keyIds;f.contentProtections.keyIds=p}l=o(f,{trackType:this.type,language:this.language,normalizedLanguage:this.normalizedLanguage,isClosedCaption:this.isClosedCaption,isDub:this.isDub,isAudioDescription:this.isAudioDescription,isSignInterpreted:this.isSignInterpreted})}l?(d.push(c),c.isSupported===void 0?(this.supportStatus.hasCodecWithUndefinedSupport=!0,this.supportStatus.hasSupportedCodec===!1&&(this.supportStatus.hasSupportedCodec=void 0)):c.isSupported&&(this.supportStatus.hasSupportedCodec=!0),c.decipherable===void 0?this.supportStatus.isDecipherable===!1&&(this.supportStatus.isDecipherable=void 0):c.decipherable&&(this.supportStatus.isDecipherable=!0)):m.debug("Filtering Representation due to representationFilter",this.type,`Adaptation: ${this.id}`,`Representation: ${c.id}`,`(${c.bitrate})`)}d.sort((u,c)=>u.bitrate-c.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 Q(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 ps(){return fn}function Sn(n){return new Promise(e=>{setTimeout(e,n)})}function gs(){return hr}function hs(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 gs()?r:Promise.race([r,Sn(1e3)])}var _t=new WeakMap,je={async attach(n,e){let t=_t.get(n),r=bg(n,t,e).then(()=>{_t.set(n,{pendingTask:null,mediaKeysState:e})},()=>{_t.set(n,{pendingTask:null,mediaKeysState:null})});return _t.set(n,{pendingTask:r,mediaKeysState:e}),r},getAwaitedState(n){var t;let e=_t.get(n);return(t=e==null?void 0:e.mediaKeysState)!=null?t:null},async getAttachedMediaKeysState(n){let e=_t.get(n);return e===void 0?null:e.pendingTask!==null?(await e.pendingTask,this.getAttachedMediaKeysState(n)):e.mediaKeysState},clearMediaKeys(n){let e=_t.get(n),t=Sg(n,e).then(()=>{_t.set(n,{pendingTask:null,mediaKeysState:null})},()=>{_t.set(n,{pendingTask:null,mediaKeysState:null})});return _t.set(n,{pendingTask:t,mediaKeysState:null}),t}};async function Cc(n){let e=n.pendingTask;if(!_(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 bg(n,e,t){if(e!==void 0&&(e.pendingTask!==null&&await Cc(e),await(!_(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 hs(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 ge("MEDIA_KEYS_ATTACHMENT_ERROR","Could not attach the MediaKeys to the media element: "+i)}}async function Sg(n,e){if(e===void 0||(e.pendingTask!==null&&await Cc(e),e.mediaKeysState===null))return;m.info("DRM: Disposing of the current MediaKeys");let{loadedSessionsStore:t}=e.mediaKeysState;return await t.closeAllSessions(),hs(e.mediaKeysState.emeImplementation,n,null)}async function Vn(n){return je.clearMediaKeys(n)}async function wo(n){if(m.info("DRM: Clearing-up DRM session."),ps())return m.info("DRM: disposing current MediaKeys."),Vn(n);let e=await je.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 st(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 Xt(n,e){return st(e,t=>{let r=setTimeout(()=>t(),n);return()=>clearTimeout(r)})}function Oo(n){let e=new U;return Promise.race([n.close().then(()=>{e.cancel()}),n.closed.then(()=>{e.cancel()}),t()]);async function t(){try{await Xt(1e3,e.signal),await r()}catch(i){if(i instanceof Pe)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 Xt(1e3,e.signal)}if(!e.isUsed())throw new Error("Compat: Couldn't know if session is closed")}}var Tg=["","webkit","moz","ms"];function _g(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 Eg(n,e){return e.filter(t=>_g(n,t))[0]}function vg(n,e){return n.reduce((t,r)=>t.concat((e===void 0?Tg:e).map(i=>i+r)),[])}function Te(n,e){let t,r=vg(n,e);return(i,o,a)=>{if(!a.isCancelled()){if(typeof HTMLElement!="undefined"&&i instanceof HTMLElement)if(typeof t=="undefined"&&(t=Eg(i,r)),w(t))i.addEventListener(t,o),a.register(()=>{t!==void 0&&i.removeEventListener(t,o)});else{y.CURRENT_ENV===y.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 Rg(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 G(!o,n);return Tn(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 G({isEnabled:i,pipWindow:null},e);return Tn(n,"webkitpresentationmodechanged",()=>{let a=n.webkitPresentationMode==="picture-in-picture";o.setValue({isEnabled:a,pipWindow:null})},e),o}let t=document.pictureInPictureElement===n,r=new G({isEnabled:t,pipWindow:null},e);return Tn(n,"enterpictureinpicture",i=>{var o;r.setValue({isEnabled:!0,pipWindow:(o=i.pictureInPictureWindow)!=null?o:null})},e),Tn(n,"leavepictureinpicture",()=>{r.setValue({isEnabled:!1,pipWindow:null})},e),r}function Ac(n,e){let t=Rg(e),r,i=new G(!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}=L.getCurrent();r=setTimeout(()=>{i.setValueIfChanged(!1)},a)}}}function xc(n){var o,a;let e=_(J.devicePixelRatio)||J.devicePixelRatio===0?1:J.devicePixelRatio,t=new G({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 wc(n,e,t){let r=_(J.devicePixelRatio)||J.devicePixelRatio===0?1:J.devicePixelRatio,i=new G({width:n.clientWidth,height:n.clientHeight,pixelRatio:r},t),o=Z;e.onUpdate(s,{clearSignal:t}),Tn(J,"resize",s,t),Tn(n,"enterpictureinpicture",s,t),Tn(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 l=i.getValue();(l.width!==void 0||l.height!==void 0||l.pixelRatio!==r)&&i.setValue({width:void 0,height:void 0,pixelRatio:r})}else{let l=()=>{c()};u.addEventListener("resize",l),o=()=>{u.removeEventListener("resize",l),o=Z},c()}else{let l=i.getValue();(l.width!==n.clientWidth||l.height!==n.clientHeight||l.pixelRatio!==r)&&i.setValue({width:n.clientWidth,height:n.clientHeight,pixelRatio:r})}function c(){let l=i.getValue();(l.width!==(u==null?void 0:u.width)||l.height!==(u==null?void 0:u.height)||l.pixelRatio!==r)&&i.setValue({width:u==null?void 0:u.width,height:u==null?void 0:u.height,pixelRatio:r})}}}var FP=Te(["loadedmetadata"]),KP=Te(["timeupdate"]),VP=Te(["addtrack"]),zP=Te(["removetrack"]),zn=Te(["sourceopen","webkitsourceopen"]),Do=Te(["sourceclose","webkitsourceclose"]),Lo=Te(["sourceended","webkitsourceended"]),Oc=Te(["update"]),Dc=Te(["removesourcebuffer"]),No=Te(["keymessage","message"]),Lc=Te(["keyadded","ready"]),Uo=Te(["keyerror","error"]),Nc=Te(["keystatuseschange"]),Uc=Te(["seeking"]),Bc=Te(["seeked"]),Fc=Te(["ended"]);function Tn(n,e,t,r){n.addEventListener(e,t),r.register(()=>{n.removeEventListener(e,t)})}var gt,{WebKitMediaKeys:Bo}=J;Bo!==void 0&&typeof Bo.isTypeSupported=="function"&&typeof Bo.prototype.createSession=="function"&&typeof HTMLMediaElement.prototype.webkitSetMediaKeys=="function"&&(gt=Bo);function ys(){return(Ga||mn)&&gt!==void 0}var Lr=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 Mt(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 At,{MSMediaKeys:Nr}=J;Nr!==void 0&&Nr.prototype!==void 0&&typeof Nr.isTypeSupported=="function"&&typeof Nr.prototype.createSession=="function"&&(At=Nr);var Is=class extends ae{constructor(e){super(),this.expiration=NaN,this.keyStatuses=new Map,this._mk=e,this._sessionClosingCanceller=new U,this.closed=new Promise(t=>{this._sessionClosingCanceller.signal.register(()=>t("closed-by-application"))}),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),No(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"message",o)},this._sessionClosingCanceller.signal),Lc(this._ss,o=>{var a;this.trigger((a=o.type)!=null?a:"keyadded",o)},this._sessionClosingCanceller.signal),Uo(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:""}},Fo=class{constructor(e){if(At===void 0)throw new Error("No MSMediaKeys API.");this._mediaKeys=new At(e)}_setVideo(e){return Mt(()=>{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 Is(this._mediaKeys)}setServerCertificate(){throw new Error("Server certificate is not implemented in your browser")}};function bs(){return{isTypeSupported:(r,i)=>{if(At===void 0)throw new Error("No MSMediaKeys API.");return i!==void 0?At.isTypeSupported(r,i):At.isTypeSupported(r)},createCustomMediaKeys:r=>new Fo(r),setMediaKeys:(r,i)=>{if(i===null)return Promise.resolve(void 0);if(!(i instanceof Fo))throw new Error("Custom setMediaKeys is supposed to be called with IE11 custom MediaKeys.");return i._setVideo(r)}}}var Zt,{MozMediaKeys:Ur}=J;Ur!==void 0&&Ur.prototype!==void 0&&typeof Ur.isTypeSupported=="function"&&typeof Ur.prototype.createSession=="function"&&(Zt=Ur);function Ss(){return{isTypeSupported:(r,i)=>{if(Zt===void 0)throw new Error("No MozMediaKeys API.");return i!==void 0?Zt.isTypeSupported(r,i):Zt.isTypeSupported(r)},createCustomMediaKeys:r=>{if(Zt===void 0)throw new Error("No MozMediaKeys API.");return new Zt(r)},setMediaKeys:(r,i)=>Mt(()=>{if(r.mozSetMediaKeys===void 0||typeof r.mozSetMediaKeys!="function")throw new Error("Can't set video on MozMediaKeys.");return r.mozSetMediaKeys(i)})}}var xt=["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","+","/"],Kc=[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 Ko(n){if(n>=Kc.length)throw new Error("Unable to parse base64 string.");let e=Kc[n];if(e===255)throw new Error("Unable to parse base64 string.");return e}function Vo(n){let e="",t,r=n.length;for(t=2;t<r;t+=3)e+=xt[n[t-2]>>2],e+=xt[(n[t-2]&3)<<4|n[t-1]>>4],e+=xt[(n[t-1]&15)<<2|n[t]>>6],e+=xt[n[t]&63];return t===r+1&&(e+=xt[n[t-2]>>2],e+=xt[(n[t-2]&3)<<4],e+="=="),t===r&&(e+=xt[n[t-2]>>2],e+=xt[(n[t-2]&3)<<4|n[t-1]>>4],e+=xt[(n[t-1]&15)<<2],e+="="),e}function ht(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=Ko(t.charCodeAt(d))<<18|Ko(t.charCodeAt(d+1))<<12|Ko(t.charCodeAt(d+2))<<6|Ko(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 zc=typeof J=="object"&&typeof J.TextDecoder=="function",Pg=typeof J=="object"&&typeof J.TextEncoder=="function";function zo(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 Ho(n){if(zc)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(Pg)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 Cg(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 Vc(n,e){let t=n.toString(16);return t.length>=e?t:new Array(e-t.length+1).join("0")+t}function Ue(n){if(zc)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=Cg(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"+Vc(a,4):"%"+Vc(a,2)}}return decodeURIComponent(r)}function Ye(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 Be(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 Wo(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 Ts(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:Ue(r)}}function Es(n){return typeof(n==null?void 0:n.webkitGenerateKeyRequest)=="function"}var _s=class extends ae{constructor(e,t){super(),this._vid=e,this._key=t,this.sessionId="",this._closeSession=Z,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("closed-by-application")}}),["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(Ue(i)),a=ht(o.keys[0].k),s=ht(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()}},qo=class{constructor(e){this._keySystem=e}_setVideo(e){return Mt(()=>{if(!Es(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 _s(this._videoElement,this._keySystem)}setServerCertificate(){throw new Error("Server certificate is not implemented in your browser")}};function vs(){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 qo(r),setMediaKeys:(r,i)=>{if(i===null)return Promise.resolve(void 0);if(!(i instanceof qo))throw new Error("Custom setMediaKeys is supposed to be called with old webkit custom MediaKeys.");return i._setVideo(r)}}}function se(...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 Go(n,e){return(n[e+0]<<8)+(n[e+1]<<0)}function Rs(n,e){return n[e+0]*65536+n[e+1]*256+n[e+2]}function re(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 ce(n){return new Uint8Array([n>>>8&255,n&255])}function ye(n){return new Uint8Array([n>>>24&255,n>>>16&255,n>>>8&255,n&255])}function Jt(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 Hc(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 qc(n){return new Uint8Array([n&255,n>>>8&255])}function Br(n){return new Uint8Array([n&255,n>>>8&255,n>>>16&255,n>>>24&255])}function ks(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=Ho(t),a=o.indexOf("skd://"),s=a>-1?o.substring(a+6):o,d=zo(s),u=0,c=new Uint8Array(t.byteLength+4+d.byteLength+4+r.byteLength);return c.set(t),u+=t.length,c.set(Br(d.byteLength),u),u+=4,c.set(d,u),u+=d.byteLength,c.set(Br(r.byteLength),u),u+=4,c.set(r,u),c}function Mg(n){return Xe(n,"com.apple.fps")}function Gc(n,e){return Mt(()=>{if(n.webkitSetMediaKeys===void 0)throw new Error("No webKitMediaKeys API.");n.webkitSetMediaKeys(e)})}var Ps=class extends ae{constructor(e,t,r){super(),this._serverCertificate=r,this._videoElement=e,this._keyType=t,this._unbindSession=Z,this._closeSession=Z,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=ks(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("closed-by-application"),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)})}}},jo=class{constructor(e){if(gt===void 0)throw new Error("No WebKitMediaKeys API.");this._keyType=e,this._mediaKeys=new gt(e)}_setVideo(e){if(this._videoElement=e,this._videoElement===void 0)throw new Error("Video not attached to the MediaKeys");return Gc(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 Ps(this._videoElement,this._keyType,this._serverCertificate)}setServerCertificate(e){return this._serverCertificate=e,Promise.resolve(!0)}};function Yo(){if(gt===void 0)throw new Error("No WebKitMediaKeys API.");return{isTypeSupported:gt.isTypeSupported,createCustomMediaKeys:r=>new jo(r),setMediaKeys:(r,i)=>{if(i===null)return Gc(r,i);if(!(i instanceof jo))throw new Error("Custom setMediaKeys is supposed to be called with webkit custom MediaKeys.");return i._setVideo(r)}}}var Ag=xg("auto"),Yc=Ag;function xg(n){var o;let e,t,r=wg,i;if((n==="standard"||n==="auto"&&!ys())&&(qt||!_(navigator.requestMediaKeySystemAccess)))e=(...a)=>navigator.requestMediaKeySystemAccess(...a),t=Te(["encrypted"]),i="standard";else{let a,s;if(n==="webkit"&&gt!==void 0){let d=Yo();t=jc(),a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="webkit"}else if(Es((o=J.HTMLVideoElement)==null?void 0:o.prototype)){t=Te(["needkey"]);let d=vs();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="older-webkit"}else if(gt!==void 0){t=jc();let d=Yo();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="webkit"}else if(fn&&At!==void 0){t=Te(["encrypted","needkey"]);let d=bs();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="ms"}else if(Zt!==void 0){t=Te(["encrypted","needkey"]);let d=Ss();a=d.isTypeSupported,s=d.createCustomMediaKeys,r=d.setMediaKeys,i="moz"}else{t=Te(["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 c="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(c)}};a=c=>(u(),ee(typeof d.isTypeSupported=="function"),d.isTypeSupported(c)),s=c=>(u(),new d(c)),i="unknown"}e=function(d,u){if(!a(d))return Promise.reject(new Error("Unsupported key type"));for(let c=0;c<u.length;c++){let l=u[c],{videoCapabilities:f,audioCapabilities:p,initDataTypes:g,distinctiveIdentifier:b}=l,h=!0;if(h=h&&(_(g)||g.some(I=>I==="cenc")),h=h&&b!=="required",h){let I={initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",persistentState:"required",sessionTypes:["temporary","persistent-license"]};f!==void 0&&(I.videoCapabilities=f),p!==void 0&&(I.audioCapabilities=p);let T=s(d);return Promise.resolve(new Lr(d,T,I))}}return Promise.reject(new Error("Unsupported configuration"))}}return{requestMediaKeySystemAccess:e,onEncrypted:t,setMediaKeys:r,implementation:i}}function jc(){let n=Te(["needkey"],void 0);return(t,r,i)=>{n(t,o=>{let a=Y(o,{forceSessionRecreation:!0});r(a)},i)}}function wg(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 Et(n,e){let t=n.length,r=0;for(;r+8<=t;){let i=re(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(re(n,r+4)===e)return r+i<=t?r:-1;r+=i}return-1}function $o(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=Et(r,1836019558);if(i<0)break;let o=re(n,i+e),a=e+i+o;if(a>n.length)break;let s=Et(r,1835295092);if(s<0)break;let d=re(n,s+e),u=e+s+d;if(u>n.length)break;let c=Math.max(a,u),l=n.subarray(e,c);t.push(l),e=c}return t.length===0?[null,r]:[t,r]}function Og(n,e,t){return new Uint8Array(Array.prototype.slice.call(n,e,t))}function Dg(n,e,t){return n.slice(e,t)}var Cs=typeof Uint8Array.prototype.slice=="function"?Dg:Og;function Ms(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 $c(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 As(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=re(n,a),a+=4,i=re(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 _n(n,e,t,r,i){let o=n.length,a;for(let s=0;s<o;s+=a){let d=s;a=re(n,d),d+=4;let u=re(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&&re(n,d)===e&&re(n,d+4)===t&&re(n,d+8)===r&&re(n,d+12)===i)return d+=16,n.subarray(d,s+a)}}function xs(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=re(n,t);t+=4;let i=re(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 Qo(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=Cs(t,i[0],i[2]),a=Xo(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 Xo(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=Cs(n,t,t+16);return Be(r)}var Fr=Math.pow(2,32)-1;var ws={};function Qc(n){if(ws[n]!==void 0)return ws[n];let e=ve(n);return ws[n]=e,e}function ue(n,e){let t=e.length+8;return t<=Fr?se(ye(t),Qc(n),e):se(ye(1),Qc(n),Jt(t+8),e)}function we(n,e){return ue(n,se(...e))}function Kr(n){let e=Re(n,1836019558);return e===null?null:Re(e,1953653094)}function Xc(n){return $c(n,1836019558).reduce((t,r)=>{let i=Re(r,1953653094);return i!==null&&t.push(i),t},[])}function Vr(n){return Re(n,1835295092)}function Os(n){let e=Re(n,1836019574);if(e===null)return null;let t=Re(e,1953653099);return t===null?null:Re(t,1835297121)}function Zc(n,e=0){return Re(n.subarray(e),1701671783)}function zr(n){let e=Hc(n,8),t=Ho(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=Wo(ht(o));return Be(a).toLowerCase()}function Hr(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=re(n,o);o+=4;let d;if(a===0)d=re(n,o),o+=4,r+=re(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 c=Go(n,o);for(o+=2;--c>=0;){let l=re(n,o);o+=4;let f=(l&2147483648)>>>31,p=l&2147483647;if(f===1)throw new Error("sidx with reference_type `1` not yet implemented");let g=re(n,o);o+=4,o+=4,u.push({time:d,duration:g,timescale:s,range:[r,r+p-1]}),d+=g,r+=p}return u}function Ds(n){let e=Kr(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 re(t,4)}function Lg(n){let e=Re(n,1952868452);if(e===null)return;let t=1,r=Rs(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),re(e,t)):void 0}function Wr(n){let e=Xc(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=Rs(i,o);o+=3;let d=(s&256)>0,u=0;if(!d&&(u=Lg(r),u===void 0))return;let c=(s&1)>0,l=(s&4)>0,f=(s&512)>0,p=(s&1024)>0,g=(s&2048)>0,b=re(i,o);o+=4,c&&(o+=4),l&&(o+=4);let h=b,I=0;for(;h-- >0;)d?(I+=re(i,o),o+=4):I+=u,f&&(o+=4),p&&(o+=4),g&&(o+=4);t+=I}return t}function qr(n){let e=Os(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 re(t,r+16);if(i===0)return re(t,r+8)}function Ls(n){let e=n.length;if(e<4)throw new Error("Cannot update box length: box too short");let t=re(n,0);if(t===0)if(e>Fr){let r=new Uint8Array(e+8);return r.set(ye(1),0),r.set(n.subarray(4,8),4),r.set(Jt(e+8),8),r.set(n.subarray(8,e),16),r}else return n.set(ye(e),0),n;else if(t===1){if(e<16)throw new Error("Cannot update box length: box too short");return n.set(Jt(e),8),n}else{if(e<=Fr)return n.set(ye(e),0),n;{let r=new Uint8Array(e+8);return r.set(ye(1),0),r.set(n.subarray(4,8),4),r.set(Jt(e+8),8),r.set(n.subarray(8,e),16),r}}}function Jc(n){let e=[],t=0;for(;t<n.length;){let r=Zc(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}=Ts(r,a);a=s;let{end:u,string:c}=Ts(r,a);a=u;let l=re(r,a);a+=4;let f=re(r,a);a+=4;let p=re(r,a);a+=4;let g=re(r,a);a+=4;let b=r.subarray(a,i),h={schemeIdUri:d,value:c,timescale:l,presentationTimeDelta:f,eventDuration:p,id:g,messageData:b};e.push(h)}}if(e.length!==0)return e}function ef(n){let e=Ms(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=Ms(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=re(ve("pssh"),0);function Ng(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||re(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=re(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=xs(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=se(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=se(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 se(r,t)}function Gr(n,e,t){m.debug("Compat: Calling generateRequest on the MediaKeySession");let r;try{r=Ng(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 Ug(n){let e=[],t=0;for(;t<n.length;){if(n.length<t+8||re(n,t+4)!==Zo)return m.warn("Compat: Unrecognized initialization data. Use as is."),[{systemId:void 0,data:n}];let r=re(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:Xo(i,8),data:i};Bg(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 Bg(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)&&he(e.data,r.data))return!0}return!1}function Jo(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=Ug(i);return{type:t,values:o,forceSessionRecreation:r}}var Fg=100;async function jr(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,Fg);function o(){a(),r(t)}function a(){clearTimeout(i),n.removeEventListener("keystatuseschange",o)}})}var en=Yc;function X(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 Yr(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):X(t,"expired")?(m.debug("DRM: isSessionUsable: MediaKeySession given has an expired key",n.sessionId),!1):X(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 Ns(n,e,t,r){let{loadedSessionsStore:i,persistentSessionsStore:o}=n;return t==="temporary"?tf(i,e):o===null?(m.warn("DRM: Cannot create persistent MediaKeySession, PersistentSessionsStore not created."),tf(i,e)):Kg(i,o,e,r)}function tf(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 Kg(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&&Yr(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 Us(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 Bs(n,e,t,r,i){let o=null,{loadedSessionsStore:a,persistentSessionsStore:s}=e,d=a.reuse(n);if(d!==null){if(o=d.mediaKeySession,Yr(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 Us(a,r<=0?r:r-1),i.cancellationError!==null))throw i.cancellationError;let u=await Ns(e,n,t,i);return{type:u.type,value:{mediaKeySession:u.value.mediaKeySession,sessionType:u.value.sessionType,keySessionRecord:u.value.keySessionRecord}}}function Fs(){return!hr&&!$a&&!Ya&&!Xa}function nf(n){return!((pr||Pt)&&n.indexOf("playready")!==-1)}var rf='<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 of(n){let e=zo(n),t=qc(e.length),r=new Uint8Array([1,0]),i=new Uint8Array([1,0]),o=Br(e.length+6),a=se(o,i,r,t,e),s=Ye("9a04f07998404286ab92e65be0885f95");return Vg(a,s)}function Vg(n,e){let t=ve("pssh"),r=new Uint8Array([0,0,0,0]),i=ye(n.length),o=ye(32+n.length);return se(o,t,r,e,i,n)}function Ks(){return fn}function zg(n,e){let{mimeType:t,codecs:r}=ea(n),{mimeType:i,codecs:o}=ea(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 Hg=7;function ea(n){var i;let[e,...t]=n.split(";"),r=(i=Q(t,o=>Xe(o,"codecs=")))!=null?i:"";return r=r.substring(Hg),r[0]==='"'&&(r=r.substring(1,r.length-1)),{mimeType:e,codecs:r}}var ta=zg;function Hn(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 Wg(n,e){var c,l,f,p,g,b,h,I,T,R;if(n.label!==e.label)return!1;let t=(c=e.distinctiveIdentifier)!=null?c:"optional",r=(l=n.distinctiveIdentifier)!=null?l:"optional";if(t!==r)return!1;let i=(f=e.persistentState)!=null?f:"optional",o=(p=n.persistentState)!=null?p:"optional";if(i!==o)return!1;let a=(g=e.initDataTypes)!=null?g:[],s=(b=n.initDataTypes)!=null?b:[];if(!sf(s,a))return!1;let d=(h=e.sessionTypes)!=null?h:[],u=(I=n.sessionTypes)!=null?I:[];if(!sf(u,d))return!1;for(let E of["audioCapabilities","videoCapabilities"]){let v=(T=n[E])!=null?T:[],k=(R=e[E])!=null?R:[];if(!v.every(P=>{var M,O,B,D,F,A;for(let C=0;C<k.length;C++){let N=k[C];if(((M=N.robustness)!=null?M:"")===((O=P.robustness)!=null?O:"")||((B=N.encryptionScheme)!=null?B:null)===((D=P.encryptionScheme)!=null?D:null)||((F=N.robustness)!=null?F:"")===((A=P.robustness)!=null?A:""))return!0}return!1}))return!1}return!0}function qg(n){let{EME_KEY_SYSTEMS:e}=L.getCurrent();for(let t of Object.keys(e))if(X(e[t],n))return t}function Gg(n){let{keyName:e,keyType:t,keySystemOptions:r}=n,i,o="optional",a="optional";Array.isArray(r.wantedSessionTypes)?(i=r.wantedSessionTypes,X(r.wantedSessionTypes,"persistent-license")&&!_(r.persistentLicenseConfig)&&(o="required")):_(r.persistentLicenseConfig)?i=["temporary"]:(o="required",i=["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:c}=L.getCurrent(),l,f,{audioCapabilitiesConfig:p,videoCapabilitiesConfig:g}=r;if((p==null?void 0:p.type)==="full")l=p.value;else{let h;(p==null?void 0:p.type)==="robustness"?h=p.value:e==="widevine"?h=u:t==="com.microsoft.playready.recommendation"?h=c:h=[],h.length===0&&h.push(void 0);let I=(p==null?void 0:p.type)==="contentType"?p.value:s;l=Hn(h,T=>I.map(R=>T!==void 0?{contentType:R,robustness:T}:{contentType:R}))}if((g==null?void 0:g.type)==="full")f=g.value;else{let h;(g==null?void 0:g.type)==="robustness"?h=g.value:e==="widevine"?h=u:t==="com.microsoft.playready.recommendation"?h=c:h=[],h.length===0&&h.push(void 0);let I=(g==null?void 0:g.type)==="contentType"?g.value:d;f=Hn(h,T=>I.map(R=>T!==void 0?{contentType:R,robustness:T}:{contentType:R}))}let b={initDataTypes:["cenc"],videoCapabilities:f,audioCapabilities:l,distinctiveIdentifier:a,persistentState:o,sessionTypes:i};return p!==void 0?g!==void 0?[b]:[b,de(oe({},b),{videoCapabilities:void 0})]:g!==void 0?[b,de(oe({},b),{audioCapabilities:void 0})]:[b,de(oe({},b),{audioCapabilities:void 0,videoCapabilities:void 0})]}function af(n,e){var u,c,l,f,p,g;let t=(c=(u=n.audioCapabilities)==null?void 0:u.map(b=>b.contentType))!=null?c:[],r=(f=(l=n.videoCapabilities)==null?void 0:l.map(b=>b.contentType))!=null?f:[],i=t.concat(r).filter(b=>b!==void 0),o=(p=e.videoCapabilities)==null?void 0:p.map(b=>b.contentType),a=(g=e.audioCapabilities)==null?void 0:g.map(b=>b.contentType),s=[...o!=null?o:[],...a!=null?a:[]].filter(b=>b!==void 0);return s.length===0?[]:i.map(b=>{let{codecs:h,mimeType:I}=ea(b),T=X(s,b);return{codec:h,mimeType:I,result:T}})}function Vs(n,e,t){m.info("DRM: Searching for compatible MediaKeySystemAccess");let r=e.reduce((o,a)=>{let{EME_KEY_SYSTEMS:s}=L.getCurrent(),d=s[a.type],u;if(!_(d))u=d.map(c=>({keyName:a.type,keyType:c,keySystemOptions:a}));else{let c=qg(a.type),l=a.type;u=[{keyName:c,keyType:l,keySystemOptions:a}]}return o.concat(u)},[]);return i(0);async function i(o){if(o>=r.length)throw new ge("INCOMPATIBLE_KEYSYSTEMS","No key system compatible with your wanted configuration has been found in the current browser.");if(_(en.requestMediaKeySystemAccess))throw new Error("requestMediaKeySystemAccess is not implemented in your browser.");let a=r[o],{keyType:s,keySystemOptions:d}=a,u=Gg(a);m.debug(`DRM: Request keysystem access ${s},${o+1} of ${r.length}`);let c,l=await je.getAttachedMediaKeysState(n);for(let f=0;f<u.length;f++){let p=u[f];if(l!==null&&!Ks()&&s===l.mediaKeySystemAccess.keySystem&&en.implementation===l.emeImplementation.implementation&&Wg(p,l.askedConfiguration))return m.info("DRM: Found cached compatible keySystem"),Promise.resolve({type:"reuse-media-key-system-access",value:{mediaKeySystemAccess:l.mediaKeySystemAccess,askedConfiguration:l.askedConfiguration,options:d,codecSupport:af(l.askedConfiguration,l.mediaKeySystemAccess.getConfiguration())}});try{return c=await jg(s,[p]),m.info("DRM: Found compatible keysystem",s,o+1),{type:"create-media-key-system-access",value:{options:d,mediaKeySystemAccess:c,askedConfiguration:p,codecSupport:af(p,c.getConfiguration())}}}catch(g){if(m.debug("DRM: Rejected access to keysystem",s,o+1,f),t.cancellationError!==null)throw t.cancellationError}}return i(o+1)}}async function jg(n,e){let t=await en.requestMediaKeySystemAccess(n,e);if(!nf(n))try{let i=(await t.createMediaKeys()).createSession(),o=of(rf);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 sf(n,e){for(let t=0;t<n.length;t++)if(!X(e,n[t]))return!1;return!0}function Wn(n,e){for(let t of n)if(!e.some(i=>he(i,t)))return!1;return!0}function df(n,e){for(let t of n)if(e.some(i=>he(i,t)))return!0;return!1}var $r=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(he(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&&Wn(t,this._keyIds))return!0;if(this._initializationData.keyIds!==void 0)return Wn(t,this._initializationData.keyIds)}return this._checkInitializationDataCompatibility(e)}_checkInitializationDataCompatibility(e){return e.keyIds!==void 0&&e.keyIds.length>0&&this._initializationData.keyIds!==void 0?Wn(e.keyIds,this._initializationData.keyIds):this._initializationData.type!==e.type?!1:this._initializationData.values.isCompatibleWith(e.values)}};var Qr=class{constructor(e){this._mediaKeys=e,this._storage=[]}createSession(e,t){let r=new $r(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"),Gr(e,t,r);if(i.isGeneratingRequest=!0,i.closingStatus.type!=="none")throw new Error("The `MediaKeySession` is being closed.");try{await Gr(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"),jr(e,t);if(r.isLoadingPersistentSession=!0,r.closingStatus.type!=="none")throw new Error("The `MediaKeySession` is being closed.");let i;try{i=await jr(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"}),Yg(t).then(()=>{e!==void 0&&(e.closingStatus={type:"done"}),r(!0)}).catch(a=>{e!==void 0&&(e.closingStatus={type:"failed"}),i(a)})}})}};async function Yg(n){m.debug("DRM: Trying to close a MediaKeySession",n.sessionId);try{await Oo(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 tn(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 dt=class{constructor(e){this.initData=e}toJSON(){return Vo(this.initData)}static decode(e){return ht(e)}};function qn(n,e){var t,r;return(r=(t=uf(n,e))!=null?t:uf(e,n))!=null?r:!1}function uf(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=dt.decode(t.data):a=t.data.initData;let s;if(o.data instanceof Uint8Array?s=o.data:typeof o.data=="string"?s=dt.decode(o.data):s=o.data.initData,!he(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 c;d.data instanceof Uint8Array?c=d.data:typeof d.data=="string"?c=dt.decode(d.data):c=d.data.initData;let l;if(u.data instanceof Uint8Array?l=u.data:typeof u.data=="string"?l=dt.decode(u.data):l=u.data.initData,!he(c,l))return!1;break}if(r===e.length)return null}return!0}return null}function $g(n){fc(n,{save:"function",load:"function"},"persistentLicenseConfig")}var Xr=class{constructor(e){$g(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=Qg(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 dt(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:tn(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=Vo(s);for(let u of o.keyIds)if(typeof u=="string"){if(d===u)return!0}else if(he(u.initData,s))return!0;return!1}))return i}else{let a=e.values.getFormattedValues();if(qn(a,o.values))return i}break;case 3:{let a=e.values.getFormattedValues();if(qn(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"?dt.decode(o.initData):o.initData.initData;if(he(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(he(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 Qg(n){return n.map(({systemId:e,data:t,hash:r})=>({systemId:e,hash:r,data:new dt(t)}))}var na=new WeakMap,En={prepare(n){na.set(n,null)},set(n,e){let t=e instanceof Uint8Array?e:new Uint8Array(e instanceof ArrayBuffer?e:e.buffer),r=tn(t);na.set(n,{hash:r,serverCertificate:t})},hasOne(n){let e=na.get(n);if(e===void 0)return!1;if(e!==null)return!0},has(n,e){let t=na.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(tn(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 Xr(e))}async function zs(n,e,t){let r=await Vs(n,e,t);if(t.cancellationError!==null)throw t.cancellationError;let{options:i,mediaKeySystemAccess:o,askedConfiguration:a,codecSupport:s}=r.value,d=await je.getAttachedMediaKeysState(n),u=Xg(i);if(r.value.options.reuseMediaKeys!==!1&&Fs()&&d!==null&&r.type==="reuse-media-key-system-access"){m.debug("DRM: Reusing already created MediaKeys");let{mediaKeys:f,loadedSessionsStore:p}=d;if(En.hasOne(f)===!1||!_(i.serverCertificate)&&En.has(f,i.serverCertificate))return{mediaKeys:f,mediaKeySystemAccess:o,askedConfiguration:a,stores:{loadedSessionsStore:p,persistentSessionsStore:u},options:i,codecSupport:s}}let c=await Zg(o);m.info("DRM: MediaKeys created with success");let l=new Qr(c);return{mediaKeys:c,mediaKeySystemAccess:o,askedConfiguration:a,stores:{loadedSessionsStore:l,persistentSessionsStore:u},options:i,codecSupport:s}}async function Zg(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 ge("CREATE_MEDIA_KEYS_ERROR",t)}}async function Hs(n,e,t){let r=await zs(n,e,t),{mediaKeys:i}=r;return n.mediaKeys!==null&&n.mediaKeys!==void 0&&i!==n.mediaKeys&&(m.debug("DRM: Disabling old MediaKeys"),await je.clearMediaKeys(n)),r}function Zr(n){let e=(Math.random()*2-1)*.3;return n*(e+1)}function Ws(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(c){if(t.cancellationError!==null)throw t.cancellationError;if(!_(a)&&!a(c)||d++>=o)throw c;typeof s=="function"&&s(c,d);let l=Jg(r,d,i);return await Sn(l),u()}}}function Jg(n,e,t){let r=n*Math.pow(2,e-1),i=Zr(r);return Math.min(i,t)}function qs(n,e){return n.indexOf("playready")!==-1&&(Gt||pr)?Wo(e):e}var Gn=class n extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,n.prototype),this.reason=e}},Gs={EXPIRED:"expired",INTERNAL_ERROR:"internal-error",OUTPUT_RESTRICTED:"output-restricted"};function js(n,e,t){let{onKeyInternalError:r,onKeyOutputRestricted:i,onKeyExpiration:o}=e,a=[],s=[],d=[];n.keyStatuses.forEach((c,l)=>{let[f,p]=typeof c=="string"?[c,l]:[l,c],g=qs(t,new Uint8Array(p)),b={keyId:g.buffer,keyStatus:f};switch(m.hasLevel("DEBUG")&&m.debug(`DRM: key status update (${Be(g)}): ${f}`),f){case Gs.EXPIRED:{let h=new ge("KEY_STATUS_CHANGE_ERROR",`A decryption key expired (${Be(g)})`,{keyStatuses:[b,...d]});if(o==="error"||o===void 0)throw h;switch(o){case"close-session":throw new Gn(h);case"fallback":a.push(g);break;default:o==="continue"||o===void 0?s.push(g):He(o);break}d.push(b);break}case Gs.INTERNAL_ERROR:{let h=new ge("KEY_STATUS_CHANGE_ERROR",`A "${f}" status has been encountered (${Be(g)})`,{keyStatuses:[b,...d]});switch(r){case void 0:case"error":throw h;case"close-session":throw new Gn(h);case"fallback":a.push(g);break;case"continue":s.push(g);break;default:if(r!==void 0)He(r);else throw h}d.push(b);break}case Gs.OUTPUT_RESTRICTED:{let h=new ge("KEY_STATUS_CHANGE_ERROR",`A "${f}" status has been encountered (${Be(g)})`,{keyStatuses:[b,...d]});switch(i){case void 0:case"error":throw h;case"fallback":a.push(g);break;case"continue":s.push(g);break;default:if(i!==void 0)He(i);else throw h}d.push(b);break}default:s.push(g);break}});let u;return d.length>0&&(u=new ge("KEY_STATUS_CHANGE_ERROR","One or several problematic key statuses have been encountered",{keyStatuses:d})),{warning:u,blacklistedKeyIds:a,whitelistedKeyIds:s}}function Ys(n,e,t,r,i){m.info("DRM: Binding session events",n.sessionId);let{getLicenseConfig:o={}}=e,a=new U;a.linkToSignal(i),_(n.closed)||n.closed.then(()=>a.cancel()).catch(c=>{i.isCancelled()||(a.cancel(),r.onError(c))}),Uo(n,c=>{a.cancel(),r.onError(new ge("KEY_ERROR",c.type))},a.signal),Nc(n,()=>{m.info("DRM: keystatuseschange event received",n.sessionId);try{s()}catch(c){if(i.isCancelled()||a.isUsed()&&c instanceof Ir)return;a.cancel(),r.onError(c)}},a.signal),No(n,c=>{let l=c,f=new Uint8Array(l.message),p=w(l.messageType)?l.messageType:"license-request";m.info(`DRM: Received message event, type ${p}`,n.sessionId);let g=u(o.retry);Ws(()=>d(f,p),g,a.signal).then(async b=>{if(!a.isUsed())if(_(b))m.info("DRM: No license given, skipping session.update");else try{await eh(n,b)}catch(h){a.cancel(),r.onError(h)}},b=>{if(a.isUsed())return;a.cancel();let h=lf(b);if(!_(b)){let{fallbackOnLastTry:I}=b;if(I===!0){m.warn("DRM: Last `getLicense` attempt failed. Blacklisting the current session."),r.onError(new jn(h));return}}r.onError(h)})},a.signal),m.info("DRM: transmitting current keystatuses",n.sessionId),s();return;function s(){if(a.isUsed()||n.keyStatuses.size===0)return;let{warning:c,blacklistedKeyIds:l,whitelistedKeyIds:f}=js(n,e,t);c!==void 0&&(r.onWarning(c),a.isUsed())||r.onKeyUpdate({whitelistedKeyIds:f,blacklistedKeyIds:l})}function d(c,l){let f;return new Promise((p,g)=>{try{m.debug("DRM: Calling `getLicense`",l);let I=e.getLicense(c,l),T=_(o.timeout)?10*1e3:o.timeout;T>=0&&(f=setTimeout(()=>{g(new Jr(`"getLicense" timeout exceeded (${T} ms)`))},T)),Promise.resolve(I).then(b,h)}catch(I){h(I)}function b(I){f!==void 0&&clearTimeout(f),p(I)}function h(I){f!==void 0&&clearTimeout(f),g(I)}})}function u(c){return{totalRetry:c!=null?c:2,baseDelay:200,maxDelay:3e3,shouldRetry:l=>l instanceof Jr||_(l)||l.noRetry!==!0,onRetry:l=>r.onWarning(lf(l))}}}function lf(n){if(n instanceof Jr)return new ge("KEY_LOAD_TIMEOUT","The license server took too much time to respond.");let e=new ge("KEY_LOAD_ERROR","An error occured when calling `getLicense`.");return!_(n)&&w(n.message)&&(e.message=n.message),e}async function eh(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 ge("KEY_UPDATE_ERROR",r)}m.info("DRM: MediaKeySession update succeeded.")}var jn=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,jn.prototype),this.message=e}};async function th(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 ge("LICENSE_SERVER_CERTIFICATE_ERROR",r)}}async function $s(n,e){if(En.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"),En.prepare(n);try{let t=await th(n,e);return En.set(n,e),{type:"success",value:t}}catch(t){return{type:"error",value:Yt(t)?t:new ge("LICENSE_SERVER_CERTIFICATE_ERROR","Unknown error when setting the server certificate.")}}}function Qs(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 Xs(n){if(Xe(n,"com.microsoft.playready")||n==="com.chromecast.playready"||n==="com.youtube.playready")return"9a04f07998404286ab92e65be0885f95";if(n==="com.widevine.alpha")return"edef8ba979d64acea3c827dcd51d21ed";if(Xe(n,"com.apple.fps"))return"94ce86fb07ff4f43adb893d2fa968ca2";if(Xe(n,"com.nagra."))return"adb41c242dbf4a6d958b4457c0d27b95"}var ei=class n{constructor(e){this._innerValues=e,this._lazyFormattedValues=null}constructRequestData(){return se(...this._innerValues.map(e=>e.data))}isCompatibleWith(e){let t=e instanceof n?e.getFormattedValues():e;return qn(this.getFormattedValues(),t)}getFormattedValues(){return this._lazyFormattedValues===null&&(this._lazyFormattedValues=nh(this._innerValues)),this._lazyFormattedValues}};function nh(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:tn(t)}))}function Zs(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(ta(r,d))return s}}var ti=class extends ae{static hasEmeApis(){return!_(en.requestMediaKeySystemAccess)}constructor(e,t){super(),m.debug("DRM: Starting ContentDecryptor logic.");let r=new U;this._currentSessions=[],this._canceller=r,this._initDataQueue=[],this._stateData={state:0,isMediaKeysAttached:0,isInitDataQueueLocked:!0,data:null},this._supportedCodecWhenEncrypted=[],this.error=null,en.onEncrypted(e,i=>{m.debug("DRM: Encrypted event received from media element.");let o=Jo(i);o!==null&&this.onInitializationData(o)},r.signal),Hs(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=Xs(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:en,loadedSessionsStore:a.loadedSessionsStore,mediaKeySystemAccess:o,mediaKeys:i,askedConfiguration:s,keySystemOptions:r};m.debug("DRM: Attaching current MediaKeys"),je.attach(e,u).then(async()=>{if(this._isStopped())return;this._stateData.isMediaKeysAttached=2;let{serverCertificate:c}=r;if(!_(c)){let f=await $s(i,c);f.type==="error"&&this.trigger("warning",f.value)}if(this._isStopped())return;let l=this._stateData.state;this._stateData={state:2,isMediaKeysAttached:2,isInitDataQueueLocked:!1,data:{mediaKeysData:t}},l!==2&&this.trigger("stateChange",2),this._isStopped()||this._processCurrentInitDataQueue()}).catch(c=>{this._onFatalError(c)})}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"),Zs(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=de(oe({},e),{values:new ei(e.values)});this._processInitializationData(r,t).catch(i=>{this._onFatalError(i)})}async _processInitializationData(e,t){var b,h,I;m.hasLevel("DEBUG")&&m.debug("DRM: processing init data",(b=e.content)==null?void 0:b.adaptation.type,(h=e.content)==null?void 0:h.representation.bitrate,((I=e.keyIds)!=null?I:[]).map(T=>Be(T)).join(", "));let{mediaKeySystemAccess:r,stores:i,options:o}=t;if(this._tryToUseAlreadyCreatedSession(e,t)||this._isStopped())return;if(o.singleLicensePer==="content"){let T=Q(this._currentSessions,R=>R.source==="created-session");if(T!==void 0){let R=e.keyIds;if(R===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(R),e.content===void 0)m.warn("DRM: Unable to fallback from a non-decipherable quality.");else{if(m.hasLevel("DEBUG")){let E=R.reduce((v,k)=>`${v}, ${Be(k)}`,"");m.debug("DRM: Blacklisting new key ids",E)}this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:R,delistedKeyIds:[]})}return}}else if(o.singleLicensePer==="periods"&&e.content!==void 0){let{period:T}=e.content,R=this._currentSessions.filter(v=>v.source==="created-session"),E=new Set;ed(E,T);for(let v of R){let k=Array.from(E);for(let x of k)if(v.record.isAssociatedWithKeyId(x)){v.record.associateKeyIds(E.values());for(let P of k)!v.keyStatuses.whitelisted.some(M=>he(M,P))&&!v.keyStatuses.blacklisted.some(M=>he(M,P))&&v.keyStatuses.blacklisted.push(P);m.hasLevel("DEBUG")&&m.debug("DRM: Session already created for",Be(x),'under singleLicensePer "periods" policy'),this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:v.keyStatuses.whitelisted,blacklistedKeyIds:v.keyStatuses.blacklisted,delistedKeyIds:[]});return}}}this._lockInitDataQueue();let a;rh(r)&&(!_(o.persistentLicenseConfig)||!ih(r))?a="persistent-license":a="temporary";let{EME_DEFAULT_MAX_SIMULTANEOUS_MEDIA_KEY_SESSIONS:s,EME_MAX_STORED_PERSISTENT_SESSION_INFORMATION:d}=L.getCurrent(),u=typeof o.maxSessionCacheSize=="number"?o.maxSessionCacheSize:s,c=await Bs(e,i,a,u,this._canceller.signal);if(this._isStopped())return;let l={record:c.value.keySessionRecord,source:c.type,keyStatuses:{whitelisted:[],blacklisted:[]},blacklistedSessionError:null};this._currentSessions.push(l);let{mediaKeySession:f,sessionType:p}=c.value,g=!1;if(Ys(f,o,r.keySystem,{onKeyUpdate:T=>{let R=sh(e,l.record,o.singleLicensePer,l.source==="created-session",T.whitelistedKeyIds,T.blacklistedKeyIds);if(l.record.associateKeyIds(R.whitelisted),l.record.associateKeyIds(R.blacklisted),l.keyStatuses={whitelisted:R.whitelisted,blacklisted:R.blacklisted},l.record.getAssociatedKeyIds().length!==0&&p==="persistent-license"&&i.persistentSessionsStore!==null&&!g){let{persistentSessionsStore:E}=i;Qs(E,d-1),E.add(e,l.record.getAssociatedKeyIds(),f),g=!0}e.content!==void 0&&this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:R.whitelisted,blacklistedKeyIds:R.blacklisted,delistedKeyIds:[]}),this._unlockInitDataQueue()},onWarning:T=>{this.trigger("warning",T)},onError:T=>{var R;if(T instanceof Gn){m.warn("DRM: A session's closing condition has been triggered"),this._lockInitDataQueue();let E=this._currentSessions.indexOf(l);E>=0&&this._currentSessions.splice(E),e.content!==void 0&&this.trigger("keyIdsCompatibilityUpdate",{whitelistedKeyIds:[],blacklistedKeyIds:[],delistedKeyIds:l.record.getAssociatedKeyIds()}),(R=i.persistentSessionsStore)==null||R.delete(f.sessionId),i.loadedSessionsStore.closeSession(f).catch(v=>{let k=v instanceof Error?v:"unknown error";m.warn("DRM: failed to close expired session",k)}).then(()=>this._unlockInitDataQueue()).catch(v=>this._onFatalError(v)),this._isStopped()||this.trigger("warning",T.reason);return}if(!(T instanceof jn)){this._onFatalError(T);return}l.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(),c.type==="created-session"){let T=e.values.constructRequestData();try{await i.loadedSessionsStore.generateLicenseRequest(f,e.type,T)}catch(R){let E=i.loadedSessionsStore.getEntryForSession(f);if(E===null||E.closingStatus.type!=="none"){let v=this._currentSessions.indexOf(l);return v>=0&&this._currentSessions.splice(v,1),Promise.resolve()}throw new ge("KEY_GENERATE_REQUEST_ERROR",R instanceof Error?R.toString():"Unknown error")}}return Promise.resolve()}_tryToUseAlreadyCreatedSession(e,t){let{stores:r,options:i}=t,o=Q(this._currentSessions,c=>c.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 c;if(i.singleLicensePer===void 0||i.singleLicensePer==="init-data"){let{blacklisted:l}=o.keyStatuses;c=df(e.keyIds,l)}else{let{whitelisted:l}=o.keyStatuses;c=!Wn(e.keyIds,l)}if(c)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=Q(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 Ne("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 rh(n){let{sessionTypes:e}=n.getConfiguration();return e!==void 0&&X(e,"persistent-license")}function ih(n){let{sessionTypes:e}=n.getConfiguration();return e!==void 0&&X(e,"temporary")}function cf(n,e){return n.filter(t=>!e.some(r=>he(r,t)))}function oh(n,e){let t=n.getAssociatedKeyIds(),r=cf(t,e);return r.length>0&&m.hasLevel("DEBUG")&&m.debug("DRM: KeySessionRecord's keys missing in the license, blacklisting them",r.map(i=>Be(i)).join(", ")),r}function ah(n,e){let t=[],{keyIds:r}=n;return r!==void 0&&(t=cf(r,e)),t.length>0&&m.hasLevel("DEBUG")&&m.debug("DRM: init data keys missing in the license, blacklisting them",t.map(i=>Be(i)).join(", ")),t}function sh(n,e,t,r,i,o){var u;let a=[...i,...o],s=oh(e,a),d=a.concat(s);if(t!==void 0&&t!=="init-data"){let c=ah(n,d);d.push(...c);let{content:l}=n;if(r&&l!==void 0){if(t==="content"){let f=new Set,{manifest:p}=l;for(let g of p.periods)ed(f,g);Js(f,d)}else if(t==="periods"){let{manifest:f}=l;for(let p of f.periods){let g=new Set;if(ed(g,p),((u=n.content)==null?void 0:u.period.id)===p.id)Js(g,d);else{let b=Array.from(g);for(let h of b)if(d.some(T=>he(T,h))){Js(g,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=>he(o,r))||e.push(r)}function ed(n,e){let t=e.adaptations,r=Rr(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 Yn(n){let e=je.getAwaitedState(n);return e===null?null:[e.mediaKeySystemAccess.keySystem,e.mediaKeySystemAccess.getConfiguration()]}var ff=ti;function mf(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 c of u.representations)c.isSupported===void 0&&e.push({mimeType:(i=c.mimeType)!=null?i:"",codec:(a=(o=c.codecs)==null?void 0:o[0])!=null?a:""})}return e}var pf=[];function wt(n){X(pf,n)||(console.warn(n),pf.push(n))}var ni=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 ri=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 c=new Dr(u,r,{representationFilter:i});return c.representations.length>0&&c.supportStatus.hasSupportedCodec===!1&&t.push(c),c}).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.thumbnailTracks=e.thumbnailTracks.map(o=>({id:o.id,mimeType:o.mimeType,index:o.index,cdnMetadata:o.cdnMetadata,height:o.height,width:o.width,horizontalTiles:o.horizontalTiles,verticalTiles:o.verticalTiles,start:o.start,end:o.end,tileDuration:o.tileDuration})),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 fs(this)}getAdaptationsForType(e){let t=this.adaptations[e];return t!=null?t:[]}getAdaptation(e){return Q(this.getAdaptations(),({id:t})=>e===t)}getSupportedAdaptations(e){return pt(this,e)}containsTime(e,t){return cs(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,thumbnailTracks:this.thumbnailTracks.map(r=>({id:r.id,mimeType:r.mimeType,height:r.height,width:r.width,horizontalTiles:r.horizontalTiles,verticalTiles:r.verticalTiles,start:r.start,end:r.end,tileDuration:r.tileDuration}))}}};function ii(n,e,t){let r={updatedAdaptations:[],removedAdaptations:[],addedAdaptations:[],updatedThumbnailTracks:[],removedThumbnailTracks:[],addedThumbnailTracks:[]};n.start=e.start,n.end=e.end,n.duration=e.duration,n.streamEvents=e.streamEvents;let i=n.thumbnailTracks,o=e.thumbnailTracks;for(let d=0;d<i.length;d++){let u=i[d],c=pe(o,l=>l.id===u.id);if(c===-1){m.warn('Manifest: ThumbnailTrack "'+i[d].id+'" not found when merging.');let[l]=i.splice(d,1);d--,r.removedThumbnailTracks.push({id:l.id})}else{let[l]=o.splice(c,1);u.mimeType=l.mimeType,u.height=l.height,u.width=l.width,u.horizontalTiles=l.horizontalTiles,u.verticalTiles=l.verticalTiles,u.start=l.start,u.end=l.end,u.tileDuration=l.tileDuration,u.cdnMetadata=l.cdnMetadata,t===0?u.index._replace(l.index):u.index._update(l.index),r.updatedThumbnailTracks.push({id:u.id,mimeType:u.mimeType,height:u.height,width:u.width,horizontalTiles:u.horizontalTiles,verticalTiles:u.verticalTiles,start:u.start,end:u.end,tileDuration:u.tileDuration})}}o.length>0&&(m.warn(`Manifest: ${o.length} new Thumbnail tracks found when merging.`),r.addedThumbnailTracks.push(...o.map(d=>({id:d.id,mimeType:d.mimeType,height:d.height,width:d.width,horizontalTiles:d.horizontalTiles,verticalTiles:d.verticalTiles,start:d.start,end:d.end,tileDuration:d.tileDuration}))),n.thumbnailTracks.push(...o));let a=n.getAdaptations(),s=e.getAdaptations();for(let d=0;d<a.length;d++){let u=a[d],c=pe(s,l=>l.id===u.id);if(c===-1){m.warn('Manifest: Adaptation "'+a[d].id+'" not found when merging.');let[l]=a.splice(d,1);d--,r.removedAdaptations.push({id:l.id,trackType:l.type})}else{let[l]=s.splice(c,1),f=[],p=[],g=[];r.updatedAdaptations.push({adaptation:u.id,trackType:u.type,updatedRepresentations:f,addedRepresentations:p,removedRepresentations:g});let b=u.representations,h=l.representations.slice();for(let I=0;I<b.length;I++){let T=b[I],R=pe(h,E=>E.id===T.id);if(R===-1){m.warn(`Manifest: Representation "${b[I].id}" not found when merging.`);let[E]=b.splice(I,1);I--,g.push(E.id)}else{let[E]=h.splice(R,1);f.push(T.getMetadataSnapshot()),T.cdnMetadata=E.cdnMetadata,t===0?T.index._replace(E.index):T.index._update(E.index)}}h.length>0&&(m.warn(`Manifest: ${h.length} new Representations found when merging.`),u.representations.push(...h),p.push(...h.map(I=>I.getMetadataSnapshot())))}}if(s.length>0){m.warn(`Manifest: ${s.length} new Adaptations found when merging.`);for(let d of s){let u=n.adaptations[d.type];u===void 0?n.adaptations[d.type]=[d]:u.push(d),r.addedAdaptations.push(d.getMetadataSnapshot())}}return r}function gf(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=ii(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 c=e.slice(r,o),l=s-r,f=n.splice(r,l,...c);t.removedPeriods.push(...f.map(p=>({id:p.id,start:p.start,end:p.end}))),t.addedPeriods.push(...c.map(p=>p.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 hf(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=pe(n,({id:s})=>s===e[0].id);if(i<0)throw new te("MANIFEST_UPDATE_ERROR","Cannot perform partial update: incoherent data");let o=ii(n[i],e[0],1);t.updatedPeriods.push({period:Y(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 c=a;c<n.length;c++)if(d.id===n[c].id){u=c;break}if(u<0){let c=-1;for(let p=a;p<n.length;p++)if(d.start<n[p].start){c=p;break}let l=c-a,f=n.splice(a,l,d);t.addedPeriods.push(d.getMetadataSnapshot()),t.removedPeriods.push(...f.map(p=>({id:p.id,start:p.start,end:p.end})))}else{if(u>a){m.warn("Manifest: old Periods not found in new when updating, removing");let l=n.splice(a,u-a);t.removedPeriods.push(...l.map(f=>({id:f.id,start:f.start,end:f.end}))),u=a}let c=ii(n[u],d,0);t.updatedPeriods.push({period:Y(n[u].getMetadataSnapshot(),{adaptations:void 0}),result:c})}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 dh=et(),oi=class extends ae{constructor(e,t,r){var s;super();let{representationFilter:i,manifestUpdateUrl:o}=t;this.manifestFormat=0,this.id=dh(),this.expired=(s=e.expired)!=null?s:null,this.transport=e.transportType,this.clockOffset=e.clockOffset,this._cachedCodecSupport=new ni([]);let a=[];if(this.periods=e.periods.map(d=>new ri(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(Qt)});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(Qt)}):null}getPeriod(e){return Q(this.periods,t=>e===t.id)}getPeriodForTime(e){return Kn(this,e)}getNextPeriod(e){return Q(this.periods,t=>t.start>e)}getPeriodAfter(e){return Co(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 Tt(this)}updateCodecSupportList(e){this._cachedCodecSupport=e}updateRepresentationsDeciperability(e){let t=uh(this,e);t.length>0&&this.trigger("decipherabilityUpdate",t)}addRepresentationsToAvoid(e){let t=[];for(let r of e){let i=this.getPeriod(r.period.id);if(i===void 0)continue;let o=i.getAdaptation(r.adaptation.id);if(o===void 0)continue;let a=o.getRepresentation(r.representation.id);a!==void 0&&(a.shouldBeAvoided=!0,t.push({manifest:this,period:i,adaptation:o,representation:a}))}t.length>0&&this.trigger("representationAvoidanceUpdate",t)}getAdaptations(){wt("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(Object.prototype.hasOwnProperty.call(t,i)){let o=t[i];r.push(...o)}return r}getAdaptationsForType(e){wt("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 wt("manifest.getAdaptation(id) is deprecated. Please use manifest.period[].getAdaptation(id) instead"),Q(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 mf(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=gf(this.periods,e.periods);else{this.timeBounds.maximumTimeData=e.timeBounds.maximumTimeData,this.updateUrl=e.uris[0],r=hf(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 uh(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 Ct(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 $n=oi;function ut(n){return n instanceof _e?new ot("PIPELINE_LOAD_ERROR",n):Ee(n,{defaultCode:"PIPELINE_LOAD_ERROR",defaultReason:"Unknown error when fetching the Manifest"})}function lh(n){return n instanceof _e?n.type===hn.ERROR_HTTP_CODE?n.status>=500||n.status===404||n.status===415||n.status===412:n.type===hn.TIMEOUT||n.type===hn.ERROR_EVENT:n instanceof it?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:Yt(n)&&n.code==="INTEGRITY_ERROR"}async function ai(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,c=l();if(c===void 0)throw new Error("No CDN to request");return f(c);function l(){if(n===null){let h=u.get(null);return h!==void 0&&h.isBlacklisted?void 0:null}else{if(e===null)return b(n);{let h=e.getCdnPreferenceForResource(n);return b(h)}}}async function f(h){try{return await t(h,i)}catch(I){if(U.isCancellationError(I))throw I;h!==null&&e!==null&&e.downgradeCdn(h);let T=u.get(h);if(T===void 0?(T={errorCounter:1,blockedUntil:void 0,isBlacklisted:!1},u.set(h,T)):T.errorCounter++,!lh(I))return T.blockedUntil=void 0,T.isBlacklisted=!0,p(I);if(T.errorCounter>s)T.blockedUntil=void 0,T.isBlacklisted=!0;else{let R=T.errorCounter,E=Math.min(o*Math.pow(2,R-1),a),v=Zr(E);T.blockedUntil=V()+v}return p(I)}}async function p(h){let I=l();if(i.isCancelled())throw i.cancellationError;if(I===void 0)throw h;if(d(h),i.isCancelled())throw i.cancellationError;return g(I,h)}function g(h,I){let T=u.get(h);if(T===void 0||T.blockedUntil===void 0)return f(h);let R=V(),E=T.blockedUntil-R;if(E<=0)return f(h);let v=new U,k=v.linkToSignal(i);return new Promise((x,P)=>{e==null||e.addEventListener("priorityChange",()=>{let B=l();if(i.isCancelled())throw i.cancellationError;if(B===void 0)return O(I);B!==h&&(v.cancel(),g(B,I).then(M,O))},v.signal),Xt(E,v.signal).then(()=>f(h).then(M,O),Z);function M(B){k(),x(B)}function O(B){k(),P(B)}})}function b(h){var T;if(u.size===0)return h[0];let I=V();return(T=h.filter(R=>{var E;return((E=u.get(R))==null?void 0:E.isBlacklisted)!==!0}).reduce((R,E)=>{var k;let v=(k=u.get(E))==null?void 0:k.blockedUntil;return v!==void 0&&v<=I&&(v=void 0),R===void 0?[E,v]:R[1]===void 0?R:v===void 0?[E,void 0]:v<R[1]?[E,v]:R},void 0))==null?void 0:T[0]}}function td(n,e,t){return ai(null,null,n,e,t)}var si=class extends ae{constructor(e,t,r){super(),this.scheduleManualRefresh=Z,this._manifestUrls=e,this._pipelines=t.manifest,this._transportName=t.transportName,this._settings=r,this._canceller=new U,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 $n?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(c=>{this.trigger("warning",ut(c))});try{let c=await d(a);return{parse:l=>this._parseLoadedManifest(c,l,a)}}catch(c){throw ut(c)}function d(c){var h;let{loadManifest:l}=o,f=r.requestTimeout===void 0?L.getCurrent().DEFAULT_REQUEST_TIMEOUT:r.requestTimeout,p=r.connectionTimeout===void 0?L.getCurrent().DEFAULT_CONNECTION_TIMEOUT:r.connectionTimeout;f<0&&(f=void 0),p<0&&(p=void 0);let g={timeout:f,connectionTimeout:p,cmcdPayload:(h=r.cmcdDataBuilder)==null?void 0:h.getCmcdDataForManifest(i)};return td(()=>l(c,g,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 b;let i=V(),o=this._canceller.signal,a=this.trigger.bind(this),{sendingTime:s,receivedTime:d}=e,u=this._getBackoffSetting(h=>{this.trigger("warning",ut(h))}),c=r!=null?r:(b=this._manifestUrls)==null?void 0:b[0],l={externalClockOffset:t.externalClockOffset,unsafeMode:t.unsafeMode,previousManifest:t.previousManifest,originalUrl:c};try{let h=this._pipelines.parseManifest(e,l,p,o,f);if(ch(h)){let{manifest:I,warnings:T}=await h;return g(I,T)}else return g(h.manifest,h.warnings)}catch(h){throw Ee(h,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"})}async function f(h){try{return await td(h,u,o)}catch(I){throw ut(I)}}function p(h){for(let I of h){if(o.isCancelled())return;let T=Ee(I,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"});a("warning",T)}}function g(h,I){p(I);let T=V()-i;return m.info(`MF: Manifest parsed in ${T}ms`),{manifest:h,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}=L.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}=L.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:V()-t,c=Math.max(this._settings.minimumManifestUpdateInterval-u,0),l=new U;if(l.linkToSignal(this._canceller.signal),this.scheduleManualRefresh=f=>{let{enablePartialRefresh:p,delay:g,canUseUnsafeMode:b}=f,h=b&&d,I=t===void 0?0:V()-t,T=Math.max(this._settings.minimumManifestUpdateInterval-I,0),R=setTimeout(()=>{l.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:p,unsafeMode:h})},Math.max((g!=null?g:0)-I,T));l.signal.register(()=>{clearTimeout(R)})},e.expired!==null){let f=setTimeout(()=>{var p;(p=e.expired)==null||p.then(()=>{l.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},Z)},c);l.signal.register(()=>{clearTimeout(f)})}if(e.lifetime!==void 0&&e.lifetime>=0){let f=e.lifetime*1e3-u,p;s===void 0?p=f:e.lifetime<3&&s>=100?(p=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,p)):s>=e.lifetime*1e3/10?(p=Math.min(Math.max(f,0)+s,f*6),m.info("MUS: Manifest took too long to parse. Postponing next request",p,p)):p=f;let g=setTimeout(()=>{l.cancel(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},Math.max(p,c));l.signal.register(()=>{clearTimeout(g)})}}_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:c,parsingTime:l}=d,f=V();if(o)e.replace(u);else try{e.update(u)}catch(g){let b=g instanceof Error?g.message:"unknown error";m.warn(`MUS: Attempt to update Manifest failed: ${b}`,"Re-downloading the Manifest fully");let{FAILED_PARTIAL_UPDATE_MANIFEST_REFRESH_DELAY:h}=L.getCurrent(),I=c===void 0?0:V()-c,T=Math.max(this._settings.minimumManifestUpdateInterval-I,0),R=Z,E=setTimeout(()=>{R(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:!1})},Math.max(h-I,T));R=this._canceller.signal.register(()=>{clearTimeout(E)});return}let p=V()-f;this._recursivelyRefreshManifest(e,{sendingTime:c,parsingTime:l,updatingTime:p})}).catch(d=>{this._isRefreshPending=!1,this._onFatalError(d)}))}_onFatalError(e){this._canceller.isUsed()||(this.trigger("error",e),this.dispose())}};function ch(n){return n instanceof Promise}var nd=si;function rd(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 id=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}},yf=id;var fh=et();function od({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=X(["audio","video"],n)?new yf:void 0,{loadSegment:u,parseSegment:c}=e;return async function(f,p,g){var j,$,z;let{segment:b,adaptation:h,representation:I,manifest:T,period:R}=f,E=bn(f),v=fh(),k,x=[],P=0,M=!1,O={segment:b,type:h.type,language:h.language,isLive:T.isLive,periodStart:R.start,periodEnd:R.end,mimeType:I.mimeType,codecs:I.codecs[0],manifestPublishTime:T.publishTime},B={onProgress(H){var q;k===void 0&&H.totalSize!==void 0&&H.size<H.totalSize&&((q=i.onProgress)==null||q.call(i,{duration:H.duration,size:H.size,totalSize:H.totalSize,timestamp:V(),id:v}))},onNewChunk(H){p.onChunk(C(H,!0))}},D=d!==void 0?d.get(f):null;if(D!==null)return m.debug("SF: Found wanted segment in cache",E),p.onChunk(C(D,!1)),Promise.resolve();m.debug("SF: Beginning request",E),(j=i.onRequestBegin)==null||j.call(i,{requestTimestamp:V(),id:v,content:f}),g.register(F);try{let H=await ai(f.representation.cdnMetadata,t,A,Y({onRetry:N},o),g);if(H.resultType==="segment-loaded"){let q=H.resultData.responseData;d!==void 0&&d.add(f,H.resultData.responseData),p.onChunk(C(q,!1))}else H.resultType==="segment-created"&&p.onChunk(C(H.resultData,!1));m.debug("SF: Segment request ended with success",E),p.onAllChunksReceived(),H.resultType!=="segment-created"?(k=H.resultData,K()):k=null,g.isCancelled()||($=i.onRequestEnd)==null||$.call(i,{id:v}),g.deregister(F)}catch(H){throw g.deregister(F),k=null,H instanceof Pe?(m.debug("SF: Segment request aborted",E),H):(m.debug("SF: Segment request failed",E),(z=i.onRequestEnd)==null||z.call(i,{id:v}),ut(H))}function F(){var H;k===void 0&&(m.debug("SF: Segment request cancelled",E),k=null,(H=i.onRequestEnd)==null||H.call(i,{id:v}))}function A(H){return s.cmcdPayload=r==null?void 0:r.getCmcdDataForSegmentRequest(f),u(H,O,s,g,B)}function C(H,q){x.push(!1);let ie=x.length-1;return function(le){let be={data:H,isChunked:q};try{let me=c(be,O,le);return x[ie]||(P=P!==void 0&&me.segmentType==="media"&&me.chunkInfos!==null&&me.chunkInfos.duration!==void 0?P+me.chunkInfos.duration:void 0,x[ie]=!0,K()),me}catch(me){throw Ee(me,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}}}function N(H){p.onRetry(ut(H))}function K(){var H;M||!_(k)&&k.size!==void 0&&k.requestDuration!==void 0&&x.length>0&&x.every(q=>q)&&(M=!0,(H=i.onMetrics)==null||H.call(i,{size:k.size,requestDuration:k.requestDuration,content:f,segmentDuration:P}))}}}function If({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}=L.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 di=class extends ae{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 G({initSegment:null,segmentQueue:[]}),i=new U;i.signal.register(()=>{r.finish()});let o={content:e,downloadQueue:r,initSegmentInfoRef:t?new G(void 0):new G(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 c=d[0];if(u.segment.id!==c.segment.id){m.debug("SQ: Next media segment changed, cancelling previous",e.adaptation.type),this._restartMediaSegmentDownloadingQueue(o);return}u.priority!==c.priority&&(m.debug("SQ: Priority of next media segment changed, updating",e.adaptation.type,u.priority,c.priority),this._segmentFetcher.updatePriority(u.request,c.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 R;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 U,c=o===null?Z:u.linkToSignal(o.signal),{segment:l,priority:f}=d,p=Y({segment:l,nextSegment:(R=s[1])==null?void 0:R.segment},r),g=!1,b=!1;u.signal.register(()=>{e.mediaSegmentRequest=null,!g&&(e.mediaSegmentAwaitingInitMetadata===l.id&&(e.mediaSegmentAwaitingInitMetadata=null),g=!0,b=!1)});let h=E=>{ee(E.segmentType==="media","Should have loaded a media segment."),this.trigger("parsedMediaSegment",Y({},E,{segment:l}))},I=()=>{let E=t.getValue().segmentQueue;if(E.length===0){g=!0,this.trigger("emptyQueue",null);return}else E[0].segment.id===l.id&&E.shift();g=!0,a()},T=this._segmentFetcher.createRequest(p,f,{onRetry:E=>{this.trigger("requestRetry",{segment:l,error:E})},beforeInterrupted(){m.info("SQ: segment request interrupted temporarly.",l.id,l.time)},onChunk:E=>{let v=i.getValue();v!==void 0?h(E(v!=null?v:void 0)):(b=!0,i.waitUntilDefined(k=>{h(E(k!=null?k:void 0))},{clearSignal:u.signal}))},onAllChunksReceived:()=>{b?(e.mediaSegmentAwaitingInitMetadata=l.id,i.waitUntilDefined(()=>{e.mediaSegmentAwaitingInitMetadata=null,b=!1,this.trigger("fullyLoadedSegment",l)},{clearSignal:u.signal})):this.trigger("fullyLoadedSegment",l)},beforeEnded:()=>{c(),e.mediaSegmentRequest=null,b?i.waitUntilDefined(I,{clearSignal:u.signal}):I()}},u.signal);T.catch(E=>{c(),g||(g=!0,this.stop(),this.trigger("error",E))}),e.mediaSegmentRequest={segment:l,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 U,a=e.currentCanceller===null?Z:o.linkToSignal(e.currentCanceller.signal),{segment:s,priority:d}=t,u=Y({segment:s,nextSegment:void 0},r),c=!1,l=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,c=!0},onChunk:f=>{var g;let p=f(void 0);ee(p.segmentType==="init","Should have loaded an init segment."),this.trigger("parsedInitSegment",Y({},p,{segment:s})),p.segmentType==="init"&&i.setValue((g=p.initTimescale)!=null?g:null)},onAllChunksReceived:()=>{this.trigger("fullyLoadedSegment",s)}},o.signal);l.catch(f=>{a(),c||(c=!0,this.stop(),this.trigger("error",f))}),o.signal.register(()=>{e.initSegmentRequest=null,!c&&(c=!0)}),e.initSegmentRequest={segment:s,priority:d,request:l,canceller:o}}};var li=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 st(i,(a,s)=>(o={hasEnded:!1,priority:t,trigger:()=>{if(o.hasEnded)return;let u=()=>{p(),this._endTask(o)},c=g=>{r.beforeEnded(),u(),a(g)},l=g=>{u(),s(g)},f=new U,p=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(c).catch(g=>{!i.isCancelled()&&f.isUsed()&&g instanceof Pe||l(g)})},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=ui(e.taskFn,this._waitingQueue);if(t>=0)this._waitingQueue.splice(t,1);else{let r=ui(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=ui(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=ui(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=ui(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 ui(n,e){return pe(e,t=>t.taskFn===n)}var ci=class{constructor(e,t,r,i){let{MIN_CANCELABLE_PRIORITY:o,MAX_HIGH_PRIORITY_LEVEL:a}=L.getCurrent();this._transport=e,this._prioritizer=new li({prioritySteps:{high:a,low:o}}),this._cdnPrioritizer=t,this._backoffOptions=i,this._cmcdDataBuilder=r}createSegmentQueue(e,t,r){let i=If(this._backoffOptions),o=this._transport[e],a=od({bufferType:e,pipeline:o,cdnPrioritizer:this._cdnPrioritizer,cmcdDataBuilder:this._cmcdDataBuilder,eventListeners:t,requestOptions:i}),s=rd(this._prioritizer,a);return new di(s,r)}};var ad=ci;function sd(n,e){let{loadThumbnail:t}=n;return async function(i,o,a,s){let d;a.connectionTimeout===void 0||a.connectionTimeout<0?d=void 0:d=a.connectionTimeout;let u={timeout:a.requestTimeout<0?void 0:a.requestTimeout,connectionTimeout:d,cmcdPayload:void 0};m.debug("TF: Beginning thumbnail request",i.time),s.register(l);let c;try{if(c=await ai(o.cdnMetadata,e,f,Y({onRetry:p},a),s),s.isCancelled())return Promise.reject(s.cancellationError);m.debug("TF: Thumbnail request ended with success",i.time),s.deregister(l)}catch(g){throw s.deregister(l),g instanceof Pe?(m.debug("TF: Thumbnail request aborted",i.time),g):(m.debug("TF: Thumbnail request failed",i.time),ut(g))}try{return n.parseThumbnail(c.responseData,{thumbnail:i,thumbnailTrack:o})}catch(g){throw Ee(g,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}function l(){m.debug("TF: Thumbnail request cancelled",i.time)}function f(g){return t(g,i,u,s)}function p(g){let b=ut(g);m.warn("TF: Thumbnail request retry ",i.time,b)}}}function ra({maxRetry:n,requestTimeout:e,connectionTimeout:t}){let{DEFAULT_MAX_THUMBNAIL_REQUESTS_RETRY_ON_ERROR:r,DEFAULT_THUMBNAIL_REQUEST_TIMEOUT:i,DEFAULT_THUMBNAIL_CONNECTION_TIMEOUT:o,INITIAL_BACKOFF_DELAY_BASE:a,MAX_BACKOFF_DELAY_BASE:s}=L.getCurrent();return{maxRetry:n!=null?n:r,baseDelay:a.REGULAR,maxDelay:s.REGULAR,requestTimeout:e===void 0?i:e,connectionTimeout:t===void 0?o:t}}var dd=sd;var vn=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 Q(this._array,e)}has(e){return X(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 fi=class extends ae{constructor(e,t,r){super(),this._canceller=new U,this._manifest=e,this._activeStreams=new Map,this._allBufferTypes=r,this._lastCurrentPeriodId=null;let i=new ud(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 vn((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)}},ud=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=ia(this._lastVideoAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}}else if(this._lastVideoAdaptation===null){let e=ia(this._lastAudioAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}else{let e=ia(this._lastAudioAdaptation),t=ia(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=oa(this._lastVideoAdaptation))!=null?e:void 0;if(this._lastVideoAdaptation===null)return(t=oa(this._lastAudioAdaptation))!=null?t:void 0;{let r=oa(this._lastAudioAdaptation),i=oa(this._lastVideoAdaptation);return typeof r!="number"||typeof i!="number"?void 0:Math.min(r,i)}}}};function ia(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 oa(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 ld(n,e,t,r,i,o){o.register(()=>{e.interruptDurationSetting()});let a=new fi(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 bf=6,cd=4e3,aa=6e3,mh=6e4,mi=class{constructor(e){this._segmentSinksStore=e,this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=null,this._lastFlushAttempt=null,this._lastSegmentInfo={audio:[],video:[]}}onNewObservation(e){var h,I;let t=V();if(this._addPositionToHistory(e,t),this._ignoreFreezeUntil!==null&&t<this._ignoreFreezeUntil)return null;this._ignoreFreezeUntil=null;let{UNFREEZING_SEEK_DELAY:r,UNFREEZING_DELTA_POSITION:i,FREEZING_FLUSH_FAILURE_DELAY:o}=L.getCurrent(),{readyState:a,rebuffering:s,freezing:d,fullyLoaded:u}=e,c=e.position.getPolled(),l=Sf(e.bufferGap);if(!(d!==null||s!==null&&a===1&&(l>=bf||u)))return this._decipherabilityFreezeStartingTimestamp=null,null;let p=(I=(h=d==null?void 0:d.timestamp)!=null?h:s==null?void 0:s.timestamp)!=null?I:null;if(m.info("FR: Freeze detected",p,t-(p!=null?p:t)),this._lastFlushAttempt!==null&&t-this._lastFlushAttempt.timestamp<o.MAXIMUM&&t-this._lastFlushAttempt.timestamp>=o.MINIMUM&&Math.abs(c-this._lastFlushAttempt.position)<o.POSITION_DELTA){let T=this._getStrategyIfFlushingFails(c);return this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+aa,T}let b=this._checkForDecipherabilityRelatedFreeze(e,t);return b!==null?b:p!==null&&t-p>r?(this._lastFlushAttempt={timestamp:t,position:c+i},m.debug("FR: trying to flush to un-freeze"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+aa,{type:"flush",value:{relativeSeek:i}}):null}_checkForDecipherabilityRelatedFreeze(e,t){let{readyState:r,rebuffering:i,freezing:o,fullyLoaded:a}=e,s=Sf(e.bufferGap),d=i!==null&&t-i.timestamp>cd,u=o!==null&&t-o.timestamp>cd;(d||u)&&(s>=bf||a)&&r<=1?this._decipherabilityFreezeStartingTimestamp===null&&(m.debug("FR: Start of a potential decipherability freeze detected"),this._decipherabilityFreezeStartingTimestamp=t):this._decipherabilityFreezeStartingTimestamp=null;let l=this._decipherabilityFreezeStartingTimestamp!==null&&V()-this._decipherabilityFreezeStartingTimestamp>cd,f=!0,p=!0;for(let g of["audio","video"]){let b=this._segmentSinksStore.getStatus(g);if(b.type==="initialized")for(let h of b.value.getLastKnownInventory()){let{representation:I}=h.infos;if(I.decipherable===!1)return m.warn("FR: we have undecipherable segments left in the buffer, reloading"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+aa,{type:"reload",value:null};I.contentProtections!==void 0&&(p=!1,I.decipherable!==!0&&(f=!1))}}return l&&!p&&f?(m.warn("FR: we are frozen despite only having decipherable segments left in the buffer, reloading"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+aa,{type:"reload",value:null}):null}_getStrategyIfFlushingFails(e){m.warn("FR: A recent flush seemed to have no effect on freeze, checking for transitions");let t=[];for(let r of["audio","video"]){let i=this._lastSegmentInfo[r];if(i.length===0)continue;let o=i[i.length-1];if(o.segment===null)continue;let a=o.segment,s;for(let d=i.length-2;d>=0;d--){let u=i[d];if(u.segment===null){s=u;break}else if(u.segment.infos.representation.uniqueId!==a.infos.representation.uniqueId&&o.timestamp-u.timestamp<5e3){s=u;break}else u.segment.start===a.start&&e-u.position<3e3&&(o=u)}if(s===void 0||s.segment===null)m.debug("FR: Freeze when beginning to play a content, try avoiding this quality"),t.push({adaptation:a.infos.adaptation,period:a.infos.period,representation:a.infos.representation});else{if(a.infos.period.id!==s.segment.infos.period.id)return m.debug("FR: Freeze when switching Period, reloading"),{type:"reload",value:null};a.infos.representation.uniqueId!==s.segment.infos.representation.uniqueId&&(m.warn("FR: Freeze when switching Representation, avoiding",a.infos.representation.bitrate),t.push({adaptation:a.infos.adaptation,period:a.infos.period,representation:a.infos.representation}))}}return t.length>0?{type:"avoid-representations",value:t}:(m.debug("FR: Reloading because flush doesn't work"),{type:"reload",value:null})}_addPositionToHistory(e,t){var i,o;let r=e.position.getPolled();for(let a of["audio","video"]){let s=this._segmentSinksStore.getStatus(a);if(s.type==="initialized")for(let c of s.value.getLastKnownInventory())((i=c.bufferedStart)!=null?i:c.start)<=r&&((o=c.bufferedEnd)!=null?o:c.end)>r&&this._lastSegmentInfo[a].push({segment:c,position:r,timestamp:t});else this._lastSegmentInfo[a].push({segment:null,position:r,timestamp:t});if(this._lastSegmentInfo[a].length>100){let c=this._lastSegmentInfo[a].length-100;this._lastSegmentInfo[a].splice(0,c)}let d=t-mh,u;for(u=0;u<this._lastSegmentInfo[a].length&&!(this._lastSegmentInfo[a][u].timestamp>d);u++);u>0&&this._lastSegmentInfo[a].splice(0,u)}}};function Sf(n){return n!==void 0&&isFinite(n)?n:0}async function fd(n,e,t,r,i){let o=e.getPeriod(t);if(o===void 0)throw new Error("Wanted Period not found.");let a=Q(o.thumbnailTracks,d=>d.id===r);if(a===void 0)throw new Error("Wanted Period has no thumbnail track.");let s=a.index.getSegments(i,1)[0];if(s===void 0)throw new Error("No thumbnail for the given timestamp");return n(s,a,ra({}),new U().signal)}function md(n,e){["video","audio","text"].forEach(t=>{var i;let r=e.getStatus(t);r.type==="initialized"&&r.value.synchronizeInventory((i=n.buffered[t])!=null?i:[])})}function sa({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&&ph(n,o,a,t.getValue(),r.getValue(),i).catch(d=>{if(i.isCancelled()&&U.isCancellationError(d))return;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 ph(n,e,t,r,i,o){if(!isFinite(r)&&!isFinite(i))return Promise.resolve();let a=[],{innerRange:s,outerRanges:d}=dc(t,e),u=()=>{if(isFinite(r)){for(let l of d)e-r>=l.end?a.push(l):e>=l.end&&e-r>l.start&&e-r<l.end&&a.push({start:l.start,end:e-r});_(s)||e-r>s.start&&a.push({start:s.start,end:e-r})}},c=()=>{if(isFinite(i)){for(let l of d)e+i<=l.start?a.push(l):e<=l.start&&e+i<l.end&&e+i>l.start&&a.push({start:e+i,end:l.end});_(s)||e+i<s.end&&a.push({start:e+i,end:s.end})}};u(),c();for(let l of a)if(l.start<l.end){if(m.debug("GC: cleaning range from SegmentSink",l.start,l.end),o.cancellationError!==null)throw o.cancellationError;await n.removeBuffer(l.start,l.end)}}var pi=class{constructor(e,t){this._history=[],this._lifetime=e,this._maxHistoryLength=t}addBufferedSegment(e,t){let r=V();this._history.push({date:r,buffered:t,context:e}),this._cleanHistory(r)}getHistoryFor(e){return this._history.filter(t=>Ct(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 gi=class{constructor(){let{BUFFERED_HISTORY_RETENTION_TIME:e,BUFFERED_HISTORY_MAXIMUM_ENTRIES:t}=L.getCurrent();this._inventory=[],this._bufferedHistory=new pi(e,t)}reset(){this._inventory.length=0}synchronizeBuffered(e){var d,u,c,l,f,p,g;let t=this._inventory,r=0,i=t[0],{MINIMUM_SEGMENT_SIZE:o}=L.getCurrent(),a=i==null?void 0:i.infos.adaptation.type;if(m.hasLevel("DEBUG")){let b=e.map(h=>`${h.start}-${h.end}`).join(",");m.debug(`SI: synchronizing ${a!=null?a:"unknown"} buffered ranges:`,b)}let s=e.length;for(let b=0;b<s;b++){if(i===void 0)return;let h=e[b].start,I=e[b].end;if(I-h<o){m.warn("SI: skipped range when synchronizing because it was too small",a,h,I);continue}let T=r;for(;i!==void 0&&((d=i.bufferedEnd)!=null?d:i.end)-h<o;)i=t[++r];let R=null,E=r-T;if(E>0){let k=t[T+E-1];R={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 P of x)P.bufferedStart===void 0&&P.bufferedEnd===void 0&&P.status!==2&&this._bufferedHistory.addBufferedSegment(P.infos,null);r=T}if(i===void 0)return;if(I-((c=i.bufferedStart)!=null?c:i.start)>=o){if(gh(i,h,R,a),r===t.length-1){_f(i,I,a);return}i=t[++r];let k=(l=i.bufferedStart)!=null?l:i.start,x=(f=i.bufferedEnd)!=null?f:i.end,P=b<s-1?e[b+1].start:void 0;for(;i!==void 0&&!(I<k||I-k<o&&x-I>=o||P!==void 0&&I-k<x-P);){let M=t[r-1];M.bufferedEnd===void 0&&(i.precizeStart?M.bufferedEnd=i.start:M.infos.segment.complete?M.bufferedEnd=M.end:M.bufferedEnd=i.start,m.debug("SI: calculating buffered end of contiguous segment",a,M.bufferedEnd,M.end)),i.bufferedStart=M.bufferedEnd,i=t[++r],i!==void 0&&(k=(p=i.bufferedStart)!=null?p:i.start,x=(g=i.bufferedEnd)!=null?g:i.end)}}let v=t[r-1];v!==void 0&&_f(v,I,a)}if(!_(i)){let{SEGMENT_SYNCHRONIZATION_DELAY:b}=L.getCurrent(),h=V();for(let I=r;I<t.length;I++){let T=t[I];h-T.insertionTs>=b&&(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(I,1),I--)}}a!==void 0&&m.hasLevel("DEBUG")&&m.debug(`SI: current ${a} inventory timeline:
2
+ `+hh(this._inventory))}insertChunk({period:e,adaptation:t,representation:r,segment:i,chunkSize:o,start:a,end:s},d,u){if(i.isInit)return;let c=t.type;if(a>=s){m.warn("SI: Invalid chunked inserted: starts before it ends",c,a,s);return}let l=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 g=l.length-1;g>=0;g--){let b=l[g];if(b.start<=a)if(b.end<=a){for(m.debug("SI: Pushing segment strictly after previous one.",c,a,b.end),this._inventory.splice(g+1,0,f),g+=2;g<l.length&&l[g].start<f.end;){if(l[g].end>f.end){m.debug("SI: Segment pushed updates the start of the next one",c,f.end,l[g].start),l[g].start=f.end,l[g].bufferedStart=void 0,l[g].precizeStart=l[g].precizeStart&&f.precizeEnd;return}m.debug("SI: Segment pushed removes the next one",c,a,s,l[g].start,l[g].end),l.splice(g,1)}return}else if(b.start===a)if(b.end<=s){for(m.debug("SI: Segment pushed replace another one",c,a,s,b.end),this._inventory.splice(g,1,f),g+=1;g<l.length&&l[g].start<f.end;){if(l[g].end>f.end){m.debug("SI: Segment pushed updates the start of the next one",c,f.end,l[g].start),l[g].start=f.end,l[g].bufferedStart=void 0,l[g].precizeStart=l[g].precizeStart&&f.precizeEnd;return}m.debug("SI: Segment pushed removes the next one",c,a,s,l[g].start,l[g].end),l.splice(g,1)}return}else{m.debug("SI: Segment pushed ends before another with the same start",c,a,s,b.end),l.splice(g,0,f),b.start=f.end,b.bufferedStart=void 0,b.precizeStart=b.precizeStart&&f.precizeEnd;return}else if(b.end<=f.end){for(m.debug("SI: Segment pushed updates end of previous one",c,a,s,b.start,b.end),this._inventory.splice(g+1,0,f),b.end=f.start,b.bufferedEnd=void 0,b.precizeEnd=b.precizeEnd&&f.precizeStart,g+=2;g<l.length&&l[g].start<f.end;){if(l[g].end>f.end){m.debug("SI: Segment pushed updates the start of the next one",c,f.end,l[g].start),l[g].start=f.end,l[g].bufferedStart=void 0,l[g].precizeStart=l[g].precizeStart&&f.precizeEnd;return}m.debug("SI: Segment pushed removes the next one",c,a,s,l[g].start,l[g].end),l.splice(g,1)}return}else{m.warn("SI: Segment pushed is contained in a previous one",c,a,s,b.start,b.end);let h={status:b.status,insertionTs:b.insertionTs,chunkSize:b.chunkSize,splitted:!0,start:f.end,end:b.end,precizeStart:b.precizeStart&&b.precizeEnd&&f.precizeEnd,precizeEnd:b.precizeEnd,bufferedStart:void 0,bufferedEnd:b.end,infos:b.infos};b.end=f.start,b.splitted=!0,b.bufferedEnd=void 0,b.precizeEnd=b.precizeEnd&&f.precizeStart,l.splice(g+1,0,f),l.splice(g+2,0,h);return}}let p=this._inventory[0];if(p===void 0){m.debug("SI: first segment pushed",c,a,s),this._inventory.push(f);return}if(p.start>=s)m.debug("SI: Segment pushed comes before all previous ones",c,a,s,p.start),this._inventory.splice(0,0,f);else if(p.end<=s){for(m.debug("SI: Segment pushed starts before and completely recovers the previous first one",c,a,s,p.start,p.end),this._inventory.splice(0,1,f);l.length>1&&l[1].start<f.end;){if(l[1].end>f.end){m.debug("SI: Segment pushed updates the start of the next one",c,f.end,l[1].start),l[1].start=f.end,l[1].bufferedStart=void 0,l[1].precizeStart=f.precizeEnd;return}m.debug("SI: Segment pushed removes the next one",c,a,s,l[1].start,l[1].end),l.splice(1,1)}return}else{m.debug("SI: Segment pushed start of the next one",c,a,s,p.start,p.end),p.start=s,p.bufferedStart=void 0,p.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(Ct(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&&Ct(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,c=t[d].end,l=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=c,this._inventory[a].bufferedEnd=l,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 pd(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}=L.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 Tf(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}=L.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 gh(n,e,t,r){let{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:i,MISSING_DATA_TRIGGER_SYNC_DELAY:o,SEGMENT_SYNCHRONIZATION_DELAY:a}=L.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&&pd(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,pd(n)&&(n.start=t.end,n.precizeStart=!0);else if(n.start-e<=i){let s=V();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,pd(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=V();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 _f(n,e,t){let{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:r,MISSING_DATA_TRIGGER_SYNC_DELAY:i,SEGMENT_SYNCHRONIZATION_DELAY:o}=L.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&&Tf(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=V();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,Tf(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=V();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 hh(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,c=d.infos.representation.id,l=t[u],f;if(l===void 0)f=a(d.infos),t[u]={[c]:f};else{let p=l[c];p===void 0?(f=a(d.infos),l[c]=f):f=p}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 Qn(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 Xn(n,e){for(let t of n)if(t.infos.period.start>e.start)return t;return null}var Ef=gi;var Zn=class{constructor(){this._segmentInventory=new Ef}synchronizeInventory(e){this._segmentInventory.synchronizeBuffered(e)}getLastKnownInventory(){return this._segmentInventory.getInventory()}getSegmentHistory(e){return this._segmentInventory.getHistoryFor(e)}};var hi=class extends Zn{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){vf(t),this._initSegmentsMap.set(e,t)}freeInitSegment(e){this._initSegmentsMap.delete(e)}async pushChunk(e){vf(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,V()),a}e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,V());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 vf(n){if(y.CURRENT_ENV!==y.PRODUCTION&&(typeof n!="object"||n!==null&&!(n instanceof ArrayBuffer)&&!(n.buffer instanceof ArrayBuffer)))throw new Error("Invalid data given to the AudioVideoSegmentSink")}var ua=hi;var yi=class extends Zn{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;Ih(t.chunk);let r=this._sender.pushTextData(de(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,V()),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 Ih(n){if(y.CURRENT_ENV!==y.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")}y.CURRENT_ENV===y.DEV&&(bh=function(e){function t(r){}});var bh;var Rf=yi;var Sh=["audio","video","text"],Ii=class n{static isNative(e){return kf(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():st(e,t=>{let r=Z,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(kf(e)){if(!_(r))return r instanceof ua&&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 ua(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 Rf(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(){Sh.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=>de(oe({},a),{infos:Th(a.infos)}))}}getSegmentSinksMetrics(){return{segmentSinks:{audio:this.createSegmentSinkMetricsForType("audio"),video:this.createSegmentSinkMetricsForType("video"),text:this.createSegmentSinkMetricsForType("text")}}}};function kf(n){return n==="audio"||n==="video"}function Th(n){return{adaptation:n.adaptation.getMetadataSnapshot(),period:n.period.getMetadataSnapshot(),representation:n.representation.getMetadataSnapshot()}}var nn=Ii;var bi=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 gd(n,e,t,r,i){let{period:o,adaptation:a,representation:s}=n,d=_h(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 l=s.index.checkDiscontinuity(e.start);if(l!==null)return{start:void 0,end:l}}return null}let u=i[d];if(u.bufferedStart!==void 0&&u.bufferedStart>e.start&&(t===null||u.infos.segment.end<=t)){let l=u.bufferedStart;return!r&&s.index.awaitSegmentBetween(e.start,l)!==!1?null:(m.debug("RS: current discontinuity encountered",a.type,u.bufferedStart),{start:void 0,end:l})}let c=Eh(i,e,d+1);if(c!==null){let l=i[c-1],f=i[c];if(t===null||f.infos.segment.end<=t){if(!r&&s.index.awaitSegmentBetween(l.infos.segment.end,f.infos.segment.time)!==!1)return null;let p=l.bufferedEnd,g=f.bufferedStart;return m.debug("RS: future discontinuity encountered",a.type,p,g),{start:p,end:g}}}if(t===null){if(r&&o.end!==void 0){if(e.end<o.end)return null;let l=vh(i,o.end);if(l!==null){let f=i[l];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 l=i.length-1;l>=0;l--){let f=i[l];if(f.bufferedStart===void 0)break;if(f.bufferedStart<e.end){if(f.bufferedEnd!==void 0&&f.bufferedEnd<e.end){let p=s.index.checkDiscontinuity(e.end);if(p!==null)return{start:f.bufferedEnd,end:p}}return null}}}return null}function _h(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 Eh(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 vh(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 hd({bufferedSegments:n,content:e,currentPlaybackTime:t,fastSwitchThreshold:r,getBufferedHistory:i,neededRange:o,segmentsBeingPushed:a,maxBufferSize:s}){let{adaptation:d,representation:u}=e,c=Rh(n,a,s),l=u.index.getSegments(o.start,o.end-o.start),f=n.filter(v=>!Pf(v.infos,e,t,r)),p=wh(f,o,i),{MINIMUM_SEGMENT_SIZE:g,MIN_BUFFER_AHEAD:b}=L.getCurrent(),h=!1,I=Math.min(1/60,g),T=!1,R=[];return{segmentsToLoad:l.filter(v=>{let k=Y({segment:v},e);if(a.length>0&&a.some(F=>Ct(k,F)))return!1;let{duration:x,time:P,end:M}=v;if(v.isInit)return!0;if(h)return R.push(v),!1;if(v.complete&&x<g||a.length>0&&a.some(F=>{if(F.period.id!==e.period.id||F.adaptation.id!==e.adaptation.id)return!1;let{segment:A}=F;if(A.time-I>P)return!1;if(A.complete){if(A.end+I<M)return!1}else if(Math.abs(P-A.time)>P)return!1;return!Pf(F,k,t,r)}))return!1;for(let D of p){let F=D.infos.period.id===e.period.id;if(D.status===1&&F){let A=D.infos.segment;if(P-A.time>-I){if(A.complete){if(A.end-M>-I)return!1}else if(Math.abs(P-A.time)<I)return!1}}}let O=x*e.representation.bitrate;if(c-O<0&&(T=!0,P>o.start+b))return h=!0,R.push(v),!1;let B=i(k);if(B.length>1){let D=B[B.length-1],F=B[B.length-2];if(D.buffered===null&&F.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,v.time),!1}for(let D=0;D<p.length;D++){let F=p[D];if(F.end+I>P){let A=F.start>P+I||kh(p,D).end<M-I;return A&&(c-=O),A}}return c-=O,!0}),segmentsOnHold:R,isBufferFull:T}}function Rh(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 kh(n,e){let t=e+1,{MINIMUM_SEGMENT_SIZE:r}=L.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}=L.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:Ph(n.representation,e.representation,r)}function Ph(n,e,t){let r=n.bitrate,{BITRATE_REBUFFERING_RATIO:i}=L.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}=L.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 Mh(n,e,t){let{MAX_TIME_MISSING_FROM_COMPLETE_SEGMENT:r}=L.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 Ah(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 xh(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 wh(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),Ah(d,r.bufferedStart))return!1;m.debug("Stream: skipping segment gc-ed at the start",r.start,r.bufferedStart)}if(Mh(r,s,e.end)){if(d=d!=null?d:t(r.infos),xh(d,r.bufferedEnd))return!1;m.debug("Stream: skipping segment gc-ed at the end",r.end,r.bufferedEnd)}return!0})}function Si(n,e){let t=n-e,{SEGMENT_PRIORITIES_STEPS:r}=L.getCurrent();for(let i=0;i<r.length;i++)if(t<r[i])return i;return r.length}function yd(n,e,t,r,i,o,a){var P,M,O;let{representation:s}=n,d=(M=(P=t.getIsPaused())!=null?P:t.getReference().getValue().paused.pending)!=null?M:t.getReference().getValue().paused.last,u=(O=t.getPlaybackRate())!=null?O:t.getReference().getValue().speed,c=e;(d===void 0||u===void 0||d||u<=0)&&(c-=.1);let l=Oh(n,c,i),f=s.index.shouldRefresh(l.start,l.end),p=a.getPendingOperations().filter(B=>B.type===2).map(B=>B.value),g=a.getLastKnownInventory(),b=t.getCurrentTime();b===void 0&&(b=t.getReference().getValue().position.getWanted());let h=a.getSegmentHistory.bind(a),{segmentsToLoad:I,segmentsOnHold:T,isBufferFull:R}=hd({content:n,bufferedSegments:g,currentPlaybackTime:b,fastSwitchThreshold:r,getBufferedHistory:h,neededRange:l,segmentsBeingPushed:p,maxBufferSize:o}),E=I.map(B=>({priority:Si(B.time,c),segment:B})),v=s.index.isInitialized()&&!s.index.isStillAwaitingFutureSegments()&&l.hasReachedPeriodEnd&&E.length===0&&T.length===0,k=null;return p.length>0&&(k=Math.min(...p.map(B=>B.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:gd(n,l,k,v,g),hasFinishedLoading:v,neededSegments:E,isBufferFull:R,shouldRefreshManifest:f}}function Oh(n,e,t){var l;let r,{manifest:i,period:o,representation:a}=n,s=a.index.getLastAvailablePosition(),d=a.index;!_(s)&&nn.isNative(n.adaptation.type)&&e>=s&&d.isInitialized()&&!d.isStillAwaitingFutureSegments()&&Dh(i,o,e)?r=s-1:r=e-.1;let u=r+t,c;return!a.index.isInitialized()||a.index.isStillAwaitingFutureSegments()||o.end===void 0?c=!1:s===void 0?c=u>=o.end:s===null?c=!0:c=u>=s,{start:Math.max(r,o.start),end:Math.min(u,(l=o.end)!=null?l:1/0),hasReachedPeriodEnd:c}}function Dh(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 Ti(n,e,t,r,i){try{return await e.pushChunk(t)}catch(o){if(i.isCancelled()&&o instanceof Pe)throw o;if(!(o instanceof at)||!o.isBufferFull){let d=o instanceof Error?o.toString():"An unknown error happened when pushing content";throw new te("BUFFER_APPEND_ERROR",d,{tracks:[Qt(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 Sn(200),i.cancellationError!==null)throw i.cancellationError;return await e.pushChunk(t)}catch(d){if(d instanceof Pe)throw d;let u=d instanceof Error?d.toString():"Could not clean the buffer";throw new te("BUFFER_FULL_ERROR",u,{tracks:[Qt(t.inventoryInfos.adaptation)]})}}}async function Id({playbackObserver:n,content:e,initSegmentUniqueId:t,segment:r,segmentSink:i,bufferGoal:o},a){let s=e.representation.getMimeTypeString(),d={initSegmentUniqueId:t,chunk:null,timestampOffset:0,appendWindow:[void 0,void 0],codec:s},u=Y({segment:r,chunkSize:void 0,start:0,end:0},e),c=await Ti(n,i,{data:d,inventoryInfos:u},o,a);return{content:e,segment:r,buffered:c}}async function bd({playbackObserver:n,bufferGoal:e,content:t,initSegmentUniqueId:r,parsedSegment:i,segment:o,segmentSink:a},s){var k,x;if(i.chunkData===null)return null;let{chunkData:d,chunkInfos:u,chunkOffset:c,chunkSize:l,appendWindow:f}=i,p=t.representation.getMimeTypeString(),{APPEND_WINDOW_SECURITIES:g}=L.getCurrent(),b=[f[0]!==void 0?Math.max(0,f[0]-g.START):void 0,f[1]!==void 0?f[1]+g.END:void 0],h={initSegmentUniqueId:r,chunk:d,timestampOffset:c,appendWindow:b,codec:p},I=(k=u==null?void 0:u.time)!=null?k:o.time,T=(x=u==null?void 0:u.duration)!=null?x:o.duration,R=I+T;b[0]!==void 0&&(I=Math.max(I,b[0])),b[1]!==void 0&&(R=Math.min(R,b[1]));let E=Y({segment:o,chunkSize:l,start:I,end:R},t),v=await Ti(n,a,{data:h,inventoryInfos:E},e,s);return{content:t,segment:o,buffered:v}}function Sd({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:c}=n,{bufferGoal:l,maxBufferSize:f,drmSystemId:p,fastSwitchThreshold:g}=e,b=u.type,h=new U;h.linkToSignal(s);let I={segment:c.index.getInitSegment(),uniqueId:null,isLoaded:!1};h.signal.register(()=>{I.uniqueId!==null&&r.freeInitSegment(I.uniqueId)});let T=I.segment!==null;T||(I.isLoaded=!0);let R=!1;if(p!==void 0){let P=c.getEncryptionData(p);if(P.length>0&&P.every(M=>M.keyIds!==void 0)&&(R=!0,a.encryptionDataEncountered(P.map(M=>Y({content:n},M))),h.isUsed()))return}i.addEventListener("error",P=>{h.signal.isCancelled()||(h.cancel(),a.error(P))}),i.addEventListener("parsedInitSegment",k,h.signal),i.addEventListener("parsedMediaSegment",k,h.signal),i.addEventListener("emptyQueue",v,h.signal),i.addEventListener("requestRetry",P=>{if(a.warning(P.error),h.signal.isCancelled())return;let M=P.segment,{index:O}=c;O.isSegmentStillAvailable(M)===!1?v():O.canBeOutOfSyncError(P.error,M)&&a.manifestMightBeOufOfSync()},h.signal),i.addEventListener("fullyLoadedSegment",P=>{r.signalSegmentComplete(Y({segment:P},n)).catch(x)},h.signal);let E=i.resetForContent(n,T);h.signal.register(()=>{i.stop()}),t.listen(v,{includeLastObservation:!1,clearSignal:h.signal}),n.manifest.addEventListener("manifestUpdate",v,h.signal),l.onUpdate(v,{emitCurrentValue:!1,clearSignal:h.signal}),f.onUpdate(v,{emitCurrentValue:!1,clearSignal:h.signal}),o.onUpdate(v,{emitCurrentValue:!1,clearSignal:h.signal}),v();return;function v(){if(h.isUsed())return;let P=t.getReference().getValue(),M=P.position.getWanted(),O=yd(n,M,t,g.getValue(),l.getValue(),f.getValue(),r),{neededSegments:B}=O,D=null;if(c.index.isInitialized()){if(B.length>0&&!I.isLoaded&&I.segment!==null){let C=B[0].priority;D={segment:I.segment,priority:C}}}else if(I.segment===null)m.warn("Stream: Uninitialized index without an initialization segment");else if(I.isLoaded)m.warn("Stream: Uninitialized index with an already loaded initialization segment");else{let C=P.position.getWanted();D={segment:I.segment,priority:Si(d.start,C)}}let F=o.getValue();if(F===null)E.setValue({initSegment:D,segmentQueue:B});else if(F.urgent){m.debug("Stream: Urgent switch, terminate now.",b),E.setValue({initSegment:null,segmentQueue:[]}),E.finish(),h.cancel(),a.terminating();return}else{let C=B[0],N=i.getRequestedInitSegment(),K=i.getRequestedMediaSegment(),j=K===null||C===void 0||K.id!==C.segment.id?[]:[C],$=N===null?null:D;if(E.setValue({initSegment:$,segmentQueue:j}),j.length===0&&$===null){m.debug("Stream: No request left, terminate",b),E.finish(),h.cancel(),a.terminating();return}}if(a.streamStatusUpdate({period:d,position:P.position.getWanted(),bufferType:b,imminentDiscontinuity:O.imminentDiscontinuity,isEmptyStream:!1,hasFinishedLoading:O.hasFinishedLoading,neededSegments:O.neededSegments}),h.signal.isCancelled())return;let{UPTO_CURRENT_POSITION_CLEANUP:A}=L.getCurrent();if(O.isBufferFull){let C=Math.max(0,M-A);C>0&&r.removeBuffer(0,C).catch(x)}O.shouldRefreshManifest&&a.needsManifestRefresh()}function k(P){for(let M of P.protectionData)c.addProtectionData(M.initDataType,M.keyId,M.initData);if(!R){let M=c.getAllEncryptionData();M.length>0&&(a.encryptionDataEncountered(M.map(O=>Y({content:n},O))),R=!0)}if(P.segmentType==="init"){if(!c.index.isInitialized()&&P.segmentList!==void 0&&c.index.initialize(P.segmentList),I.isLoaded=!0,P.initializationData!==null){let M=c.uniqueId;I.uniqueId=M,r.declareInitSegment(M,P.initializationData),Id({playbackObserver:t,bufferGoal:l,content:n,initSegmentUniqueId:M,segment:P.segment,segmentData:P.initializationData,segmentSink:r},h.signal).then(O=>{O!==null&&a.addedSegment(O)}).catch(x)}v();return}else{let{inbandEvents:M,predictedSegments:O,needsManifestRefresh:B}=P;if(O!==void 0&&c.index.addPredictedSegments(O,P.segment),B===!0&&(a.needsManifestRefresh(),h.isUsed())||M!==void 0&&M.length>0&&(a.inbandEvent(M),h.isUsed()))return;let D=I.uniqueId;bd({playbackObserver:t,bufferGoal:l,content:n,initSegmentUniqueId:D,parsedSegment:P,segment:P.segment,segmentSink:r},h.signal).then(F=>{F!==null&&a.addedSegment(F)}).catch(x)}}function x(P){h.isUsed()&&P instanceof Pe||(m.warn("Stream: Received fatal buffer error",u.type,c.bitrate,P instanceof Error?P:null),h.cancel(),a.error(P))}}var Cf=Sd;function Td(n,e,t,r,i){var f,p,g,b;if(t.switchingMode==="lazy")return{type:"continue",value:void 0};let o=r.getLastKnownInventory(),a=[];for(let h of o)h.infos.period.id===n.id&&(h.infos.adaptation.id!==e.id||!X(t.representationIds,h.infos.representation.id))&&jt(a,{start:(f=h.bufferedStart)!=null?f:h.start,end:(p=h.bufferedEnd)!=null?p:h.end});let s=r.getPendingOperations();for(let h of s)if(h.type===0){let I=h.value.inventoryInfos;if(I.period.id===n.id&&(I.adaptation.id!==e.id||!X(t.representationIds,I.representation.id))){let T=I.segment.time,R=T+I.segment.duration;jt(a,{start:T,end:R})}}if(a.length===0)return{type:"continue",value:void 0};if(t.switchingMode==="reload"){let h=i.getReadyState();if(h===void 0||h>1)return{type:"needs-reload",value:void 0}}let d=t.switchingMode==="direct",u=[],c=Qn(o,n);if(c!==null&&(c.bufferedEnd===void 0||n.start-c.bufferedEnd<1)&&u.push({start:0,end:n.start+1}),!d){let{ADAP_REP_SWITCH_BUFFER_PADDINGS:h}=L.getCurrent(),I=e.type,T=(g=h[I].before)!=null?g:0,R=(b=h[I].after)!=null?b:0,E=i.getCurrentTime();E===void 0&&(E=i.getReference().getValue().position.getPolled()),u.push({start:E-T,end:E+R})}if(n.end!==void 0){let h=Xn(o,n);h!==null&&(h.bufferedStart===void 0||h.bufferedStart-n.end<1)&&u.push({start:n.end-1,end:Number.MAX_VALUE})}let l=To(a,u);return l.length===0?{type:"continue",value:void 0}:d?{type:"flush-buffer",value:l}:{type:"clean-buffer",value:l}}function _d({playbackObserver:n,content:e,options:t,representationEstimator:r,segmentSink:i,segmentQueueCreator:o,wantedBufferAhead:a,maxVideoBufferSize:s},d,u){let{manifest:c,period:l,adaptation:f}=e,p=new U;p.linkToSignal(u);let g=new Map,b=new G(null,p.signal),h,I=e.representations.getValue().representationIds,T=Mf(e.adaptation.representations,I),R=new G(T,p.signal),{estimates:E,callbacks:v}=r({manifest:c,period:l,adaptation:f},b,R,n,p.signal),k=new G(!1);n.listen(A=>{var N;let C=(N=A.canStream)!=null?N:!0;k.getValue()===C&&(m.debug("Stream: isMediaSegmentQueueInterrupted updated to",!C),k.setValue(!C))},{clearSignal:p.signal});let x=o.createSegmentQueue(f.type,{onRequestBegin:v.requestBegin,onRequestEnd:v.requestEnd,onProgress:v.requestProgress,onMetrics:v.metrics},k),P=new G(0);E.onUpdate(({bitrate:A,knownStableBitrate:C})=>{t.enableFastSwitching&&P.setValueIfChanged(C),!(A===void 0||A===h)&&(h=A,m.debug(`Stream: new ${f.type} bitrate estimate`,A),d.bitrateEstimateChange({type:f.type,bitrate:A}))},{emitCurrentValue:!0,clearSignal:p.signal});let M;e.representations.onUpdate(A=>{M!==void 0&&M.cancel();let C=e.representations.getValue().representationIds,N=Mf(e.adaptation.representations,C);R.setValueIfChanged(N),M=new U,M.linkToSignal(p.signal),O(A,M.signal).catch(K=>{(M==null?void 0:M.isUsed())===!0&&U.isCancellationError(K)||(p.cancel(),d.error(K))})},{clearSignal:p.signal,emitCurrentValue:!0});return;async function O(A,C){let N=Td(l,f,A,i,n);switch(N.type){case"continue":break;case"needs-reload":return Rt(()=>{n.listen(()=>{if(C.isCancelled())return;let{DELTA_POSITION_AFTER_RELOAD:K}=L.getCurrent(),j=K.bitrateSwitch;return d.waitingMediaSourceReload({bufferType:f.type,period:l,timeOffset:j,stayInPeriod:!0})},{includeLastObservation:!0,clearSignal:C})});case"flush-buffer":case"clean-buffer":for(let K of N.value)if(await i.removeBuffer(K.start,K.end),C.isCancelled())return;if(N.type==="flush-buffer"&&(d.needsBufferFlush(),C.isCancelled()))return;break;default:He(N)}B(C)}function B(A){let C=new U;C.linkToSignal(A);let{representation:N}=E.getValue();if(N===null)return;let K=new G(null,C.signal);E.onUpdate(z=>{if(!(z.representation===null||z.representation.id===N.id))return z.urgent?(m.info("Stream: urgent Representation switch",f.type),K.setValue({urgent:!0})):(m.info("Stream: slow Representation switch",f.type),K.setValue({urgent:!1}))},{clearSignal:C.signal,emitCurrentValue:!0});let j={type:f.type,adaptation:f,period:l,representation:N};if(b.setValue(N),A.isCancelled()||(d.representationChange(j),A.isCancelled()))return;let $={streamStatusUpdate:d.streamStatusUpdate,encryptionDataEncountered:d.encryptionDataEncountered,manifestMightBeOufOfSync:d.manifestMightBeOufOfSync,needsManifestRefresh:d.needsManifestRefresh,inbandEvent:d.inbandEvent,warning:d.warning,error(z){p.cancel(),d.error(z)},addedSegment(z){v.addedSegment(z)},terminating(){if(!C.isUsed())return C.cancel(),B(A)}};D(N,K,$,A)}function D(A,C,N,K){let j=!1,$=new U;$.linkToSignal(K);let z=cn(a,ie=>F(A,ie),$.signal),H=f.type==="video"?s:new G(1/0);m.info("Stream: changing representation",f.type,A.id,A.bitrate);let q=Y({},N,{error(ie){var le;if(j){m.warn("Stream: Ignoring RepresentationStream error",ie);return}j=!0;let ne=Ee(ie,{defaultCode:"NONE",defaultReason:"Unknown `RepresentationStream` error"});if(ne.code!=="BUFFER_FULL_ERROR")N.error(ie);else{m.warn("Stream: received BUFFER_FULL_ERROR",f.type,A.bitrate);let be=a.getValue(),W=((le=g.get(A.id))!=null?le:1)*.7;if(g.set(A.id,W),W<=.05||F(A,be)<=2){N.error(ne);return}Xt(4e3,K).then(()=>D(A,C,N,K)).catch(Z)}},terminating(){$.cancel(),N.terminating()}});Cf({playbackObserver:n,content:{representation:A,adaptation:f,period:l,manifest:c},segmentSink:i,segmentQueue:x,terminate:C,options:{bufferGoal:z,maxBufferSize:H,drmSystemId:t.drmSystemId,fastSwitchThreshold:P}},q,K),c.addEventListener("manifestUpdate",ie=>{for(let ne of ie.updatedPeriods)if(ne.period.id===l.id){for(let le of ne.result.updatedAdaptations)if(le.adaptation===f.id){for(let be of le.removedRepresentations)if(be===A.id)return K.isCancelled()?void 0:d.waitingMediaSourceReload({bufferType:f.type,period:l,timeOffset:0,stayInPeriod:!0})}}else if(ne.period.start>l.start)break},K)}function F(A,C){let N=g.get(A.id),K=N!==void 0?N:1;return N===void 0&&g.set(A.id,K),K<1&&C===1/0?5*60*1e3*K:C*K}}function Mf(n,e){let t=n.filter(r=>X(e,r.id)&&!r.shouldBeAvoided&&r.isPlayable()!==!1);return t.length>0?t:n.filter(r=>X(e,r.id)&&r.isPlayable()!==!1)}var Af=_d;function Ed(n,e,t,r,i,o){var p,g,b,h;if(n.codec!==void 0&&o.onCodecSwitch==="reload"&&!Lh(t,n.codec))return{type:"needs-reload",value:void 0};let a=n.getLastKnownInventory(),s=[];for(let I of a)I.infos.period.id===e.id&&I.infos.adaptation.id!==t.id&&jt(s,{start:(p=I.bufferedStart)!=null?p:I.start,end:(g=I.bufferedEnd)!=null?g:I.end});let d=n.getPendingOperations();for(let I of d)if(I.type===0){let T=I.value.inventoryInfos;if(T.period.id===e.id&&T.adaptation.id!==t.id){let R=T.segment.time,E=R+T.segment.duration;jt(s,{start:R,end:E})}}if(s.length===0)return{type:"continue",value:void 0};if(r==="reload"){let I=i.getReadyState();if(I===void 0||I>1)return{type:"needs-reload",value:void 0}}let u=r==="direct",c=[],l=Qn(a,e);if(l!==null&&(l.bufferedEnd===void 0||e.start-l.bufferedEnd<1)&&c.push({start:0,end:e.start+1}),!u){let I=t.type,{ADAP_REP_SWITCH_BUFFER_PADDINGS:T}=L.getCurrent(),R=(b=T[I].before)!=null?b:0,E=(h=T[I].after)!=null?h:0,v=i.getCurrentTime();v===void 0&&(v=i.getReference().getValue().position.getPolled()),c.push({start:v-R,end:v+E})}if(e.end!==void 0){let I=Xn(a,e);I!==null&&(I.bufferedStart===void 0||I.bufferedStart-e.end<1)&&c.push({start:e.end-1,end:Number.MAX_VALUE})}let f=To(s,c);return f.length===0?{type:"continue",value:void 0}:u&&t.type!=="text"?{type:"flush-buffer",value:f}:{type:"clean-buffer",value:f}}function Lh(n,e){return n.representations.some(t=>t.isPlayable()===!0&&ta(t.getMimeTypeString(),e))}function vd({bufferType:n,content:e,garbageCollectors:t,playbackObserver:r,representationEstimator:i,segmentQueueCreator:o,segmentSinksStore:a,options:s,wantedBufferAhead:d,maxVideoBufferSize:u},c,l){let{manifest:f,period:p}=e,g=new G(void 0,l);if(c.periodStreamReady({type:n,manifest:f,period:p,adaptationRef:g}),l.isCancelled())return;let b,h=!0;g.onUpdate(R=>{(async()=>{var F;if(R===void 0)return;let E=new U;if(E.linkToSignal(l),b==null||b.cancel(),b=E,R===null){m.info(`Stream: Set no ${n} Adaptation. P:`,p.start);let A=a.getStatus(n);if(A.type==="initialized"){if(m.info(`Stream: Clearing previous ${n} SegmentSink`),nn.isNative(n))return T(0,!0,E.signal);{let C=(F=p.end)!=null?F:1/0;if(p.start>C)m.warn("Stream: Can't free buffer: period's start is after its end");else if(await A.value.removeBuffer(p.start,C),E.isUsed())return}}else if(A.type==="uninitialized"&&(a.disableSegmentSink(n),E.isUsed()))return;return c.adaptationChange({type:n,adaptation:null,period:p}),E.isUsed()?void 0:xf(r,d,n,{period:p},c,E.signal)}let v=p.adaptations[n],k=Q(v!=null?v:[],A=>A.id===R.adaptationId);if(k===void 0){b.cancel(),m.warn("Stream: Unfound chosen Adaptation choice",R.adaptationId);return}let{DELTA_POSITION_AFTER_RELOAD:x}=L.getCurrent(),P=!1,M;if(h)M=0;else if(R.relativeResumingPosition!==void 0)M=R.relativeResumingPosition;else switch(P=!0,n){case"audio":M=x.trackSwitch.audio;break;case"video":M=x.trackSwitch.video;break;default:M=x.trackSwitch.other;break}if(h=!1,nn.isNative(n)&&a.getStatus(n).type==="disabled")return T(M,!0,E.signal);f.addEventListener("manifestUpdate",A=>{for(let C of A.updatedPeriods)if(C.period.id===p.id){for(let N of C.result.removedAdaptations)if(N.id===k.id)return T(M,!0,E.signal)}else if(C.period.start>p.start)break},b.signal);let{representations:O}=R;if(m.info(`Stream: Updating ${n} adaptation`,`A: ${k.id}`,`P: ${p.start}`),c.adaptationChange({type:n,adaptation:k,period:p}),E.isUsed())return;let B=Nh(a,n,k),D=Ed(B,p,k,R.switchingMode,r,s);if(D.type==="needs-reload")return T(M,!0,E.signal);if(await a.waitForUsableBuffers(E.signal),!E.isUsed()){if(D.type==="flush-buffer"||D.type==="clean-buffer"){for(let{start:A,end:C}of D.value)if(await B.removeBuffer(A,C),E.isUsed())return;if(D.type==="flush-buffer"&&(c.needsBufferFlush({relativeResumingPosition:M,relativePosHasBeenDefaulted:P}),E.isUsed()))return}t.get(B)(E.signal),I(k,O,B,E.signal)}})().catch(E=>{E instanceof Pe||(b==null||b.cancel(),c.error(E))})},{clearSignal:l,emitCurrentValue:!0});function I(R,E,v,k){let x=Bh(r,R.type);Af({content:{manifest:f,period:p,adaptation:R,representations:E},options:s,playbackObserver:x,representationEstimator:i,segmentSink:v,segmentQueueCreator:o,wantedBufferAhead:d,maxVideoBufferSize:u},de(oe({},c),{error:P}),k);function P(M){if(!nn.isNative(n)){m.error(`Stream: ${n} Stream crashed. Aborting it.`,M instanceof Error?M:""),a.disposeSegmentSink(n);let O=Ee(M,{defaultCode:"NONE",defaultReason:"Unknown `AdaptationStream` error"});return c.warning(O),k.isCancelled()?void 0:xf(r,d,n,{period:p},c,k)}m.error(`Stream: ${n} Stream crashed. Stopping playback.`,M instanceof Error?M:""),c.error(M)}}function T(R,E,v){Rt(()=>{r.listen(()=>{v.isCancelled()||c.waitingMediaSourceReload({bufferType:n,period:p,timeOffset:R,stayInPeriod:E})},{includeLastObservation:!0,clearSignal:v})})}}function Nh(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=Uh(t);return n.createSegmentSink(e,i)}function Uh(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:[Qt(n)]});return e[0].getMimeTypeString()}function Bh(n,e){return n.deriveReadOnlyObserver(function(r,i){let o=new G(a(),i);return r.onUpdate(s,{clearSignal:i,emitCurrentValue:!1}),o;function a(){let d=r.getValue(),u=d.buffered[e],c=u!==null?So(u,d.position.getWanted()):0;return Y({},d,{bufferGap:c,buffered:u})}function s(){o.setValue(a())}})}function xf(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(),c=e.getValue(),l=u.position.getWanted();a.end!==void 0&&l+c>=a.end&&(m.debug('Stream: full "empty" AdaptationStream',t),s=!0),i.streamStatusUpdate({period:a,bufferType:t,imminentDiscontinuity:null,position:l,isEmptyStream:!0,hasFinishedLoading:s,neededSegments:[]})}}var wf=vd;function la(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 Rd(n,e,t,r,i,o,a,s){let{manifest:d,initialPeriod:u}=n,{maxBufferAhead:c,maxBufferBehind:l,wantedBufferAhead:f,maxVideoBufferSize:p}=o,{MINIMUM_MAX_BUFFER_AHEAD:g,MAXIMUM_MAX_BUFFER_AHEAD:b,MAXIMUM_MAX_BUFFER_BEHIND:h}=L.getCurrent(),I=new bi(E=>{var P,M;let{bufferType:v}=E,k=(P=h[v])!=null?P:1/0,x=(M=b[v])!=null?M:1/0;return O=>{sa({segmentSink:E,playbackObserver:e,maxBufferBehind:cn(l,B=>Math.min(B,k),O),maxBufferAhead:cn(c,B=>{var F;let D=Math.max(B,(F=g[v])!=null?F:0);return Math.min(D,x)},O)},O)}});for(let E of r.getBufferTypes())T(E,u);function T(E,v){let k=new vn((D,F)=>D.start-F.start),x=!1,P=new U;return P.linkToSignal(s),e.listen(({position:D})=>{var C;let F=D.getWanted();if(!x||!O(F))return;for(m.info("Stream: Destroying all PeriodStreams due to out of bounds situation",E,F),x=!1;k.length()>0;){let N=k.get(k.length()-1);k.removeElement(N),a.periodStreamCleared({type:E,manifest:d,period:N})}P.cancel(),P=new U,P.linkToSignal(s);let A=(C=d.getPeriodForTime(F))!=null?C:d.getNextPeriod(F);if(A===void 0){m.warn("Stream: The wanted position is not found in the Manifest."),x=!0;return}M(A)},{clearSignal:s,includeLastObservation:!0}),d.addEventListener("decipherabilityUpdate",D=>{s.isCancelled()||B(D).catch(F=>{s.isCancelled()||(P.cancel(),a.error(F))})},s),M(v);function M(D){let F=de(oe({},a),{waitingMediaSourceReload(A){let C=k.head();C===void 0||C.id!==A.period.id?a.lockedStream({bufferType:A.bufferType,period:A.period}):a.needsMediaSourceReload({timeOffset:A.timeOffset,minimumPosition:A.stayInPeriod?A.period.start:void 0,maximumPosition:A.stayInPeriod?A.period.end:void 0})},periodStreamReady(A){x=!0,k.add(A.period),a.periodStreamReady(A)},periodStreamCleared(A){k.removeElement(A.period),a.periodStreamCleared(A)},error(A){P.cancel(),a.error(A)}});R(E,D,F,P.signal)}function O(D){let F=k.head(),A=k.last();return F===void 0||A===void 0?!0:F.start>D||(_(A.end)?1/0:A.end)<D}async function B(D){let F=r.getStatus(E),A=D.filter(z=>z.adaptation.type===E);if(A.length===0||F.type!=="initialized"||A.every(z=>z.representation.decipherable===!0))return;let C=F.value,N=A.filter(z=>z.representation.decipherable===void 0),K=A.filter(z=>z.representation.decipherable===!1),j=la(C,K),$=la(C,N);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})}P.cancel(),P=new U,P.linkToSignal(s);for(let{start:z,end:H}of[...j,...$]){if(s.isCancelled())return;if(z<H){if(s.isCancelled())return;await C.removeBuffer(z,H)}}Rt(()=>{if(s.isCancelled())return;let z=e.getReference().getValue();if(Of(z,j)){if(a.needsDecipherabilityFlush(),s.isCancelled())return}else if(Of(z,$)&&(a.needsBufferFlush(),s.isCancelled()))return;let H=z.position.getWanted(),q=d.getPeriodForTime(H);if(q===void 0){a.error(new te("MEDIA_TIME_NOT_FOUND","The wanted position is not found in the Manifest."));return}M(q)})}}function R(E,v,k,x){m.info("Stream: Creating new Stream for",E,v.start);let P=null,M=new U;M.linkToSignal(x),e.listen(({position:A},C)=>{if(v.end!==void 0&&A.getWanted()>=v.end){let N=d.getPeriodAfter(v);if(v.containsTime(A.getWanted(),N))return;m.info("Stream: Destroying PeriodStream as the current playhead moved above it",E,v.start,A.getWanted(),v.end),C(),k.periodStreamCleared({type:E,manifest:d,period:v}),M.cancel()}},{clearSignal:x,includeLastObservation:!0});let O={bufferType:E,content:{manifest:d,period:v},garbageCollectors:I,maxVideoBufferSize:p,segmentQueueCreator:i,segmentSinksStore:r,options:o,playbackObserver:e,representationEstimator:t,wantedBufferAhead:f},B=de(oe({},k),{streamStatusUpdate(A){if(A.hasFinishedLoading){let C=d.getPeriodAfter(v);C!==null&&D(C)}else P!==null&&(m.info("Stream: Destroying next PeriodStream due to current one being active",E,P.period.start),k.periodStreamCleared({type:E,manifest:d,period:P.period}),P.canceller.cancel(),P=null);k.streamStatusUpdate(A)},error(A){P!==null&&(P.canceller.cancel(),P=null),M.cancel(),k.error(A)}});wf(O,B,M.signal),F(M.signal);function D(A){if(P!==null){if(P.period.id===A.id)return;m.warn("Stream: Creating next `PeriodStream` while one was already created.",E,A.id,P.period.id),k.periodStreamCleared({type:E,manifest:d,period:P.period}),P.canceller.cancel()}let C=new U;C.linkToSignal(x),P={canceller:C,period:A},R(E,A,k,P.canceller.signal)}function F(A){d.addEventListener("manifestUpdate",C=>{for(let N of C.removedPeriods)if(N.id===v.id){if(d.periods.length>0&&d.periods[0].start<=N.start)return Rt(()=>{if(!A.isCancelled())return a.needsMediaSourceReload({timeOffset:0,minimumPosition:void 0,maximumPosition:void 0})})}else if(N.start>v.start)break;if(C.addedPeriods.length>0&&P!==null){let N=d.getPeriodAfter(v);(N===null||P.period.id!==N.id)&&(m.warn("Stream: Destroying next PeriodStream due to new one being added",E,P.period.start),k.periodStreamCleared({type:E,manifest:d,period:P.period}),P.canceller.cancel(),P=null)}},A)}}}function Of(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 Df=Rd;var Lf=Df;var Fh={dashParsers:{wasm:null,native:null,fastJs:null},createDebugElement:null,directfile:null,decrypt:null,htmlTextDisplayer:null,htmlTextTracksParsers:{},mainThreadMediaSourceInit:null,multithread:null,nativeTextDisplayer:null,nativeTextTracksParsers:{},transports:{}},_i=Fh;function ca(n){for(let e of n)if(typeof e=="function")e(_i);else if(!_(e)&&typeof e._addFeature=="function")e._addFeature(_i);else throw new Error("Unrecognized feature")}var fe=_i;var Kh={createSync(n){return{syncValue:n,getValueAsAsync(){return Promise.resolve(n)}}},createAsync(n){let e=null;return n.then(t=>{e=t},Z),{get syncValue(){return e},getValueAsAsync(){return n}}}},Nf=Kh;var Jn=class extends ae{};function kd(n,e){let t={audio:null,video:null,text:null};if(e!==null&&(t.text=e.getBufferedRanges()),n===null)return t;let r=Q(n.sourceBuffers,s=>s.type==="audio"),i=Q(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 Pd(n,{autoPlay:e,initialPlayPerformed:t,manifest:r,mediaSource:i,speed:o,textDisplayer:a},s){return n.deriveReadOnlyObserver(function(u,c){let l=new U;l.linkToSignal(c),l.linkToSignal(s);let f=new G(p(),l.signal);return o.onUpdate(g,{clearSignal:l.signal,emitCurrentValue:!1}),u.onUpdate(g,{clearSignal:l.signal,emitCurrentValue:!1}),i==null||i.addEventListener("streamingChanged",()=>{g()},l.signal),f;function p(){var I;let b=u.getValue(),h=o.getValue();return Vh(b,r),{maximumPosition:Tt(r),bufferGap:b.bufferGap,position:b.position,buffered:kd(i,a),duration:b.duration,rebuffering:b.rebuffering,freezing:b.freezing,paused:{last:b.paused,pending:zh(t,e)},readyState:b.readyState,speed:h,canStream:(I=i==null?void 0:i.streaming)!=null?I:!0,fullyLoaded:b.fullyLoaded}}function g(){f.setValue(p())}})}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 zh(n,e){return n.getValue()?void 0:!e}function er(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 Cd(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 Hh(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t];r.updating&&e.push(r)}return e}function Ei(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=Hh(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 U;i.linkToSignal(e);for(let o of r)Oc(o,()=>{i.cancel(),Ei(n,e)},i.signal);Dc(t,()=>{i.cancel(),Ei(n,e)},i.signal)}function Uf(n,e){let t=new U;t.linkToSignal(e),zn(n,()=>{m.debug("Init: MediaSource re-opened while end-of-stream is active"),t.cancel(),t=new U,t.linkToSignal(e),Ei(n,t.signal)},e),Ei(n,t.signal)}function Md(){return pn}var Wh=365*24*3600,vi=class{constructor(e){this._mediaSource=e,this._currentMediaSourceDurationUpdateCanceller=null}updateDuration(e,t){this._currentMediaSourceDurationUpdateCanceller!==null&&this._currentMediaSourceDurationUpdateCanceller.cancel(),this._currentMediaSourceDurationUpdateCanceller=new U;let r=this._mediaSource,i=this._currentMediaSourceDurationUpdateCanceller.signal,o=jh(r,i),a=new U;a.linkToSignal(i),o.onUpdate(s,{emitCurrentValue:!0,clearSignal:i});function s(){if(a.cancel(),!o.getValue())return;a=new U,a.linkToSignal(i);let d=Gh(r.sourceBuffers,a.signal),u=new U;return u.linkToSignal(a.signal),d.onUpdate(c=>{u.cancel(),u=new U,u.linkToSignal(a.signal),!c&&Ff(r,e,t,u.signal)},{clearSignal:a.signal,emitCurrentValue:!0})}}stopUpdating(){this._currentMediaSourceDurationUpdateCanceller!==null&&(this._currentMediaSourceDurationUpdateCanceller.cancel(),this._currentMediaSourceDurationUpdateCanceller=null)}};function qh(n,e,t){let r=e;t||(r=Md()?1/0:Bf(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=Bf(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 Gh(n,e){if(n.length===0){let i=new G(!1);return i.finish(),i}let t=new G(!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 jh(n,e){let t=new G(n.readyState==="open",e);return zn(n,()=>{m.debug("Init: Reacting to MediaSource open in duration updater"),t.setValueIfChanged(!0)},e),Lo(n,()=>{m.debug("Init: Reacting to MediaSource ended in duration updater"),t.setValueIfChanged(!1)},e),Do(n,()=>{m.debug("Init: Reacting to MediaSource close in duration updater"),t.setValueIfChanged(!1)},e),t}function Ff(n,e,t,r){if(qh(n,e,t)==="success")return;let o=setTimeout(()=>{a(),Ff(n,e,t,r)},2e3),a=r.register(()=>{clearTimeout(o)})}function Bf(n){return Math.max(Math.pow(2,32),n+Wh)}var Ri=class extends ae{constructor(e){if(super(),this.id=e,this.sourceBuffers=[],this._canceller=new U,_(kt))throw new te("MEDIA_SOURCE_NOT_SUPPORTED","No MediaSource Object was found in the current browser.");m.info("Init: Creating MediaSource");let t=new kt,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 vi(t),this._endOfStreamCanceller=null,zn(t,()=>{this.readyState=t.readyState,this.trigger("mediaSourceOpen",null)},this._canceller.signal),Lo(t,()=>{this.readyState=t.readyState,this.trigger("mediaSourceEnded",null)},this._canceller.signal),Do(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 Ad(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 U,this._endOfStreamCanceller.linkToSignal(this._canceller.signal),m.debug("Init: end-of-stream order received."),Uf(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(),Yh(this._mediaSource)}},Ad=class{constructor(e,t,r){this.type=e,this.codec=t,this._canceller=new U,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 xe(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 at(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(xe(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 Pe;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=Y({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 c;s instanceof ArrayBuffer?c=new Uint8Array(s):s instanceof Uint8Array?c=s:c=new Uint8Array(s.buffer);let l=[c];for(;((t=this._operationQueue[0])==null?void 0:t.operationName)===0;){let f=this._operationQueue[0],p=(r=d.appendWindow)!=null?r:[void 0,void 0],g=(i=f.params[1].appendWindow)!=null?i:[void 0,void 0],b=(o=d.timestampOffset)!=null?o:0,h=(a=f.params[1].timestampOffset)!=null?a:0;if(p[0]===g[0]&&p[1]===g[1]&&d.codec===f.params[1].codec&&b===h){let I=f.params[0],T;I instanceof ArrayBuffer?T=new Uint8Array(I):I instanceof Uint8Array?T=I:T=new Uint8Array(I.buffer),l.push(T),this._operationQueue.splice(0,1),this._currentOperations.push({operationName:0,resolve:f.resolve,reject:f.reject})}else break}l.length>1&&(m.info(`MMSI: Merging ${l.length} segments together for perf`,this.type),u=se(...l))}try{this._appendBufferNow(u,d)}catch(c){let l=c instanceof Error?new at(c.name,c.message,c.name==="QuotaExceededError"):new at("Error","Unknown SourceBuffer Error during appendBuffer",!1);this._currentOperations.forEach(f=>{f.reject(l)}),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 c=u instanceof Error?new at(u.name,u.message,!1):new at("Error","Unknown SourceBuffer Error during remove",!1);e.reject(c),this._currentOperations.forEach(l=>{l.reject(c)}),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),Cd(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 Yh(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 $h=et();function xd(n,e){if(e!==null&&n.src===e&&(m.info("Init: Clearing HTMLMediaElement's src"),er(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 Qh(n,e){if(Zl&&"disableRemotePlayback"in n){let t=n.disableRemotePlayback;e.register(()=>{n.disableRemotePlayback=t}),n.disableRemotePlayback=!0}}function Xh(n,e){let t=w(n.src)?n.src:null;xd(n,t);let r=new Ri($h());return Qh(n,e),e.register(()=>{r.dispose()}),r}function fa(n,e){return st(e,t=>{let r=Xh(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(()=>{xd(n,null)});else{let i=URL.createObjectURL(r.handle.value);n.src=i,e.register(()=>{xd(n,i)})}})}function wd(n,e,t){var i;if(!_(t)){let o=yn(n),a=Tt(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=Tt(n),d,{DEFAULT_LIVE_GAP:u}=L.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 l=n.availabilityStartTime===void 0?0:n.availabilityStartTime,f=(V()+a)/1e3-l;d=Math.min(s,f)}let c=o!=null?o:e?u.LOW_LATENCY:u.DEFAULT;return m.debug(`Init: ${d} defined as the live time, applying a live gap of ${c}`),Math.max(d-c,r)}return m.info("Init: starting at the minimum available position:",r),r}function ki(){return ja}function Od(n){return!(n&&mn)}function Dd(){return pn}function Pi(n,e,t){let r=new U;r.linkToSignal(t);let i=new G(!1,r.signal);return n.listen(o=>{if(o.rebuffering!==null||o.freezing!==null||o.readyState===0)return;if(!Od(e)){if(isNaN(o.duration))return;if(o.duration>0){i.setValue(!0),r.cancel();return}}let a=Dd()?4:3;if(o.readyState>=a&&(o.currentRange!==null||o.ended)&&(!ki()||o.duration>0)){i.setValue(!0),r.cancel();return}},{includeLastObservation:!0,clearSignal:r.signal}),i}var Zh=!mn,Kf=Zh;var tr=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 Ci({mediaElement:n,playbackObserver:e,startTime:t,mustAutoPlay:r,isDirectfile:i,onWarning:o},a){let s=new G(!1,a);return{autoPlayResult:new Promise((u,c)=>{let l=a.register(I=>{c(I)});if(a.isCancelled())return;let f=!1,p=I=>{e.setCurrentTime(I),f=!0};if(!i||typeof t=="number"){let I=typeof t=="number"?t:t();I!==0&&I!==void 0&&p(I),g()}else e.listen((I,T)=>{let R=typeof t=="number"?t:t();R===void 0&&I.readyState<HTMLMediaElement.HAVE_CURRENT_DATA||I.readyState>=1&&(T(),R!==0&&R!==void 0&&(Kf?p(R):setTimeout(()=>{p(R)},0)),g())},{includeLastObservation:!0,clearSignal:a});function g(){let I=!1;e.listen((T,R)=>{if(!I&&(T.seeking!==0||T.event==="seeking"||T.event==="internal-seeking")&&(I=!0),!(f&&!I||T.readyState===0)){if(R(),ki()&&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()||b()}},{includeLastObservation:!0,clearSignal:a})}function b(){e.listen((I,T)=>{I.seeking===0&&I.rebuffering===null&&I.readyState>=1&&(T(),h())},{includeLastObservation:!0,clearSignal:a})}function h(){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(),l(),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(),l(),u({type:"skipped"});let I;try{I=(T=n.play())!=null?T:Promise.resolve()}catch(R){return l(),c(R)}I.then(()=>{if(!a.isCancelled())return s.setValue(!0),s.finish(),l(),u({type:"autoplay"})}).catch(R=>{if(l(),!a.isCancelled())if(R instanceof Error&&R.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 c(R)})}}),initialPlayPerformed:s}}function Mi(n,e,t,r){if(e.length===0)return u("No `keySystems` option given.");if(fe.decrypt===null)return u("EME feature not activated.");let i=new U;i.linkToSignal(r);let o=new G({initializationState:{type:"uninitialized",value:null},drmSystemId:void 0},r),a=fe.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=c=>{var l;c>0&&((l=t.onCodecSupportUpdate)==null||l.call(t),s.removeEventListener("stateChange",d))};return s.addEventListener("stateChange",d),s.addEventListener("stateChange",c=>{if(c===1){let l=new G(!1);l.onUpdate((f,p)=>{f&&(p(),c===1&&s.attach())},{clearSignal:i.signal}),o.setValue({initializationState:{type:"awaiting-media-link",value:{isMediaLinked:l}},drmSystemId:s.systemId})}else c===2&&(o.setValue({initializationState:{type:"initialized",value:null},drmSystemId:s.systemId}),s.removeEventListener("stateChange"))}),s.addEventListener("error",c=>{i.cancel(),t.onError(c)}),s.addEventListener("warning",c=>{t.onWarning(c)}),s.addEventListener("blackListProtectionData",c=>{t.onBlackListProtectionData(c)}),s.addEventListener("keyIdsCompatibilityUpdate",c=>{t.onKeyIdsCompatibilityUpdate(c)}),i.signal.register(()=>{s.dispose()}),{statusRef:o,contentDecryptor:{enabled:!0,value:s}};function u(c){let l=new ge("MEDIA_IS_ENCRYPTED_ERROR",c),f=new G({initializationState:{type:"initialized",value:null},drmSystemId:void 0});return f.finish(),{statusRef:f,contentDecryptor:{enabled:!1,value:l}}}}var Ai=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 Jh=gr,nr=Jh;var xi=1/60,Rn=class extends ae{constructor(e,t,r){super(),this._playbackObserver=e,this._manifest=t,this._speed=r,this._discontinuitiesStore=[],this._isStarted=!1,this._canceller=new U}start(){if(this._isStarted)return;this._isStarted=!0;let e=new Ud(this._playbackObserver,this._speed);this._canceller.signal.register(()=>{e.dispose()}),this._playbackObserver.listen(t=>{let r=this._discontinuitiesStore,{buffered:i,position:o,readyState:a,rebuffering:s,freezing:d}=t,{BUFFER_DISCONTINUITY_THRESHOLD:u,FREEZING_STALLED_DELAY:c}=L.getCurrent();if(d!==null&&V()-d.timestamp>c){s===null?e.stopRebuffering():e.startRebuffering(),this.trigger("stalled","freezing");return}if(s===null){if(e.stopRebuffering(),a===1){let h;t.seeking!==0?h=t.seeking===1?"internal-seek":"seeking":h="not-ready",this.trigger("stalled",h);return}this.trigger("unstalled",null);return}let l=s.reason==="seeking"&&t.seeking===1?"internal-seek":s.reason;if(o.isAwaitingFuturePosition()?(e.stopRebuffering(),m.debug("Init: let rebuffering happen as we're awaiting a future position")):e.startRebuffering(),this._manifest===null||nr&&V()-s.timestamp<=1e3){this.trigger("stalled",l);return}let{position:f}=s,p=t.position.isAwaitingFuturePosition()?t.position.getWanted():this._playbackObserver.getCurrentTime();if(f!=null&&this._speed.getValue()>0){let h=ey(r,this._manifest,f);if(h!==null){let I=h+.001;if(I<=p)m.info("Init: position to seek already reached, no seeking",p,I);else{m.warn("SA: skippable discontinuity found in the stream",o.getPolled(),I),this._playbackObserver.setCurrentTime(I),this.trigger("warning",Nd(f,I));return}}}let g=f!=null?f:o.getPolled(),b=sc(i,g);if((!nr||V()-s.timestamp>1e3)&&this._speed.getValue()>0&&b<u){let h=g+b+xi;if(p<h){m.warn("Init: discontinuity encountered inferior to the threshold",g,h,u),this._playbackObserver.setCurrentTime(h),this.trigger("warning",Nd(g,h));return}}for(let h=this._manifest.periods.length-2;h>=0;h--){let I=this._manifest.periods[h];if(I.end!==void 0&&I.end<=g){if(this._manifest.periods[h+1].start>g&&this._manifest.periods[h+1].start>p){let T=this._manifest.periods[h+1];this._playbackObserver.setCurrentTime(T.start),this.trigger("warning",Nd(g,T.start));return}break}}this.trigger("stalled",l)},{includeLastObservation:!0,clearSignal:this._canceller.signal})}updateDiscontinuityInfo(e){this._isStarted||this.start();let t=this._playbackObserver.getReference().getValue();ty(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 ey(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:c}=s,l=u!=null?u:d;if(t>=l-xi)if(c===null){let f=Co(e,o);f!==null?a=f.start+xi:m.warn("Init: discontinuity at Period's end but no next Period")}else t<c+xi&&(a=c+xi);a!==void 0&&(m.info("Init: discontinuity found",t,a),r=r!==null&&r>a?r:a)}}return r}function Ld(n){return n.discontinuity!==null}function ty(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){Ld(e)?n[a]=e:n.splice(a,1);return}}else if(n[a].period.start>i.start){Ld(e)&&n.splice(a,0,e);return}Ld(e)&&n.push(e)}}function Nd(n,e){return new te("DISCONTINUITY_ENCOUNTERED","A discontinuity has been encountered at position "+String(n)+", seeking at position "+String(e))}var Ud=class{constructor(e,t){this._speedUpdateCanceller=new U,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 U,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 ny(n,e){return n.id===e.id&&n.start===e.start&&n.end===e.end}var Vf=ny;function ry(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(Vf(f,{id:d,start:a,end:s})){t.push(f);return}let c;if(u.value.element!==void 0)c=u.value.element;else if(u.value.xmlData!==void 0){let f=u.value.xmlData.namespaces.reduce((g,b)=>g+"xmlns:"+b.key+'="'+b.value+'" ',"<toremove ");f+=">";let p=new DOMParser().parseFromString(f+u.value.xmlData.data+"</toremove>","application/xml").documentElement;c=p.children.length>0?p.children[0]:p.childNodes[0]}else return;let l={type:u.type,value:de(oe({},u.value),{element:c})};if(s===void 0){let f={start:a,id:d,data:l,publicEvent:{start:a,data:l}};t.push(f)}else{let f={start:a,end:s,id:d,data:l,publicEvent:{start:a,end:s,data:l}};t.push(f)}})}return t}var Bd=ry;var wi=class extends ae{constructor(e,t){super(),this._manifest=e,this._playbackObserver=t,this._canceller=null,this._scheduledEventsRef=new G([]),this._eventsBeingPlayed=new WeakMap}start(){if(this._canceller!==null)return;this._canceller=new U;let e=this._canceller.signal,t=this._playbackObserver,r=!1,i=new U;i.linkToSignal(e),this._scheduledEventsRef.setValue(Bd([],this._manifest)),this._scheduledEventsRef.onUpdate(({length:o})=>{if(o===0){r&&(i.cancel(),i=new U,i.linkToSignal(e),r=!1);return}else if(r)return;r=!0;let a=c(),s=()=>{let l=c();this._emitStreamEvents(this._scheduledEventsRef.getValue(),a,l,i.signal),a=l},{STREAM_EVENT_EMITTER_POLL_INTERVAL:d}=L.getCurrent(),u=setInterval(s,d);t.listen(s,{includeLastObservation:!1,clearSignal:i.signal}),i.signal.register(()=>{clearInterval(u)});function c(){var g;let l=t.getReference().getValue(),f=(g=t.getCurrentTime())!=null?g:t.getReference().getValue().position.getPolled(),p=l.seeking!==0;return{currentTime:f,isSeeking:p}}},{emitCurrentValue:!0,clearSignal:e})}onManifestUpdate(e){let t=this._scheduledEventsRef.getValue();this._scheduledEventsRef.setValue(Bd(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 c=0;c<e.length;c++){let l=e[c],f=l.start,p=Fd(l)?l.end:void 0;this._eventsBeingPlayed.has(l)?(f>s||p!==void 0&&s>=p)&&(Fd(l)&&u.push(l.publicEvent),this._eventsBeingPlayed.delete(l)):f<=s&&p!==void 0&&s<p?(d.push({type:"stream-event",value:l.publicEvent}),this._eventsBeingPlayed.set(l,!0)):o<f&&s>=(p!=null?p:f)&&(a?d.push({type:"stream-event-skip",value:l.publicEvent}):(d.push({type:"stream-event",value:l.publicEvent}),Fd(l)&&u.push(l.publicEvent)))}if(d.length>0){for(let c of d)if(c.type==="stream-event"?this.trigger("event",c.value):this.trigger("eventSkip",c.value),i.isCancelled())return}if(u.length>0){for(let c of u)if(typeof c.onExit=="function"&&c.onExit(),i.isCancelled())return}}};function Fd(n){return n.end!==void 0}var zf=wi;function Oi(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 kn=class extends Jn{constructor(e){super(),this._initSettings=e,this._initCanceller=new U,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 Sc(e.cmcd),this._manifestFetcher=new nd(t,e.transport,de(oe({},e.manifestRequestSettings),{lowLatencyMode:e.lowLatencyMode,cmcdDataBuilder:this._cmcdDataBuilder}))}prepare(){this._manifest===null&&(this._manifest=Nf.createAsync(st(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(),Oi(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 st(t.signal,r=>{let{keySystems:i}=this._initSettings,{statusRef:o,contentDecryptor:a}=Mi(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();ay(d,s)})().catch(Z)},onKeyIdsCompatibilityUpdate:s=>{(async()=>{var u;if(this._manifest===null)return;let d=(u=this._manifest.syncValue)!=null?u:await this._manifest.getValueAsAsync();oy(d,s.whitelistedKeyIds,s.blacklistedKeyIds,s.delistedKeyIds)})().catch(Z)},onCodecSupportUpdate:()=>{var d,u;let s=(d=this._manifest)==null?void 0:d.syncValue;_(s)?(u=this._manifest)==null||u.getValueAsAsync().then(c=>{this._initCanceller.isUsed()||this._refreshManifestCodecSupport(c)},Z):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 U;u.linkToSignal(t.signal),fa(e,u.signal).then(c=>{let l=o.getValue();if(l.initializationState.type==="awaiting-media-link")l.initializationState.value.isMediaLinked.setValue(!0),o.onUpdate((f,p)=>{if(f.initializationState.type==="initialized"){p(),r({mediaSource:c,drmSystemId:f.drmSystemId,unlinkMediaSource:u});return}},{emitCurrentValue:!0,clearSignal:t.signal});else if(s.initializationState.type==="initialized"){r({mediaSource:c,drmSystemId:s.drmSystemId,unlinkMediaSource:u});return}}).catch(c=>{u.isUsed()||this._onFatalError(c)})},{emitCurrentValue:!0,clearSignal:t.signal})})}async _onInitialMediaSourceReady(e,t,r,i,o){var k;let{adaptiveOptions:a,autoPlay:s,bufferOptions:d,lowLatencyMode:u,segmentRequestOptions:c,speed:l,startAt:f,textTrackOptions:p,transport:g}=this._initSettings,b=this._initCanceller;ee(this._manifest!==null);let h;try{h=(k=this._manifest.syncValue)!=null?k:await this._manifest.getValueAsAsync()}catch(x){return}h.addEventListener("manifestUpdate",x=>{this.trigger("manifestUpdate",x),this._refreshManifestCodecSupport(h)},b.signal),h.addEventListener("decipherabilityUpdate",x=>{this.trigger("decipherabilityUpdate",x)},b.signal),h.addEventListener("supportUpdate",()=>{this.trigger("codecSupportUpdate",null)},b.signal),m.debug("Init: Calculating initial time");let I=wd(h,u,f);m.debug("Init: Initial time calculated:",I);let T=Ic(a),R=Y({textTrackOptions:p,drmSystemId:i},d),E=new Fn(b.signal),v=new ad(g,E,this._cmcdDataBuilder,c);this._refreshManifestCodecSupport(h),this.trigger("manifestReady",h),!b.isUsed()&&this._setupContentWithNewMediaSource({mediaElement:e,playbackObserver:r,mediaSource:t,initialTime:I,autoPlay:s,manifest:h,representationEstimator:T,cdnPrioritizer:E,segmentQueueCreator:v,speed:l,bufferOptions:R},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 U;o.linkToSignal(r.signal),fa(e.mediaElement,o.signal).then(a=>{this._setupContentWithNewMediaSource(de(oe({},e),{mediaSource:a,initialTime:i.position,autoPlay:i.autoPlay}),o)}).catch(a=>{o.isUsed()||this._onFatalError(a)})}}_startLoadingContentOnMediaSource(e,t,r){var F,A;let{autoPlay:i,bufferOptions:o,initialTime:a,manifest:s,mediaElement:d,mediaSource:u,playbackObserver:c,representationEstimator:l,cdnPrioritizer:f,segmentQueueCreator:p,speed:g}=e,{transport:b}=this._initSettings,h=(F=s.getPeriodForTime(a))!=null?F:s.getNextPeriod(a);if(h===void 0){let C=new te("MEDIA_STARTING_TIME_NOT_FOUND","Wanted starting time not found in the Manifest.");return this._onFatalError(C)}let I=null,T=iy(d,this._initSettings.textTrackOptions);if(T!==null){let C=new Ai(T);I=C,r.register(()=>{C.stop(),T==null||T.stop()})}let R=new nn(u,d.nodeName==="VIDEO",I);r.register(()=>{R.disposeAll()});let{autoPlayResult:E,initialPlayPerformed:v}=Ci({mediaElement:d,playbackObserver:c,startTime:a,mustAutoPlay:i,onWarning:C=>{this.trigger("warning",C)},isDirectfile:!1},r);if(r.isCancelled())return;v.onUpdate((C,N)=>{if(C){N();let K=new zf(s,c);s.addEventListener("manifestUpdate",()=>{K.onManifestUpdate(s)},r),K.addEventListener("event",j=>{this.trigger("streamEvent",j)},r),K.addEventListener("eventSkip",j=>{this.trigger("streamEventSkip",j)},r),K.start(),r.register(()=>{K.stop()})}},{clearSignal:r,emitCurrentValue:!0});let k=Pd(c,{autoPlay:i,manifest:s,mediaSource:u,textDisplayer:T,initialPlayPerformed:v,speed:g},r);(A=this._cmcdDataBuilder)==null||A.startMonitoringPlayback(k),r.register(()=>{var C;(C=this._cmcdDataBuilder)==null||C.stopMonitoringPlayback()});let x=this._createRebufferingController(c,s,g,r),P=new mi(R);Jl&&s.addEventListener("decipherabilityUpdate",C=>{C.some(N=>N.representation.decipherable!==!0)&&D(0,void 0,void 0)},r),k.listen(C=>{md(C,R);let N=P.onNewObservation(C);if(N===null)return;let K=()=>{var H;let j=c.getReference().getValue(),$=j.position.isAwaitingFuturePosition()?j.position.getWanted():(H=k.getCurrentTime())!=null?H:j.position.getPolled(),z=v.getValue()?!c.getIsPaused():i;t({position:$,autoPlay:z})};sy(N,{enableRepresentationAvoidance:this._initSettings.enableRepresentationAvoidance,manifest:s,triggerReload:K,playbackObserver:c})},{clearSignal:r});let M=ld(s,u,k,R,{onWarning:C=>this.trigger("warning",C),onPeriodChanged:C=>this.trigger("activePeriodChanged",{period:C})},r);E.then(()=>{Pi(c,!1,r).onUpdate((C,N)=>{C&&(N(),this.trigger("loaded",{getSegmentSinkMetrics:async()=>new Promise(K=>K(R.getSegmentSinksMetrics())),getThumbnailData:async(K,j,$)=>{let z=dd(b.thumbnails,f);return fd(z,s,K,j,$)}}))},{emitCurrentValue:!0,clearSignal:r})}).catch(C=>{r.isCancelled()||this._onFatalError(C)});let O=this;Lf({manifest:s,initialPeriod:h},k,l,R,p,o,B(),r);function B(){return{needsBufferFlush:C=>{var H;let N,K=c.getReference().getValue(),j=K.position.isAwaitingFuturePosition()?K.position.getWanted():d.currentTime,$=(H=C==null?void 0:C.relativeResumingPosition)!=null?H:0,z=!!(C!=null&&C.relativePosHasBeenDefaulted);$===0&&z?N=j+.001:N=j+$,c.setCurrentTime(N),c.listen((q,ie)=>{(q.currentRange!==null||q.position.getPolled()>N+.1)&&(ie(),c.setCurrentTime(q.position.getWanted()+.001))},{includeLastObservation:!1,clearSignal:r})},streamStatusUpdate(C){let{period:N,bufferType:K,imminentDiscontinuity:j,position:$}=C;x.updateDiscontinuityInfo({period:N,bufferType:K,discontinuity:j,position:$}),!r.isCancelled()&&s.isLastPeriodKnown&&C.period.id===s.periods[s.periods.length-1].id&&(C.hasFinishedLoading||C.isEmptyStream?M.onLastSegmentFinishedLoading(C.bufferType):M.onLastSegmentLoadingResume(C.bufferType))},needsManifestRefresh:()=>O._manifestFetcher.scheduleManualRefresh({enablePartialRefresh:!0,canUseUnsafeMode:!0}),manifestMightBeOufOfSync:()=>{let{OUT_OF_SYNC_MANIFEST_REFRESH_DELAY:C}=L.getCurrent();O._manifestFetcher.scheduleManualRefresh({enablePartialRefresh:!1,canUseUnsafeMode:!1,delay:C})},lockedStream:C=>x.onLockedStream(C.bufferType,C.period),adaptationChange:C=>{O.trigger("adaptationChange",C),!r.isCancelled()&&M.onAdaptationChange(C.type,C.period,C.adaptation)},representationChange:C=>{O.trigger("representationChange",C),!r.isCancelled()&&M.onRepresentationChange(C.type,C.period)},inbandEvent:C=>O.trigger("inbandEvents",C),warning:C=>O.trigger("warning",C),periodStreamReady:C=>O.trigger("periodStreamReady",C),periodStreamCleared:C=>{M.onPeriodCleared(C.type,C.period),!r.isCancelled()&&O.trigger("periodStreamCleared",{type:C.type,periodId:C.period.id})},bitrateEstimateChange:C=>{var N;(N=O._cmcdDataBuilder)==null||N.updateThroughput(C.type,C.bitrate),O.trigger("bitrateEstimateChange",C)},needsMediaSourceReload:C=>{D(C.timeOffset,C.minimumPosition,C.maximumPosition)},needsDecipherabilityFlush(){var N,K,j,$;let C=Yn(d);if(Za(C==null?void 0:C[0])){let z=k.getReference().getValue(),H=z.position.isAwaitingFuturePosition()?z.position.getWanted():(N=k.getCurrentTime())!=null?N:z.position.getPolled(),q=(j=(K=z.paused.pending)!=null?K:k.getIsPaused())!=null?j:z.paused.last;t({position:H,autoPlay:!q})}else{let z=k.getReference().getValue(),H=z.position.isAwaitingFuturePosition()?z.position.getWanted():($=k.getCurrentTime())!=null?$:z.position.getPolled();H+.001<z.duration?c.setCurrentTime(d.currentTime+.001):c.setCurrentTime(H)}},encryptionDataEncountered:C=>{if(O._decryptionCapabilities.status==="disabled"){O._onFatalError(O._decryptionCapabilities.value);return}else if(O._decryptionCapabilities.status==="uninitialized"){m.error("Init: received encryption data without known decryption capabilities");return}for(let N of C)if(O._decryptionCapabilities.value.onInitializationData(N),r.isCancelled())return},error:C=>O._onFatalError(C)}}function D(C,N,K){var q,ie,ne;let j=k.getReference().getValue(),$=j.position.isAwaitingFuturePosition()?j.position.getWanted():(q=k.getCurrentTime())!=null?q:j.position.getPolled(),z=(ne=(ie=j.paused.pending)!=null?ie:k.getIsPaused())!=null?ne:j.paused.last,H=$+C;N!==void 0&&(H=Math.max(N,H)),K!==void 0&&(H=Math.min(K,H)),t({position:H,autoPlay:!z})}}_createRebufferingController(e,t,r,i){let o=new Rn(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=qa(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 iy(n,e){return e.textTrackMode==="html"&&fe.htmlTextDisplayer!==null?new fe.htmlTextDisplayer(n,e.textTrackElement):fe.nativeTextDisplayer!==null?new fe.nativeTextDisplayer(n):null}function oy(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(he(d,s))return!1;for(let d of e)if(he(d,s))return!0;for(let d of r)if(he(d,s))return}return o.decipherable})}function ay(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(c=>(u.systemId===void 0||c.systemId===u.systemId)&&he(c.data,u.data))))return!1;return r.decipherable})}function sy(n,{playbackObserver:e,enableRepresentationAvoidance:t,manifest:r,triggerReload:i}){switch(n.type){case"reload":{m.info("Init: Planning reload due to freeze"),i();break}case"flush":{m.info("Init: Flushing buffer due to freeze");let o=e.getReference().getValue(),a=o.position.isAwaitingFuturePosition()?o.position.getWanted():e.getCurrentTime(),s=n.value.relativeSeek,d=a+s;e.setCurrentTime(d);break}case"avoid-representations":{let o=n.value;t&&r.addRepresentationsToAvoid(o),i();break}default:He(n)}}function Kd(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=Kd(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 vt(n,e){var t;return(n-((t=e.indexTimeOffset)!=null?t:0))/e.timescale}function Hf(n,e,t){return[n*t,(n+e)*t]}function dy(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 ma(n,e,t){let{timeline:r}=n,i=We(e,n);if(i<0)return null;let o=dy(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?vt(d,n):null}function Ot(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 uy(n,e){let t=n.toString();return t.length>=e?t:(new Array(e+1).join("0")+t).slice(-e)}function Vd(n){return(e,t,r)=>{let i=w(r)?parseInt(r,10):1;return uy(String(n),i)}}function lt(n,e,t){return ly(n,e,t)}function ly(n,e,t){return n.indexOf("$")===-1?n:n.replace(/\$\$/g,"$").replace(/\$RepresentationID\$/g,String(e)).replace(/\$Bandwidth(%0(\d+)d)?\$/g,Vd(t===void 0?0:t))}function pa(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 Vd(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 Vd(n)(i,o,a)})}}function cy(n,e,t){let r=t-n;return r>0?Math.floor(r/e):0}function Di(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:c,timescale:l,segmentUrlTemplate:f,startNumber:p,endNumber:g}=n,b=p!=null?p:1,h=[],I=c.length;for(let R=0;R<I;R++){let E=c[R],{duration:v,start:k,range:x}=E,P;a===void 0?P=i:P=Math.min(a*l,i!=null?i:1/0);let M=Kd(E,c[R+1],P),O=n.availabilityTimeComplete!==!1||R!==I-1&&M!==0,B=cy(k,v,d),D=k+B*v;for(;D<u&&B<=M;){let F=b+B;if(g!==void 0&&F>g)break;let A=f===null?null:pa(D,F)(f),C=D-n.indexTimeOffset,N=v;C<0&&(N=v+C,C=0);let K={id:String(D),time:C/l,end:(C+N)/l,duration:N/l,isInit:!1,range:x,timescale:1,url:A,number:F,timestampOffset:-(n.indexTimeOffset/l),complete:O,privateInfos:{isEMSGWhitelisted:o}};h.push(K),B++,D=k+B*v}if(D>=u||(b+=M+1,g!==void 0&&b>g))return h}return h}function fy(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 Pn=class{constructor(e,t){var g,b,h,I;let{periodStart:r,periodEnd:i,representationId:o,representationBitrate:a,isEMSGWhitelisted:s}=t,d=(g=e.timescale)!=null?g:1,c=((b=e.presentationTimeOffset)!=null?b:0)-r*d,l=((h=e.initialization)==null?void 0:h.media)===void 0?null:lt(e.initialization.media,o,a),f=e.media===void 0?null:lt(e.media,o,a),p;e.initialization!==void 0?p=e.initialization.range:e.indexRange!==void 0&&(p=[0,e.indexRange[0]-1]),this._index={indexRange:e.indexRange,indexTimeOffset:c,initialization:{url:l,range:p},segmentUrlTemplate:f,startNumber:e.startNumber,endNumber:e.endNumber,timeline:(I=e.timeline)!=null?I:[],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 Ot(this._index,this._isEMSGWhitelisted)}getSegments(e,t){return Di(this._index,e,t,this._manifestBoundsCalculator,this._scaledPeriodEnd,this._isEMSGWhitelisted)}shouldRefresh(){return!1}getFirstAvailablePosition(){let e=this._index;return e.timeline.length===0?null:vt(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 vt(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++)fy(this._index,e[t]);this._isInitialized=!0}}addPredictedSegments(){m.warn("Cannot add predicted segments to a `BaseRepresentationIndex`")}getTargetSegmentDuration(){let{timeline:e,timescale:t}=this._index,r=e[0];if(r!==void 0)return{duration:r.duration/t,isPrecize:!1}}_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 Cn=class{constructor(e,t){var p,g,b;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=(p=e.presentationTimeOffset)!=null?p:0,u=(g=e.timescale)!=null?g:1,c=d-r*u,l=((b=e.initialization)==null?void 0:b.media)===void 0?null:lt(e.initialization.media,o,a),f=e.list.map(h=>({url:h.media===void 0?null:lt(h.media,o,a),mediaRange:h.mediaRange}));this._index={list:f,timescale:u,duration:e.duration,indexTimeOffset:c,indexRange:e.indexRange,initialization:_(e.initialization)?void 0:{url:l,range:e.initialization.range}}}getInitSegment(){let e=Ot(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,c]=Hf(d,t,a),l=Math.min(o.length-1,Math.floor(c/i)),f=[],p=Math.floor(u/i);for(;p<=l;){let g=o[p].mediaRange,b=o[p].url,h=p*s+this._periodStart,I={id:String(p),time:h,isInit:!1,range:g,duration:s,timescale:1,end:h+s,url:b,timestampOffset:-(r.indexTimeOffset/a),complete:!0,privateInfos:{isEMSGWhitelisted:this._isEMSGWhitelisted}};f.push(I),p++}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`")}getTargetSegmentDuration(){let{duration:e,timescale:t}=this._index;return{duration:e/t,isPrecize:!0}}_replace(e){this._index=e._index}_update(){m.error("A `ListRepresentationIndex` cannot be updated")}};function rr(n){return L.getCurrent().DEFAULT_MAXIMUM_TIME_ROUNDING_ERROR*n}var Mn=class{constructor(e,t){var I,T,R;let{availabilityTimeOffset:r,manifestBoundsCalculator:i,isDynamic:o,periodEnd:a,periodStart:s,representationId:d,representationBitrate:u,isEMSGWhitelisted:c}=t,l=(I=e.timescale)!=null?I:1;this._availabilityTimeOffset=r,this._manifestBoundsCalculator=i;let f=(T=e.presentationTimeOffset)!=null?T:0,p=s*l,g=f-p;if(e.duration===void 0)throw new Error("Invalid SegmentTemplate: no duration");let b=((R=e.initialization)==null?void 0:R.media)===void 0?null:lt(e.initialization.media,d,u),h=e.media===void 0?null:lt(e.media,d,u);this._index={duration:e.duration,timescale:l,indexRange:e.indexRange,indexTimeOffset:g,initialization:_(e.initialization)?void 0:{url:b,range:e.initialization.range},url:h,presentationTimeOffset:f,startNumber:e.startNumber,endNumber:e.endNumber},this._isDynamic=o,this._periodStart=s,this._scaledRelativePeriodEnd=a===void 0?void 0:(a-s)*l,this._isEMSGWhitelisted=c}getInitSegment(){return Ot(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,c=this._scaledRelativePeriodEnd,l=e*s-u,f=(e+t)*s-u,p=this._getFirstSegmentStart(),g=this._getLastSegmentStart();if(_(p)||_(g))return[];let b=Math.max(p,l),h=Math.min(g,f);if(h+i<=b)return[];let I=[],T=o!=null?o:1,R=Math.floor(b/i);for(let E=R*i;E<=h;E+=i){let v=R+T;if(a!==void 0&&v>a)return I;let k=!_(c)&&E+i>c?c-E:i,x=E+u,P=E+this._index.presentationTimeOffset,M=d===null?null:pa(P,v)(d),O={id:String(v),number:v,time:x/s,end:(x+k)/s,duration:k/s,timescale:1,isInit:!1,scaledDuration:k/s,url:M,timestampOffset:-(r.indexTimeOffset/s),complete:!0,privateInfos:{isEMSGWhitelisted:this._isEMSGWhitelisted}};I.push(O),R++}return I}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=rr(r),o=this._periodStart*r,a=e*r-o,s=t*r-o,d=this._getLastSegmentStart();if(_(d)){let l=this._estimateRelativeScaledEnd();return l===void 0?s+i>=0:s+i>=0&&a<l-i}let u=d+this._index.duration,c=this._estimateRelativeScaledEnd();return c===void 0?s>u-i:s>u-i&&a<c-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=rr(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`")}getTargetSegmentDuration(){return{duration:this._index.duration/this._index.timescale,isPrecize:!0}}_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 l=Math.ceil(this._scaledRelativePeriodEnd/e);return r!==void 0&&r-i+1<l&&(l=r-i+1),(l-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 c=Math.floor(u/e);return r!==void 0&&r-i+1<c&&(c=r-i+1),c<=0?null:(c-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,c=L.getCurrent().MINIMUM_SEGMENT_SIZE*t;return r!==void 0||s-u>c||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 Li(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 Ni(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 c=t-1;c>=0;c--){let l=n[c].start;if(l===r){let f=t-c;return n.splice(c,f,...e),!1}else if(l<r){let f=n[c];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(c+1,t-(c+1),...e),!1;if(f.start+f.duration*(f.repeatCount+1)<=r)return n.splice(c+1,t-(c+1),...e),!1;let g=(r-f.start)/f.duration-1;if(g%1===0&&f.duration===e[0].duration){let b=e[0].repeatCount<0?-1:e[0].repeatCount+g+1;return n.splice(c,t-c,...e),n[c].start=f.start,n[c].repeatCount=b,!1}return m.warn("RepresentationIndex: Manifest update removed previous segments"),n[c].repeatCount=Math.floor(g),n.splice(c+1,t-(c+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 Ui(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 Bi(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 Fi(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 rn(n){let e=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)e.push(Bi(n[r]));else for(let r=0;r<n.length;r++)e.push(Fi(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=Ui(i,o,a);s!==null&&t.push(s)}return t}function zd(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"),c=_(u)?null:parseInt(u,10);if(c===null||Number.isNaN(c))return null;let l=a!==null?a.attributes.r:s==null?void 0:s.getAttribute("r"),f=_(l)?null:parseInt(l,10);if(f!==null){if(Number.isNaN(f)||f<0)return null;if(f>0){let b=t-d;if(b%c===0&&b/c<=f)return{repeatNumberInPrevSegments:0,repeatNumberInNewElements:b/c,prevSegmentsIdx:0,newElementsIdx:o}}d+=c*(f+1)}else d+=c;if(o++,o>=e.length)return null;Array.isArray(e)?a=e[o]:s=e[o];let p=a!==null?a.attributes.t:s==null?void 0:s.getAttribute("t"),g=_(p)?null:parseInt(p,10);if(g!==null){if(Number.isNaN(g))return null;d=g}if(d===t)return{newElementsIdx:o,prevSegmentsIdx:0,repeatNumberInPrevSegments:0,repeatNumberInNewElements:0};if(d>i)return null}}}function Hd(n,e){var b;let t=zd(e,n);if(t===null)return m.warn('DASH: Cannot perform "based" update. Common segment not found.'),rn(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'),rn(n);let u=e.slice(r);if(o>0){let h=u[0];h.start+=h.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.'),rn(n);let c=u[u.length-1],l=Array.isArray(n)?Bi(n[d]):Fi(n[d]),f=((b=l.repeatCount)!=null?b:0)-a;if(l.duration!==c.duration||c.repeatCount>f)return m.info('DASH: Cannot perform "based" update. The new timeline has a different form at the beginning.'),rn(n);l.repeatCount!==void 0&&l.repeatCount>c.repeatCount&&(c.repeatCount=l.repeatCount);let p=[],g=[];if(Array.isArray(n))for(let h=d+1;h<n.length;h++)g.push(Bi(n[h]));else for(let h=d+1;h<n.length;h++)g.push(Fi(n[h]));for(let h=0;h<g.length;h++){let I=g[h],T=p[p.length-1]===void 0?c:p[p.length-1],R=g[h+1]===void 0?null:g[h+1],E=Ui(I,T,R);E!==null&&p.push(E)}return u.concat(p)}var Ki=class n{constructor(e,t){var E,v,k,x,P;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:c,periodEnd:l,isEMSGWhitelisted:f}=t,p=(E=e.timescale)!=null?E:1,g=(v=e.presentationTimeOffset)!=null?v:0,b=c*p,h=g-b;this._manifestBoundsCalculator=o,this._isEMSGWhitelisted=f,this._isLastPeriod=s,this._lastUpdate=(k=t.receivedTime)!=null?k:V(),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 I=((P=e.initialization)==null?void 0:P.media)===void 0?null:lt(e.initialization.media,d,u),T=e.media===void 0?null:lt(e.media,d,u),R;i===void 0&&r===void 0?R=1/0:R=i!=null?i:0,this._index={availabilityTimeComplete:r!=null?r:!0,availabilityTimeOffset:R,indexRange:e.indexRange,indexTimeOffset:h,initialization:_(e.initialization)?void 0:{url:I,range:e.initialization.range},segmentUrlTemplate:T,startNumber:e.startNumber,endNumber:e.endNumber,timeline:e.timeline===void 0?null:Wd(e.timeline,e.startNumber,e.endNumber),timescale:p},this._scaledPeriodStart=We(c,this._index),this._scaledPeriodEnd=l===void 0?void 0:We(l,this._index)}getInitSegment(){return Ot(this._index,this._isEMSGWhitelisted)}getSegments(e,t){return this._refreshTimeline(),this._index.timeline===null&&(this._index.timeline=this._getTimeline()),Di(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:vt(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=ga(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 vt(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 vt(t,this._index)}awaitSegmentBetween(e,t){var u,c;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=rr(r),a=We(t,this._index),s=ga(this._index,this._manifestBoundsCalculator,this._scaledPeriodEnd);if(s!==null&&Math.min(s.end,(u=this._scaledPeriodEnd)!=null?u:1/0)+o>=Math.min(a,(c=this._scaledPeriodEnd)!=null?c:1/0))return!1;let d=We(e,this._index);if(i.length>0&&s!==null&&!s.isLastOfTimeline){let l=i[i.length-1],p=ke(l,null,this._scaledPeriodEnd)+o;if(d<p+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()),my(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),ma({timeline:t,timescale:this._index.timescale,indexTimeOffset:this._index.indexTimeOffset},e,this._scaledPeriodEnd)}canBeOutOfSyncError(e){return this._isDynamic?e instanceof ot&&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()),Ni(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=rr(this._index.timescale),r=ga(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`")}getTargetSegmentDuration(){this._refreshTimeline();let{timeline:e,timescale:t}=this._index;if(e===null)return;let r=e[0];if(r!==void 0)return{duration:r.duration/t,isPrecize:!1}}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=Li(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}=L.getCurrent();if(this._unsafelyBaseOnPreviousIndex===null||e.length<t)return Wd(rn(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,Wd(Hd(e,r),this._index.startNumber,this._index.endNumber)}};function Wd(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 my(n,e,t,r){let i=ga(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 ga(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(vt(a,n)<=r){let s=ke(o,n.timeline[i+1],t);if(vt(s,n)<=r)return{isLastOfTimeline:i===n.timeline.length-1,timelineIdx:i,newRepeatCount:o.repeatCount,end:a};{let u=We(r,n)-o.start,c=Math.floor(u/o.duration);return ee(c>=1),{isLastOfTimeline:!1,timelineIdx:i,newRepeatCount:c-1,end:o.start+c*o.duration}}}}return null}var ha=Ki;var Vi=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 qd(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"),qd(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),qd(e,t),!0)}_getReferenced(e){return this._refs.get(e)}};function qd(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=Q(n.contentProtections.initData,a=>a.type==="cenc");o===void 0?n.contentProtections.initData.push({type:"cenc",values:i}):o.values.push(...i)}function ya(n){let e=Date.parse(n)-V();if(isNaN(e)){m.warn("DASH Parser: Invalid clock received: ",n);return}return e}function Gd(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 Ia(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 jd(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=Ia(r);if(s===void 0)return{safe:void 0,unsafe:void 0};o=s}if(i!==void 0){let s=Ia(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 ba(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 Yd(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=ba(r);if(s===void 0)return;o=s}if(i!==void 0){let s=ba(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 $d(n){if(n.length===0)throw new Error("DASH Parser: no period available for a dynamic content");let e=Yd(n),t=jd(n);return{minimumSafePosition:e,maximumSafePosition:t.safe,maximumUnsafePosition:t.unsafe}}var zi=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(V()+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+V()/1e3,0):this._lastPosition}};function Qd(n,e){return n.type!=="dynamic"?0:_(n.availabilityStartTime)?e!=null?e:0:n.availabilityStartTime}function Xd(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 py(n,e){for(let t of e){let{adaptation:r,trickModeAttachedAdaptationIds:i}=t;for(let o of i)for(let a of $t){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 Wf=py;var gy=["subtitle","caption"];function Jd(n,e){var s,d,u,c;let t=(c=Q((s=n.children.essentialProperties)!=null?s:[],l=>l.schemeIdUri==="http://dashif.org/guidelines/thumbnail_tile"||l.schemeIdUri==="http://dashif.org/thumbnail_tile"))!=null?c:Q((u=(d=e!=null?e:n.children.representations[0])==null?void 0:d.children.essentialProperties)!=null?u:[],l=>l.schemeIdUri==="http://dashif.org/guidelines/thumbnail_tile"||l.schemeIdUri==="http://dashif.org/thumbnail_tile");if(t===void 0)return null;let r=/(\d+)x(\d+)/;if(t===void 0||t.value===void 0||!r.test(t.value))return m.warn("DASH: Invalid thumbnails Representation, no tile-related information"),null;let i=t.value.match(r),o=parseInt(i[1],10),a=parseInt(i[2],10);return{horizontalTiles:o,verticalTiles:a}}function eu(n,e){if(n.attributes.contentType==="image")return Jd(n)!==null?"thumbnails":void 0;let t=w(n.attributes.mimeType)?n.attributes.mimeType:null,r=w(n.attributes.codecs)?n.attributes.codecs:null,i=_(n.children.roles)?null:n.children.roles;function o(s,d){let u=s.split("/")[0];if(X($t,u))return u;if(s==="application/ttml+xml")return"text";if(s==="application/mp4")return d!==null&&Q(d,c=>c.schemeIdUri==="urn:mpeg:dash:role:2011"&&X(gy,c.value))!==void 0?"text":void 0}function a(s){switch(s.substring(0,3)){case"avc":case"hev":case"hvc":case"vp8":case"vp9":case"av1":return"video";case"vtt":return"text"}switch(s.substring(0,4)){case"mp4a":return"audio";case"wvtt":case"stpp":return"text"}}if(t!==null){let s=o(t,i);if(s!==void 0)return s}if(r!==null){let s=a(r);if(s!==void 0)return s}for(let s=0;s<e.length;s++){let d=e[s],{mimeType:u,codecs:c}=d.attributes;if(u!==void 0){let l=o(u,i);if(l!==void 0)return l}if(c!==void 0){let l=a(c);if(l!==void 0)return l}}}var hy=/[, ]+/g;function qf(n){return w(n)?n.trim().replace(hy,", "):""}function Gf(n){let[e,t,r,i,o,a,s,d]=n.split(".");if(e!=="vp08"&&e!=="vp09"&&e!=="vp10")return;let u,c,l;if((i!==void 0&&i==="10"||i==="12")&&(u=parseInt(i,10)),s!==void 0&&(s==="16"?c="pq":s==="18"&&(c="hlg")),a!==void 0&&d!==void 0&&a==="09"&&d==="09"&&(l="rec2020"),!(u===void 0||c===void 0))return{colorDepth:u,eotf:c,colorSpace:l}}function tu(n,e){var g,b,h;let{availabilityTimeOffset:t,manifestBoundsCalculator:r,isDynamic:i,end:o,start:a,receivedTime:s,unsafelyBaseOnPreviousRepresentation:d,inbandEventStreams:u,isLastPeriod:c}=e,f={availabilityTimeComplete:void 0,availabilityTimeOffset:t,unsafelyBaseOnPreviousRepresentation:d,isEMSGWhitelisted:I=>u===void 0?!1:u.some(({schemeIdUri:T})=>T===I.schemeIdUri),isLastPeriod:c,manifestBoundsCalculator:r,isDynamic:i,periodEnd:o,periodStart:a,receivedTime:s,representationBitrate:n.attributes.bitrate,representationId:n.attributes.id},p;if(n.children.segmentBase!==void 0){let{segmentBase:I}=n.children;p=new Pn(I,f)}else if(n.children.segmentList!==void 0){let{segmentList:I}=n.children;p=new Cn(I,f)}else if(n.children.segmentTemplate!==void 0||e.parentSegmentTemplates.length>0){let I=e.parentSegmentTemplates.slice(),T=n.children.segmentTemplate;T!==void 0&&I.push(T);let R=Y({},...I);(R.availabilityTimeOffset!==void 0||e.availabilityTimeOffset!==void 0)&&(f.availabilityTimeOffset=((g=R.availabilityTimeOffset)!=null?g:0)+((b=e.availabilityTimeOffset)!=null?b:0)),(R.availabilityTimeComplete!==void 0||e.availabilityTimeComplete!==void 0)&&(f.availabilityTimeComplete=(h=R.availabilityTimeComplete)!=null?h:e.availabilityTimeComplete),p=ha.isTimelineIndexArgument(R)?new ha(R,f):new Mn(R,f)}else{let I=e.adaptation.children;if(I.segmentBase!==void 0){let{segmentBase:T}=I;p=new Pn(T,f)}else if(I.segmentList!==void 0){let{segmentList:T}=I;p=new Cn(T,f)}else p=new Mn({duration:Number.MAX_VALUE,timescale:1,startNumber:0,media:""},f)}return p}function Dt(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=gn(a.url,d.url);r.push({url:u,serviceLocation:(i=d.serviceLocation)!=null?i:a.serviceLocation})}}return r}function yy(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 Iy({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=Q([...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 Gf(i)}function nu(n,e,t){var i,o,a,s,d,u,c;let r=[];for(let l of n){let f=l.attributes.id!==void 0?l.attributes.id:String(l.attributes.bitrate)+(l.attributes.height!==void 0?`-${l.attributes.height}`:"")+(l.attributes.width!==void 0?`-${l.attributes.width}`:"")+(l.attributes.mimeType!==void 0?`-${l.attributes.mimeType}`:"")+(l.attributes.codecs!==void 0?`-${l.attributes.codecs}`:"");for(;r.some(M=>M.id===f);)f+="-dup";let p=(o=(i=t.unsafelyBaseOnPreviousAdaptation)==null?void 0:i.getRepresentation(f))!=null?o:null,g=yy(l,e),b=(a=l.attributes.availabilityTimeComplete)!=null?a:t.availabilityTimeComplete,h;(l.attributes.availabilityTimeOffset!==void 0||t.availabilityTimeOffset!==void 0)&&(h=((s=l.attributes.availabilityTimeOffset)!=null?s:0)+((d=t.availabilityTimeOffset)!=null?d:0));let I=Y({},t,{availabilityTimeOffset:h,availabilityTimeComplete:b,unsafelyBaseOnPreviousRepresentation:p,adaptation:e,inbandEventStreams:g}),T=tu(l,I),R;l.attributes.bitrate===void 0?(m.warn("DASH: No usable bitrate found in the Representation."),R=0):R=l.attributes.bitrate;let E=Dt(t.baseURLs,l.children.baseURLs),v=E.length===0?[{baseUrl:"",id:void 0}]:E.map(M=>({baseUrl:M.url,id:M.serviceLocation})),k={bitrate:R,cdnMetadata:v,index:T,id:f};l.children.supplementalProperties!==void 0&&Q(l.children.supplementalProperties,M=>M.schemeIdUri==="tag:dolby.com,2018:dash:EC3_ExtensionType:2018"&&M.value==="JOC")!==void 0&&(k.isSpatialAudio=!0);let x;l.attributes.codecs!==void 0?x=l.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 P;l.attributes.supplementalCodecs!==void 0?P=l.attributes.supplementalCodecs:e.attributes.supplementalCodecs!==void 0&&(P=e.attributes.supplementalCodecs),P!==void 0&&(k.supplementalCodecs=qf(P)),l.attributes.frameRate!==void 0?k.frameRate=l.attributes.frameRate:e.attributes.frameRate!==void 0&&(k.frameRate=e.attributes.frameRate),l.attributes.height!==void 0?k.height=l.attributes.height:e.attributes.height!==void 0&&(k.height=e.attributes.height),l.attributes.mimeType!==void 0?k.mimeType=l.attributes.mimeType:e.attributes.mimeType!==void 0&&(k.mimeType=e.attributes.mimeType),l.attributes.width!==void 0?k.width=l.attributes.width:e.attributes.width!==void 0&&(k.width=e.attributes.width);{let M=[...(u=e.children.contentProtections)!=null?u:[],...(c=l.children.contentProtections)!=null?c:[]];for(let O of M)t.contentProtectionParser.add(k,O)}k.hdrInfo=Iy({adaptationProfiles:e.attributes.profiles,supplementalProperties:e.children.supplementalProperties,essentialProperties:e.children.essentialProperties,manifestProfiles:t.manifestProfiles,codecs:x}),r.push(k)}return r}function by(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 Sy(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 Ty(n){return n===void 0?!1:n.schemeIdUri==="urn:mpeg:dash:role:2011"&&n.value==="sign"}function _y(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 Ey(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=>w(r))}return[]}function ru(n,e){var d,u,c,l,f,p,g;let t={video:[],audio:[],text:[]},r=[],i=[],o={},a=[];for(let b=0;b<n.length;b++){let h=n[b],I=h.children,{essentialProperties:T,roles:R,label:E}=I,v=Array.isArray(R)&&R.some(W=>W.value==="main")&&R.some(W=>W.schemeIdUri==="urn:mpeg:dash:role:2011"),k=h.children.representations,x=(d=h.attributes.availabilityTimeComplete)!=null?d:e.availabilityTimeComplete,P;(h.attributes.availabilityTimeOffset!==void 0||e.availabilityTimeOffset!==void 0)&&(P=((u=h.attributes.availabilityTimeOffset)!=null?u:0)+((c=e.availabilityTimeOffset)!=null?c:0));let M=eu(h,k);if(M===void 0)continue;let O=(l=h.attributes.selectionPriority)!=null?l:1,B=h.attributes.id,D=Ey(h),F=[];e.segmentTemplate!==void 0&&F.push(e.segmentTemplate),h.children.segmentTemplate!==void 0&&F.push(h.children.segmentTemplate);let A={availabilityTimeComplete:x,availabilityTimeOffset:P,baseURLs:Dt(e.baseURLs,I.baseURLs),contentProtectionParser:e.contentProtectionParser,manifestBoundsCalculator:e.manifestBoundsCalculator,end:e.end,isDynamic:e.isDynamic,isLastPeriod:e.isLastPeriod,manifestProfiles:e.manifestProfiles,parentSegmentTemplates:F,receivedTime:e.receivedTime,start:e.start,unsafelyBaseOnPreviousAdaptation:null},C=Array.isArray(T)?Q(T,W=>W.schemeIdUri==="http://dashif.org/guidelines/trickmode"):void 0,N=(f=C==null?void 0:C.value)==null?void 0:f.split(" "),K=N!==void 0,{accessibilities:j}=I,$;R!==void 0&&R.some(W=>W.value==="dub")&&($=!0);let z;M!=="text"?z=!1:z=Sy(j,R);let H;M==="text"&&R!==void 0&&R.some(W=>W.value==="forced-subtitle"||W.value==="forced_subtitle")&&(H=!0);let q;M!=="audio"?q=!1:j!==void 0&&(q=j.some(by));let ie;M!=="video"?ie=!1:j!==void 0&&(ie=j.some(Ty));let ne=_y(h,{isAudioDescription:q,isForcedSubtitle:H,isClosedCaption:z,isSignInterpreted:ie,isTrickModeTrack:K,type:M});for(;X(a,ne);)ne+="-dup";let le=ne;a.push(ne),A.unsafelyBaseOnPreviousAdaptation=(g=(p=e.unsafelyBaseOnPreviousPeriod)==null?void 0:p.getAdaptation(ne))!=null?g:null;let be=nu(k,h,A);if(M==="thumbnails"){let W=vy(h,be);W!==null&&r.push(...W);continue}let me={id:ne,representations:be,type:M,isTrickModeTrack:K};if(_(h.attributes.language)||(me.language=h.attributes.language),_(z)||(me.closedCaption=z),_(q)||(me.audioDescription=q),$===!0&&(me.isDub=!0),H!==void 0&&(me.forcedSubtitles=H),ie===!0&&(me.isSignInterpreted=!0),E!==void 0&&(me.label=E),N!==void 0)i.push({adaptation:me,trickModeAttachedAdaptationIds:N});else{let W=-1;for(let Ce of D){let nt=o[Ce];if(nt!==void 0&&nt.newID!==le&&X(nt.adaptationSetSwitchingIDs,B)){W=pe(t[M],zt=>zt[0].id===Ce);let Ae=t[M][W];if(Ae!==void 0&&Ae[0].audioDescription===me.audioDescription&&Ae[0].closedCaption===me.closedCaption&&Ae[0].language===me.language){m.info('DASH Parser: merging "switchable" AdaptationSets',B,Ce),Ae[0].representations.push(...me.representations),Ae[1]={priority:Math.max(O,Ae[1].priority),isMainAdaptation:v||Ae[1].isMainAdaptation,indexInMpd:Math.min(b,Ae[1].indexInMpd)};break}}}W<0&&t[M].push([me,{priority:O,isMainAdaptation:v,indexInMpd:b}])}!_(B)&&_(o[B])&&(o[B]={newID:le,adaptationSetSwitchingIDs:D})}let s=$t.reduce((b,h)=>{let I=t[h];return I.length>0&&(I.sort(jf),b[h]=I.map(([T])=>T)),b},{});return t.video.sort(jf),Wf(s,i),{adaptations:s,thumbnailTracks:r}}function vy(n,e){var r,i;let t=[];for(let o=0;o<e.length;o++){let a=e[o];if(a!==void 0){if(a.mimeType===void 0){m.warn("DASH: Invalid thumbnails Representation, no mime-type");continue}let s=Jd(n,n.children.representations[o]);if(s===null)continue;if(a.height===void 0){m.warn("DASH: Invalid thumbnails Representation, no height information");continue}if(a.width===void 0){m.warn("DASH: Invalid thumbnails Representation, no width information");continue}let d=(r=a.index.getFirstAvailablePosition())!=null?r:void 0,u=(i=a.index.getEnd())!=null?i:void 0,c,l=a.index.getTargetSegmentDuration();l!==void 0&&l.isPrecize?c=l.duration:m.warn("DASH: Cannot produce duration estimate for thumbnail track"),t.push({id:a.id,cdnMetadata:a.cdnMetadata,index:a.index,mimeType:a.mimeType,height:a.height,width:a.width,horizontalTiles:s.horizontalTiles,verticalTiles:s.verticalTiles,start:d,end:u,tileDuration:c===void 0?void 0:c/(s.horizontalTiles*s.verticalTiles)})}}return t}function jf(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 Ry=et();function iu(n,e){var a,s,d,u,c;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 l=n.length-1;l>=0;l--){let f=l===n.length-1,p=n[l],g=e.xlinkInfos.get(p),b=Dt(e.baseURLs,p.children.baseURLs),{periodStart:h,periodDuration:I,periodEnd:T}=r[l],R;for(_(p.attributes.id)?(m.warn("DASH: No usable id found in the Period. Generating one."),R="gen-dash-period-"+Ry()):R=p.attributes.id;t.some(K=>K.id===R);)R+="-dup";let E=g!==void 0?g.receivedTime:e.receivedTime,v=(s=(a=e.unsafelyBaseOnPreviousManifest)==null?void 0:a.getPeriod(R))!=null?s:null,k=p.attributes.availabilityTimeComplete,x=p.attributes.availabilityTimeOffset,{manifestProfiles:P,contentProtectionParser:M}=e,{segmentTemplate:O}=p.children;M.addReferences((d=p.children.contentProtections)!=null?d:[]);let B={availabilityTimeComplete:k,availabilityTimeOffset:x,baseURLs:b,contentProtectionParser:M,manifestBoundsCalculator:o,end:T,isDynamic:i,isLastPeriod:f,manifestProfiles:P,receivedTime:E,segmentTemplate:O,start:h,unsafelyBaseOnPreviousPeriod:v},{adaptations:D,thumbnailTracks:F}=ru(p.children.adaptations,B),A=((u=e.xmlNamespaces)!=null?u:[]).concat((c=p.attributes.namespaces)!=null?c:[]),C=Py(p.children.eventStreams,h,A),N={id:R,start:h,end:T,duration:I,thumbnailTracks:F,adaptations:D,streamEvents:C};if(t.unshift(N),!o.lastPositionIsKnown()){let K=ky(D);if(!i)typeof K=="number"&&o.setLastPosition(K);else if(typeof K=="number"){let j=V()/1e3;o.setLastPosition(K,j)}else{let j=Yf(e,h);if(j!==void 0){let[$,z]=j;o.setLastPosition($,z)}}}}if(e.isDynamic&&!o.lastPositionIsKnown()){let l=Yf(e,0);if(l!==void 0){let[f,p]=l;o.setLastPosition(f,p)}}return Xd(t)}function Yf(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=V()/1e3;return[r,i]}}else{let t=n.clockOffset/1e3-n.availabilityStartTime,r=V()/1e3,i=r+t;if(i>=e)return[i,r]}}function ky(n){let e=null,t=!0,r=Bn(n).filter(o=>!_(o)),i=Hn(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 Py(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 c of a.children.events)if(c.eventStreamData!==void 0){let l=((o=c.presentationTime)!=null?o:0)/d+e,f=c.duration===void 0?void 0:l+c.duration/d,p,g;if(!Wt&&c.eventStreamData instanceof Element)p=c.eventStreamData;else try{g={namespaces:u,data:typeof c.eventStreamData=="string"?c.eventStreamData:Ue(new Uint8Array(c.eventStreamData))}}catch(b){m.error("DASH: Error while parsing event-stream:",b instanceof Error?b.message:"Unknown error")}r.push({start:l,end:f,id:c.id,data:{type:"dash-event-stream",value:{schemeIdUri:s,timescale:d,element:p,xmlData:g}}})}}return r}function ir(n,e,t,r,i=new WeakMap){let{children:o,attributes:a}=n;if(_(e.externalClockOffset)){let d=a.type==="dynamic",u=Q(o.utcTimings,f=>f.schemeIdUri==="urn:mpeg:dash:utc:direct:2014"&&!_(f.value)),c=!_(u)&&!_(u.value)?ya(u.value):void 0,l=!_(c)&&!isNaN(c)?c:void 0;if(!_(l)&&r!==!0)e.externalClockOffset=l;else if(d&&r!==!0){let f=Gd(n);if(!_(f)&&f.length>0)return{type:"needs-clock",value:{url:f,continue:function(g){return g.success?(e.externalClockOffset=ya(g.data),ir(n,e,t,!0)):(t.push(g.error),m.warn("DASH Parser: Error on fetching the clock ressource",g.error),ir(n,e,t,!0))}}}}}let s=[];for(let d=0;d<o.periods.length;d++){let{xlinkHref:u,xlinkActuate:c}=o.periods[d].attributes;!_(u)&&c==="onLoad"&&s.push({index:d,ressource:u})}return s.length===0?Cy(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 c=u.length-1;c>=0;c--){let l=s[c].index,{parsed:f,warnings:p,receivedTime:g,sendingTime:b,url:h}=u[c];p.length>0&&t.push(...p);for(let I of f)i.set(I,{receivedTime:g,sendingTime:b,url:h});o.periods.splice(l,1,...f)}return ir(n,e,t,r,i)}}}}function Cy(n,e,t,r){var A,C,N,K,j;let{children:i,attributes:o}=n,a=o.type==="dynamic",s=e.url!==void 0?[{url:e.url.substring(0,Mr(e.url))}]:[],d=Dt(s,i.baseURLs),u=Qd(o,e.referenceDateTime),c=o.timeShiftBufferDepth,l=o.maxSegmentDuration,{externalClockOffset:f,unsafelyBaseOnPreviousManifest:p}=e,{externalClockOffset:g}=e,b=new zi({availabilityStartTime:u,isDynamic:a,timeShiftBufferDepth:c,serverTimestampOffset:g}),h=new Vi;h.addReferences((A=i.contentProtections)!=null?A:[]);let I={availabilityStartTime:u,baseURLs:d,clockOffset:f,contentProtectionParser:h,duration:o.duration,isDynamic:a,manifestBoundsCalculator:b,manifestProfiles:n.attributes.profiles,receivedTime:e.manifestReceivedTime,unsafelyBaseOnPreviousManifest:p,xlinkInfos:r,xmlNamespaces:n.attributes.namespaces},T=iu(i.periods,I);h.finalize();let R=o.duration,E,v,k=null,x;o.minimumUpdatePeriod!==void 0&&o.minimumUpdatePeriod>=0&&(E=o.minimumUpdatePeriod===0?L.getCurrent().DASH_FALLBACK_LIFETIME_WHEN_MINIMUM_UPDATE_PERIOD_EQUAL_0:o.minimumUpdatePeriod);let{minimumSafePosition:P,maximumSafePosition:M,maximumUnsafePosition:O}=$d(T),B=V();if(a){let $;M!==void 0?$=M:g===void 0?(m.warn("DASH Parser: use system clock to define maximum position"),$=Date.now()/1e3-u):$=(V()+g)/1e3-u;let z=b.getEstimatedLiveEdge();z===void 0&&(O!==void 0?z=O:z=$),x={isLinear:!0,maximumSafePosition:$,livePosition:z,time:B},v=P,k=c!=null?c:null,k!==null&&(k+=l!=null?l:0),k!==null&&v!==void 0&&z-v>k&&(k=z-v)}else{v=P,v===void 0&&(v=(N=(C=T[0])==null?void 0:C.start)!=null?N:0);let $=R!=null?R:1/0;if(T[T.length-1]!==void 0){let z=T[T.length-1],H=(K=z.end)!=null?K:z.duration!==void 0?z.start+z.duration:void 0;H!==void 0&&H<$&&($=H)}M!==void 0&&M<$&&($=M),x={isLinear:!1,maximumSafePosition:$,livePosition:void 0,time:B}}let D=!a||n.attributes.minimumUpdatePeriod===void 0&&(((j=T[T.length-1])==null?void 0:j.end)!==void 0||n.attributes.duration!==void 0);return{type:"done",value:{parsed:{availabilityStartTime:u,clockOffset:e.externalClockOffset,isDynamic:a,isLive:a,isLastPeriodKnown:D,periods:T,publishTime:o.publishTime,suggestedPresentationDelay:o.suggestedPresentationDelay,transportType:"dash",timeBounds:{minimumSafePosition:v,timeshiftDepth:k,maximumTimeData:x},lifetime:E,uris:_(e.url)?i.locations:[e.url,...i.locations]},warnings:t}}}var $f=ir;function Lt(n){let e=n.textContent,t=[];return e===null||e.length===0?[void 0,t]:[{value:e},t]}var My=/^P(([\d.]*)Y)?(([\d.]*)M)?(([\d.]*)D)?T?(([\d.]*)H)?(([\d.]*)M)?(([\d.]*)S)?/,Ay=/([0-9]+)-([0-9]+)/;function qe(n,e){return n==="true"?[!0,null]:n==="false"?[!1,null]:[!1,new tt(`\`${e}\` property is not a boolean value but "${n}"`)]}function Ie(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 $e(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 ou(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 Sa(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 yt(n,e){if(!w(n))return[0,new tt(`\`${e}\` property is empty`)];let t=My.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 An(n,e){let t=Ay.exec(n);return t===null?[null,new tt(`\`${e}\` property has an unrecognized format "${n}"`)]:[[+t[1],+t[2]],null]}function Qf(n,e){try{return[ht(n),null]}catch(t){return[null,new tt(`\`${e}\` is not a valid base64 string: "${n}"`)]}}function or(n,e){let t=/^(\d+)\/(\d+)$/.exec(n);return t!==null?[+t[1]/+t[2],null]:$e(n,e)}function Le(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 Oe(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 xy(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]=Qf(o,"cenc:pssh");s!==null&&(m.warn(s.message),e.push(s)),a!==null&&t.push(a)}}}return[{cencPssh:t},e]}function wy(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=Ye(r.value.replace(/-/g,""));break;case"ref":e.ref=r.value;break;case"refId":e.refId=r.value;break}}return e}function Nt(n){let[e,t]=xy(n.childNodes),r=wy(n);return[{children:e,attributes:r},t]}function au(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 su(n){let e={},t=[],r=Oe(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:An,dashName:"range"});break;case"sourceURL":e.media=o.value;break}}return[e,t]}function Ut(n){let e={},t=[],r=Oe(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]=su(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:Ie,dashName:"timescale"});break;case"presentationTimeOffset":r(a.value,{asKey:"presentationTimeOffset",parser:$e,dashName:"presentationTimeOffset"});break;case"indexRange":r(a.value,{asKey:"indexRange",parser:An,dashName:"indexRange"});break;case"indexRangeExact":r(a.value,{asKey:"indexRangeExact",parser:qe,dashName:"indexRangeExact"});break;case"availabilityTimeOffset":r(a.value,{asKey:"availabilityTimeOffset",parser:$e,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(a.value,{asKey:"availabilityTimeComplete",parser:qe,dashName:"availabilityTimeComplete"});break;case"duration":r(a.value,{asKey:"duration",parser:Ie,dashName:"duration"});break;case"startNumber":r(a.value,{asKey:"startNumber",parser:Ie,dashName:"startNumber"});break;case"endNumber":r(a.value,{asKey:"endNumber",parser:Ie,dashName:"endNumber"});break}}return[e,t]}function du(n){let e={},t=[],r=Oe(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:An,dashName:"indexRange"});break;case"index":e.index=o.value;break;case"mediaRange":r(o.value,{asKey:"mediaRange",parser:An,dashName:"mediaRange"});break}}return[e,t]}function Hi(n){let[e,t]=Ut(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,c]=du(d);i.push(u),r=r.concat(c)}}return[Y(e,{list:i}),r]}function uu(n){let e=null;return function(){if(e===null){let t=n.getElementsByTagName("S");return e=t,t}return e}}function xn(n){let[e,t]=Ut(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=uu(d))}let o=Y({},e,{duration:e.duration,timelineParser:i}),a=Oe(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:$e,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":a(d.value,{asKey:"availabilityTimeComplete",parser:qe,dashName:"availabilityTimeComplete"});break;case"media":o.media=d.value;break;case"bitstreamSwitching":a(d.value,{asKey:"bitstreamSwitching",parser:qe,dashName:"bitstreamSwitching"});break}}return[o,r]}function Oy(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]=Lt(o);a!==void 0&&e.baseURLs.push(a),r=r.concat(s);break}case"InbandEventStream":e.inbandEventStreams===void 0&&(e.inbandEventStreams=[]),e.inbandEventStreams.push(Le(o));break;case"SegmentBase":{let[a,s]=Ut(o);e.segmentBase=a,s.length>0&&(r=r.concat(s));break}case"SegmentList":{let[a,s]=Hi(o);r=r.concat(s),e.segmentList=a;break}case"SegmentTemplate":{let[a,s]=xn(o);r=r.concat(s),e.segmentTemplate=a;break}case"ContentProtection":{let[a,s]=Nt(o);s.length>0&&(r=r.concat(s)),a!==void 0&&t.push(a);break}case"EssentialProperty":_(e.essentialProperties)?e.essentialProperties=[Le(o)]:e.essentialProperties.push(Le(o));break;case"SupplementalProperty":_(e.supplementalProperties)?e.supplementalProperties=[Le(o)]:e.supplementalProperties.push(Le(o));break}}return t.length>0&&(e.contentProtections=t),[e,r]}function Dy(n){let e={},t=[],r=Oe(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:Ie,dashName:"bandwidth"});break;case"codecs":e.codecs=o.value;break;case"codingDependency":r(o.value,{asKey:"codingDependency",parser:qe,dashName:"codingDependency"});break;case"frameRate":r(o.value,{asKey:"frameRate",parser:or,dashName:"frameRate"});break;case"height":r(o.value,{asKey:"height",parser:Ie,dashName:"height"});break;case"id":e.id=o.value;break;case"maxPlayoutRate":r(o.value,{asKey:"maxPlayoutRate",parser:$e,dashName:"maxPlayoutRate"});break;case"maximumSAPPeriod":r(o.value,{asKey:"maximumSAPPeriod",parser:$e,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:Ie,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:Ie,dashName:"width"});break;case"availabilityTimeOffset":r(o.value,{asKey:"availabilityTimeOffset",parser:$e,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(o.value,{asKey:"availabilityTimeComplete",parser:qe,dashName:"availabilityTimeComplete"});break}}return e.bitrate===void 0&&t.push(new tt("No bitrate found on a Representation")),[e,t]}function Xf(n){let[e,t]=Oy(n.childNodes),[r,i]=Dy(n),o=t.concat(i);return[{children:e,attributes:r},o]}function Ly(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=[Le(o)]:e.accessibilities.push(Le(o));break;case"BaseURL":{let[a,s]=Lt(o);a!==void 0&&e.baseURLs.push(a),s.length>0&&(r=r.concat(s));break}case"ContentComponent":e.contentComponent=au(o);break;case"EssentialProperty":_(e.essentialProperties)?e.essentialProperties=[Le(o)]:e.essentialProperties.push(Le(o));break;case"InbandEventStream":e.inbandEventStreams===void 0&&(e.inbandEventStreams=[]),e.inbandEventStreams.push(Le(o));break;case"Label":{let a=o.textContent;a!=null&&(e.label=a);break}case"Representation":{let[a,s]=Xf(o);e.representations.push(a),s.length>0&&(r=r.concat(s));break}case"Role":_(e.roles)?e.roles=[Le(o)]:e.roles.push(Le(o));break;case"SupplementalProperty":_(e.supplementalProperties)?e.supplementalProperties=[Le(o)]:e.supplementalProperties.push(Le(o));break;case"SegmentBase":{let[a,s]=Ut(o);e.segmentBase=a,s.length>0&&(r=r.concat(s));break}case"SegmentList":{let[a,s]=Hi(o);e.segmentList=a,s.length>0&&(r=r.concat(s));break}case"SegmentTemplate":{let[a,s]=xn(o);e.segmentTemplate=a,s.length>0&&(r=r.concat(s));break}case"ContentProtection":{let[a,s]=Nt(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 Ny(n){let e={},t=[],r=Oe(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:Ie,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:Ie,dashName:"minBandwidth"});break;case"maxBandwidth":r(o.value,{asKey:"maxBitrate",parser:Ie,dashName:"maxBandwidth"});break;case"minWidth":r(o.value,{asKey:"minWidth",parser:Ie,dashName:"minWidth"});break;case"maxWidth":r(o.value,{asKey:"maxWidth",parser:Ie,dashName:"maxWidth"});break;case"minHeight":r(o.value,{asKey:"minHeight",parser:Ie,dashName:"minHeight"});break;case"maxHeight":r(o.value,{asKey:"maxHeight",parser:Ie,dashName:"maxHeight"});break;case"minFrameRate":r(o.value,{asKey:"minFrameRate",parser:or,dashName:"minFrameRate"});break;case"maxFrameRate":r(o.value,{asKey:"maxFrameRate",parser:or,dashName:"maxFrameRate"});break;case"selectionPriority":r(o.value,{asKey:"selectionPriority",parser:Ie,dashName:"selectionPriority"});break;case"segmentAlignment":r(o.value,{asKey:"segmentAlignment",parser:ou,dashName:"segmentAlignment"});break;case"subsegmentAlignment":r(o.value,{asKey:"subsegmentAlignment",parser:ou,dashName:"subsegmentAlignment"});break;case"bitstreamSwitching":r(o.value,{asKey:"bitstreamSwitching",parser:qe,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:qe,dashName:"codingDependency"});break;case"frameRate":r(o.value,{asKey:"frameRate",parser:or,dashName:"frameRate"});break;case"height":r(o.value,{asKey:"height",parser:Ie,dashName:"height"});break;case"maxPlayoutRate":r(o.value,{asKey:"maxPlayoutRate",parser:$e,dashName:"maxPlayoutRate"});break;case"maximumSAPPeriod":r(o.value,{asKey:"maximumSAPPeriod",parser:$e,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:Ie,dashName:"width"});break;case"availabilityTimeOffset":r(o.value,{asKey:"availabilityTimeOffset",parser:$e,dashName:"availabilityTimeOffset"});break;case"availabilityTimeComplete":r(o.value,{asKey:"availabilityTimeComplete",parser:qe,dashName:"availabilityTimeComplete"});break}}return[e,t]}function Zf(n){let e=n.childNodes,[t,r]=Ly(e),[i,o]=Ny(n),a=r.concat(o);return[{children:t,attributes:i},a]}function lu(n){let e={children:{events:[]},attributes:{}},t=[],r=Oe(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:Ie,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]=Uy(o);e.children.events.push(a),s.length>0&&(t=t.concat(s));break}}}return[e,t]}function Uy(n){let e={eventStreamData:n},t=[],r=Oe(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:Ie,dashName:"presentationTime"});break;case"duration":r(o.value,{asKey:"duration",parser:Ie,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,c]=Lt(d);u!==void 0&&e.push(u),o=o.concat(c);break}case"AdaptationSet":{let[u,c]=Zf(d);t.push(u),o=o.concat(c);break}case"EventStream":{let[u,c]=lu(d);a.push(u),o=o.concat(c);break}case"SegmentTemplate":{let[u,c]=xn(d);r=u,c.length>0&&(o=o.concat(c));break}case"ContentProtection":{let[u,c]=Nt(d);c.length>0&&(o=o.concat(c)),u!==void 0&&i.push(u);break}}}return[{baseURLs:e,adaptations:t,eventStreams:a,segmentTemplate:r,contentProtections:i},o]}function Fy(n){let e={},t=[],r=Oe(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:yt,dashName:"start"});break;case"duration":r(o.value,{asKey:"duration",parser:yt,dashName:"duration"});break;case"bitstreamSwitching":r(o.value,{asKey:"bitstreamSwitching",parser:qe,dashName:"bitstreamSwitching"});break;case"xlink:href":e.xlinkHref=o.value;break;case"xlink:actuate":e.xlinkActuate=o.value;break}}return[e,t]}function Ta(n){let[e,t]=By(n.childNodes),[r,i]=Fy(n),o=t.concat(i);return[{children:e,attributes:r},o]}function Ky(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,c]=Lt(d);u!==void 0&&e.push(u),a=a.concat(c);break}case"Location":t.push(d.textContent===null?"":d.textContent);break;case"Period":{let[u,c]=Ta(d);r.push(u),a=a.concat(c);break}case"UTCTiming":{let u=Le(d);i.push(u);break}case"ContentProtection":{let[u,c]=Nt(d);c.length>0&&(a=a.concat(c)),u!==void 0&&o.push(u);break}}}return[{baseURLs:e,locations:t,periods:r,utcTimings:i,contentProtections:o},a]}function Vy(n){let e={},t=[],r=Oe(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:Sa,dashName:"availabilityStartTime"});break;case"availabilityEndTime":r(o.value,{asKey:"availabilityEndTime",parser:Sa,dashName:"availabilityEndTime"});break;case"publishTime":r(o.value,{asKey:"publishTime",parser:Sa,dashName:"publishTime"});break;case"mediaPresentationDuration":r(o.value,{asKey:"duration",parser:yt,dashName:"mediaPresentationDuration"});break;case"minimumUpdatePeriod":r(o.value,{asKey:"minimumUpdatePeriod",parser:yt,dashName:"minimumUpdatePeriod"});break;case"minBufferTime":r(o.value,{asKey:"minBufferTime",parser:yt,dashName:"minBufferTime"});break;case"timeShiftBufferDepth":r(o.value,{asKey:"timeShiftBufferDepth",parser:yt,dashName:"timeShiftBufferDepth"});break;case"suggestedPresentationDelay":r(o.value,{asKey:"suggestedPresentationDelay",parser:yt,dashName:"suggestedPresentationDelay"});break;case"maxSegmentDuration":r(o.value,{asKey:"maxSegmentDuration",parser:yt,dashName:"maxSegmentDuration"});break;case"maxSubsegmentDuration":r(o.value,{asKey:"maxSubsegmentDuration",parser:yt,dashName:"maxSubsegmentDuration"});break}}return[e,t]}function Jf(n){let[e,t]=Ky(n.childNodes),[r,i]=Vy(n),o=t.concat(i);return[{children:e,attributes:r},o]}function cu(n,e){let t=n.documentElement;if(_(t)||t.nodeName!=="MPD")throw new Error("DASH Parser: document root should be MPD");let[r,i]=Jf(t),o=$f(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 l=0;l<d.length;l++){let{responseData:f,receivedTime:p,sendingTime:g,url:b}=d[l];if(!f.success)throw f.error;let h="<root>"+f.data+"</root>",I=new DOMParser().parseFromString(h,"text/xml");if(_(I)||I.children.length===0)throw new Error("DASH parser: Invalid external ressources");let T=I.children[0].children,R=[],E=[];for(let v=0;v<T.length;v++)if(T[v].nodeType===Node.ELEMENT_NODE){let[k,x]=Ta(T[v]);E.push(...x),R.push(k)}u.push({url:b,receivedTime:p,sendingTime:g,parsed:R,warnings:E})}let c=s.value.continue(u);return a(c)}}};He(s)}}var em=cu;function ze(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 fu(n,e){return(t,r,i)=>new Promise((o,a)=>{let s=Date.now()-V(),d=!1,f={reject:b=>{var R,E;if(d||i.isCancelled())return;d=!0,i.deregister(g);let h=b,I=(R=h==null?void 0:h.message)!=null?R:"Unknown error when fetching the Manifest through a custom manifestLoader.",T=new it(I,(E=h==null?void 0:h.canRetry)!=null?E:!1,h==null?void 0:h.xhr);a(T)},resolve:b=>{if(d||i.isCancelled())return;d=!0,i.deregister(g);let h=b.receivingTime!==void 0?b.receivingTime-s:void 0,I=b.sendingTime!==void 0?b.sendingTime-s:void 0;o({responseData:b.data,size:b.size,requestDuration:b.duration,url:b.url,receivedTime:h,sendingTime:I})},fallback:()=>{d||i.isCancelled()||(d=!0,i.deregister(g),e(t,r,i).then(o,a))}},p=n({url:t,timeout:r.timeout,cmcdPayload:r.cmcdPayload},f);i.register(g);function g(b){d||(d=!0,typeof p=="function"&&p(),a(b))}})}function zy(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"?ze(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 Se({url:o,headers:a,responseType:"arraybuffer",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});case"text":return Se({url:o,headers:a,responseType:"text",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});case"document":return Se({url:o,headers:a,responseType:"document",timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i});default:He(n)}}}function Wi({customManifestLoader:n},e,t){let r=zy(e),i=typeof n!="function"?r:fu(n,r);return t!==null?t(i):i}function on(n,e){if(e){if(Et(n,1718909296)<0)throw new Ne("INTEGRITY_ERROR","Incomplete `ftyp` box");if(Et(n,1836019574)<0)throw new Ne("INTEGRITY_ERROR","Incomplete `moov` box")}else{if(Et(n,1836019558)<0)throw new Ne("INTEGRITY_ERROR","Incomplete `moof` box");if(Et(n,1835295092)<0)throw new Ne("INTEGRITY_ERROR","Incomplete `mdat` box")}}function It(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 _a(n){return(e,t,r,i,o)=>{return new Promise((s,d)=>{let u=new U,c=u.linkToSignal(i);u.signal.register(d),n(e,t,r,u.signal,de(oe({},o),{onNewChunk(f){try{a(f),o.onNewChunk(f)}catch(p){l(),u.cancel(),d(p)}}})).then(f=>{if(l(),!u.isUsed()){if(f.resultType==="segment-loaded")try{a(f.resultData.responseData)}catch(p){d(p);return}s(f)}},f=>{l(),d(f)});function l(){u.signal.deregister(d),c()}});function a(s){!(s instanceof ArrayBuffer)&&!(s instanceof Uint8Array)||It(t.type,t.mimeType)!=="mp4"||on(new Uint8Array(s),t.segment.isInit)}}}function tm(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 c=d[u];for(;Hy(a[s]);)s--;for(let l=c.length-1;l>=0;l--){if(a[s]!==c[l])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 c=u.length-1;c>=0;c--){let l=u[c];for(;Wy(d.getUint8(s));)s--;for(let f=l.length-1;f>=0;f--){if(d.getUint8(s)!==l[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 Ne("INTEGRITY_ERROR","MPD does not end with </MPD>")}}}function Hy(n){return n===" "||n===" "||n==="\r"||n===`
5
+ `}function Wy(n){return n===32||n===9||n===13||n===10}function mu(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,c=o.externalClockOffset,l=(T=i.url)!=null?T:o.originalUrl,f=t!=null?t:c,g={unsafelyBaseOnPreviousManifest:o.unsafeMode?o.previousManifest:null,url:l,referenceDateTime:e,externalClockOffset:f},b=fe.dashParsers;if(b.wasm===null||b.wasm.status==="uninitialized"||b.wasm.status==="failure")return m.debug("DASH: WASM MPD Parser not initialized. Running JS one."),h();{let R=$y(u);if(!Qy(R))return m.info("DASH: MPD doesn't seem to be UTF-8-encoded. Running JS parser instead of the WASM one."),h();if(b.wasm.status==="initialized"){m.debug("DASH: Running WASM MPD Parser.");let E=b.wasm.runWasmParser(R,g);return I(E)}else return m.debug("DASH: Awaiting WASM initialization before parsing the MPD."),b.wasm.waitForInitialization().catch(()=>{}).then(()=>{if(b.wasm===null||b.wasm.status!=="initialized")return m.warn("DASH: WASM MPD parser initialization failed. Running JS parser instead"),h();m.debug("DASH: Running WASM MPD Parser.");let v=b.wasm.runWasmParser(R,g);return I(v)})}function h(){if(b.fastJs!==null){let R=jy(u),E=b.fastJs(R,g);return I(E)}else if(b.native!==null){let R=Yy(u),E=b.native(R,g);return I(E)}else throw new Error("No MPD parser is imported")}function I(R){if(R.type==="done"){if(R.value.warnings.length>0&&a(R.value.warnings),s.isCancelled())return Promise.reject(s.cancellationError);let k=[];return{manifest:new $n(R.value.parsed,n,k),url:l,warnings:k}}let{value:E}=R,v=E.urls.map(k=>d(()=>{let x=L.getCurrent().DEFAULT_REQUEST_TIMEOUT,P=L.getCurrent().DEFAULT_CONNECTION_TIMEOUT;return E.format==="string"?Se({url:k,responseType:"text",timeout:x,connectionTimeout:P,cancelSignal:s}):Se({url:k,responseType:"arraybuffer",timeout:x,connectionTimeout:P,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 Y(x,{responseData:{success:!0,data:x.responseData}})}else{if(!(x.responseData instanceof ArrayBuffer))throw new Error("External DASH resources should have been ArrayBuffers");return Y(x,{responseData:{success:!0,data:x.responseData}})}},x=>{let P=Ee(x,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"An unknown error occured when parsing ressources."});return Y({},{size:void 0,requestDuration:void 0,responseData:{success:!1,error:P}})}));return Promise.all(v).then(k=>E.format==="string"?(qy(k),I(E.continue(k))):(Gy(k),I(E.continue(k))))}}}function qy(n){y.CURRENT_ENV!==y.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 Gy(n){y.CURRENT_ENV!==y.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 jy(n){if(n instanceof ArrayBuffer)return Ue(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 Yy(n){if(n instanceof ArrayBuffer)return new DOMParser().parseFromString(Ue(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 $y(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 Qy(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 Qe([n,e]){return e===1/0?`bytes=${n}-`:`bytes=${n}-${e}`}function wn(n,e){return n===null?null:e.url===null?n.baseUrl:gn(n.baseUrl,e.url)}function qi(n,e,t,r,i){var u,c;let o=n;((u=t.cmcdPayload)==null?void 0:u.type)==="query"&&(o=ze(o,t.cmcdPayload.value));let a=((c=t.cmcdPayload)==null?void 0:c.type)==="headers"?t.cmcdPayload.value:void 0;if(e.range===void 0)return Se({url:o,responseType:"arraybuffer",headers:a,timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(l=>({resultType:"segment-loaded",resultData:l}));if(e.indexRange===void 0)return Se({url:o,headers:de(oe({},a),{Range:Qe(e.range)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(l=>({resultType:"segment-loaded",resultData:l}));if(e.range[1]+1===e.indexRange[0])return Se({url:o,headers:de(oe({},a),{Range:Qe([e.range[0],e.indexRange[1]])}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}).then(l=>({resultType:"segment-loaded",resultData:l}));let s=Se({url:o,headers:de(oe({},a),{Range:Qe(e.range)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress}),d=Se({url:o,headers:de(oe({},a),{Range:Qe(e.indexRange)}),responseType:"arraybuffer",timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r,onProgress:i.onProgress});return Promise.all([s,d]).then(([l,f])=>{let p=se(new Uint8Array(l.responseData),new Uint8Array(f.responseData)),g=Math.min(l.sendingTime,f.sendingTime),b=Math.max(l.receivedTime,f.receivedTime);return{resultType:"segment-loaded",resultData:{url:o,responseData:p,size:l.size+f.size,requestDuration:b-g,sendingTime:g,receivedTime:b}}})}async function Gi(n,e,t,r){let i=null;function o(s){let d=new Uint8Array(s.chunk),u=i!==null?se(i,d):d,c=$o(u),l=c[0];i=c[1],!(l!==null&&(l.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 Po({url:n,headers:e.headers,onData:o,timeout:e.timeout,connectionTimeout:e.connectionTimeout,cancelSignal:r})}}async function nm(n,e,t,r,i,o){var f,p;if(e.segment.isInit)return qi(n,e.segment,r,o,i);let a=((f=r.cmcdPayload)==null?void 0:f.type)==="query"?ze(n,r.cmcdPayload.value):n,s=((p=r.cmcdPayload)==null?void 0:p.type)==="headers"?r.cmcdPayload.value:void 0,{segment:d}=e,u;d.range!==void 0?u=de(oe({},s),{Range:Qe(d.range)}):s!==void 0&&(u=s);let c=It(e.type,e.mimeType);if(t&&(c==="mp4"||c===void 0)){if(xr())return Gi(a,{headers:u,timeout:r.timeout,connectionTimeout:r.connectionTimeout},i,o);wt("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 Se({url:a,responseType:"arraybuffer",headers:u,timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:o,onProgress:i.onProgress})}}function pu({lowLatencyMode:n,segmentLoader:e,checkMediaSegmentIntegrity:t}){return t!==!0?r:_a(r);function r(i,o,a,s,d){let u=wn(i,o.segment);return u===null?Promise.resolve({resultType:"segment-created",resultData:null}):n||e===void 0?nm(u,o,n,a,d,s):new Promise((c,l)=>{let f=!1,I={reject:k=>{var O,B;if(f||s.isCancelled())return;f=!0,s.deregister(v);let x=k,P=(O=x==null?void 0:x.message)!=null?O:"Unknown error when fetching a DASH segment through a custom segmentLoader.",M=new it(P,(B=x==null?void 0:x.canRetry)!=null?B:!1,x==null?void 0:x.xhr);l(M)},resolve:k=>{f||s.isCancelled()||(f=!0,s.deregister(v),c({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(v),nm(u,o,n,a,d,s).then(c,l))}},T;o.segment.range!==void 0&&(T=[o.segment.range],o.segment.indexRange!==void 0&&T.push(o.segment.indexRange));let R={isInit:o.segment.isInit,timeout:a.timeout,byteRanges:T,trackType:o.type,url:u,cmcdPayload:a.cmcdPayload},E=e(R,I);s.register(v);function v(k){f||(f=!0,typeof E=="function"&&E(),l(k))}})}}var hu=408125543,rm=357149030,Xy=2807729,Zy=17545,Jy=475249515,eI=187,tI=179,nI=183,rI=241;function an(n,e,t,[r,i]){let o=r;for(;o<i;){let a=oI(t,o);if(a===null)return null;let{value:s,length:d}=a,u=o+d,c=aI(t,u);if(c===null)return null;let{length:l,value:f}=c,p=u+l,g=p+f;if(s===n)return[p,g];if(e.length>0){for(let b=0;b<e.length;b++)if(s===e[b]){let h=e.slice(b+1,e.length);return an(n,h,t,[p,g])}}o=g}return null}function Ea(n,e){let t=an(Xy,[hu,rm],n,[e,n.length]);if(t===null)return null;let r=t[1]-t[0];return 1e9/gu(n,t[0],r)}function iI(n,e){let t=an(Zy,[hu,rm],n,[e,n.length]);if(t===null)return null;let r=t[1]-t[0];return r===4?sI(n,t[0]):r===8?dI(n,t[0]):null}function yu(n,e){let t=an(hu,[],n,[e,n.length]);if(t===null)return null;let[r,i]=t,o=Ea(n,r);if(o===null)return null;let a=iI(n,r);if(a===null)return null;let s=an(Jy,[],n,[r,i]);if(s===null)return null;let d=[],u=s[0];for(;u<s[1];){let l=an(eI,[],n,[u,s[1]]);if(l===null)break;let f=an(tI,[],n,[l[0],l[1]]);if(f===null)return null;let p=gu(n,f[0],f[1]-f[0]),g=an(rI,[nI],n,[l[0],l[1]]);if(g===null)return null;let b=gu(n,g[0],g[1]-g[0])+r;d.push({time:p,rangeStart:b}),u=l[1]}let c=[];for(let l=0;l<d.length;l++){let f=d[l];l===d.length-1?c.push({time:f.time,timescale:o,duration:l===0?a:a-f.time,range:[f.rangeStart,1/0]}):c.push({time:f.time,timescale:o,duration:d[l+1].time-f.time,range:[f.rangeStart,d[l+1].rangeStart-1]})}return c}function im(n,e){for(let t=1;t<=8;t++)if(n[e]>=Math.pow(2,8-t))return t}function oI(n,e){let t=im(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 aI(n,e){let t=im(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 sI(n,e){return new DataView(n.buffer).getFloat32(e)}function dI(n,e){return new DataView(n.buffer).getFloat64(e)}function gu(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 ji(n,e,t,r){let i=Ds(n);if(i===void 0||r===void 0)return null;let o=t.timestampOffset!==void 0?i+t.timestampOffset*r:i,a=Wr(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 uI(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=Ue(a),d=Date.parse(s);if(o===void 0||d===void 0||isNaN(d)||d>=o)return!0}return!1}function Iu(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:uI(t,e);return{inbandEvents:i,needsManifestRefresh:o}}function bu({__priv_patchLastSegmentInSidx:n}){return function(t,r,i){var R,E;let{segment:o,periodStart:a,periodEnd:s}=r,{data:d,isChunked:u}=t,c=[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:c};let l=d instanceof Uint8Array?d:new Uint8Array(d),f=It(r.type,r.mimeType),p=f==="mp4"||f===void 0,g=[];if(p){let v=Qo(l),k;o.isInit&&(k=(R=ef(l))!=null?R:void 0),(v.length>0||k!==void 0)&&g.push({initDataType:"cenc",keyId:k,initData:v})}if(!o.isInit){let v=p?ji(l,u,o,i):null,k=(E=o.timestampOffset)!=null?E:0;if(p){let x=Jc(l);if(x!==void 0){let P=x.filter(O=>o.privateInfos===void 0||o.privateInfos.isEMSGWhitelisted===void 0?!1:o.privateInfos.isEMSGWhitelisted(O)),M=Iu(P,r.manifestPublishTime);if(M!==void 0){let{needsManifestRefresh:O,inbandEvents:B}=M;return{segmentType:"media",chunkData:l,chunkSize:l.length,chunkInfos:v,chunkOffset:k,appendWindow:c,inbandEvents:B,protectionData:g,needsManifestRefresh:O}}}}return{segmentType:"media",chunkData:l,chunkSize:l.length,chunkInfos:v,chunkOffset:k,protectionData:g,appendWindow:c}}let{indexRange:b}=o,h;if(f==="webm")h=yu(l,0);else if(p&&(h=Hr(l,Array.isArray(b)?b[0]:0),n===!0&&h!==null&&h.length>0)){let v=h[h.length-1];Array.isArray(v.range)&&(v.range[1]=1/0)}let I;p?I=qr(l):f==="webm"&&(I=Ea(l,0));let T=_(I)?void 0:I;return{segmentType:"init",initializationData:l,initializationDataSize:l.length,protectionData:g,initTimescale:T,segmentList:h!=null?h:void 0}}}function Su({lowLatencyMode:n,checkMediaSegmentIntegrity:e}){return e!==!0?t:_a(t);async function t(r,i,o,a,s){var h,I;let{segment:d}=i,u=wn(r,d);if(u===null)return Promise.resolve({resultType:"segment-created",resultData:null});if(d.isInit)return qi(u,d,o,a,s);let c=((h=o.cmcdPayload)==null?void 0:h.type)==="query"?ze(u,o.cmcdPayload.value):u,l=((I=o.cmcdPayload)==null?void 0:I.type)==="headers"?o.cmcdPayload.value:void 0,f;d.range!==void 0?f=de(oe({},l),{Range:Qe(d.range)}):l!==void 0&&(f=l);let p=It(i.type,i.mimeType),g=p==="mp4"||p===void 0;if(n&&g){if(xr())return Gi(c,{headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout},s,a);wt("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 b;return g?b=await Se({url:c,responseType:"arraybuffer",headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout,onProgress:s.onProgress,cancelSignal:a}):b=await Se({url:c,responseType:"text",headers:f,timeout:o.timeout,connectionTimeout:o.connectionTimeout,onProgress:s.onProgress,cancelSignal:a}),{resultType:"segment-loaded",resultData:b}}}function lI(n){let e=Vr(n);return e===null?"":Ue(e)}function cI(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 fI(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 om({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=cI(t);return{data:lI(r),type:d,language:e,start:a,end:s}}function am(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=fI(n.codecs,n.mimeType);return{data:e,type:a,language:n.language,start:i,end:o}}function mI(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 p=Hr(d,Array.isArray(s)?s[0]:0);if(i===!0&&p!==null&&p.length>0){let b=p[p.length-1];Array.isArray(b.range)&&(b.range[1]=1/0)}let g=qr(d);return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:g,segmentList:p!=null?p:void 0}}let u=ji(d,e,o,r),c=om(t,d,u,e),l=(f=o.timestampOffset)!=null?f:0;return{segmentType:"media",chunkData:c,chunkSize:d.length,chunkInfos:u,chunkOffset:l,protectionData:[],appendWindow:[t.periodStart,t.periodEnd]}}function pI(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 c=n instanceof Uint8Array?n:new Uint8Array(n);s=Ue(c),d=c.length}else s=n;return{segmentType:"media",chunkData:am(t,s,e),chunkSize:d,chunkInfos:null,chunkOffset:a,protectionData:[],appendWindow:[r,i]}}function Tu({__priv_patchLastSegmentInSidx:n}){return function(t,r,i){var l;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:(l=s.timestampOffset)!=null?l:0,protectionData:[],appendWindow:[o,a]};let c=It(r.type,r.mimeType);if(c==="webm")throw new Error("Text tracks with a WEBM container are not yet handled.");return c==="mp4"?mI(d,u,r,i,n):pI(d,u,r)}}async function sm(n,e,t,r){var d,u;let i=wn(n,e);if(i===null)return Promise.reject(new Error("Cannot load thumbnail: no URL"));let o=((d=t.cmcdPayload)==null?void 0:d.type)==="query"?ze(i,t.cmcdPayload.value):i,a=((u=t.cmcdPayload)==null?void 0:u.type)==="headers"?t.cmcdPayload.value:void 0,s;return e.range!==void 0?s=de(oe({},a),{Range:Qe(e.range)}):a!==void 0&&(s=a),wr({url:o,responseType:"arraybuffer",headers:s,timeout:t.timeout,connectionTimeout:t.connectionTimeout,cancelSignal:r})}function dm(n,e){var u;let{thumbnailTrack:t,thumbnail:r}=e,i=t.height/t.verticalTiles,o=t.width/t.horizontalTiles,a=[],s=(u=t.tileDuration)!=null?u:(r.end-r.time)/(t.horizontalTiles*t.verticalTiles),d=r.time;for(let c=0;c<t.verticalTiles;c++)for(let l=0;l<t.horizontalTiles;l++)a.push({start:d,end:d+s,offsetX:Math.round(l*o),offsetY:Math.round(c*i),height:Math.floor(i),width:Math.floor(o)}),d+=s;return{mimeType:t.mimeType,data:n,thumbnails:a}}function um(n){let e=Wi({customManifestLoader:n.manifestLoader},gI()?"text":"arraybuffer",n.checkManifestIntegrity===!0?tm:null),t=mu(n),r=pu(n),i=bu(n),o=Su(n),a=Tu(n);return{transportName:"dash",manifest:{loadManifest:e,parseManifest:t},audio:{loadSegment:r,parseSegment:i},video:{loadSegment:r,parseSegment:i},text:{loadSegment:o,parseSegment:a},thumbnails:{loadThumbnail:sm,parseThumbnail:dm}}}function gI(){return fe.dashParsers.wasm!==null&&(fe.dashParsers.wasm.status==="initialized"||fe.dashParsers.wasm.status==="initializing")}var lm=um;function _u(n){n.transports.dash===void 0&&(n.transports.dash=lm),n.dashParsers.native=em,n.mainThreadMediaSourceInit=kn}var hI=typeof MediaSource=="function"&&MediaSource.canConstructInDedicatedWorker===!0,cm=hI;var Yi=class extends Jn{constructor(e){super(),this._settings=e,this._initCanceller=new U}prepare(){}start(e,t){let r=this._initCanceller.signal,{keySystems:i,speed:o,url:a}=this._settings;er(e);let{statusRef:s}=Mi(e,i,{onError:u=>this._onFatalError(u),onWarning:u=>this.trigger("warning",u),onBlackListProtectionData:Z,onKeyIdsCompatibilityUpdate:Z},r);Oi(e,u=>this._onFatalError(u),r);let d=new Rn(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,c)=>{u.initializationState.type!=="uninitialized"&&(c(),m.info("Setting URL to HTMLMediaElement",a),e.src=a,r.register(()=>{m.info("Init: Removing directfile src from media element",e.src),er(e)}),u.initializationState.type==="awaiting-media-link"?(u.initializationState.value.isMediaLinked.setValue(!0),s.onUpdate((l,f)=>{l.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;Ci({mediaElement:e,playbackObserver:t,startTime:()=>{m.debug("Init: Calculating initial time");let s=yI(e,o);return m.debug("Init: Initial time calculated:",s),s},mustAutoPlay:i,onWarning:s=>this.trigger("warning",s),isDirectfile:!0},r).autoPlayResult.then(()=>Pi(t,!0,r).onUpdate((s,d)=>{s&&(d(),this.trigger("loaded",{getSegmentSinkMetrics:null,getThumbnailData:()=>Promise.reject(new Error("Thumbnail data not available with directfile contents"))}))},{emitCurrentValue:!0,clearSignal:r})).catch(s=>{r.isCancelled()||this._onFatalError(s)})}};function yI(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 Eu(n,e){for(let t=0;t<n.length;t++)(!gr||t!==e)&&(n[t].enabled=!1);return e<0||e>=n.length?!1:(n[e].enabled=!0,!0)}function ar(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 vu(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:Or(o.language),audioDescription:o.kind==="descriptions"||o.kind==="description",representations:[]};e.push({track:u,nativeTrack:o})}return e}function Ru(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,c={language:o.language,forced:u,label:o.label,id:d,normalized:Or(o.language),closedCaption:o.kind==="captions"};e.push({track:c,nativeTrack:o})}return e}function ku(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 $i=class extends ae{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?vu(this._nativeAudioTracks):[],this._videoTracks=this._nativeVideoTracks!==void 0?ku(this._nativeVideoTracks):[],this._textTracks=this._nativeTextTracks!==void 0?Ru(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(){fm(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(){mm(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){fm(this._textTracks);return}else for(let e=0;e<this._textTracks.length;e++){let{nativeTrack:t}=this._textTracks[e];if(t===this._textTrackLockedOn){II(this._textTracks,t),t.mode!=="showing"&&(t.mode="showing");return}}}_setPreviouslyLockedVideoTrack(){if(this._videoTrackLockedOn!==void 0)if(this._videoTrackLockedOn===null){mm(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=vu(this._nativeAudioTracks);if(ar(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=vu(this._nativeAudioTracks);if(ar(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=Ru(this._nativeTextTracks);if(ar(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=Ru(this._nativeTextTracks);if(ar(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=ku(this._nativeVideoTracks);if(ar(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=ku(this._nativeVideoTracks);if(ar(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){Eu(this._audioTracks.map(({nativeTrack:t})=>t),e)}};function fm(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.mode="disabled"}}function II(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 mm(n){for(let e=0;e<n.length;e++){let{nativeTrack:t}=n[e];t.selected=!1}}function Pu(n){n.directfile={initDirectFile:Yi,mediaElementTracksStore:$i}}function Cu(n){n.decrypt=ff}var pm=J.ResizeObserver;function Mu(n,e,t){let{height:r,width:i}=n.getBoundingClientRect(),o=new G({height:r,width:i},t),a=r,s=i;if(pm!==void 0){let d=new pm(u=>{if(u.length===0){m.error("Compat: Resized but no observed element.");return}let c=u[0],{height:l,width:f}=c.contentRect;(l!==a||f!==s)&&(a=l,s=f,o.setValue({height:l,width:f}))});d.observe(n),t.register(()=>{d.disconnect()})}else{let d=setInterval(()=>{let{height:u,width:c}=n.getBoundingClientRect();(u!==a||c!==s)&&(a=u,s=c,o.setValue({height:u,width:c}))},e);t.register(()=>{clearInterval(d)})}return o}var On=class{constructor(){this._ranges=[],this.length=0}insert(e,t){y.CURRENT_ENV===y.DEV&&(ee(e>=0,"invalid start time"),ee(t-e>0,"invalid end time")),jt(this._ranges,{start:e,end:t}),this.length=this._ranges.length}remove(e,t){y.CURRENT_ENV===y.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=cc(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 Au(n,e,t,r){m.debug("HTSB: Finding parser for html text tracks:",n);let i=fe.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 Bt(n,e,t=.2){return Math.abs(n-e)<=Math.min(t,.2)}var bI=.05;function gm(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<=bI}function Qi(n,e){for(let t=n.length-1;t>=0;t--)if(n[t].start<e)return n.slice(0,t+1);return[]}function sr(n,e){for(let t=0;t<n.length;t++)if(n[t].end>e)return n.slice(t,n.length);return[]}function xu(n,e,t){let r=Math.max(n.start,e),i=Qi(n.cues,e),o={start:n.start,end:r,cues:i},a=Math.min(t,n.end),s=sr(n.cues,t),d={start:a,end:n.end,cues:s};return[o,d]}var hm=.001,SI=5,Xi=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)(Bt(e,s.start,hm)||Bt(e,s.end,hm))&&r.push(s.element);return r}}return[]}remove(e,t){y.CURRENT_ENV===y.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=sr(a.cues,r),a.start=r;else{let[s,d]=xu(a,e,r);this._cuesBuffer[o]=s,i.splice(o+1,0,d)}return}a.start>=e?(i.splice(o,1),o--):(a.cues=Qi(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)/SI;function s(d){let u=i[d];u===void 0||Bt(o.end,u.end,a)?i[d]=o:(u.start>=o.end||(u.cues=sr(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(gm(o,u)){if(Bt(r,u.end,a)){i[d]=o;return}else if(r<u.end){u.cues=sr(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(Bt(r,u.start,a)){u.start=r,i.splice(d,0,o);return}else if(Bt(r,u.end,a)){i.splice(d,1,o);return}else if(r<u.end){u.cues=sr(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(Bt(u.end,r,a)){u.cues=Qi(u.cues,t),u.end=t,i.splice(d+1,0,o);return}else if(u.end>r){let[c,l]=xu(u,t,r);this._cuesBuffer[d]=c,i.splice(d+1,0,o),i.splice(d+2,0,l);return}else{u.cues=Qi(u.cues,t),u.end=t;let c=d+1;for(u=i[c];u!==void 0&&r>u.end;)i.splice(c,1),u=i[c];s(c);return}}}if(i.length>0){let d=i[i.length-1];Bt(d.end,t,a)&&(d.end=t)}i.push(o)}};function wu(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 c=s.getAttribute("data-proportional-height");c!==null&&!isNaN(+c)&&(s.style.height=String(+c*i[1])+"px");let l=s.getAttribute("data-proportional-line-height");l!==null&&!isNaN(+l)&&(s.style.lineHeight=String(+l*i[1])+"px");let f=s.getAttribute("data-proportional-left");f!==null&&!isNaN(+f)&&(s.style.left=String(+f*i[0])+"px");let p=s.getAttribute("data-proportional-top");p!==null&&!isNaN(+p)&&(s.style.top=String(+p*i[1])+"px");let g=s.getAttribute("data-proportional-padding-top");g!==null&&!isNaN(+g)&&(s.style.paddingTop=String(+g*i[1])+"px");let b=s.getAttribute("data-proportional-padding-bottom");b!==null&&!isNaN(+b)&&(s.style.paddingBottom=String(+b*i[1])+"px");let h=s.getAttribute("data-proportional-padding-left");h!==null&&!isNaN(+h)&&(s.style.paddingLeft=String(+h*i[0])+"px");let I=s.getAttribute("data-proportional-padding-right");I!==null&&!isNaN(+I)&&(s.style.paddingRight=String(+I*i[0])+"px")}}return o.length>0}function ym(n,e){try{n.removeChild(e)}catch(t){m.warn("HTD: Can't remove text track: not in the element.")}}function TI(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 Zi=class{constructor(e,t){m.debug("HTD: Creating HTMLTextDisplayer"),this._buffered=new On,this._videoElement=e,this._textTrackElement=t,this._sizeUpdateCanceller=new U,this._subtitlesIntervalCanceller=new U,this._buffer=new Xi,this._currentCues=[],this._isAutoRefreshing=!1}pushTextData(e){var b,h;m.debug("HTD: Appending new html text tracks");let{timestampOffset:t,appendWindow:r,chunk:i}=e;if(i===null)return xe(this._buffered);let{start:o,end:a,data:s,type:d,language:u}=i,c=(b=r[0])!=null?b:0,l=(h=r[1])!=null?h:1/0,f=Au(d,s,t,u);if(c!==0&&l!==1/0){let I=0;for(;I<f.length&&f[I].end<=c;)I++;for(f.splice(0,I),I=0;I<f.length&&f[I].start<c;)f[I].start=c,I++;for(I=f.length-1;I>=0&&f[I].start>=l;)I--;for(f.splice(I,f.length),I=f.length-1;I>=0&&f[I].end>l;)f[I].end=l,I--}let p;if(o!==void 0)p=Math.max(c,o);else{if(f.length<=0)return m.warn("HTD: Current text tracks have no cues nor start time. Aborting"),xe(this._buffered);m.warn("HTD: No start time given. Guessing from cues."),p=f[0].start}let g;if(a!==void 0)g=Math.min(l,a);else{if(f.length<=0)return m.warn("HTD: Current text tracks have no cues nor end time. Aborting"),xe(this._buffered);m.warn("HTD: No end time given. Guessing from cues."),g=f[f.length-1].end}return g<=p?(m.warn("HTD: Invalid text track appended: ","the start time is inferior or equal to the end time."),xe(this._buffered)):(this._buffer.insert(f,p,g),this._buffered.insert(p,g),!this._isAutoRefreshing&&!this._buffer.isEmpty()&&this.autoRefreshSubtitles(this._subtitlesIntervalCanceller.signal),xe(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 U),xe(this._buffered)}getBufferedRanges(){return xe(this._buffered)}reset(){m.debug("HTD: Resetting HTMLTextDisplayer"),this.stop(),this._subtitlesIntervalCanceller=new U}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)ym(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)ym(this._textTrackElement,i.element);this._currentCues=[];for(let i of e){let o=TI(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 U,this._sizeUpdateCanceller.linkToSignal(this._subtitlesIntervalCanceller.signal);let{TEXT_TRACK_SIZE_CHECKS_INTERVAL:i}=L.getCurrent();Mu(this._textTrackElement,i,this._sizeUpdateCanceller.signal).onUpdate(({height:a,width:s})=>{for(let d of r){let{resolution:u,element:c}=d;wu(a,s,u,c)}},{clearSignal:this._sizeUpdateCanceller.signal,emitCurrentValue:!0})}}autoRefreshSubtitles(e){if(this._isAutoRefreshing||e.isCancelled())return;let t=null,{MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:r}=L.getCurrent(),i=()=>{this._isAutoRefreshing=!1,t!==null&&(t.cancel(),t=null)},o=()=>{i(),this._isAutoRefreshing=!0,t=new U,t.linkToSignal(e);let a=setInterval(()=>this.refreshSubtitles(),r);t.signal.register(()=>{clearInterval(a)}),this.refreshSubtitles()};Uc(this._videoElement,()=>{i(),this._disableCurrentCues()},e),Bc(this._videoElement,o,e),Fc(this._videoElement,o,e),o()}refreshSubtitles(){let{MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL:e}=L.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)}};y.CURRENT_ENV===y.DEV&&(_I=function(e){function t(r){}});var _I;var sn=Zi;var EI=/&#([0-9]+);/g,vI=/<br>/gi,RI=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,kI=/\s*<p (?:class=([^>]+))?>(.*)/i,PI=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i;function CI(n){let e=/\.(\S+)\s*{([^}]*)}/gi,t={},r=e.exec(n);for(;r!==null;){let i=r[1],o=AI(r[2],"lang");!_(i)&&!_(o)&&(t[o]=i),r=e.exec(n)}return t}function MI(n){let t=/p\s*{([^}]*)}/gi.exec(n);return t===null?"":t[1]}function AI(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(EI,(e,t)=>String.fromCharCode(Number(t)))}function wI(n,e,t){let r=/<sync[ >]/gi,i=/<sync[ >]|<\/body>/gi,o=[],a=RI.exec(n),s=Array.isArray(a)?a[1]:"",d,u;i.exec(n);let c=CI(s),l=MI(s),f;if(w(t)&&(f=c[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 g=n.slice(d.index,u.index),b=PI.exec(g);if(!Array.isArray(b))throw new Error("parse error (sync time attribute)");let h=+b[1];if(isNaN(h))throw new Error("parse error (sync time attribute NaN)");p(g.split(`
6
+ `),h/1e3)}return o;function p(g,b){let h=g.length;for(;--h>=0;){let I=kI.exec(g[h]);if(!Array.isArray(I))continue;let[,T,R]=I;if(f===T)if(R==="&nbsp;")o[o.length-1].end=b;else{let E=document.createElement("DIV");E.className="rxp-texttrack-region";let v=document.createElement("DIV");v.className="rxp-texttrack-div",v.style.position="absolute",v.style.bottom="0",v.style.width="100%",v.style.color="#fff",v.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(l)&&(k.style.cssText=l);let x=R.split(vI);for(let P=0;P<x.length;P++){P!==0&&k.appendChild(document.createElement("BR"));let M=document.createElement("SPAN");M.className="rxp-texttrack-span",M.textContent=xI(x[P]),k.appendChild(M)}v.appendChild(k),E.appendChild(v),o.push({element:E,start:b+e,end:-1})}}}}var Im=wI;function Ou(n){n.htmlTextTracksParsers.sami=Im,n.htmlTextDisplayer=sn}function Du(n,e){let t=e+1;for(;w(n[t]);)t++;return t}function Ji(n){let e=[];for(let t=0;t<n.length;t++)if(w(n[t])){let r=Du(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 va(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 eo(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=va(t),a=va(r);return o===void 0||a===void 0?null:{start:o+e,end:a+e,payload:i}}function Lu(n,e){let t=n.split(/\r\n|\n|\r/),r=Ji(t),i=[];for(let o of r){let a=eo(o,e);if(a!==null){let s=OI(a);s!==null&&i.push(s)}}return i}function OI(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=DI(r[o]);i.appendChild(a)}return{start:e,end:t,element:i}}function DI(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 c=document.createTextNode(d[u]);o.appendChild(c)}}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(LI(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 LI(n){return n.nodeName==="FONT"&&"color"in n}function Nu(n){n.htmlTextTracksParsers.srt=Lu,n.htmlTextDisplayer=sn}var NI=/(\d+) (\d+)/;function Uu(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 b=NI.exec(a);if(b===null||b.length<3)m.warn("TTML Parser: Invalid cellResolution");else{let h=parseInt(b[1],10),I=parseInt(b[2],10);isNaN(h)||isNaN(I)?m.warn("TTML Parser: Invalid cellResolution"):s={columns:h,rows:I}}}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 c=Number(r);(isNaN(c)||c<=0)&&(c=void 0);let l=d,f=u!=null?u:1,p=o!=null?o:"default",g=c!=null?c:d*u;if(i!==null){let b=/^(\d+) (\d+)$/g.exec(i);if(b!==null){let h=Number(b[1]),I=Number(b[2]),T=h/I;l=d*T}}return{cellResolution:s,tickRate:g,frameRate:l,subFrameRate:f,spaceStyle:p}}function Dn(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 c=s;for(let l=0;l<=c.attributes.length-1;l++){let f=c.attributes[l],p=f.name;if(p==="style")d=f.value;else if(p==="region")u=f.value;else{let g=p.substring(4);if(X(o,g)&&(i[g]=f.value,o.splice(l,1),o.length===0))return i}}}if(w(d)){let c=Q(t,l=>l.id===d);if(c!==void 0)for(let l=0;l<=o.length-1;l++){let f=o[l];if(!w(i[f])&&w(c.style[f])){if(i[f]=c.style[f],o.splice(l,1),o.length===0)return i;l--}}}if(w(u)){let c=Q(r,l=>l.id===u);if(c!==void 0)for(let l=0;l<=o.length-1;l++){let f=o[l];if(!w(i[f])&&w(c.style[f])){if(i[f]=c.style[f],o.splice(l,1),o.length===0)return i;l--}}}}}return i}function Bu(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(Xe(i.name,"tts")){let o=i.name.substring(4);t[o]=i.value}}return t}function Fu(n){let e=[];function t(r,i){e.push(i);for(let o of r.extendsStyles){let a=pe(n,s=>s.id===o);if(a<0)m.warn("TTML Parser: unknown style inheritance: "+o);else{let s=n[a];X(e,a)?m.warn("TTML Parser: infinite style inheritance loop avoided"):t(s,a),r.style=Y({},s.style,r.style)}}r.extendsStyles.length=0}for(let r=0;r<n.length;r++)t(n[r],r),e.length=0}function bm(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 Ra(n){let e=bm(n,"div");if(e.length===0){let t=bm(n,"tt:div");t.length>0&&(e=t)}return e}function Sm(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 Tm(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 _m(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 Em(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 ka(n){return n.nodeName==="br"||n.nodeName==="tt:br"}function Pa(n){return n.nodeName==="span"||n.nodeName==="tt:span"}var vm=["align","backgroundColor","color","direction","display","displayAlign","extent","fontFamily","fontSize","fontStyle","fontWeight","lineHeight","opacity","origin","overflow","padding","textAlign","textDecoration","textOutline","unicodeBidi","visibility","wrapOption","writingMode"];function to(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=Sm(o),s=Tm(o),d=_m(o),u=Em(o),c=Uu(o),l=[];for(let h=0;h<=s.length-1;h++){let I=s[h];if(I instanceof Element){let T=I.getAttribute("xml:id");if(T!==null){let R=I.getAttribute("style"),E=R===null?[]:R.split(" ");l.push({id:T,style:Bu(I),extendsStyles:E})}}}Fu(l);let f=[];for(let h=0;h<=d.length-1;h++){let I=d[h];if(I instanceof Element){let T=I.getAttribute("xml:id");if(T!==null){let R=Bu(I),E=I.getAttribute("style");if(w(E)){let v=Q(l,k=>k.id===E);v!==void 0&&(R=Y({},v.style,R))}f.push({id:T,style:R,extendsStyles:[]})}}}let p=Dn(vm,a!==null?[a]:[],l,f),b=(a!==null?a.getAttribute("xml:space"):void 0)==="default"||c.spaceStyle==="default";for(let h=0;h<u.length;h++){let I=u[h];if(I instanceof Element){let T=Ra(I),R=Y({},p,Dn(vm,[I,...T],l,f)),E=I.getAttribute("xml:space"),v=w(E)?E==="default":b,k={paragraph:I,timeOffset:e,idStyles:l,regionStyles:f,body:a,paragraphStyle:R,ttParams:c,shouldTrimWhiteSpace:v};k!==null&&t.push(k)}}}return t}function Rm(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 km(n){n.extent="70% 20%",n.fontSize="1c",n.origin="15% 80%",n.displayAlign="before",n.textAlign="center"}var Ku=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Vu=/^(?:(\d{2,}):)?(\d{2}):(\d{2})$/,zu=/^(?:(\d{2,}):)?(\d{2}):(\d{2}\.\d{2,})$/,Hu=/^(\d*\.?\d*)f$/,Wu=/^(\d*\.?\d*)t$/,qu=/^(?:(\d*\.?\d*)h)?(?:(\d*\.?\d*)m)?(?:(\d*\.?\d*)s)?(?:(\d*\.?\d*)ms)?$/,Gu=/^(\d{1,2}|100)% (\d{1,2}|100)%$/,Ge=/^((?:\+|-)?\d*(?:\.\d+)?)(px|em|c|%|rh|rw)$/,Pm=/^#([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])$/,Mm=/^rgb\( *(\d+) *, *(\d+) *, *(\d+) *\)/,Am=/^rgba\( *(\d+) *, *(\d+) *, *(\d+) *, *(\d+) *\)/;function UI(n,e){if(Ku.test(n))return KI(e,n);if(Vu.test(n))return ju(Vu,n);if(zu.test(n))return ju(zu,n);if(Hu.test(n))return BI(e,n);if(Wu.test(n))return FI(e,n);if(qu.test(n))return ju(qu,n)}function BI(n,e){let t=Hu.exec(e);return Number(t[1])/n.frameRate}function FI(n,e){let t=Wu.exec(e);return Number(t[1])/n.tickRate}function KI(n,e){let t=Ku.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 ju(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 Ca=UI;function no(n,e){let t=n.getAttribute("begin"),r=n.getAttribute("dur"),i=n.getAttribute("end"),o=w(t)?Ca(t,e):null,a=w(r)?Ca(r,e):null,s=w(i)?Ca(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 Yu;function Me(n,e){Yu===void 0&&(Yu=n.classList!==void 0&&typeof n.classList.add=="function"),Yu?n.classList.add(e):(" "+n.className+" ").indexOf(" "+e+" ")<0&&(n.className+=" "+e)}function $u(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"?(Me(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"?(Me(n,"proportional-style"),n.setAttribute("data-proportional-height",o[1])):m.warn("TTML Parser: unhandled extent unit:",o[2]))}function Qu(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",Me(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",Me(n,"proportional-style"),n.setAttribute("data-proportional-font-size",String(o/100)))}else m.warn("TTML Parser: unhandled fontSize unit:",i[2])}function Xu(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"?(Me(n,"proportional-style"),n.setAttribute("data-proportional-line-height",i[1])):m.warn("TTML Parser: unhandled lineHeight unit:",i[2]))}function Zu(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"?(Me(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"?(Me(n,"proportional-style"),n.setAttribute("data-proportional-top",o[1])):m.warn("TTML Parser: unhandled origin unit:",o[2]))}function Ju(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"?(Me(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"?(Me(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"?(Me(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"?(Me(n,"proportional-style"),n.setAttribute("data-proportional-padding-left",s[1])):m.warn("TTML Parser: unhandled padding unit:",s[2])}function dr(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 dn(n){let e;return e=Pm.exec(n),_(e)?(e=Cm.exec(n),_(e)?(e=Mm.exec(n),_(e)?(e=Am.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 VI=["color","direction","display","fontFamily","fontSize","fontStyle","fontWeight","textDecoration","textOutline","unicodeBidi","visibility","wrapOption"];function zI(n,e,t){let r=e.color;w(r)&&(n.style.color=dn(r));let i=e.backgroundColor;w(i)&&(n.style.backgroundColor=dn(i));let o=e.textOutline;if(w(o)){let h=o.trim().replace(/\s+/g," ").split(" "),I=h.length;if(I===3){let T=dn(h[0]),R=h[1];n.style.textShadow=dr(T,R)}else if(w(r)&&I===1){let T=h[0];n.style.textShadow=dr(r,T)}else if(I===2){let T=/^[#A-Z]/i.test(h[0]),R=/^[0-9]/.test(h[0]);if(T!==R){if(T){let E=dn(h[0]),v=h[1];n.style.textShadow=dr(E,v)}else if(w(r)){let E=h[0];n.style.textShadow=dr(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 c=e.fontSize;w(c)?Qu(n,c):(Me(n,"proportional-style"),n.setAttribute("data-proportional-font-size","1"));let l=e.direction;w(l)&&(n.style.direction=l);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 p=e.visibility;w(p)&&(n.style.visibility=p),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 HI(n,e){n.style.color="white",n.style.position="absolute";let t=e.extent;w(t)&&$u(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)&&Ju(n,o);let a=e.origin;w(a)&&Zu(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 WI(n,e){n.style.margin="0px",Me(n,"proportional-style"),n.setAttribute("data-proportional-font-size","1");let t=e.backgroundColor;w(t)&&(n.style.backgroundColor=dn(t));let r=e.lineHeight;w(r)&&Xu(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 qI(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",zI(r,e,t),r}function GI(n,e,t,r,i){function o(a,s,d,u){let c=a.childNodes,l=[];for(let f=0;f<c.length;f++){let p=c[f];if(p.nodeName==="#text"){let{backgroundColor:g}=Dn(["backgroundColor"],d,t,e);w(g)?s.backgroundColor=g:s.backgroundColor="";let b=qI(p,s,u);l.push(b)}else if(ka(p)){let g=document.createElement("BR");l.push(g)}else if(Pa(p)&&p.nodeType===Node.ELEMENT_NODE&&p.childNodes.length>0){let g=p.getAttribute("xml:space"),b=w(g)?g==="default":u,h=Y({},s,Dn(VI,[p],t,e));l.push(...o(p,h,[p,...d],b))}}return l}return o(n,Y({},r),[],i)}function el(n,e,t,r,i,{cellResolution:o,shouldTrimWhiteSpace:a}){let s=Ra(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)),HI(d,i),e!==null){let{bodyBackgroundColor:l}=Dn(["backgroundColor"],[...s,e],r,t);w(l)&&(d.style.backgroundColor=dn(l))}let u=document.createElement("p");u.className="rxp-texttrack-p",WI(u,i);let c=GI(n,t,r,i,a);for(let l=0;l<c.length;l++)u.appendChild(c[l]);return d.appendChild(u),d}function tl(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:c,end:l}=no(e,t),f=el(e,r,i,o,a,{cellResolution:u,shouldTrimWhiteSpace:d});return{start:c+s,end:l+s,element:f}}function nl(n,e){let t=to(n,e),r=[];for(let i of t){let{paragraphStyle:o}=i;Rm(o)&&km(o);let a=tl(i);a!==null&&r.push(a)}return r}var xm=nl;function rl(n){n.htmlTextTracksParsers.ttml=xm,n.htmlTextDisplayer=sn}function Ma(n){let e=0;for(;e<n.length;){if(n[e]==="")return e+1;e++}return e}function il(n,e){return typeof n[e]=="string"&&/^STYLE( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function jI(n,e){return typeof n[e]=="string"&&/^NOTE( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function YI(n,e){return typeof n[e]=="string"&&/^REGION( .*)?$/g.test(n[e])&&(n[e+1]===void 0||n[e+1].indexOf("-->")<0)}function wm(n,e){let t=n[e];if(t===void 0||t===""||il(n,e)||YI(n,e)||jI(n,e))return!1;if(t.indexOf("-->")>=0)return!0;let r=n[e+1];return r!==void 0&&r.indexOf("-->")>=0}function Om(n,e){let t=e+1;for(;w(n[t]);)t++;return t}function ro(n,e){let t=[];for(let r=e;r<n.length;r++)if(wm(n,r)){let i=Om(n,r);t.push(n.slice(r,i)),r=i}else if(w(n[r]))for(;w(n[r]);)r++;return t}function ol(n,e){let t=[];for(let r=e;r<n.length;r++)if(il(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 Aa(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 $I(n){return n.split(/ |\t/).reduce((t,r)=>{let i=r.split(":");return i.length===2&&(t[i[0]]=i[1]),t},{})}function QI(n){let t=/^([\d:.]+)[ |\t]+-->[ |\t]+([\d:.]+)[ |\t]*(.*)$/.exec(n);if(t===null)return null;let r=Aa(t[1]),i=Aa(t[2]);if(r===void 0||i===void 0)return null;let o=$I(t[3]);return{start:r,end:i,settings:o}}function io(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=QI(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 al={white:"#ffffff",lime:"#00ff00",cyan:"#00ffff",red:"#ff0000",yellow:"#ffff00",magenta:"#ff00ff",blue:"#0000ff",black:"#000000"};function sl(){return Object.keys(al).reduce((n,e)=>(n[e]=`color: ${al[e]};`,n[`bg_${e}`]=`background-color: ${al[e]};`,n),{})}function dl(n){let e=sl(),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 oo(n,e){let t=["u","i","b"],r=["u","i","b","c","#text"],i=n.nodeName.toLowerCase().split(".")[0],o;if(X(r,i))if(i==="#text"){let a=n.wholeText.split(`
8
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(c=>{d.value+=c});let u=X(t,i)?i:"span";o=document.createElement(u),o.setAttributeNode(d)}else{let d=X(t,i)?i:"span";o=document.createElement(d)}for(let d=0;d<n.childNodes.length;d++){let u=oo(n.childNodes[d],e);o.appendChild(u)}}else{o=document.createElement("span");for(let a=0;a<n.childNodes.length;a++){let s=oo(n.childNodes[a],e);o.appendChild(s)}}return o}function ul(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(oo(i[a],e));return o}function ll(n){let e=document.createAttribute("style");return e.value=XI(n),e}var XI=n=>{if(!(n!==void 0&&Bn(n).length!==0))return"text-align:center";let t=ZI(n),r=tb(n);return`position: absolute;margin: 0;transform: translate(${t.offset}%,${r.offset}%);width: ${ib(n.size)}%;left: ${t.position}%;top: ${r.position!==null?`${r.position}%`:"auto"};text-align: ${cl(n.align)};`};var ZI=n=>({position:JI(n),offset:eb(n)}),JI=n=>{let e=fl(n.position);if(e!==null)return e;let t=cl(n.align);return{left:0,center:50,right:100}[t]},eb=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?cl(n.align):"center";return i[o]},tb=n=>({position:nb(n.line),offset:rb(n.line)}),nb=n=>fl(n),rb=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},cl=n=>{switch(n){case"left":case"start":return"left";case"right":case"end":return"right";default:return"center"}},ib=n=>ob(n,100),ob=(n,e)=>{let t=fl(n);return t!==null?t:e},fl=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 ml(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"),c=ll(i);u.setAttributeNode(c);let l=document.createElement("span"),f=document.createAttribute("style");f.value="background-color:rgba(0,0,0,0.8);color:white;",l.setAttributeNode(f);let{global:p,classes:g}=e,b=w(o)?g[o]:void 0,h=[p,b].filter(I=>I!==void 0).join("");return f.value+=h,l.setAttributeNode(f),ul(a.join(`
9
- `),g).forEach(I=>{l.appendChild(I)}),s.appendChild(u),u.appendChild(l),{start:t,end:r,element:s}}function pl(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=Ma(r),a=ol(r,o),s=ro(r,o),d=dl(a);for(let u=0;u<s.length;u++){let c=io(s[u],e);if(c!==null){let l=ml(c,d);i.push(l)}}return i}var Dm=pl;function gl(n){n.htmlTextTracksParsers.vtt=Dm,n.htmlTextDisplayer=an}function hl(n){var i;let e,t,r="subtitles";if(qt){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 ab(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 yl(n,e){if(fn&&ab(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 Il(n,e,t,r){m.debug("NTSB: Finding parser for native text tracks:",n);let i=fe.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 ao=class{constructor(e){m.debug("NTD: Creating NativeTextDisplayer");let{track:t,trackElement:r}=hl(e);this._buffered=new On,this._videoElement=e,this._track=t,this._trackElement=r}pushTextData(e){var b,h;if(m.debug("NTD: Appending new native text tracks"),e.chunk===null)return xe(this._buffered);let{timestampOffset:t,appendWindow:r,chunk:i}=e,{start:o,end:a,data:s,type:d,language:u}=i,c=(b=r[0])!=null?b:0,l=(h=r[1])!=null?h:1/0,f=Il(d,s,t,u);if(c!==0&&l!==1/0){let I=0;for(;I<f.length&&f[I].endTime<=c;)I++;for(f.splice(0,I),I=0;I<f.length&&f[I].startTime<c;)f[I].startTime=c,I++;for(I=f.length-1;I>=0&&f[I].startTime>=l;)I--;for(f.splice(I,f.length),I=f.length-1;I>=0&&f[I].endTime>l;)f[I].endTime=l,I--}let p;if(o!==void 0)p=Math.max(c,o);else{if(f.length<=0)return m.warn("NTD: Current text tracks have no cues nor start time. Aborting"),xe(this._buffered);m.warn("NTD: No start time given. Guessing from cues."),p=f[0].startTime}let g;if(a!==void 0)g=Math.min(l,a);else{if(f.length<=0)return m.warn("NTD: Current text tracks have no cues nor end time. Aborting"),xe(this._buffered);m.warn("NTD: No end time given. Guessing from cues."),g=f[f.length-1].endTime}if(g<=p)return m.warn("NTD: Invalid text track appended: ","the start time is inferior or equal to the end time."),xe(this._buffered);if(f.length>0){let I=f[0],T=this._track.cues;T!==null&&T.length>0&&I.startTime<T[T.length-1].startTime&&this._removeData(I.startTime,1/0);for(let R of f)this._track.addCue(R)}return this._buffered.insert(p,g),xe(this._buffered)}removeBuffer(e,t){return this._removeData(e,t),xe(this._buffered)}getBufferedRanges(){return xe(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&&yl(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="")}};y.CURRENT_ENV===y.DEV&&(sb=function(e){function t(r){}});var sb;var dn=ao;function Bt(n,e,t){if(n>=e)return m.warn(`Compat: Invalid cue times: ${n} - ${e}`),null;if(_(J.VTTCue)){if(_(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 db=/&#([0-9]+);/g,ub=/<br>/gi,lb=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,cb=/\s*<p (?:class=([^>]+))?>(.*)/i,fb=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i;function mb(n){let e=[];for(let t=0;t<n.length;t++){let{start:r,end:i,text:o}=n[t];if(w(o)&&!_(i)){let a=Bt(r,i,o);a!==null&&e.push(a)}}return e}function pb(n){let e=/\.(\S+)\s*{([^}]*)}/gi,t={},r=e.exec(n);for(;Array.isArray(r);){let i=r[1],o=gb(r[2],"lang");!_(i)&&!_(o)&&(t[o]=i),r=e.exec(n)}return t}function gb(n,e){let t=new RegExp("\\s*"+e+":\\s*(\\S+);","i").exec(n);return Array.isArray(t)?t[1]:null}function hb(n){return n.replace(ub,`
9
+ `),g).forEach(I=>{l.appendChild(I)}),s.appendChild(u),u.appendChild(l),{start:t,end:r,element:s}}function pl(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=Ma(r),a=ol(r,o),s=ro(r,o),d=dl(a);for(let u=0;u<s.length;u++){let c=io(s[u],e);if(c!==null){let l=ml(c,d);i.push(l)}}return i}var Dm=pl;function gl(n){n.htmlTextTracksParsers.vtt=Dm,n.htmlTextDisplayer=sn}function hl(n){var i;let e,t,r="subtitles";if(Gt){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 ab(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 yl(n,e){if(Pt&&ab(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 Il(n,e,t,r){m.debug("NTSB: Finding parser for native text tracks:",n);let i=fe.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 ao=class{constructor(e){m.debug("NTD: Creating NativeTextDisplayer");let{track:t,trackElement:r}=hl(e);this._buffered=new On,this._videoElement=e,this._track=t,this._trackElement=r}pushTextData(e){var b,h;if(m.debug("NTD: Appending new native text tracks"),e.chunk===null)return xe(this._buffered);let{timestampOffset:t,appendWindow:r,chunk:i}=e,{start:o,end:a,data:s,type:d,language:u}=i,c=(b=r[0])!=null?b:0,l=(h=r[1])!=null?h:1/0,f=Il(d,s,t,u);if(c!==0&&l!==1/0){let I=0;for(;I<f.length&&f[I].endTime<=c;)I++;for(f.splice(0,I),I=0;I<f.length&&f[I].startTime<c;)f[I].startTime=c,I++;for(I=f.length-1;I>=0&&f[I].startTime>=l;)I--;for(f.splice(I,f.length),I=f.length-1;I>=0&&f[I].endTime>l;)f[I].endTime=l,I--}let p;if(o!==void 0)p=Math.max(c,o);else{if(f.length<=0)return m.warn("NTD: Current text tracks have no cues nor start time. Aborting"),xe(this._buffered);m.warn("NTD: No start time given. Guessing from cues."),p=f[0].startTime}let g;if(a!==void 0)g=Math.min(l,a);else{if(f.length<=0)return m.warn("NTD: Current text tracks have no cues nor end time. Aborting"),xe(this._buffered);m.warn("NTD: No end time given. Guessing from cues."),g=f[f.length-1].endTime}if(g<=p)return m.warn("NTD: Invalid text track appended: ","the start time is inferior or equal to the end time."),xe(this._buffered);if(f.length>0){let I=f[0],T=this._track.cues;T!==null&&T.length>0&&I.startTime<T[T.length-1].startTime&&this._removeData(I.startTime,1/0);for(let R of f)this._track.addCue(R)}return this._buffered.insert(p,g),xe(this._buffered)}removeBuffer(e,t){return this._removeData(e,t),xe(this._buffered)}getBufferedRanges(){return xe(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&&yl(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="")}};y.CURRENT_ENV===y.DEV&&(sb=function(e){function t(r){}});var sb;var un=ao;function Ft(n,e,t){if(n>=e)return m.warn(`Compat: Invalid cue times: ${n} - ${e}`),null;if(_(J.VTTCue)){if(_(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 db=/&#([0-9]+);/g,ub=/<br>/gi,lb=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,cb=/\s*<p (?:class=([^>]+))?>(.*)/i,fb=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i;function mb(n){let e=[];for(let t=0;t<n.length;t++){let{start:r,end:i,text:o}=n[t];if(w(o)&&!_(i)){let a=Ft(r,i,o);a!==null&&e.push(a)}}return e}function pb(n){let e=/\.(\S+)\s*{([^}]*)}/gi,t={},r=e.exec(n);for(;Array.isArray(r);){let i=r[1],o=gb(r[2],"lang");!_(i)&&!_(o)&&(t[o]=i),r=e.exec(n)}return t}function gb(n,e){let t=new RegExp("\\s*"+e+":\\s*(\\S+);","i").exec(n);return Array.isArray(t)?t[1]:null}function hb(n){return n.replace(ub,`
10
10
  `).replace(db,(e,t)=>String.fromCharCode(Number(t)))}function yb(n,e,t){let r=/<sync[ >]/gi,i=/<sync[ >]|<\/body>/gi,o=[],a=lb.exec(n),s=a!==null?a[1]:"",d,u;i.exec(n);let c=pb(s),l;if(w(t)&&(l=c[t],l===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),g=fb.exec(p);if(g===null)throw new Error("parse error (sync time attribute)");let b=+g[1];if(isNaN(b))throw new Error("parse error (sync time attribute NaN)");f(p.split(`
11
- `),b/1e3)}return mb(o);function f(p,g){let b=p.length,h;for(;--b>=0;){if(h=cb.exec(p[b]),h===null)continue;let[,I,T]=h;l===I&&(T==="&nbsp;"?o[o.length-1].end=g:o.push({text:hb(T),start:g+e}))}}}var Lm=yb;function bl(n){n.nativeTextTracksParsers.sami=Lm,n.nativeTextDisplayer=dn}function Sl(n,e){let t=n.split(/\r\n|\n|\r/),r=Ji(t),i=[];for(let o=0;o<r.length;o++){let a=eo(r[o],e);if(a!==null){let s=Ib(a);s!==null&&i.push(s)}}return i}function Ib(n){let{start:e,end:t,payload:r}=n,i=r.join(`
12
- `);return Bt(e,t,i)}function Tl(n){n.nativeTextTracksParsers.srt=Sl,n.nativeTextDisplayer=dn}function so(n){return typeof J.VTTCue=="function"&&n instanceof J.VTTCue}var bb={left:"start",center:"center",right:"end",start:"start",end:"end"},Sb={left:"line-left",center:"center",right:"line-right"};function _l(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}=no(e,i),d=Tb(e,o),u=Bt(a+t,s+t,d);return u===null?null:(so(u)&&_b(u,r),u)}function Tb(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 l=u.trim();l=l.replace(/\s+/g," "),u=l}let c=u.replace(/&|\u0026/g,"&amp;").replace(/<|\u003C/g,"&lt;").replace(/>|\u2265/g,"&gt;").replace(/\u200E/g,"&lrm;").replace(/\u200F/g,"&rlm;").replace(/\u00A0/g,"&nbsp;");a+=c}else if(ka(d))a+=`
13
- `;else if(Pa(d)&&d.nodeType===Node.ELEMENT_NODE&&d.childNodes.length>0){let u=d.getAttribute("xml:space"),c=w(u)?u==="default":i;a+=t(d,c)}}return a}return t(n,e)}function _b(n,e){let t=e.extent;if(w(t)){let a=Gu.exec(t);_(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=Gu.exec(i);_(a)}let o=e.align;if(w(o)){n.align=o,o==="center"&&(n.align!=="center"&&(n.align="middle"),n.position="auto");let a=Sb[o];n.positionAlign=a===void 0?"":a;let s=bb[o];n.lineAlign=s===void 0?"":s}}function El(n,e){let t=to(n,e),r=[];for(let i of t){let o=_l(i);o!==null&&r.push(o)}return r}var Nm=El;function vl(n){n.nativeTextTracksParsers.ttml=Nm,n.nativeTextDisplayer=dn}function Rl(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,X(["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,X(["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"&&X(["start","center","end","left"],n.align)&&(e.align=n.align)}function kl(n){let{start:e,end:t,payload:r}=n,i=r.join(`
14
- `);return Bt(e,t,i)}function Pl(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=Ma(t),i=ro(t,r),o=[];for(let a of i){let s=io(a,e);if(s!==null){let d=kl(s);d!==null&&(so(d)&&Rl(s.settings,d),o.push(d))}}return o}var Um=Pl;function Cl(n){n.nativeTextTracksParsers.vtt=Um,n.nativeTextDisplayer=dn}function ur(n){let e=[];n.periods.forEach(t=>{let r=t.id;if(X(e,r)){m.warn("Two periods with the same ID found. Updating.");let a=r+"-dup";t.id=a,ur(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(X(o,u)){m.warn("Two adaptations with the same ID found. Updating.",u);let l=u+"-dup";d.id=l,ur(n),o.push(l)}else o.push(u);let c=[];d.representations.forEach(l=>{let f=l.id;if(X(c,f)){m.warn("Two representations with the same ID found. Updating.",f);let p=`${f}-dup`;l.id=p,ur(n),c.push(p)}else c.push(f)})})})})}function Bm(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 Fm(n){let e=/00000001\d7([0-9a-fA-F]{6})/.exec(n);return e===null||!w(e[1])?"avc1.4D401E":"avc1."+e[1]}function Ml(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 c=e[r-1];if(d===void 0||isNaN(d)){if(c.duration===void 0||isNaN(c.duration))throw new Error("Smooth: Invalid CNodes. Missing timestamp.");d=c.start+c.duration*(c.repeatCount+1)}}if(u===void 0||isNaN(u)){let c=n[r+1];if(c!==void 0){let l=c.getAttribute("t"),f=w(l)?+l: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:se([8,1,18,16],n)}]}function Al(n,e=Eb){if(n.firstElementChild===null||n.firstElementChild.nodeName!=="ProtectionHeader")throw new Error("Protection should have ProtectionHeader child");let t=n.firstElementChild,r=ht(t.textContent===null?"":t.textContent),i=zr(r),o=Ye(i),a=t.getAttribute("SystemID"),s=(a!==null?a:"").toLowerCase().replace(/\{|\}/g,"");return{keyId:o,keySystems:[{systemId:s,privateData:r}].concat(e(o))}}function Km(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 vb(n,e,t){let r=e-n;return r>0?Math.floor(r/t):0}function Rb(n,e,t){let r=n===void 0||n===0?1:n;return{up:e*r,to:(e+t)*r}}function kb(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 uo=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),c=s/1e3*o.timescale;this._scaledLiveGap=c-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}=Rb(r,e,t),s=this._media,d,u=[],c=i.length,l=this._scaledLiveGap===void 0?void 0:V()/1e3*r-this._scaledLiveGap;for(let f=0;f<c;f++){let p=i[f],{duration:g,start:b}=p,h=kb(p,i[f+1]),I=vb(b,o,g),T=b+I*g,R=g;for(;T<a&&I<=h&&(l===void 0||T+R<=l);){let E=T,v=d!==void 0?d+I:void 0,k={id:String(T),isInit:!1,time:E/r,end:(E+g)/r,duration:g/r,timescale:1,number:v,url:Vm(s,E),complete:!0,privateInfos:{smoothMediaSegment:{time:E,duration:g}}};u.push(k),I++,T=b+I*g}if(T>=a)return u;d!==void 0&&(d+=h+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=V()/1e3*t,{start:a,duration:s,repeatCount:d}=i;for(let u=d;u>=0;u--){let c=a+s*(u+1);if(c<=o-this._scaledLiveGap)return c/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(),ma(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 ot&&(e.isHttpError(404)||e.isHttpError(412)):!1}getTargetSegmentDuration(){this._refreshTimeline();let{timeline:e,timescale:t}=this._sharedSmoothTimeline,r=e[0];if(r!==void 0)return{duration:r.duration/t,isPrecize:!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 xl(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 lo=class{constructor(e){let{timeline:t,timescale:r,timeShiftBufferDepth:i,manifestReceivedTime:o}=e;this.timeline=t,this.timescale=r;let a=o!=null?o:V();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=(V()-this.validityTime)/1e3+this._initialScaledLastPosition/this.timescale;if(e!==void 0){let i=(r-e)*this.timescale;Li(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 c=t[u],l=ke(c,null);if(l===d){this.timeline=this.timeline.concat(t.slice(u+1));return}if(l>d){if(c.duration!==s.duration)return;let f=d-c.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%c.duration!==0)return;let p=f/c.duration-1,g=c.repeatCount-p;if(g<0)return;s.repeatCount+=g;let b=t.slice(u+1);this.timeline=this.timeline.concat(b);return}}}update(e){Ni(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)xl(this.timeline,this.timescale,i,t.privateInfos.smoothMediaSegment)}};function wl(n){return typeof n=="boolean"?n:typeof n=="string"?n.toUpperCase()==="TRUE":!1}function lr(n,e,t){let r=n.firstElementChild,i=t;for(;r!==null;)i=e(i,r.nodeName,r),r=r.nextElementSibling;return i}var Pb={audio:"audio/mp4",video:"video/mp4",text:"application/ttml+xml"},co={AACL:"audio/mp4",AVC1:"video/mp4",H264:"video/mp4",TTML:"application/ttml+xml+mp4",DFXP:"application/ttml+xml+mp4"};function Cb(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 c=lr(d,(f,p,g)=>(p==="CustomAttributes"&&f.push(...lr(g,(b,h,I)=>{if(h==="Attribute"){let T=I.getAttribute("Name"),R=I.getAttribute("Value");T!==null&&R!==null&&b.push(T+"="+R)}return b},[])),f),[]);function l(f){let p=d.getAttribute(f);return p===null?void 0:p}switch(u){case"audio":{let f=l("AudioTag"),p=l("BitsPerSample"),g=l("Channels"),b=l("CodecPrivateData"),h=l("FourCC"),I=l("PacketSize"),T=l("SamplingRate"),R=l("Bitrate"),E=R===void 0?0:parseInt(R,10);if(E=isNaN(E)?0:E,h!==void 0&&co[h]===void 0||b===void 0)return m.warn("Smooth parser: Unsupported audio codec. Ignoring quality level."),null;let v=Bm(b,h);return{audiotag:f!==void 0?parseInt(f,10):f,bitrate:E,bitsPerSample:p!==void 0?parseInt(p,10):p,channels:g!==void 0?parseInt(g,10):g,codecPrivateData:b,codecs:v,customAttributes:c,mimeType:h!==void 0?co[h]:h,packetSize:I!==void 0?parseInt(I,10):I,samplingRate:T!==void 0?parseInt(T,10):T}}case"video":{let f=l("CodecPrivateData"),p=l("FourCC"),g=l("MaxWidth"),b=l("MaxHeight"),h=l("Bitrate"),I=h===void 0?0:parseInt(h,10);if(I=isNaN(I)?0:I,p!==void 0&&co[p]===void 0||f===void 0)return m.warn("Smooth parser: Unsupported video codec. Ignoring quality level."),null;let T=Fm(f);return{bitrate:I,customAttributes:c,mimeType:p!==void 0?co[p]:p,codecPrivateData:f,codecs:T,width:g!==void 0?parseInt(g,10):void 0,height:b!==void 0?parseInt(b,10):void 0}}case"text":{let f=l("CodecPrivateData"),p=l("FourCC"),g=l("Bitrate"),b=g===void 0?0:parseInt(g,10);return b=isNaN(b)?0:b,{bitrate:b,customAttributes:c,mimeType:p!==void 0?co[p]:p,codecPrivateData:f!=null?f:""}}default:return m.error("Smooth Parser: Unrecognized StreamIndex type: "+u),null}}function a(d){let{root:u,timescale:c,baseUrl:l,protections:f,timeShiftBufferDepth:p,manifestReceivedTime:g,isLive:b}=d,h=u.getAttribute("Timescale"),I=h===null?c:+h;isNaN(I)&&(I=c);let T=u.getAttribute("Type");if(T===null)throw new Error("StreamIndex without type.");X(Yt,T)||m.warn("Smooth Parser: Unrecognized adaptation type:",T);let R=T,E=u.getAttribute("Subtype"),v=u.getAttribute("Language"),k=u.getAttribute("Url"),x=k===null?"":k;y.CURRENT_ENV===y.DEV&&ee(x!=="");let{qualityLevels:P,cNodes:M}=lr(u,(A,C,N)=>{switch(C){case"QualityLevel":{let K=o(N,R);if(K===null)return A;(R!=="video"||K.bitrate>t)&&A.qualityLevels.push(K);break}case"c":A.cNodes.push(N);break}return A},{qualityLevels:[],cNodes:[]}),O=new lo({timeline:Ml(M),timescale:I,timeShiftBufferDepth:p,manifestReceivedTime:g});ee(P.length!==0,"Adaptation should have at least one playable representation.");let B=R+(w(v)?"_"+v:""),D=P.map(A=>{let C=Km(x,A.bitrate,A.customAttributes),N=w(A.mimeType)?A.mimeType:Pb[R],K=A.codecs,j=B+"_"+(_(R)?"":R+"-")+(_(N)?"":N+"-")+(_(K)?"":K+"-")+String(A.bitrate),$=[],z;f.length>0&&(z=f[0],f.forEach(ne=>{$.push(ne.keyId)}));let H={bitsPerSample:A.bitsPerSample,channels:A.channels,codecPrivateData:A.codecPrivateData,packetSize:A.packetSize,samplingRate:A.samplingRate,height:A.height,width:A.width,protection:_(z)?void 0:{keyId:z.keyId}},q=new uo({isLive:b,sharedSmoothTimeline:O,media:C,segmentPrivateInfos:H}),ie=Y({},A,{index:q,cdnMetadata:[{baseUrl:l}],mimeType:N,codecs:K,id:j});if($.length>0||z!==void 0){let ne=z===void 0?[]:z.keySystems.map(le=>{let{systemId:be,privateData:me}=le,W=be.replace(/-/g,""),Ce=Mb(W,me);return{systemId:W,data:Ce}});if(ne.length>0){let le=[{type:"cenc",values:ne}];ie.contentProtections={keyIds:$,initData:le}}else ie.contentProtections={keyIds:$,initData:[]}}return ie});if(E==="ADVT")return null;let F={id:B,type:R,representations:D,language:v===null?void 0:v};return R==="text"&&E==="DESC"&&(F.closedCaption=!0),F}function s(d,u,c){let l="";if(u!==void 0){let q=Mr(u);l=u.substring(0,q)}let f=d.documentElement;if(_(f)||f.nodeName!=="SmoothStreamingMedia")throw new Error("document root should be SmoothStreamingMedia");let p=f.getAttribute("MajorVersion"),g=f.getAttribute("MinorVersion");if(p===null||g===null||!/^[2]-[0-2]$/.test(p+"-"+g))throw new Error("Version should be 2.0, 2.1 or 2.2");let b=f.getAttribute("Timescale"),h=w(b)?+b:1e7;isNaN(h)&&(h=1e7);let{protections:I,adaptationNodes:T}=lr(f,(q,ie,ne)=>{switch(ie){case"Protection":{q.protections.push(Al(ne,n.keySystems));break}case"StreamIndex":q.adaptationNodes.push(ne);break}return q},{adaptationNodes:[],protections:[]}),R={},E=wl(f.getAttribute("IsLive")),v;if(E){let q=f.getAttribute("DVRWindowLength");q!==null&&!isNaN(+q)&&+q!=0&&(v=+q/h)}let k=T.reduce((q,ie)=>{let ne=a({root:ie,baseUrl:l,timescale:h,protections:I,isLive:E,timeShiftBufferDepth:v,manifestReceivedTime:c});if(ne===null)return q;let le=ne.type,be=q[le];return be===void 0?q[le]=[ne]:be.push(ne),q},R),x,P,M,O=null,B,D=k.video!==void 0?k.video[0]:void 0,F=k.audio!==void 0?k.audio[0]:void 0,A,C,N;if(D!==void 0||F!==void 0){let q=[],ie=[];if(D!==void 0){let ne=D.representations[0];if(ne!==void 0){let le=ne.index.getFirstAvailablePosition(),be=ne.index.getLastAvailablePosition();_(le)||q.push(le),_(be)||ie.push(be)}}if(F!==void 0){let ne=F.representations[0];if(ne!==void 0){let le=ne.index.getFirstAvailablePosition(),be=ne.index.getLastAvailablePosition();_(le)||q.push(le),_(be)||ie.push(be)}}q.length>0&&(A=Math.max(...q)),ie.length>0&&(C=Math.min(...ie),N=Math.max(...ie))}let K=f.getAttribute("Duration"),j=K!==null&&+K!=0?+K/h:void 0;if(E){x=n.suggestedPresentationDelay,P=e,M=A!=null?A:P;let q=N;q===void 0&&(q=Date.now()/1e3-P);let ie=C;ie===void 0&&(ie=q),B={isLinear:!0,maximumSafePosition:ie,livePosition:q,time:V()},O=v!=null?v:null}else{M=A!=null?A:0;let q=C;q===void 0&&(q=j!==void 0?M+j:1/0),B={isLinear:!1,maximumSafePosition:q,livePosition:void 0,time:V()}}let $=E?0:M,z=E?void 0:B.maximumSafePosition,H={availabilityStartTime:P===void 0?0:P,clockOffset:i,isLive:E,isDynamic:E,isLastPeriodKnown:!0,timeBounds:{minimumSafePosition:M,timeshiftDepth:O,maximumTimeData:B},periods:[{adaptations:k,duration:z!==void 0?z-$:j,end:z,id:"gen-smooth-period-0",start:$,thumbnailTracks:[]}],suggestedPresentationDelay:x,transportType:"smooth",uris:_(u)?[]:[u]};return ur(H),H}return s}function Mb(n,e){if(n.length!==32)throw new Error("HSS: wrong system id length");return ue("pssh",se([0,0,0,0],Ye(n),ye(e.length),e))}var zm=Cb;var Hm=zm;function Wm(n,e,t,r,i,o,a){return ue("avc1",se(6,ce(1),16,ce(n),ce(e),ce(t),2,ce(r),6,[0,1,i.length],ve(i),31-i.length,ce(o),[255,255],a))}function qm(n,e,t,r,i,o,a,s){return ue("encv",se(6,ce(1),16,ce(n),ce(e),ce(t),2,ce(r),6,[0,1,i.length],ve(i),31-i.length,ce(o),[255,255],a,s))}function Gm(n,e,t,r,i,o){return ue("mp4a",se(6,ce(n),8,ce(e),ce(t),2,ce(r),ce(i),2,o))}function jm(n,e,t,r,i,o,a){return ue("enca",se(6,ce(n),8,ce(e),ce(t),2,ce(r),ce(i),2,o,a))}function Ym(n){return ue("dref",se(7,[1],n))}function $m(n,e){let t=se(...[ve(n),[0,0,0,1]].concat(e.map(ve)));return ue("ftyp",t)}function xa(n,e){return ue("schm",se(4,ve(n),ye(e)))}function Qm(n){return ue("tfdt",se([1,0,0,0],Zt(n)))}function Xm(){let n=new Uint8Array(12);return n[3]=1,ue("vmhd",n)}function Zm(n){return ue("trex",se(4,ye(n),[0,0,0,1],12))}function Jm(n){return ue("free",new Uint8Array(n-8))}function ep(n,e){return ue("esds",se(4,[3,25],ce(n),[0,4,17,64,21],11,[5,2],Ye(e),[6,1,2]))}function wa(n){return ue("frma",ve(n))}function tp(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 ue("avcC",se([1,i,o,a,252|r,225],ce(n.length),n,[1],ce(e.length),e))}function np(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 ue("hdlr",se(8,ve(e),12,ve(t),1))}function rp(n){return ue("mdhd",se(12,ye(n),8))}function ip(n,e){return ue("mvhd",se(12,ye(n),4,[0,1],2,[1,0],10,[0,1],14,[0,1],14,[64,0,0,0],26,ce(e+1)))}function op(n,e,t,r){return ue("saio",se(4,[0,0,0,1],ye(n.length+e.length+t.length+r.length+8+8+8+8)))}function ap(n){if(n.length===0)return ue("saiz",new Uint8Array(0));let e=re(n,0),t=re(n,4),r=new Uint8Array(t+9);r.set(ye(t),5);let i=9,o=8,a,s;for(;o<n.length;)o+=8,(e&2)===2?(s=2,a=Go(n,o),o+=a*6+2):(a=0,s=0),r[i]=a*6+8+s,i++;return ue("saiz",r)}function sp(){return ue("smhd",new Uint8Array(8))}function cr(n){let e=[7,[n.length]];return ue("stsd",se(...e.concat(n)))}function dp(n,e,t){return ue("tkhd",se(ye(7),8,ye(t),20,[1,0,0,0],[0,1,0,0],12,[0,1,0,0],12,[64,0,0,0],ce(n),2,ce(e),2))}function Oa(n,e,t){return ue("tenc",se(6,[n,e],t))}function Ab(n,e,t){return we("moov",[n,e,t])}function fo(n,e,t,r,i,o){let a=we("stbl",[t,ue("stts",new Uint8Array(8)),ue("stsc",new Uint8Array(8)),ue("stsz",new Uint8Array(12)),ue("stco",new Uint8Array(8))]),s=ue("url ",new Uint8Array([0,0,0,1])),d=Ym(s),u=we("dinf",[d]),c=we("minf",[r,u,a]),l=np(e),f=rp(n),p=we("mdia",[f,l,c]),g=dp(i,o,1),b=we("trak",[g,p]),h=Zm(1),I=we("mvex",[h]),T=ip(n,1),R=Ab(T,I,b),E=$m("isom",["isom","iso2","iso6","avc1","dash"]);return se(E,R)}var xb=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];function Ol(n,e,t){let r=xb.indexOf(e),i;return i=(n&63)<<4,i=(i|r&31)<<4,i=(i|t&31)<<3,Be(ce(i))}function Da(n,e,t,r,i,o,a){let s=o.length===0?Ol(2,i,e):o,d=ep(1,s),u=(()=>{if(a===void 0){let h=Gm(1,e,t,r,i,d);return cr([h])}let c=Oa(1,8,a),l=we("schi",[c]),f=xa("cenc",65536),p=wa("mp4a"),g=we("sinf",[p,f,l]),b=jm(1,e,t,r,i,d,g);return cr([b])})();return fo(n,"audio",u,sp(),0,0)}function La(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 c=Ye(d),l=Ye(u),f=tp(c,l,o),p;if(s===void 0){let g=Wm(e,t,r,i,"AVC Coding",24,f);p=cr([g])}else{let g=Oa(1,8,s),b=we("schi",[g]),h=xa("cenc",65536),I=wa("avc1"),T=we("sinf",[I,h,b]),R=qm(e,t,r,i,"AVC Coding",24,f,T);p=cr([R])}return fo(n,"video",p,Xm(),e,t)}function Na(n){let e=_n(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=re(e,o*8+5),a=re(e,o*8+5+4)),t.push({time:s,duration:a})}return t}function Ua(n){let e=_n(n,1830656773,1121273062,2162299933,2952222642);if(e!==void 0)return{duration:Ke(e,12),time:Ke(e,4)}}function Dl(){return!qt}function Ll(n,e,t,r,i){let o=[n,e,t];return i!==void 0&&o.push(ue("senc",i),ap(i),op(r,n,e,t)),we("traf",o)}function Ba(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=As(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 c=Qm(e),l=wb(u,s[1]-s[0]),f=_n(o,2721664850,1520127764,2722393154,2086964724),p=Ll(d,c,l,i,f),g=we("moof",[i,p]),b=Ve(g,1836019558),h=Ve(p,1953653094),I=Ve(l,1953658222);if(b===null||h===null||I===null)throw new Error("Smooth: Invalid moof, trun or traf generation");let T=b[1]-b[0]+i.length+(h[1]-h[0])+d.length+c.length+(I[1]-I[0])+8,R=t[2]-t[0],E=g.length-R,v=Ve(n,1835295092);if(v===null)throw new Error("Smooth: Invalid ISOBMFF given");if(Dl()&&(E===0||E<=-8)){let k=v[1];return g.set(ye(k),T),n.set(g,t[0]),E<=-8&&n.set(Jm(-E),g.length),n}else{let k=v[1]+E;g.set(ye(k),T);let x=new Uint8Array(n.length+E),P=n.subarray(0,t[0]),M=n.subarray(t[2],n.length);return x.set(P,0),x.set(g,P.length),x.set(M,P.length+g.length),x}}function wb(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),Ls(r)}function Fa(n,e,t,r,i){var p;let o=[],a,s,d;if(i){let g=Kr(n);g!==null?(d=Na(g),s=Ua(g)):m.warn("smooth: could not find traf atom")}if(d!==void 0)for(let g of d)o.push({time:g.time,duration:g.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,c=Math.min(t*.9,u/4),l=Wr(n),f=((p=r.privateInfos)==null?void 0:p.smoothMediaSegment)!==void 0?r.privateInfos.smoothMediaSegment.time:Math.round(r.time*t);return l!==void 0&&Math.abs(l-u)<=c?a={time:r.time,duration:l/t}:a={time:r.time,duration:r.duration},{nextSegments:o,chunkInfos:a,scaledSegmentTime:f}}function Ln(n){return typeof n=="string"&&n.indexOf("mp4")>=0}async function up(n,e,t,r,i,o){var p,g;let a=((p=r.cmcdPayload)==null?void 0:p.type)==="headers"?r.cmcdPayload.value:void 0,s=e.segment.range,d;Array.isArray(s)?d=de(oe({},a),{Range:Qe(s)}):a!==void 0&&(d=a);let u=((g=r.cmcdPayload)==null?void 0:g.type)==="query"?ze(n,r.cmcdPayload.value):n,c=await Se({url:u,responseType:"arraybuffer",headers:d,timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i,onProgress:t.onProgress});if(!Ln(e.mimeType)||o!==!0)return{resultType:"segment-loaded",resultData:c};let f=new Uint8Array(c.responseData);return rn(f,e.segment.isInit),{resultType:"segment-loaded",resultData:de(oe({},c),{responseData:f})}}var Ob=({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:c,timescale:l,height:f,width:p,protection:g={keyId:void 0,keySystems:void 0}}=d;if(c===void 0)throw new Error("Smooth: no codec private data.");switch(r.type){case"video":{u=La(l,p!=null?p:0,f!=null?f:0,72,72,4,c,g.keyId);break}case"audio":{let{channels:b=0,bitsPerSample:h=0,packetSize:I=0,samplingRate:T=0}=d;u=Da(l,b,h,I,T,c,g.keyId);break}default:y.CURRENT_ENV===y.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"?up(t,r,a,i,o,n):new Promise((d,u)=>{let c=!1,b={reject:E=>{var P,M;if(c||o.isCancelled())return;c=!0,o.deregister(R);let v=E,k=(P=v==null?void 0:v.message)!=null?P:"Unknown error when fetching a Smooth segment through a custom segmentLoader.",x=new it(k,(M=v==null?void 0:v.canRetry)!=null?M:!1,v==null?void 0:v.xhr);u(x)},resolve:E=>{if(c||o.isCancelled())return;c=!0,o.deregister(R),(!Ln(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);rn(k,r.segment.isInit),d({resultType:"segment-loaded",resultData:{responseData:k,size:E.size,requestDuration:E.duration}})},fallback:()=>{c||o.isCancelled()||(c=!0,o.deregister(R),up(t,r,a,i,o,n).then(d,u))},progress:E=>{c||o.isCancelled()||a.onProgress({duration:E.duration,size:E.size,totalSize:E.totalSize})}},h;r.segment.range!==void 0&&(h=[r.segment.range],r.segment.indexRange!==void 0&&h.push(r.segment.indexRange));let I={isInit:r.segment.isInit,timeout:i.timeout,byteRanges:h,trackType:r.type,url:t,cmcdPayload:i.cmcdPayload},T=e(I,b);o.register(R);function R(E){c||(c=!0,!c&&typeof T=="function"&&T(),u(E))}})},lp=Ob;function Nl(n,e){return n===null?null:e.url===null?n.baseUrl:gn(n.baseUrl,e.url)}function cp(n){let e=Hm(n),t=lp(n),r={customManifestLoader:n.manifestLoader},o={loadManifest:Wi(r,"text",null),parseManifest(d,u){var I;let c=(I=d.url)!=null?I:u.originalUrl,{receivedTime:l,responseData:f}=d,p=typeof f=="string"?new DOMParser().parseFromString(f,"text/xml"):f,g=e(p,c,l),b=[];return{manifest:new $n(g,{representationFilter:n.representationFilter},b),url:c,warnings:b}}},a={loadSegment(d,u,c,l,f){let p=Nl(d,u.segment);return t(p,u,c,l,f)},parseSegment(d,u,c){var v,k;let{segment:l}=u,{data:f,isChunked:p}=d;if(f===null)return l.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 g=f instanceof Uint8Array?f:new Uint8Array(f);if(l.isInit){let x=(k=(v=l.privateInfos)==null?void 0:v.smoothInitSegment)==null?void 0:k.timescale;return{segmentType:"init",initializationData:f,initializationDataSize:f.byteLength,initTimescale:x,protectionData:[]}}let b=c!==void 0?Fa(g,p,c,l,u.isLive):null;if(b===null||b.chunkInfos===null||b.scaledSegmentTime===void 0)throw new Error("Smooth Segment without time information");let{nextSegments:h,chunkInfos:I,scaledSegmentTime:T}=b,R=Ba(g,T),E=h.length>0?h:void 0;return{segmentType:"media",chunkData:R,chunkInfos:I,chunkOffset:0,chunkSize:R.length,protectionData:[],predictedSegments:E,appendWindow:[void 0,void 0]}}};return{transportName:"smooth",manifest:o,audio:a,video:a,text:{loadSegment(d,u,c,l,f){var h,I,T,R;let{segment:p}=u,g=Nl(d,p);return p.isInit||g===null?Promise.resolve({resultType:"segment-created",resultData:null}):Ln(u.mimeType)?Se({url:((T=c.cmcdPayload)==null?void 0:T.type)==="query"?ze(g,c.cmcdPayload.value):g,headers:((R=c.cmcdPayload)==null?void 0:R.type)==="headers"?c.cmcdPayload.value:void 0,responseType:"arraybuffer",timeout:c.timeout,connectionTimeout:c.connectionTimeout,cancelSignal:l,onProgress:f.onProgress}).then(E=>{if(n.checkMediaSegmentIntegrity!==!0)return{resultType:"segment-loaded",resultData:E};let v=new Uint8Array(E.responseData);return rn(v,u.segment.isInit),{resultType:"segment-loaded",resultData:de(oe({},E),{responseData:v})}}):Se({url:((h=c.cmcdPayload)==null?void 0:h.type)==="query"?ze(g,c.cmcdPayload.value):g,headers:((I=c.cmcdPayload)==null?void 0:I.type)==="headers"?c.cmcdPayload.value:void 0,responseType:"text",timeout:c.timeout,connectionTimeout:c.connectionTimeout,cancelSignal:l,onProgress:f.onProgress}).then(E=>({resultType:"segment-loaded",resultData:E}))},parseSegment(d,u,c){var B;let{segment:l,language:f,mimeType:p="",codecs:g=""}=u,b=Ln(u.mimeType),{data:h,isChunked:I}=d,T;if(l.isInit)return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0};if(h===null)return{segmentType:"media",chunkData:null,chunkInfos:null,chunkOffset:0,chunkSize:0,protectionData:[],appendWindow:[void 0,void 0]};let R,E=null,v,k,x,P;if(b){let D;typeof h=="string"?D=ve(h):D=h instanceof Uint8Array?h:new Uint8Array(h),T=D.length;let F=c!==void 0?Fa(D,I,c,l,u.isLive):null;R=F==null?void 0:F.nextSegments,E=(B=F==null?void 0:F.chunkInfos)!=null?B:null,E===null?I?m.warn("Smooth: Unavailable time data for current text track."):(v=l.time,k=l.end):(v=E.time,k=E.duration!==void 0?E.time+E.duration:l.end);let A=g.toLowerCase();if(p==="application/ttml+xml+mp4"||A==="stpp"||A==="stpp.ttml"||A==="stpp.ttml.im1t")P="ttml";else if(A==="wvtt")P="vtt";else throw new Error(`could not find a text-track parser for the type ${p}`);let C=Vr(D);x=C===null?"":Ue(C)}else{v=l.time,k=l.end;let D;if(typeof h!="string"){let F=h instanceof Uint8Array?h:new Uint8Array(h);T=F.length,D=Ue(F)}else D=h;switch(p){case"application/x-sami":case"application/smil":P="sami";break;case"application/ttml+xml":P="ttml";break;case"text/vtt":P="vtt";break}if(P===void 0)if(g.toLowerCase()==="srt")P="srt";else throw new Error(`could not find a text-track parser for the type ${p}`);x=D}let M=Array.isArray(R)&&R.length>0?R:void 0,O=v!=null?v:0;return{segmentType:"media",chunkData:{type:P,data:x,start:v,end:k,language:f},chunkSize:T,chunkInfos:E,chunkOffset:O,protectionData:[],predictedSegments:M,appendWindow:[void 0,void 0]}}},thumbnails:{loadThumbnail:()=>Promise.reject(new Error("Thumbnail tracks aren't implemented with smooth")),parseThumbnail:()=>{throw new Error("Thumbnail tracks aren't implemented with smooth")}}}}var fp=cp;function Ul(n){n.transports.smooth===void 0&&(n.transports.smooth=fp),n.mainThreadMediaSourceInit=kn}function mp(){if(!fn)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 Bl(){if(!fn)return!0;let n=mp();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 mo(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 Fl(){return Qa&&typeof Worker=="object"||typeof Worker=="function"}var Nn=class n extends Error{constructor(e,t){super(Je(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="WorkerInitializationError",this.type="WORKER_INITIALIZATION_ERROR",this.code=e}};function Ka(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 Ka(this,i,t)}}}var Db=["canplay","ended","play","pause","seeking","seeked","loadedmetadata","ratechange"],po=class{constructor(e,t){this._internalSeeksIncoming=[],this._mediaElement=e,this._withMediaSource=t.withMediaSource,this._lowLatencyMode=t.lowLatencyMode,this._canceller=new U,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 Z;this._observationRef.onUpdate(e,{clearSignal:t.clearSignal,emitCurrentValue:t.includeLastObservation})}deriveReadOnlyObserver(e){return Ka(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}=L.getCurrent(),i=new G(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 Db.map(u=>{let c=()=>{d(),this._generateObservationForEvent(u)};this._mediaElement.addEventListener(u,c),this._canceller.signal.register(()=>{this._mediaElement.removeEventListener(u,c)})}),this._canceller.signal.register(()=>{clearInterval(s),i.finish()}),i;function d(){clearInterval(s),s=setInterval(a,o)}}_getCurrentObservation(e){var R,E;let t=e,r=this._observationRef===void 0?Fb(this._mediaElement):this._observationRef.getValue(),i=!1,o=this._pendingSeek,a=gp(this._mediaElement),{buffered:s,readyState:d,position:u,seeking:c}=a;if(t==="seeking")if(this._internalSeeksIncoming.length>0){i=!0,t="internal-seeking";let v=this._internalSeeksIncoming.shift();this._expectedSeekingPosition=nr?Math.max(u,v!=null?v:0):u}else this._expectedSeekingPosition=u;else c?this._expectedSeekingPosition=Math.max(u,(R=this._expectedSeekingPosition)!=null?R:0):nr&&this._expectedSeekingPosition!==null&&u<this._expectedSeekingPosition?o=this._expectedSeekingPosition:this._expectedSeekingPosition=null;c&&r.seeking===1&&e!=="seeking"&&(i=!0);let l=(E=this._expectedSeekingPosition)!=null?E:u,f,p;!this._withMediaSource&&s.length===0&&d>=3?(f=void 0,p=void 0):(f=ns(s,l),p=f!==null?f.end-l:1/0);let g=Lb(l,f,a.ended,a.duration,this._lowLatencyMode),b=Nb({previousObservation:r,currentObservation:a,basePosition:l,observationEvent:t,lowLatencyMode:this._lowLatencyMode,withMediaSource:this._withMediaSource,bufferGap:p,fullyLoaded:g}),h=Ub(r,a,t,p),I;i?I=1:c?I=2:I=0;let T=Y({},a,{position:new tr(a.position,o),event:t,seeking:I,rebuffering:b,freezing:h,bufferGap:p,currentRange:f,fullyLoaded:g});return m.hasLevel("DEBUG")&&m.debug("API: current media element state tick","event",T.event,"position",T.position.getPolled(),"seeking",T.seeking,"internalSeek",i,"rebuffering",T.rebuffering!==null,"freezing",T.freezing!==null,"ended",T.ended,"paused",T.paused,"playbackRate",T.playbackRate,"readyState",T.readyState,"pendingPosition",o),T}_generateObservationForEvent(e){let t=this._getCurrentObservation(e);m.hasLevel("DEBUG")&&m.debug(`API: current playback timeline:
11
+ `),b/1e3)}return mb(o);function f(p,g){let b=p.length,h;for(;--b>=0;){if(h=cb.exec(p[b]),h===null)continue;let[,I,T]=h;l===I&&(T==="&nbsp;"?o[o.length-1].end=g:o.push({text:hb(T),start:g+e}))}}}var Lm=yb;function bl(n){n.nativeTextTracksParsers.sami=Lm,n.nativeTextDisplayer=un}function Sl(n,e){let t=n.split(/\r\n|\n|\r/),r=Ji(t),i=[];for(let o=0;o<r.length;o++){let a=eo(r[o],e);if(a!==null){let s=Ib(a);s!==null&&i.push(s)}}return i}function Ib(n){let{start:e,end:t,payload:r}=n,i=r.join(`
12
+ `);return Ft(e,t,i)}function Tl(n){n.nativeTextTracksParsers.srt=Sl,n.nativeTextDisplayer=un}function so(n){return typeof J.VTTCue=="function"&&n instanceof J.VTTCue}var bb={left:"start",center:"center",right:"end",start:"start",end:"end"},Sb={left:"line-left",center:"center",right:"line-right"};function _l(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}=no(e,i),d=Tb(e,o),u=Ft(a+t,s+t,d);return u===null?null:(so(u)&&_b(u,r),u)}function Tb(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 l=u.trim();l=l.replace(/\s+/g," "),u=l}let c=u.replace(/&|\u0026/g,"&amp;").replace(/<|\u003C/g,"&lt;").replace(/>|\u2265/g,"&gt;").replace(/\u200E/g,"&lrm;").replace(/\u200F/g,"&rlm;").replace(/\u00A0/g,"&nbsp;");a+=c}else if(ka(d))a+=`
13
+ `;else if(Pa(d)&&d.nodeType===Node.ELEMENT_NODE&&d.childNodes.length>0){let u=d.getAttribute("xml:space"),c=w(u)?u==="default":i;a+=t(d,c)}}return a}return t(n,e)}function _b(n,e){let t=e.extent;if(w(t)){let a=Gu.exec(t);_(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=Gu.exec(i);_(a)}let o=e.align;if(w(o)){n.align=o,o==="center"&&(n.align!=="center"&&(n.align="middle"),n.position="auto");let a=Sb[o];n.positionAlign=a===void 0?"":a;let s=bb[o];n.lineAlign=s===void 0?"":s}}function El(n,e){let t=to(n,e),r=[];for(let i of t){let o=_l(i);o!==null&&r.push(o)}return r}var Nm=El;function vl(n){n.nativeTextTracksParsers.ttml=Nm,n.nativeTextDisplayer=un}function Rl(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,X(["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,X(["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"&&X(["start","center","end","left"],n.align)&&(e.align=n.align)}function kl(n){let{start:e,end:t,payload:r}=n,i=r.join(`
14
+ `);return Ft(e,t,i)}function Pl(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=Ma(t),i=ro(t,r),o=[];for(let a of i){let s=io(a,e);if(s!==null){let d=kl(s);d!==null&&(so(d)&&Rl(s.settings,d),o.push(d))}}return o}var Um=Pl;function Cl(n){n.nativeTextTracksParsers.vtt=Um,n.nativeTextDisplayer=un}function ur(n){let e=[];n.periods.forEach(t=>{let r=t.id;if(X(e,r)){m.warn("Two periods with the same ID found. Updating.");let a=r+"-dup";t.id=a,ur(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(X(o,u)){m.warn("Two adaptations with the same ID found. Updating.",u);let l=u+"-dup";d.id=l,ur(n),o.push(l)}else o.push(u);let c=[];d.representations.forEach(l=>{let f=l.id;if(X(c,f)){m.warn("Two representations with the same ID found. Updating.",f);let p=`${f}-dup`;l.id=p,ur(n),c.push(p)}else c.push(f)})})})})}function Bm(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 Fm(n){let e=/00000001\d7([0-9a-fA-F]{6})/.exec(n);return e===null||!w(e[1])?"avc1.4D401E":"avc1."+e[1]}function Ml(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 c=e[r-1];if(d===void 0||isNaN(d)){if(c.duration===void 0||isNaN(c.duration))throw new Error("Smooth: Invalid CNodes. Missing timestamp.");d=c.start+c.duration*(c.repeatCount+1)}}if(u===void 0||isNaN(u)){let c=n[r+1];if(c!==void 0){let l=c.getAttribute("t"),f=w(l)?+l: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:se([8,1,18,16],n)}]}function Al(n,e=Eb){if(n.firstElementChild===null||n.firstElementChild.nodeName!=="ProtectionHeader")throw new Error("Protection should have ProtectionHeader child");let t=n.firstElementChild,r=ht(t.textContent===null?"":t.textContent),i=zr(r),o=Ye(i),a=t.getAttribute("SystemID"),s=(a!==null?a:"").toLowerCase().replace(/\{|\}/g,"");return{keyId:o,keySystems:[{systemId:s,privateData:r}].concat(e(o))}}function Km(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 vb(n,e,t){let r=e-n;return r>0?Math.floor(r/t):0}function Rb(n,e,t){let r=n===void 0||n===0?1:n;return{up:e*r,to:(e+t)*r}}function kb(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 uo=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),c=s/1e3*o.timescale;this._scaledLiveGap=c-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}=Rb(r,e,t),s=this._media,d,u=[],c=i.length,l=this._scaledLiveGap===void 0?void 0:V()/1e3*r-this._scaledLiveGap;for(let f=0;f<c;f++){let p=i[f],{duration:g,start:b}=p,h=kb(p,i[f+1]),I=vb(b,o,g),T=b+I*g,R=g;for(;T<a&&I<=h&&(l===void 0||T+R<=l);){let E=T,v=d!==void 0?d+I:void 0,k={id:String(T),isInit:!1,time:E/r,end:(E+g)/r,duration:g/r,timescale:1,number:v,url:Vm(s,E),complete:!0,privateInfos:{smoothMediaSegment:{time:E,duration:g}}};u.push(k),I++,T=b+I*g}if(T>=a)return u;d!==void 0&&(d+=h+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=V()/1e3*t,{start:a,duration:s,repeatCount:d}=i;for(let u=d;u>=0;u--){let c=a+s*(u+1);if(c<=o-this._scaledLiveGap)return c/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(),ma(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 ot&&(e.isHttpError(404)||e.isHttpError(412)):!1}getTargetSegmentDuration(){this._refreshTimeline();let{timeline:e,timescale:t}=this._sharedSmoothTimeline,r=e[0];if(r!==void 0)return{duration:r.duration/t,isPrecize:!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 xl(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 lo=class{constructor(e){let{timeline:t,timescale:r,timeShiftBufferDepth:i,manifestReceivedTime:o}=e;this.timeline=t,this.timescale=r;let a=o!=null?o:V();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=(V()-this.validityTime)/1e3+this._initialScaledLastPosition/this.timescale;if(e!==void 0){let i=(r-e)*this.timescale;Li(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 c=t[u],l=ke(c,null);if(l===d){this.timeline=this.timeline.concat(t.slice(u+1));return}if(l>d){if(c.duration!==s.duration)return;let f=d-c.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%c.duration!==0)return;let p=f/c.duration-1,g=c.repeatCount-p;if(g<0)return;s.repeatCount+=g;let b=t.slice(u+1);this.timeline=this.timeline.concat(b);return}}}update(e){Ni(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)xl(this.timeline,this.timescale,i,t.privateInfos.smoothMediaSegment)}};function wl(n){return typeof n=="boolean"?n:typeof n=="string"?n.toUpperCase()==="TRUE":!1}function lr(n,e,t){let r=n.firstElementChild,i=t;for(;r!==null;)i=e(i,r.nodeName,r),r=r.nextElementSibling;return i}var Pb={audio:"audio/mp4",video:"video/mp4",text:"application/ttml+xml"},co={AACL:"audio/mp4",AVC1:"video/mp4",H264:"video/mp4",TTML:"application/ttml+xml+mp4",DFXP:"application/ttml+xml+mp4"};function Cb(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 c=lr(d,(f,p,g)=>(p==="CustomAttributes"&&f.push(...lr(g,(b,h,I)=>{if(h==="Attribute"){let T=I.getAttribute("Name"),R=I.getAttribute("Value");T!==null&&R!==null&&b.push(T+"="+R)}return b},[])),f),[]);function l(f){let p=d.getAttribute(f);return p===null?void 0:p}switch(u){case"audio":{let f=l("AudioTag"),p=l("BitsPerSample"),g=l("Channels"),b=l("CodecPrivateData"),h=l("FourCC"),I=l("PacketSize"),T=l("SamplingRate"),R=l("Bitrate"),E=R===void 0?0:parseInt(R,10);if(E=isNaN(E)?0:E,h!==void 0&&co[h]===void 0||b===void 0)return m.warn("Smooth parser: Unsupported audio codec. Ignoring quality level."),null;let v=Bm(b,h);return{audiotag:f!==void 0?parseInt(f,10):f,bitrate:E,bitsPerSample:p!==void 0?parseInt(p,10):p,channels:g!==void 0?parseInt(g,10):g,codecPrivateData:b,codecs:v,customAttributes:c,mimeType:h!==void 0?co[h]:h,packetSize:I!==void 0?parseInt(I,10):I,samplingRate:T!==void 0?parseInt(T,10):T}}case"video":{let f=l("CodecPrivateData"),p=l("FourCC"),g=l("MaxWidth"),b=l("MaxHeight"),h=l("Bitrate"),I=h===void 0?0:parseInt(h,10);if(I=isNaN(I)?0:I,p!==void 0&&co[p]===void 0||f===void 0)return m.warn("Smooth parser: Unsupported video codec. Ignoring quality level."),null;let T=Fm(f);return{bitrate:I,customAttributes:c,mimeType:p!==void 0?co[p]:p,codecPrivateData:f,codecs:T,width:g!==void 0?parseInt(g,10):void 0,height:b!==void 0?parseInt(b,10):void 0}}case"text":{let f=l("CodecPrivateData"),p=l("FourCC"),g=l("Bitrate"),b=g===void 0?0:parseInt(g,10);return b=isNaN(b)?0:b,{bitrate:b,customAttributes:c,mimeType:p!==void 0?co[p]:p,codecPrivateData:f!=null?f:""}}default:return m.error("Smooth Parser: Unrecognized StreamIndex type: "+u),null}}function a(d){let{root:u,timescale:c,baseUrl:l,protections:f,timeShiftBufferDepth:p,manifestReceivedTime:g,isLive:b}=d,h=u.getAttribute("Timescale"),I=h===null?c:+h;isNaN(I)&&(I=c);let T=u.getAttribute("Type");if(T===null)throw new Error("StreamIndex without type.");X($t,T)||m.warn("Smooth Parser: Unrecognized adaptation type:",T);let R=T,E=u.getAttribute("Subtype"),v=u.getAttribute("Language"),k=u.getAttribute("Url"),x=k===null?"":k;y.CURRENT_ENV===y.DEV&&ee(x!=="");let{qualityLevels:P,cNodes:M}=lr(u,(A,C,N)=>{switch(C){case"QualityLevel":{let K=o(N,R);if(K===null)return A;(R!=="video"||K.bitrate>t)&&A.qualityLevels.push(K);break}case"c":A.cNodes.push(N);break}return A},{qualityLevels:[],cNodes:[]}),O=new lo({timeline:Ml(M),timescale:I,timeShiftBufferDepth:p,manifestReceivedTime:g});ee(P.length!==0,"Adaptation should have at least one playable representation.");let B=R+(w(v)?"_"+v:""),D=P.map(A=>{let C=Km(x,A.bitrate,A.customAttributes),N=w(A.mimeType)?A.mimeType:Pb[R],K=A.codecs,j=B+"_"+(_(R)?"":R+"-")+(_(N)?"":N+"-")+(_(K)?"":K+"-")+String(A.bitrate),$=[],z;f.length>0&&(z=f[0],f.forEach(ne=>{$.push(ne.keyId)}));let H={bitsPerSample:A.bitsPerSample,channels:A.channels,codecPrivateData:A.codecPrivateData,packetSize:A.packetSize,samplingRate:A.samplingRate,height:A.height,width:A.width,protection:_(z)?void 0:{keyId:z.keyId}},q=new uo({isLive:b,sharedSmoothTimeline:O,media:C,segmentPrivateInfos:H}),ie=Y({},A,{index:q,cdnMetadata:[{baseUrl:l}],mimeType:N,codecs:K,id:j});if($.length>0||z!==void 0){let ne=z===void 0?[]:z.keySystems.map(le=>{let{systemId:be,privateData:me}=le,W=be.replace(/-/g,""),Ce=Mb(W,me);return{systemId:W,data:Ce}});if(ne.length>0){let le=[{type:"cenc",values:ne}];ie.contentProtections={keyIds:$,initData:le}}else ie.contentProtections={keyIds:$,initData:[]}}return ie});if(E==="ADVT")return null;let F={id:B,type:R,representations:D,language:v===null?void 0:v};return R==="text"&&E==="DESC"&&(F.closedCaption=!0),F}function s(d,u,c){let l="";if(u!==void 0){let q=Mr(u);l=u.substring(0,q)}let f=d.documentElement;if(_(f)||f.nodeName!=="SmoothStreamingMedia")throw new Error("document root should be SmoothStreamingMedia");let p=f.getAttribute("MajorVersion"),g=f.getAttribute("MinorVersion");if(p===null||g===null||!/^[2]-[0-2]$/.test(p+"-"+g))throw new Error("Version should be 2.0, 2.1 or 2.2");let b=f.getAttribute("Timescale"),h=w(b)?+b:1e7;isNaN(h)&&(h=1e7);let{protections:I,adaptationNodes:T}=lr(f,(q,ie,ne)=>{switch(ie){case"Protection":{q.protections.push(Al(ne,n.keySystems));break}case"StreamIndex":q.adaptationNodes.push(ne);break}return q},{adaptationNodes:[],protections:[]}),R={},E=wl(f.getAttribute("IsLive")),v;if(E){let q=f.getAttribute("DVRWindowLength");q!==null&&!isNaN(+q)&&+q!=0&&(v=+q/h)}let k=T.reduce((q,ie)=>{let ne=a({root:ie,baseUrl:l,timescale:h,protections:I,isLive:E,timeShiftBufferDepth:v,manifestReceivedTime:c});if(ne===null)return q;let le=ne.type,be=q[le];return be===void 0?q[le]=[ne]:be.push(ne),q},R),x,P,M,O=null,B,D=k.video!==void 0?k.video[0]:void 0,F=k.audio!==void 0?k.audio[0]:void 0,A,C,N;if(D!==void 0||F!==void 0){let q=[],ie=[];if(D!==void 0){let ne=D.representations[0];if(ne!==void 0){let le=ne.index.getFirstAvailablePosition(),be=ne.index.getLastAvailablePosition();_(le)||q.push(le),_(be)||ie.push(be)}}if(F!==void 0){let ne=F.representations[0];if(ne!==void 0){let le=ne.index.getFirstAvailablePosition(),be=ne.index.getLastAvailablePosition();_(le)||q.push(le),_(be)||ie.push(be)}}q.length>0&&(A=Math.max(...q)),ie.length>0&&(C=Math.min(...ie),N=Math.max(...ie))}let K=f.getAttribute("Duration"),j=K!==null&&+K!=0?+K/h:void 0;if(E){x=n.suggestedPresentationDelay,P=e,M=A!=null?A:P;let q=N;q===void 0&&(q=Date.now()/1e3-P);let ie=C;ie===void 0&&(ie=q),B={isLinear:!0,maximumSafePosition:ie,livePosition:q,time:V()},O=v!=null?v:null}else{M=A!=null?A:0;let q=C;q===void 0&&(q=j!==void 0?M+j:1/0),B={isLinear:!1,maximumSafePosition:q,livePosition:void 0,time:V()}}let $=E?0:M,z=E?void 0:B.maximumSafePosition,H={availabilityStartTime:P===void 0?0:P,clockOffset:i,isLive:E,isDynamic:E,isLastPeriodKnown:!0,timeBounds:{minimumSafePosition:M,timeshiftDepth:O,maximumTimeData:B},periods:[{adaptations:k,duration:z!==void 0?z-$:j,end:z,id:"gen-smooth-period-0",start:$,thumbnailTracks:[]}],suggestedPresentationDelay:x,transportType:"smooth",uris:_(u)?[]:[u]};return ur(H),H}return s}function Mb(n,e){if(n.length!==32)throw new Error("HSS: wrong system id length");return ue("pssh",se([0,0,0,0],Ye(n),ye(e.length),e))}var zm=Cb;var Hm=zm;function Wm(n,e,t,r,i,o,a){return ue("avc1",se(6,ce(1),16,ce(n),ce(e),ce(t),2,ce(r),6,[0,1,i.length],ve(i),31-i.length,ce(o),[255,255],a))}function qm(n,e,t,r,i,o,a,s){return ue("encv",se(6,ce(1),16,ce(n),ce(e),ce(t),2,ce(r),6,[0,1,i.length],ve(i),31-i.length,ce(o),[255,255],a,s))}function Gm(n,e,t,r,i,o){return ue("mp4a",se(6,ce(n),8,ce(e),ce(t),2,ce(r),ce(i),2,o))}function jm(n,e,t,r,i,o,a){return ue("enca",se(6,ce(n),8,ce(e),ce(t),2,ce(r),ce(i),2,o,a))}function Ym(n){return ue("dref",se(7,[1],n))}function $m(n,e){let t=se(...[ve(n),[0,0,0,1]].concat(e.map(ve)));return ue("ftyp",t)}function xa(n,e){return ue("schm",se(4,ve(n),ye(e)))}function Qm(n){return ue("tfdt",se([1,0,0,0],Jt(n)))}function Xm(){let n=new Uint8Array(12);return n[3]=1,ue("vmhd",n)}function Zm(n){return ue("trex",se(4,ye(n),[0,0,0,1],12))}function Jm(n){return ue("free",new Uint8Array(n-8))}function ep(n,e){return ue("esds",se(4,[3,25],ce(n),[0,4,17,64,21],11,[5,2],Ye(e),[6,1,2]))}function wa(n){return ue("frma",ve(n))}function tp(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 ue("avcC",se([1,i,o,a,252|r,225],ce(n.length),n,[1],ce(e.length),e))}function np(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 ue("hdlr",se(8,ve(e),12,ve(t),1))}function rp(n){return ue("mdhd",se(12,ye(n),8))}function ip(n,e){return ue("mvhd",se(12,ye(n),4,[0,1],2,[1,0],10,[0,1],14,[0,1],14,[64,0,0,0],26,ce(e+1)))}function op(n,e,t,r){return ue("saio",se(4,[0,0,0,1],ye(n.length+e.length+t.length+r.length+8+8+8+8)))}function ap(n){if(n.length===0)return ue("saiz",new Uint8Array(0));let e=re(n,0),t=re(n,4),r=new Uint8Array(t+9);r.set(ye(t),5);let i=9,o=8,a,s;for(;o<n.length;)o+=8,(e&2)===2?(s=2,a=Go(n,o),o+=a*6+2):(a=0,s=0),r[i]=a*6+8+s,i++;return ue("saiz",r)}function sp(){return ue("smhd",new Uint8Array(8))}function cr(n){let e=[7,[n.length]];return ue("stsd",se(...e.concat(n)))}function dp(n,e,t){return ue("tkhd",se(ye(7),8,ye(t),20,[1,0,0,0],[0,1,0,0],12,[0,1,0,0],12,[64,0,0,0],ce(n),2,ce(e),2))}function Oa(n,e,t){return ue("tenc",se(6,[n,e],t))}function Ab(n,e,t){return we("moov",[n,e,t])}function fo(n,e,t,r,i,o){let a=we("stbl",[t,ue("stts",new Uint8Array(8)),ue("stsc",new Uint8Array(8)),ue("stsz",new Uint8Array(12)),ue("stco",new Uint8Array(8))]),s=ue("url ",new Uint8Array([0,0,0,1])),d=Ym(s),u=we("dinf",[d]),c=we("minf",[r,u,a]),l=np(e),f=rp(n),p=we("mdia",[f,l,c]),g=dp(i,o,1),b=we("trak",[g,p]),h=Zm(1),I=we("mvex",[h]),T=ip(n,1),R=Ab(T,I,b),E=$m("isom",["isom","iso2","iso6","avc1","dash"]);return se(E,R)}var xb=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];function Ol(n,e,t){let r=xb.indexOf(e),i;return i=(n&63)<<4,i=(i|r&31)<<4,i=(i|t&31)<<3,Be(ce(i))}function Da(n,e,t,r,i,o,a){let s=o.length===0?Ol(2,i,e):o,d=ep(1,s),u=(()=>{if(a===void 0){let h=Gm(1,e,t,r,i,d);return cr([h])}let c=Oa(1,8,a),l=we("schi",[c]),f=xa("cenc",65536),p=wa("mp4a"),g=we("sinf",[p,f,l]),b=jm(1,e,t,r,i,d,g);return cr([b])})();return fo(n,"audio",u,sp(),0,0)}function La(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 c=Ye(d),l=Ye(u),f=tp(c,l,o),p;if(s===void 0){let g=Wm(e,t,r,i,"AVC Coding",24,f);p=cr([g])}else{let g=Oa(1,8,s),b=we("schi",[g]),h=xa("cenc",65536),I=wa("avc1"),T=we("sinf",[I,h,b]),R=qm(e,t,r,i,"AVC Coding",24,f,T);p=cr([R])}return fo(n,"video",p,Xm(),e,t)}function Na(n){let e=_n(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=re(e,o*8+5),a=re(e,o*8+5+4)),t.push({time:s,duration:a})}return t}function Ua(n){let e=_n(n,1830656773,1121273062,2162299933,2952222642);if(e!==void 0)return{duration:Ke(e,12),time:Ke(e,4)}}function Dl(){return!Gt}function Ll(n,e,t,r,i){let o=[n,e,t];return i!==void 0&&o.push(ue("senc",i),ap(i),op(r,n,e,t)),we("traf",o)}function Ba(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=As(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 c=Qm(e),l=wb(u,s[1]-s[0]),f=_n(o,2721664850,1520127764,2722393154,2086964724),p=Ll(d,c,l,i,f),g=we("moof",[i,p]),b=Ve(g,1836019558),h=Ve(p,1953653094),I=Ve(l,1953658222);if(b===null||h===null||I===null)throw new Error("Smooth: Invalid moof, trun or traf generation");let T=b[1]-b[0]+i.length+(h[1]-h[0])+d.length+c.length+(I[1]-I[0])+8,R=t[2]-t[0],E=g.length-R,v=Ve(n,1835295092);if(v===null)throw new Error("Smooth: Invalid ISOBMFF given");if(Dl()&&(E===0||E<=-8)){let k=v[1];return g.set(ye(k),T),n.set(g,t[0]),E<=-8&&n.set(Jm(-E),g.length),n}else{let k=v[1]+E;g.set(ye(k),T);let x=new Uint8Array(n.length+E),P=n.subarray(0,t[0]),M=n.subarray(t[2],n.length);return x.set(P,0),x.set(g,P.length),x.set(M,P.length+g.length),x}}function wb(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),Ls(r)}function Fa(n,e,t,r,i){var p;let o=[],a,s,d;if(i){let g=Kr(n);g!==null?(d=Na(g),s=Ua(g)):m.warn("smooth: could not find traf atom")}if(d!==void 0)for(let g of d)o.push({time:g.time,duration:g.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,c=Math.min(t*.9,u/4),l=Wr(n),f=((p=r.privateInfos)==null?void 0:p.smoothMediaSegment)!==void 0?r.privateInfos.smoothMediaSegment.time:Math.round(r.time*t);return l!==void 0&&Math.abs(l-u)<=c?a={time:r.time,duration:l/t}:a={time:r.time,duration:r.duration},{nextSegments:o,chunkInfos:a,scaledSegmentTime:f}}function Ln(n){return typeof n=="string"&&n.indexOf("mp4")>=0}async function up(n,e,t,r,i,o){var p,g;let a=((p=r.cmcdPayload)==null?void 0:p.type)==="headers"?r.cmcdPayload.value:void 0,s=e.segment.range,d;Array.isArray(s)?d=de(oe({},a),{Range:Qe(s)}):a!==void 0&&(d=a);let u=((g=r.cmcdPayload)==null?void 0:g.type)==="query"?ze(n,r.cmcdPayload.value):n,c=await Se({url:u,responseType:"arraybuffer",headers:d,timeout:r.timeout,connectionTimeout:r.connectionTimeout,cancelSignal:i,onProgress:t.onProgress});if(!Ln(e.mimeType)||o!==!0)return{resultType:"segment-loaded",resultData:c};let f=new Uint8Array(c.responseData);return on(f,e.segment.isInit),{resultType:"segment-loaded",resultData:de(oe({},c),{responseData:f})}}var Ob=({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:c,timescale:l,height:f,width:p,protection:g={keyId:void 0,keySystems:void 0}}=d;if(c===void 0)throw new Error("Smooth: no codec private data.");switch(r.type){case"video":{u=La(l,p!=null?p:0,f!=null?f:0,72,72,4,c,g.keyId);break}case"audio":{let{channels:b=0,bitsPerSample:h=0,packetSize:I=0,samplingRate:T=0}=d;u=Da(l,b,h,I,T,c,g.keyId);break}default:y.CURRENT_ENV===y.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"?up(t,r,a,i,o,n):new Promise((d,u)=>{let c=!1,b={reject:E=>{var P,M;if(c||o.isCancelled())return;c=!0,o.deregister(R);let v=E,k=(P=v==null?void 0:v.message)!=null?P:"Unknown error when fetching a Smooth segment through a custom segmentLoader.",x=new it(k,(M=v==null?void 0:v.canRetry)!=null?M:!1,v==null?void 0:v.xhr);u(x)},resolve:E=>{if(c||o.isCancelled())return;c=!0,o.deregister(R),(!Ln(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);on(k,r.segment.isInit),d({resultType:"segment-loaded",resultData:{responseData:k,size:E.size,requestDuration:E.duration}})},fallback:()=>{c||o.isCancelled()||(c=!0,o.deregister(R),up(t,r,a,i,o,n).then(d,u))},progress:E=>{c||o.isCancelled()||a.onProgress({duration:E.duration,size:E.size,totalSize:E.totalSize})}},h;r.segment.range!==void 0&&(h=[r.segment.range],r.segment.indexRange!==void 0&&h.push(r.segment.indexRange));let I={isInit:r.segment.isInit,timeout:i.timeout,byteRanges:h,trackType:r.type,url:t,cmcdPayload:i.cmcdPayload},T=e(I,b);o.register(R);function R(E){c||(c=!0,!c&&typeof T=="function"&&T(),u(E))}})},lp=Ob;function Nl(n,e){return n===null?null:e.url===null?n.baseUrl:gn(n.baseUrl,e.url)}function cp(n){let e=Hm(n),t=lp(n),r={customManifestLoader:n.manifestLoader},o={loadManifest:Wi(r,"text",null),parseManifest(d,u){var I;let c=(I=d.url)!=null?I:u.originalUrl,{receivedTime:l,responseData:f}=d,p=typeof f=="string"?new DOMParser().parseFromString(f,"text/xml"):f,g=e(p,c,l),b=[];return{manifest:new $n(g,{representationFilter:n.representationFilter},b),url:c,warnings:b}}},a={loadSegment(d,u,c,l,f){let p=Nl(d,u.segment);return t(p,u,c,l,f)},parseSegment(d,u,c){var v,k;let{segment:l}=u,{data:f,isChunked:p}=d;if(f===null)return l.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 g=f instanceof Uint8Array?f:new Uint8Array(f);if(l.isInit){let x=(k=(v=l.privateInfos)==null?void 0:v.smoothInitSegment)==null?void 0:k.timescale;return{segmentType:"init",initializationData:f,initializationDataSize:f.byteLength,initTimescale:x,protectionData:[]}}let b=c!==void 0?Fa(g,p,c,l,u.isLive):null;if(b===null||b.chunkInfos===null||b.scaledSegmentTime===void 0)throw new Error("Smooth Segment without time information");let{nextSegments:h,chunkInfos:I,scaledSegmentTime:T}=b,R=Ba(g,T),E=h.length>0?h:void 0;return{segmentType:"media",chunkData:R,chunkInfos:I,chunkOffset:0,chunkSize:R.length,protectionData:[],predictedSegments:E,appendWindow:[void 0,void 0]}}};return{transportName:"smooth",manifest:o,audio:a,video:a,text:{loadSegment(d,u,c,l,f){var h,I,T,R;let{segment:p}=u,g=Nl(d,p);return p.isInit||g===null?Promise.resolve({resultType:"segment-created",resultData:null}):Ln(u.mimeType)?Se({url:((T=c.cmcdPayload)==null?void 0:T.type)==="query"?ze(g,c.cmcdPayload.value):g,headers:((R=c.cmcdPayload)==null?void 0:R.type)==="headers"?c.cmcdPayload.value:void 0,responseType:"arraybuffer",timeout:c.timeout,connectionTimeout:c.connectionTimeout,cancelSignal:l,onProgress:f.onProgress}).then(E=>{if(n.checkMediaSegmentIntegrity!==!0)return{resultType:"segment-loaded",resultData:E};let v=new Uint8Array(E.responseData);return on(v,u.segment.isInit),{resultType:"segment-loaded",resultData:de(oe({},E),{responseData:v})}}):Se({url:((h=c.cmcdPayload)==null?void 0:h.type)==="query"?ze(g,c.cmcdPayload.value):g,headers:((I=c.cmcdPayload)==null?void 0:I.type)==="headers"?c.cmcdPayload.value:void 0,responseType:"text",timeout:c.timeout,connectionTimeout:c.connectionTimeout,cancelSignal:l,onProgress:f.onProgress}).then(E=>({resultType:"segment-loaded",resultData:E}))},parseSegment(d,u,c){var B;let{segment:l,language:f,mimeType:p="",codecs:g=""}=u,b=Ln(u.mimeType),{data:h,isChunked:I}=d,T;if(l.isInit)return{segmentType:"init",initializationData:null,initializationDataSize:0,protectionData:[],initTimescale:void 0};if(h===null)return{segmentType:"media",chunkData:null,chunkInfos:null,chunkOffset:0,chunkSize:0,protectionData:[],appendWindow:[void 0,void 0]};let R,E=null,v,k,x,P;if(b){let D;typeof h=="string"?D=ve(h):D=h instanceof Uint8Array?h:new Uint8Array(h),T=D.length;let F=c!==void 0?Fa(D,I,c,l,u.isLive):null;R=F==null?void 0:F.nextSegments,E=(B=F==null?void 0:F.chunkInfos)!=null?B:null,E===null?I?m.warn("Smooth: Unavailable time data for current text track."):(v=l.time,k=l.end):(v=E.time,k=E.duration!==void 0?E.time+E.duration:l.end);let A=g.toLowerCase();if(p==="application/ttml+xml+mp4"||A==="stpp"||A==="stpp.ttml"||A==="stpp.ttml.im1t")P="ttml";else if(A==="wvtt")P="vtt";else throw new Error(`could not find a text-track parser for the type ${p}`);let C=Vr(D);x=C===null?"":Ue(C)}else{v=l.time,k=l.end;let D;if(typeof h!="string"){let F=h instanceof Uint8Array?h:new Uint8Array(h);T=F.length,D=Ue(F)}else D=h;switch(p){case"application/x-sami":case"application/smil":P="sami";break;case"application/ttml+xml":P="ttml";break;case"text/vtt":P="vtt";break}if(P===void 0)if(g.toLowerCase()==="srt")P="srt";else throw new Error(`could not find a text-track parser for the type ${p}`);x=D}let M=Array.isArray(R)&&R.length>0?R:void 0,O=v!=null?v:0;return{segmentType:"media",chunkData:{type:P,data:x,start:v,end:k,language:f},chunkSize:T,chunkInfos:E,chunkOffset:O,protectionData:[],predictedSegments:M,appendWindow:[void 0,void 0]}}},thumbnails:{loadThumbnail:()=>Promise.reject(new Error("Thumbnail tracks aren't implemented with smooth")),parseThumbnail:()=>{throw new Error("Thumbnail tracks aren't implemented with smooth")}}}}var fp=cp;function Ul(n){n.transports.smooth===void 0&&(n.transports.smooth=fp),n.mainThreadMediaSourceInit=kn}function mp(){if(!Pt)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 Bl(){if(!Pt)return!0;let n=mp();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 mo(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 Fl(){return Qa&&typeof Worker=="object"||typeof Worker=="function"}var Nn=class n extends Error{constructor(e,t){super(Je(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="WorkerInitializationError",this.type="WORKER_INITIALIZATION_ERROR",this.code=e}};function Ka(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 Ka(this,i,t)}}}var Db=["canplay","ended","play","pause","seeking","seeked","loadedmetadata","ratechange"],po=class{constructor(e,t){this._internalSeeksIncoming=[],this._mediaElement=e,this._withMediaSource=t.withMediaSource,this._lowLatencyMode=t.lowLatencyMode,this._canceller=new U,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 Z;this._observationRef.onUpdate(e,{clearSignal:t.clearSignal,emitCurrentValue:t.includeLastObservation})}deriveReadOnlyObserver(e){return Ka(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}=L.getCurrent(),i=new G(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 Db.map(u=>{let c=()=>{d(),this._generateObservationForEvent(u)};this._mediaElement.addEventListener(u,c),this._canceller.signal.register(()=>{this._mediaElement.removeEventListener(u,c)})}),this._canceller.signal.register(()=>{clearInterval(s),i.finish()}),i;function d(){clearInterval(s),s=setInterval(a,o)}}_getCurrentObservation(e){var R,E;let t=e,r=this._observationRef===void 0?Fb(this._mediaElement):this._observationRef.getValue(),i=!1,o=this._pendingSeek,a=gp(this._mediaElement),{buffered:s,readyState:d,position:u,seeking:c}=a;if(t==="seeking")if(this._internalSeeksIncoming.length>0){i=!0,t="internal-seeking";let v=this._internalSeeksIncoming.shift();this._expectedSeekingPosition=nr?Math.max(u,v!=null?v:0):u}else this._expectedSeekingPosition=u;else c?this._expectedSeekingPosition=Math.max(u,(R=this._expectedSeekingPosition)!=null?R:0):nr&&this._expectedSeekingPosition!==null&&u<this._expectedSeekingPosition?o=this._expectedSeekingPosition:this._expectedSeekingPosition=null;c&&r.seeking===1&&e!=="seeking"&&(i=!0);let l=(E=this._expectedSeekingPosition)!=null?E:u,f,p;!this._withMediaSource&&s.length===0&&d>=3?(f=void 0,p=void 0):(f=ns(s,l),p=f!==null?f.end-l:1/0);let g=Lb(l,f,a.ended,a.duration,this._lowLatencyMode),b=Nb({previousObservation:r,currentObservation:a,basePosition:l,observationEvent:t,lowLatencyMode:this._lowLatencyMode,withMediaSource:this._withMediaSource,bufferGap:p,fullyLoaded:g}),h=Ub(r,a,t,p),I;i?I=1:c?I=2:I=0;let T=Y({},a,{position:new tr(a.position,o),event:t,seeking:I,rebuffering:b,freezing:h,bufferGap:p,currentRange:f,fullyLoaded:g});return m.hasLevel("DEBUG")&&m.debug("API: current media element state tick","event",T.event,"position",T.position.getPolled(),"seeking",T.seeking,"internalSeek",i,"rebuffering",T.rebuffering!==null,"freezing",T.freezing!==null,"ended",T.ended,"paused",T.paused,"playbackRate",T.playbackRate,"readyState",T.readyState,"pendingPosition",o),T}_generateObservationForEvent(e){let t=this._getCurrentObservation(e);m.hasLevel("DEBUG")&&m.debug(`API: current playback timeline:
15
15
  `+Bb(t.buffered,t.position.getPolled()),`
16
16
  ${e}`),this._observationRef.setValue(t)}};function pp(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}=L.getCurrent();switch(n.reason){case"seeking":return r[t];case"not-ready":return i[t];case"buffering":return o[t]}}function Lb(n,e,t,r,i){let{REBUFFERING_GAP:o}=L.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 gp(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 Nb({previousObservation:n,currentObservation:e,basePosition:t,observationEvent:r,withMediaSource:i,lowLatencyMode:o,bufferGap:a,fullyLoaded:s}){let{REBUFFERING_GAP:d}=L.getCurrent(),{position:u,paused:c,readyState:l,ended:f}=e,{rebuffering:p,event:g,position:b}=n,h=l>=1&&r!=="loadedmetadata"&&p===null&&!(s||f),I=null,T,R,E=o?d.LOW_LATENCY:d.DEFAULT;if(i){if(h)a===1/0?(T=!0,I=t):a===void 0?l<3&&(T=!0,I=void 0):a<=E&&(T=!0,I=t+a);else if(p!==null){let v=pp(p,o);T!==!0&&p!==null&&l>1&&(s||f||a!==void 0&&isFinite(a)&&a>v)||a===void 0&&l>=3?R=!0:a===void 0?I=void 0:a===1/0?I=t:a<=v&&(I=t+a)}}else h&&(!c&&r==="timeupdate"&&g==="timeupdate"&&u===b.getPolled()||r==="seeking"&&(a===1/0||a===void 0&&l<3))?T=!0:p!==null&&(r!=="seeking"&&u!==b.getPolled()||r==="canplay"||a===void 0&&l>=3||a!==void 0&&a<1/0&&(a>pp(p,o)||s||f))&&(R=!0);if(R===!0)return null;if(T===!0||p!==null){let v;return r==="seeking"||p!==null&&p.reason==="seeking"||e.seeking?v="seeking":l===1?v="not-ready":v="buffering",p!==null&&p.reason===v?{reason:p.reason,timestamp:p.timestamp,position:I}:{reason:v,timestamp:V(),position:I}}return null}function Ub(n,e,t,r){let{MINIMUM_BUFFER_AMOUNT_BEFORE_FREEZING:i}=L.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:V()}: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),c=`${s}|==${u}==|${d}`;if(t+=c,r.length===0&&a>e){let l=t.length-Math.floor(c.length/2);r=" ".repeat(l)+`^${e}`}if(i<n.length-1){let l=n.start(i+1),p=` ~${(l-a).toFixed(2)}~ `;if(t+=p,r.length===0&&e<l){let g=t.length-Math.floor(p.length/2);r=" ".repeat(g)+`^${e}`}}}return r.length===0&&(r=" ".repeat(t.length)+`^${e}`),t+`
17
- `+r}function Fb(n){let e=gp(n);return Y(e,{rebuffering:null,event:"init",seeking:0,position:new tr(e.position,null),freezing:null,bufferGap:0,currentRange:null,fullyLoaded:!1})}async function Kl(n,e){let{time:t,container:r}=e;if(n===null||n.fetchThumbnailDataCallback===null||n.manifest===null)return Promise.reject(new ct("NO_CONTENT","Cannot get thumbnail: no content loaded"));let{thumbnailRequestsInfo:i,currentContentCanceller:o}=n,a=new U;a.linkToSignal(o.signal);let s,d=i.pendingRequests.get(r);d==null||d.cancel(),i.pendingRequests.set(r,a);let u=()=>{a.cancel(),i.pendingRequests.delete(r),setTimeout(()=>{s!==void 0&&URL.revokeObjectURL(s)},0)};try{let l=Kn(n.manifest,t);if(l===void 0)throw new ct("NO_THUMBNAIL","Wanted Period not found.");let f=l.thumbnailTracks,p=e.thumbnailTrackId!==void 0?Q(f,v=>v.id===e.thumbnailTrackId):f[0];if(p===void 0)throw e.thumbnailTrackId!==void 0?new ct("NO_THUMBNAIL","Given `thumbnailTrackId` not found"):new ct("NO_THUMBNAIL","Wanted Period has no thumbnail track.");let{lastResponse:g}=i,b;if(g!==null&&g.thumbnailTrackId===p.id&&g.periodId===l.id){let v=g.response.thumbnails;v.length>0&&t>=v[0].start&&t<v[v.length-1].end&&(b=g.response)}if(b===void 0&&(b=await n.fetchThumbnailDataCallback(l.id,p.id,t),i.lastResponse={response:b,periodId:l.id,thumbnailTrackId:p.id}),a.signal.cancellationError!==null)throw a.signal.cancellationError;let h=document.createElement("canvas"),I=h.getContext("2d");if(I===null)throw new ct("RENDERING","Cannot display thumbnail: cannot create canvas context");let T=pe(b.thumbnails,v=>v.start<=t&&v.end>t);if(T<0)throw new Error("Cannot display thumbnail: time not found in fetched data");let R=new Image,E=new Blob([b.data],{type:b.mimeType});return s=URL.createObjectURL(E),R.src=s,h.height=b.thumbnails[T].height,h.width=b.thumbnails[T].width,new Promise((v,k)=>{R.onload=()=>{try{I.drawImage(R,b.thumbnails[T].offsetX,b.thumbnails[T].offsetY,b.thumbnails[T].width,b.thumbnails[T].height,0,0,b.thumbnails[T].width,b.thumbnails[T].height),h.style.width="100%",h.style.height="100%",h.className="__rx-thumbnail__",c(),r.appendChild(h),v()}catch(x){k(new ct("RENDERING","Could not draw the image in a canvas:"+(x instanceof Error?x.toString():"Unknown Error")))}u()},R.onerror=()=>{e.keepPreviousThumbnailOnError!==!0&&c(),k(new ct("RENDERING","Could not load the corresponding image in the DOM")),u()}})}catch(l){if(e.keepPreviousThumbnailOnError!==!0&&c(),l!==null&&l===a.signal.cancellationError)throw new ct("ABORTED","Thumbnail rendering has been aborted");let f=Ee(l,{defaultCode:"NONE",defaultReason:"Unknown error"}),p;throw f.type==="NETWORK_ERROR"?p=new ct("LOADING",f.message):p=new ct("NOT_FOUND",f.message),u(),p}function c(){for(let l=r.children.length-1;l>=0;l--){let f=r.children[l];f.className==="__rx-thumbnail__"&&r.removeChild(f)}}}var ct=class n extends Error{constructor(e,t){super(Je(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="ThumbnailRenderingError",this.code=e}};var go=class extends ae{constructor(e){super(),this._canceller=new U,this._adaptationRef=e,this._updateToken=!1,this._lastEmitted=void 0,this.refresh=Z}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 U,this._lastEmitted=null,this._adaptationRef.setValue(null);return}let{adaptation:t,switchingMode:r,relativeResumingPosition:i}=e;this._canceller.cancel(),this._canceller=new U;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 G({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(l=>St(l)===!0),s="lazy";else{let{representationIds:l}=a;if(s=a.switchingMode,d=e.adaptation.representations.filter(p=>X(l,p.id)).filter(p=>St(p)===!0),d.length===0){r.trigger("noPlayableLockedRepresentation",null);return}}if(d.length<=0){r.trigger("noPlayableRepresentation",null);return}let u=t.getValue(),c=d.map(l=>l.id).slice().sort();if(c.length!==u.representationIds.length){t.setValue({representationIds:c,switchingMode:s});return}for(let l=0;l<c.length;l++)if(u.representationIds[l]!==c[l]){t.setValue({representationIds:c,switchingMode:s});return}}function o(){r.refresh=Z}}dispose(){this.removeEventListener(),this._canceller.cancel(),this._adaptationRef.finish()}};var ho=class extends ae{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:L.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,c,l;let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:t}=L.getCurrent(),{periods:r}=e;if(y.CURRENT_ENV===y.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 p=this._storedPeriodInfo[f].period,g=r[o];if(g===void 0)for(let b=this._storedPeriodInfo.length-1;b>=f;b--)this._storedPeriodInfo[b].inManifest=!1,Vl(this._storedPeriodInfo[b])&&this._removePeriodObject(b);else if(p===g){o++;let b=this._storedPeriodInfo[f].text.storedSettings;if(!_(b)&&!pt(g,"text").some(E=>E.id===b.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:Ft(g),trackType:"text",reason:"missing"}),this._isDisposed)return;let v=ft(this._storedPeriodInfo,E.period.id);v!==void 0&&v.isPeriodAdvertised&&v.text.storedSettings===null&&((a=v.text.dispatcher)==null||a.updateTrack(null))}let h=this._storedPeriodInfo[f].video.storedSettings;if(!_(h)){let T=pt(g,"video");if(!T.some(E=>E.id===h.adaptation.id)){m.warn("TS: Chosen video Adaptation not available anymore");let E=this._storedPeriodInfo[f],v;if(T.length===0)v=null;else{let x=T[0],P=Va(x,this._isTrickModeTrackEnabled),M=new G(null);v={adaptationBase:x,adaptation:P,switchingMode:t,lockedRepresentations:M}}if(E.video.storedSettings=v,this.trigger("trackUpdate",{period:Ft(g),trackType:"video",reason:"missing"}),this._isDisposed)return;let k=ft(this._storedPeriodInfo,E.period.id);k!==void 0&&k.isPeriodAdvertised&&k.video.storedSettings===v&&((s=k.video.dispatcher)==null||s.updateTrack(v))}}let I=this._storedPeriodInfo[f].audio.storedSettings;if(!_(I)){let T=pt(g,"audio");if(!T.some(E=>E.id===I.adaptation.id)){m.warn("TS: Chosen audio Adaptation not available anymore");let E=this._storedPeriodInfo[f],v=T.length===0?null:{adaptation:T[0],switchingMode:this._defaultAudioTrackSwitchingMode,lockedRepresentations:new G(null)};if(E.audio.storedSettings=v,this.trigger("trackUpdate",{period:Ft(g),trackType:"audio",reason:"missing"}),this._isDisposed)return;let k=ft(this._storedPeriodInfo,E.period.id);k!==void 0&&k.isPeriodAdvertised&&k.audio.storedSettings===v&&((d=k.audio.dispatcher)==null||d.updateTrack(v))}}}else if(p.start<=g.start)this._storedPeriodInfo[f].inManifest=!1,Vl(this._storedPeriodInfo[f])&&(this._removePeriodObject(f),f--);else{let b=zl(g,!0);this._storedPeriodInfo.splice(f,0,b),i.push(b),o++}}if(o<r.length){let f=r.slice(o).map(p=>zl(p,!0));this._storedPeriodInfo.push(...f),i.push(...f)}for(let f of this._storedPeriodInfo)(u=f.audio.dispatcher)==null||u.refresh(),(c=f.video.dispatcher)==null||c.refresh(),(l=f.text.dispatcher)==null||l.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){m.debug("TS: Adding Track Reference",e,t.id);let i=ft(this._storedPeriodInfo,t.id);if(i===void 0){i=zl(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)}i[e].dispatcher!==null&&(m.error(`TS: Subject already added for ${e} and Period ${t.start}`),i[e].dispatcher.dispose());let o=new go(r);if(i[e].dispatcher=o,o.addEventListener("noPlayableRepresentation",()=>{var l,f,p,g;let s=Q((l=t.adaptations[e])!=null?l:[],b=>b.supportStatus.hasSupportedCodec===!1||b.supportStatus.isDecipherable===!1?!1:b.representations.filter(I=>St(I)===!0).length>0);if(s===void 0){let b=new te("NO_PLAYABLE_REPRESENTATION",`No ${e} Representation can be played`,{tracks:void 0});this.trigger("error",b),this.dispose();return}let d=(f=ft(this._storedPeriodInfo,t.id))==null?void 0:f[e];if(_(d))return;let u=e==="audio"?this._defaultAudioTrackSwitchingMode:"reload",c={adaptation:s,switchingMode:u,lockedRepresentations:new G(null)};d.storedSettings=c,this.trigger("trackUpdate",{period:Ft(t),trackType:e,reason:"no-playable-representation"}),!this._isDisposed&&(d=(p=ft(this._storedPeriodInfo,t.id))==null?void 0:p[e],!(_(d)||d.storedSettings!==c)&&((g=d.dispatcher)==null||g.updateTrack(c)))}),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){m.debug("TS: Removing Track Reference",e,t);let r;for(let a=0;a<this._storedPeriodInfo.length;a++)if(this._storedPeriodInfo[a].period.id===t){r=a;break}if(r===void 0){m.warn(`TS: ${e} not found for period`,t);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}`);return}o.dispatcher.dispose(),o.dispatcher=null,Vl(i)&&this._removePeriodObject(r)}getPeriodObjectFromPeriod(e){let t=ft(this._storedPeriodInfo,e.id);return t===void 0&&e!==void 0?this._cachedPeriodInfo.get(e):t}getPeriodObjectFromId(e){return ft(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;m.debug("TS: Resetting Period Objects");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 p,g;if(!t.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let s=t.period,d=Q((p=s.adaptations[e])!=null?p:[],({id:b,supportStatus:h})=>h.hasSupportedCodec!==!1&&h.isDecipherable!==!1&&b===r);if(d===void 0)throw new Error(`Wanted ${e} track not found.`);let u=t[e],c;if(o===null)c=new G(null);else{let b=this._getRepresentationsToLock(d,o),h=e==="audio"?this._defaultAudioTrackSwitchingMode:"direct";c=new G({representationIds:b,switchingMode:h})}let l={adaptation:d,switchingMode:i,lockedRepresentations:c,relativeResumingPosition:a};if(u.storedSettings=l,this.trigger("trackUpdate",{period:Ft(s),trackType:e,reason:"manual"}),this._isDisposed)return;let f=ft(this._storedPeriodInfo,s.id);f!==void 0&&f[e].storedSettings===l&&((g=f[e].dispatcher)==null||g.updateTrack(l))}setVideoTrack(e){var b,h;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=Q((b=s.adaptations.video)!=null?b:[],({id:I,supportStatus:T})=>T.isDecipherable!==!1&&T.hasSupportedCodec!==!1&&I===r);if(d===void 0)throw new Error("Wanted video track not found.");let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:u}=L.getCurrent(),c=t.video,l=Va(d,this._isTrickModeTrackEnabled),f;if(o===null)f=new G(null);else{let I=this._getRepresentationsToLock(d,o),T=u;f=new G({representationIds:I,switchingMode:T})}let p={adaptationBase:d,switchingMode:i!=null?i:u,adaptation:l,relativeResumingPosition:a,lockedRepresentations:f};if(c.storedSettings=p,this.trigger("trackUpdate",{period:Ft(s),trackType:"video",reason:"manual"}),this._isDisposed)return;let g=ft(this._storedPeriodInfo,s.id);g!==void 0&&g.video.storedSettings===p&&((h=g.video.dispatcher)==null||h.updateTrack(p))}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=ft(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:Mo(e.audio.storedSettings.adaptation,t)}getChosenTextTrack(e){return _(e.text.storedSettings)?null:Ao(e.text.storedSettings.adaptation)}getChosenVideoTrack(e,t){return _(e.video.storedSettings)?null:xo(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 Y(Mo(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 Y(Ao(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=xo(a,t),u=d.trickModeTracks!==void 0?d.trickModeTracks.map(l=>{let f=i===null?!1:i===l.id;return Y(l,{active:f})}):[],c=Y(d,{active:s});return u!==void 0&&(c.trickModeTracks=u),c})}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}=L.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}=L.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=Va(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=ft(this._storedPeriodInfo,o.id);d!==void 0&&d.isPeriodAdvertised&&d.video.storedSettings===s&&((r=d.video.dispatcher)==null||r.updateTrack(s))}}}_removePeriodObject(e){y.CURRENT_ENV===y.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=Q(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}=L.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 c=[...(i=u.adaptations.audio)!=null?i:[],...(o=u.adaptations.video)!=null?o:[]],l=c.every(I=>I.supportStatus.hasCodecWithUndefinedSupport);if(c.length>0&&l)continue;let f=pt(u,"audio")[0];d.audio.storedSettings=f===void 0?null:{adaptation:f,switchingMode:this._defaultAudioTrackSwitchingMode,lockedRepresentations:new G(null)};let p=pt(u,"video")[0],g=Va(p,this._isTrickModeTrackEnabled);d.video.storedSettings=g===void 0?null:{adaptation:g,adaptationBase:p,switchingMode:e,lockedRepresentations:new G(null)};let b=null,h=((a=u.adaptations.text)!=null?a:[]).filter(I=>I.isForcedSubtitles===!0);if(h.length>0){if(f!=null){let I=Q(h,T=>T.normalizedLanguage===f.normalizedLanguage);I!==void 0&&(b=I)}b===null&&(b=(s=Q(h,I=>I.normalizedLanguage===void 0))!=null?s:null)}d.text.storedSettings=b===null?null:{adaptation:b,switchingMode:"direct",lockedRepresentations:new G(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 c of u){let l=d[c];if(l.dispatcher!==null&&l.storedSettings!==void 0&&!l.dispatcher.hasSetTrack()&&(l.dispatcher.updateTrack(l.storedSettings),this._isDisposed))return}}}_shouldAdvertisePeriod(e){return!e.isPeriodAdvertised&&e.text.dispatcher!==null&&e.video.dispatcher!==null&&e.audio.dispatcher!==null}};function ft(n,e){for(let t=0;t<n.length;t++){let r=n[t];if(r.period.id===e)return r}}function Vl(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 Va(n,e){var t;return e&&((t=n.trickModeTracks)==null?void 0:t[0])!==void 0?n.trickModeTracks[0]:n}function zl(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 hp=ho;function yp(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:c,DEFAULT_MAX_VIDEO_BUFFER_SIZE:l,DEFAULT_THROTTLE_VIDEO_BITRATE_WHEN_HIDDEN:f,DEFAULT_WANTED_BUFFER_AHEAD:p}=L.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=c;else if(t=Number(n.maxBufferBehind),isNaN(t))throw new Error("Invalid maxBufferBehind parameter. Should be a number.");if(_(n.wantedBufferAhead))r=p;else if(r=Number(n.wantedBufferAhead),isNaN(r))throw new Error("Invalid wantedBufferAhead parameter. Should be a number.");if(_(n.maxVideoBufferSize))i=l;else if(i=Number(n.maxVideoBufferSize),isNaN(i))throw new Error("Invalid maxVideoBufferSize parameter. Should be a number.");let g=_(n.videoResolutionLimit)?d:n.videoResolutionLimit,b=_(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:g,videoElement:o,wantedBufferAhead:r,maxVideoBufferSize:i,throttleVideoBitrateWhenHidden:b,baseBandwidth:a}}function Ip(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 bp(n){var E,v,k,x;let e,t,r,i,o,a,s,{DEFAULT_AUTO_PLAY:d,DEFAULT_CODEC_SWITCHING_BEHAVIOR:u,DEFAULT_ENABLE_FAST_SWITCHING:c,DEFAULT_TEXT_TRACK_MODE:l}=L.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 P of r)if(typeof P.type!="string"||typeof P.getLicense!="function")throw new Error("Invalid key system given: Missing type string or getLicense callback")}let p=n.lowLatencyMode===void 0?!1:!!n.lowLatencyMode,g=n.initialManifest,b=(E=n.minimumManifestUpdateInterval)!=null?E:0,h=(v=n.defaultAudioTrackSwitchingMode)!=null?v:void 0;h!==void 0&&!X(["seamless","direct","reload"],h)&&(m.warn("The `defaultAudioTrackSwitchingMode` loadVideo option must match one of the following strategy name:\n- `seamless`\n- `direct`\n- `reload`"),h=void 0);let I=_(n.onCodecSwitch)?u:n.onCodecSwitch;if(X(["continue","reload"],I)||(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"),I=u),_(n.textTrackMode))i=l;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(!X(["auto","multithread","main"],n.mode))throw new Error("Invalid `mode` option.");o=n.mode}let T=_(n.enableFastSwitching)?c:n.enableFastSwitching;if(!_(n.startAt))if("wallClockTime"in n.startAt&&n.startAt.wallClockTime instanceof Date){let P=n.startAt.wallClockTime.getTime()/1e3;s=Y({},n.startAt,{wallClockTime:P})}else s=n.startAt;let R=(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:h,enableFastSwitching:T,initialManifest:g,keySystems:r,lowLatencyMode:p,manifestLoader:n.manifestLoader,minimumManifestUpdateInterval:b,requestConfig:R,onCodecSwitch:I,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,experimentalOptions:{enableRepresentationAvoidance:((x=n.experimentalOptions)==null?void 0:x.enableRepresentationAvoidance)===!0}}}function Sp(n,e,t,r){if(r.isCancelled())return;let i=n.getReference().getValue().seeking===2;i&&(e(),r.isCancelled())||n.listen(o=>{o.event==="seeking"?(i=!0,e()):i&&o.event==="seeked"&&(i=!1,t())},{includeLastObservation:!0,clearSignal:r})}function Tp(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 _p(n,e,t,r){let i=new G("LOADING",r);n.addEventListener("loaded",()=>{if(i.getValue()==="LOADING"){if(i.setValue("LOADED"),!r.isCancelled()){let s=Hl(e,null);s!=="PAUSED"&&i.setValue(s)}}else i.getValue()==="RELOADING"?i.setValue(Hl(e,null)):a(null)},r),n.addEventListener("reloadingMediaSource",()=>{fr(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=>{X(["seeking","ended","play","pause"],s.event)&&a(o)},{clearSignal:r}),i;function a(s){if(!fr(i.getValue()))return;let d=Hl(e,s);i.getValue()==="LOADED"&&d==="PAUSED"||i.setValueIfChanged(d)}}function Hl(n,e){let{FORCED_ENDED_THRESHOLD:t}=L.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 fr(n){return n!=="LOADING"&&n!=="RELOADING"&&n!=="STOPPED"}var Kb=et(),Vb=["manifestLoader","segmentLoader"],Kt=class Kt extends ae{static get ErrorTypes(){return Ze}static get ErrorCodes(){return ls}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){ca(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}=yp(e);s.preload="auto",this.version="4.3.0",this.log=m,this.state="STOPPED",this.videoElement=s,Kt._priv_registerVideoElement(this.videoElement);let c=new U;this._destroyCanceller=c,this._priv_pictureInPictureRef=Mc(s,c.signal),this._priv_speed=new G(s.playbackRate,this._destroyCanceller.signal),this._priv_preferTrickModeTracks=!1,this._priv_contentLock=new G(!1,this._destroyCanceller.signal),this._priv_bufferOptions={wantedBufferAhead:new G(d,this._destroyCanceller.signal),maxBufferAhead:new G(i,this._destroyCanceller.signal),maxBufferBehind:new G(o,this._destroyCanceller.signal),maxVideoBufferSize:new G(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;let l=()=>{this.trigger("volumeChange",{volume:s.volume,muted:s.muted})};s.addEventListener("volumechange",l),c.signal.register(()=>{s.removeEventListener("volumechange",l)})}attachWorker(e){return new Promise((t,r)=>{var a;if(!Fl())return m.warn("API: Cannot rely on a WebWorker: Worker API unavailable"),r(new Nn("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 Nn("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 Nn("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:Un(),date:Date.now(),timestamp:V(),hasVideo:((a=this.videoElement)==null?void 0:a.nodeName.toLowerCase())==="video",hasMseInWorker:cm}}),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:Un()}}))},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}))};L.updated&&o(L.getCurrent()),L.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),Vn(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=bp(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 c,l,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.");Ip(e);let a;if(((c=e==null?void 0:e.reloadAt)==null?void 0:c.position)!==void 0)a={position:e.reloadAt.position};else if(((l=e==null?void 0:e.reloadAt)==null?void 0:l.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=de(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(fe.createDebugElement===null)throw new Error("Feature `DEBUG_ELEMENT` not added to the RxPlayer");let t=new U;return fe.createDebugElement(e,this,t.signal),{dispose(){t.cancel()}}}getAvailableThumbnailTracks({time:e,periodId:t}={}){if(this._priv_contentInfos===null||this._priv_contentInfos.manifest===null)return[];let{manifest:r}=this._priv_contentInfos,i;if(e!==void 0){if(i=Kn(this._priv_contentInfos.manifest,e),i===void 0||i.thumbnailTracks.length===0)return[]}else if(t!==void 0){if(i=Q(r.periods,o=>o.id===t),i===void 0)return m.error("API: getAvailableThumbnailTracks: periodId not found"),[]}else{let{currentPeriod:o}=this._priv_contentInfos;if(o===null)return[];i=o}return i.thumbnailTracks.map(o=>({id:o.id,width:Math.floor(o.width/o.horizontalTiles),height:Math.floor(o.height/o.verticalTiles),mimeType:o.mimeType}))}async renderThumbnail(e){if(_(e.time))throw new Error("You have to provide a `time` property to `renderThumbnail`, indicating the wanted thumbnail time in seconds.");if(_(e.container))throw new Error("You have to provide a `container` property to `renderThumbnail`, specifying the HTML Element in which the thumbnail should be inserted.");return Kl(this._priv_contentInfos,e)}_priv_initializeContentPlayback(e){var q,ie,ne,le,be,me;let{autoPlay:t,cmcd:r,defaultAudioTrackSwitchingMode:i,enableFastSwitching:o,initialManifest:a,keySystems:s,lowLatencyMode:d,minimumManifestUpdateInterval:u,requestConfig:c,onCodecSwitch:l,startAt:f,transport:p,checkMediaSegmentIntegrity:g,checkManifestIntegrity:b,manifestLoader:h,referenceDateTime:I,segmentLoader:T,serverSyncInfos:R,mode:E,experimentalOptions:v,__priv_manifestUpdateUrl:k,__priv_patchLastSegmentInSidx:x,url:P}=e;if(this.videoElement===null)throw new Error("the attached video element is disposed");let M=p==="directfile",O=new U,B=this.videoElement,D,F=!1,A=null;if(M){if(fe.directfile===null)throw this.stop(),this._priv_currentError=null,new Error("DirectFile feature not activated in your build.");if(_(P))throw new Error("No URL for a DirectFile content");if(m.info("API: Initializing DirectFile mode in the main thread"),A=this._priv_initializeMediaElementTracksStore(O.signal),O.isUsed())return;D=new fe.directfile.initDirectFile({autoPlay:t,keySystems:s,speed:this._priv_speed,startAt:f,url:P})}else{let W={lowLatencyMode:d,maxRetry:(q=c.manifest)==null?void 0:q.maxRetry,requestTimeout:(ie=c.manifest)==null?void 0:ie.timeout,connectionTimeout:(ne=c.manifest)==null?void 0:ne.connectionTimeout,minimumManifestUpdateInterval:u,initialManifest:a},Ce=Bl(),nt={throttleBitrate:{},limitResolution:{}};this._priv_throttleVideoBitrateWhenHidden&&(Ce?nt.throttleBitrate={video:ln(Ac(this._priv_pictureInPictureRef,O.signal),zt=>zt?1/0:0,O.signal)}:m.warn("API: Can't apply throttleVideoBitrateWhenHidden because browser can't be trusted for visibility.")),this._priv_videoResolutionLimit==="videoElement"?Ce?nt.limitResolution={video:wc(B,this._priv_pictureInPictureRef,O.signal)}:m.warn("API: Can't apply videoResolutionLimit because browser can't be trusted for video size."):this._priv_videoResolutionLimit==="screen"&&(nt.limitResolution={video:xc(O.signal)});let Ae={initialBitrates:this._priv_bitrateInfos.lastBitrates,lowLatencyMode:d,throttlers:nt},Vt=e.textTrackMode==="native"?{textTrackMode:"native"}:{textTrackMode:"html",textTrackElement:e.textTrackElement},un=Y({enableFastSwitching:o,onCodecSwitch:l},this._priv_bufferOptions),mt={lowLatencyMode:d,maxRetry:(le=c.segment)==null?void 0:le.maxRetry,requestTimeout:(be=c.segment)==null?void 0:be.timeout,connectionTimeout:(me=c.segment)==null?void 0:me.connectionTimeout},bt=fe.multithread!==null&&this._priv_worker!==null&&p==="dash"&&Vb.every(zt=>_(e[zt]))&&typeof e.representationFilter!="function";if(E==="main"||E==="auto"&&!bt){if(fe.mainThreadMediaSourceInit===null)throw new Error("Cannot load video, neither in a WebWorker nor with the `MEDIA_SOURCE_MAIN` feature");let zt=fe.transports[p];if(typeof zt!="function")throw this.stop(),this._priv_currentError=null,new Error(`transport "${p}" not supported`);let vp=typeof e.representationFilter=="string"?kc(e.representationFilter):e.representationFilter;m.info("API: Initializing MediaSource mode in the main thread");let Rp=zt({lowLatencyMode:d,checkMediaSegmentIntegrity:g,checkManifestIntegrity:b,manifestLoader:h,referenceDateTime:I,representationFilter:vp,segmentLoader:T,serverSyncInfos:R,__priv_manifestUpdateUrl:k,__priv_patchLastSegmentInSidx:x});D=new fe.mainThreadMediaSourceInit({adaptiveOptions:Ae,autoPlay:t,bufferOptions:un,cmcd:r,enableRepresentationAvoidance:v.enableRepresentationAvoidance,keySystems:s,lowLatencyMode:d,transport:Rp,manifestRequestSettings:W,segmentRequestOptions:mt,speed:this._priv_speed,startAt:f,textTrackOptions:Vt,url:P})}else{if(fe.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 zt={lowLatencyMode:d,checkMediaSegmentIntegrity:g,checkManifestIntegrity:b,referenceDateTime:I,serverSyncInfos:R,manifestLoader:void 0,segmentLoader:void 0,representationFilter:e.representationFilter,__priv_manifestUpdateUrl:k,__priv_patchLastSegmentInSidx:x};D=new fe.multithread.init({adaptiveOptions:Ae,autoPlay:t,bufferOptions:un,cmcd:r,enableRepresentationAvoidance:v.enableRepresentationAvoidance,keySystems:s,lowLatencyMode:d,transportOptions:zt,manifestRequestSettings:W,segmentRequestOptions:mt,speed:this._priv_speed,startAt:f,textTrackOptions:Vt,worker:this._priv_worker,url:P})}}let C={contentId:Kb(),originalUrl:P,currentContentCanceller:O,defaultAudioTrackSwitchingMode:i,initializer:D,isDirectFile:M,manifest:null,currentPeriod:null,activeAdaptations:null,activeRepresentations:null,tracksStore:null,mediaElementTracksStore:A,useWorker:F,segmentSinkMetricsCallback:null,fetchThumbnailDataCallback:null,thumbnailRequestsInfo:{pendingRequests:new WeakMap,lastResponse:null}};D.addEventListener("error",W=>{this._priv_onFatalError(W,C)}),D.addEventListener("warning",W=>{let Ce=Ee(W,{defaultCode:"NONE",defaultReason:"An unknown error happened."});m.warn("API: Sending warning:",Ce),this.trigger("warning",Ce)}),D.addEventListener("reloadingMediaSource",W=>{C.tracksStore!==null&&C.tracksStore.resetPeriodObjects(),this._priv_contentInfos!==null&&(this._priv_contentInfos.segmentSinkMetricsCallback=null),this._priv_lastAutoPlay=W.autoPlay}),D.addEventListener("inbandEvents",W=>this.trigger("inbandEvents",W)),D.addEventListener("streamEvent",W=>this.trigger("streamEvent",W)),D.addEventListener("streamEventSkip",W=>this.trigger("streamEventSkip",W)),D.addEventListener("activePeriodChanged",W=>this._priv_onActivePeriodChanged(C,W)),D.addEventListener("periodStreamReady",W=>this._priv_onPeriodStreamReady(C,W)),D.addEventListener("periodStreamCleared",W=>this._priv_onPeriodStreamCleared(C,W)),D.addEventListener("representationChange",W=>this._priv_onRepresentationChange(C,W)),D.addEventListener("adaptationChange",W=>this._priv_onAdaptationChange(C,W)),D.addEventListener("bitrateEstimateChange",W=>this._priv_onBitrateEstimateChange(W)),D.addEventListener("manifestReady",W=>this._priv_onManifestReady(C,W)),D.addEventListener("manifestUpdate",W=>this._priv_onManifestUpdate(C,W)),D.addEventListener("codecSupportUpdate",()=>this._priv_onCodecSupportUpdate(C)),D.addEventListener("decipherabilityUpdate",W=>this._priv_onDecipherabilityUpdate(C,W)),D.addEventListener("loaded",W=>{this._priv_contentInfos!==null&&(this._priv_contentInfos.segmentSinkMetricsCallback=W.getSegmentSinkMetrics,this._priv_contentInfos.fetchThumbnailDataCallback=W.getThumbnailData)}),D.prepare(),this.stop();let N=new po(B,{withMediaSource:!M,lowLatencyMode:d});O.signal.register(()=>{N.stop()});let K=_p(D,B,N,O.signal);O.signal.register(()=>{D.dispose()});let j=W=>{switch(W){case"STOPPED":case"RELOADING":case"LOADING":break;case"ENDED":this._priv_reloadingMetadata.reloadInPause=!0,this._priv_reloadingMetadata.reloadPosition=N.getReference().getValue().position.getPolled();break;default:{let Ce=N.getReference().getValue();this._priv_reloadingMetadata.reloadInPause=Ce.paused,this._priv_reloadingMetadata.reloadPosition=Ce.position.getWanted();break}}},$=null,z=W=>{$!==null&&($.cancel(),$=null),K.onUpdate((Ce,nt)=>{fr(Ce)&&(nt(),$!==null&&$.cancel(),$=new U,$.linkToSignal(O.signal),W!==!B.paused&&(B.paused?this.trigger("pause",null):this.trigger("play",null)),Tp(B,()=>this.trigger("play",null),()=>this.trigger("pause",null),O.signal))},{emitCurrentValue:!1,clearSignal:O.signal})};z(t),D.addEventListener("reloadingMediaSource",W=>{z(W.autoPlay)}),this._priv_currentError=null,this._priv_contentInfos=C;let H=null;K.onUpdate(W=>{j(W),this._priv_setPlayerState(W),!O.isUsed()&&(H!==null?fr(this.state)||(H.cancel(),H=null):fr(this.state)&&(H=new U,H.linkToSignal(O.signal),Sp(N,()=>this.trigger("seeking",null),()=>this.trigger("seeked",null),H.signal)))},{emitCurrentValue:!0,clearSignal:O.signal}),N.listen(W=>{j(this.state),this._priv_triggerPositionUpdate(C,W)},{clearSignal:O.signal}),O.signal.register(()=>{D.removeEventListener()}),this._priv_contentLock.onUpdate((W,Ce)=>{W||(Ce(),D.start(B,N))},{emitCurrentValue:!0,clearSignal:O.signal})}getError(){return this._priv_currentError}getVideoElement(){return this.videoElement}getPlayerState(){return this.state}isContentLoaded(){return!X(["LOADING","RELOADING","STOPPED"],this.state)}isBuffering(){return X(["BUFFERING","SEEKING","LOADING","RELOADING"],this.state)}isPaused(){return this.videoElement!==null?X(["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=uc(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=mo(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=mo(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=Yn(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 c;return(c=d.getAvailableAudioTracks(u,o))!=null?c:[]})}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 c;return(c=d.getAvailableVideoTracks(u,o))!=null?c:[]})}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 c=typeof e=="string"?e:e.trackId;r==null||r.setAudioTrackById(c);return}catch(c){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,(c,l)=>c.setAudioTrack({periodRef:l,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 c=typeof e=="string"?e:e.trackId;r==null||r.setVideoTrackById(c);return}catch(c){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,(c,l)=>c.setVideoTrack({periodRef:l,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:Tt(t):null}async __priv_getSegmentSinkMetrics(){var e,t;return(t=(e=this._priv_contentInfos)==null?void 0:e.segmentSinkMetricsCallback)==null?void 0:t.call(e)}__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_contentEventsMemory={};let e=()=>{this.videoElement!==null&&(m.debug("Unlocking `contentLock`. Next content can begin."),this._priv_contentLock.setValue(!1))};_(this.videoElement)?e():wo(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 hp({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(!(Q(i,c=>c[0].id===o.period.id&&c[1]===o.adaptation.type)!==void 0)){let c=e.tracksStore;if(c===null)return i;let l=!1,f=c.getPeriodObjectFromPeriod(o.period);if(f===void 0)return i;switch(o.adaptation.type){case"audio":l=((s=c.getChosenAudioTrack(f,!1))==null?void 0:s.id)===o.adaptation.id;break;case"video":l=((d=c.getChosenVideoTrack(f,!1))==null?void 0:d.id)===o.adaptation.id;break;case"text":l=((u=c.getChosenTextTrack(f))==null?void 0:u.id)===o.adaptation.id;break}l&&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,c,l,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 p=i.getPeriodObjectFromPeriod(t);if(p!==void 0){let g=i.getChosenAudioTrack(p,!0);this._priv_triggerEventIfNotStopped("audioTrackChange",g,r);let b=i.getChosenTextTrack(p);this._priv_triggerEventIfNotStopped("textTrackChange",b,r);let h=i.getChosenVideoTrack(p,!0);this._priv_triggerEventIfNotStopped("videoTrackChange",h,r)}}let o=(c=(u=this.__priv_getCurrentRepresentations())==null?void 0:u.audio)!=null?c:null;this._priv_triggerEventIfNotStopped("audioRepresentationChange",o,r);let a=(f=(l=this.__priv_getCurrentRepresentations())==null?void 0:l.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:He(r)}}_priv_onPeriodStreamCleared(e,t){var d;if(e.contentId!==((d=this._priv_contentInfos)==null?void 0:d.contentId))return;let{type:r,periodId: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])){let u=a[i];delete u[r],Object.keys(u).length===0&&delete a[i]}if(!_(s)&&!_(s[i])){let u=s[i];delete u[r],Object.keys(u).length===0&&delete s[i]}}_priv_onAdaptationChange(e,{type:t,adaptation:r,period:i}){var c;if(e.contentId!==((c=this._priv_contentInfos)==null?void 0:c.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 l=d.getPeriodObjectFromPeriod(i);if(l===void 0)return;switch(t){case"audio":{let f=d.getChosenAudioTrack(l,!0);this._priv_triggerEventIfNotStopped("audioTrackChange",f,u);break}case"text":{let f=d.getChosenTextTrack(l);this._priv_triggerEventIfNotStopped("textTrackChange",f,u);break}case"video":{let f=d.getChosenVideoTrack(l,!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?Tt(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 c=In(i);c!==void 0&&(a.liveGap=c-t.position.getPolled())}else if(r&&this.videoElement!==null){let u=mo(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(fe.directfile!==null,"Initializing `MediaElementTracksStore` without Directfile feature"),ee(this.videoElement!==null,"Initializing `MediaElementTracksStore` on a disposed RxPlayer");let t=new fe.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:He(e)}}_priv_onFatalError(e,t){let r=Ee(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 za=Kt;za.version="4.3.0";var Ep=za;var Ha=Ep;Wa();Ha.addFeatures([Ul,_u,Pu,Cu,vl,bl,Cl,Tl,rl,Ou,gl,Nu]);Un()?m.setLevel("DEBUG","full"):y.CURRENT_ENV===y.DEV&&m.setLevel(S.CURRENT_LEVEL,"standard");var use=Ha;J.RxPlayer=Ha;})();
17
+ `+r}function Fb(n){let e=gp(n);return Y(e,{rebuffering:null,event:"init",seeking:0,position:new tr(e.position,null),freezing:null,bufferGap:0,currentRange:null,fullyLoaded:!1})}async function Kl(n,e){let{time:t,container:r}=e;if(n===null||n.fetchThumbnailDataCallback===null||n.manifest===null)return Promise.reject(new ct("NO_CONTENT","Cannot get thumbnail: no content loaded"));let{thumbnailRequestsInfo:i,currentContentCanceller:o}=n,a=new U;a.linkToSignal(o.signal);let s,d=i.pendingRequests.get(r);d==null||d.cancel(),i.pendingRequests.set(r,a);let u=()=>{a.cancel(),i.pendingRequests.delete(r),setTimeout(()=>{s!==void 0&&URL.revokeObjectURL(s)},0)};try{let l=Kn(n.manifest,t);if(l===void 0)throw new ct("NO_THUMBNAIL","Wanted Period not found.");let f=l.thumbnailTracks,p=e.thumbnailTrackId!==void 0?Q(f,v=>v.id===e.thumbnailTrackId):f[0];if(p===void 0)throw e.thumbnailTrackId!==void 0?new ct("NO_THUMBNAIL","Given `thumbnailTrackId` not found"):new ct("NO_THUMBNAIL","Wanted Period has no thumbnail track.");let{lastResponse:g}=i,b;if(g!==null&&g.thumbnailTrackId===p.id&&g.periodId===l.id){let v=g.response.thumbnails;v.length>0&&t>=v[0].start&&t<v[v.length-1].end&&(b=g.response)}if(b===void 0&&(b=await n.fetchThumbnailDataCallback(l.id,p.id,t),i.lastResponse={response:b,periodId:l.id,thumbnailTrackId:p.id}),a.signal.cancellationError!==null)throw a.signal.cancellationError;let h=document.createElement("canvas"),I=h.getContext("2d");if(I===null)throw new ct("RENDERING","Cannot display thumbnail: cannot create canvas context");let T=pe(b.thumbnails,v=>v.start<=t&&v.end>t);if(T<0)throw new Error("Cannot display thumbnail: time not found in fetched data");let R=new Image,E=new Blob([b.data],{type:b.mimeType});return s=URL.createObjectURL(E),R.src=s,h.height=b.thumbnails[T].height,h.width=b.thumbnails[T].width,new Promise((v,k)=>{R.onload=()=>{try{I.drawImage(R,b.thumbnails[T].offsetX,b.thumbnails[T].offsetY,b.thumbnails[T].width,b.thumbnails[T].height,0,0,b.thumbnails[T].width,b.thumbnails[T].height),h.style.width="100%",h.style.height="100%",h.className="__rx-thumbnail__",c(),r.appendChild(h),v()}catch(x){k(new ct("RENDERING","Could not draw the image in a canvas:"+(x instanceof Error?x.toString():"Unknown Error")))}u()},R.onerror=()=>{e.keepPreviousThumbnailOnError!==!0&&c(),k(new ct("RENDERING","Could not load the corresponding image in the DOM")),u()}})}catch(l){if(e.keepPreviousThumbnailOnError!==!0&&c(),l!==null&&l===a.signal.cancellationError)throw new ct("ABORTED","Thumbnail rendering has been aborted");let f=Ee(l,{defaultCode:"NONE",defaultReason:"Unknown error"}),p;throw f.type==="NETWORK_ERROR"?p=new ct("LOADING",f.message):p=new ct("NOT_FOUND",f.message),u(),p}function c(){for(let l=r.children.length-1;l>=0;l--){let f=r.children[l];f.className==="__rx-thumbnail__"&&r.removeChild(f)}}}var ct=class n extends Error{constructor(e,t){super(Je(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="ThumbnailRenderingError",this.code=e}};var go=class extends ae{constructor(e){super(),this._canceller=new U,this._adaptationRef=e,this._updateToken=!1,this._lastEmitted=void 0,this.refresh=Z}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 U,this._lastEmitted=null,this._adaptationRef.setValue(null);return}let{adaptation:t,switchingMode:r,relativeResumingPosition:i}=e;this._canceller.cancel(),this._canceller=new U;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 G({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(l=>St(l)===!0),s="lazy";else{let{representationIds:l}=a;if(s=a.switchingMode,d=e.adaptation.representations.filter(p=>X(l,p.id)).filter(p=>St(p)===!0),d.length===0){r.trigger("noPlayableLockedRepresentation",null);return}}if(d.length<=0){r.trigger("noPlayableRepresentation",null);return}let u=t.getValue(),c=d.map(l=>l.id).slice().sort();if(c.length!==u.representationIds.length){t.setValue({representationIds:c,switchingMode:s});return}for(let l=0;l<c.length;l++)if(u.representationIds[l]!==c[l]){t.setValue({representationIds:c,switchingMode:s});return}}function o(){r.refresh=Z}}dispose(){this.removeEventListener(),this._canceller.cancel(),this._adaptationRef.finish()}};var ho=class extends ae{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:L.getCurrent().DEFAULT_AUDIO_TRACK_SWITCHING_MODE}getAvailablePeriods(){return this._storedPeriodInfo.reduce((e,t)=>(t.isPeriodAdvertised&&e.push(Kt(t.period)),e),[])}onManifestCodecSupportUpdate(){this._selectInitialTrackIfNeeded()}onManifestUpdate(e){var a,s,d,u,c,l;let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:t}=L.getCurrent(),{periods:r}=e;if(y.CURRENT_ENV===y.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 p=this._storedPeriodInfo[f].period,g=r[o];if(g===void 0)for(let b=this._storedPeriodInfo.length-1;b>=f;b--)this._storedPeriodInfo[b].inManifest=!1,Vl(this._storedPeriodInfo[b])&&this._removePeriodObject(b);else if(p===g){o++;let b=this._storedPeriodInfo[f].text.storedSettings;if(!_(b)&&!pt(g,"text").some(E=>E.id===b.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:Kt(g),trackType:"text",reason:"missing"}),this._isDisposed)return;let v=ft(this._storedPeriodInfo,E.period.id);v!==void 0&&v.isPeriodAdvertised&&v.text.storedSettings===null&&((a=v.text.dispatcher)==null||a.updateTrack(null))}let h=this._storedPeriodInfo[f].video.storedSettings;if(!_(h)){let T=pt(g,"video");if(!T.some(E=>E.id===h.adaptation.id)){m.warn("TS: Chosen video Adaptation not available anymore");let E=this._storedPeriodInfo[f],v;if(T.length===0)v=null;else{let x=T[0],P=Va(x,this._isTrickModeTrackEnabled),M=new G(null);v={adaptationBase:x,adaptation:P,switchingMode:t,lockedRepresentations:M}}if(E.video.storedSettings=v,this.trigger("trackUpdate",{period:Kt(g),trackType:"video",reason:"missing"}),this._isDisposed)return;let k=ft(this._storedPeriodInfo,E.period.id);k!==void 0&&k.isPeriodAdvertised&&k.video.storedSettings===v&&((s=k.video.dispatcher)==null||s.updateTrack(v))}}let I=this._storedPeriodInfo[f].audio.storedSettings;if(!_(I)){let T=pt(g,"audio");if(!T.some(E=>E.id===I.adaptation.id)){m.warn("TS: Chosen audio Adaptation not available anymore");let E=this._storedPeriodInfo[f],v=T.length===0?null:{adaptation:T[0],switchingMode:this._defaultAudioTrackSwitchingMode,lockedRepresentations:new G(null)};if(E.audio.storedSettings=v,this.trigger("trackUpdate",{period:Kt(g),trackType:"audio",reason:"missing"}),this._isDisposed)return;let k=ft(this._storedPeriodInfo,E.period.id);k!==void 0&&k.isPeriodAdvertised&&k.audio.storedSettings===v&&((d=k.audio.dispatcher)==null||d.updateTrack(v))}}}else if(p.start<=g.start)this._storedPeriodInfo[f].inManifest=!1,Vl(this._storedPeriodInfo[f])&&(this._removePeriodObject(f),f--);else{let b=zl(g,!0);this._storedPeriodInfo.splice(f,0,b),i.push(b),o++}}if(o<r.length){let f=r.slice(o).map(p=>zl(p,!0));this._storedPeriodInfo.push(...f),i.push(...f)}for(let f of this._storedPeriodInfo)(u=f.audio.dispatcher)==null||u.refresh(),(c=f.video.dispatcher)==null||c.refresh(),(l=f.text.dispatcher)==null||l.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){m.debug("TS: Adding Track Reference",e,t.id);let i=ft(this._storedPeriodInfo,t.id);if(i===void 0){i=zl(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)}i[e].dispatcher!==null&&(m.error(`TS: Subject already added for ${e} and Period ${t.start}`),i[e].dispatcher.dispose());let o=new go(r);if(i[e].dispatcher=o,o.addEventListener("noPlayableRepresentation",()=>{var l,f,p,g;let s=Q((l=t.adaptations[e])!=null?l:[],b=>b.supportStatus.hasSupportedCodec===!1||b.supportStatus.isDecipherable===!1?!1:b.representations.filter(I=>St(I)===!0).length>0);if(s===void 0){let b=new te("NO_PLAYABLE_REPRESENTATION",`No ${e} Representation can be played`,{tracks:void 0});this.trigger("error",b),this.dispose();return}let d=(f=ft(this._storedPeriodInfo,t.id))==null?void 0:f[e];if(_(d))return;let u=e==="audio"?this._defaultAudioTrackSwitchingMode:"reload",c={adaptation:s,switchingMode:u,lockedRepresentations:new G(null)};d.storedSettings=c,this.trigger("trackUpdate",{period:Kt(t),trackType:e,reason:"no-playable-representation"}),!this._isDisposed&&(d=(p=ft(this._storedPeriodInfo,t.id))==null?void 0:p[e],!(_(d)||d.storedSettings!==c)&&((g=d.dispatcher)==null||g.updateTrack(c)))}),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){m.debug("TS: Removing Track Reference",e,t);let r;for(let a=0;a<this._storedPeriodInfo.length;a++)if(this._storedPeriodInfo[a].period.id===t){r=a;break}if(r===void 0){m.warn(`TS: ${e} not found for period`,t);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}`);return}o.dispatcher.dispose(),o.dispatcher=null,Vl(i)&&this._removePeriodObject(r)}getPeriodObjectFromPeriod(e){let t=ft(this._storedPeriodInfo,e.id);return t===void 0&&e!==void 0?this._cachedPeriodInfo.get(e):t}getPeriodObjectFromId(e){return ft(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;m.debug("TS: Resetting Period Objects");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 p,g;if(!t.isPeriodAdvertised)throw new Error("Wanted Period not yet advertised.");let s=t.period,d=Q((p=s.adaptations[e])!=null?p:[],({id:b,supportStatus:h})=>h.hasSupportedCodec!==!1&&h.isDecipherable!==!1&&b===r);if(d===void 0)throw new Error(`Wanted ${e} track not found.`);let u=t[e],c;if(o===null)c=new G(null);else{let b=this._getRepresentationsToLock(d,o),h=e==="audio"?this._defaultAudioTrackSwitchingMode:"direct";c=new G({representationIds:b,switchingMode:h})}let l={adaptation:d,switchingMode:i,lockedRepresentations:c,relativeResumingPosition:a};if(u.storedSettings=l,this.trigger("trackUpdate",{period:Kt(s),trackType:e,reason:"manual"}),this._isDisposed)return;let f=ft(this._storedPeriodInfo,s.id);f!==void 0&&f[e].storedSettings===l&&((g=f[e].dispatcher)==null||g.updateTrack(l))}setVideoTrack(e){var b,h;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=Q((b=s.adaptations.video)!=null?b:[],({id:I,supportStatus:T})=>T.isDecipherable!==!1&&T.hasSupportedCodec!==!1&&I===r);if(d===void 0)throw new Error("Wanted video track not found.");let{DEFAULT_VIDEO_TRACK_SWITCHING_MODE:u}=L.getCurrent(),c=t.video,l=Va(d,this._isTrickModeTrackEnabled),f;if(o===null)f=new G(null);else{let I=this._getRepresentationsToLock(d,o),T=u;f=new G({representationIds:I,switchingMode:T})}let p={adaptationBase:d,switchingMode:i!=null?i:u,adaptation:l,relativeResumingPosition:a,lockedRepresentations:f};if(c.storedSettings=p,this.trigger("trackUpdate",{period:Kt(s),trackType:"video",reason:"manual"}),this._isDisposed)return;let g=ft(this._storedPeriodInfo,s.id);g!==void 0&&g.video.storedSettings===p&&((h=g.video.dispatcher)==null||h.updateTrack(p))}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:Kt(e.period),trackType:t,reason:"manual"}),this._isDisposed))return;let i=ft(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:Mo(e.audio.storedSettings.adaptation,t)}getChosenTextTrack(e){return _(e.text.storedSettings)?null:Ao(e.text.storedSettings.adaptation)}getChosenVideoTrack(e,t){return _(e.video.storedSettings)?null:xo(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 Y(Mo(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 Y(Ao(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=xo(a,t),u=d.trickModeTracks!==void 0?d.trickModeTracks.map(l=>{let f=i===null?!1:i===l.id;return Y(l,{active:f})}):[],c=Y(d,{active:s});return u!==void 0&&(c.trickModeTracks=u),c})}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}=L.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}=L.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=Va(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:Kt(o),trackType:"video",reason:e}),this._isDisposed)return;let d=ft(this._storedPeriodInfo,o.id);d!==void 0&&d.isPeriodAdvertised&&d.video.storedSettings===s&&((r=d.video.dispatcher)==null||r.updateTrack(s))}}}_removePeriodObject(e){y.CURRENT_ENV===y.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=Q(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}=L.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 c=[...(i=u.adaptations.audio)!=null?i:[],...(o=u.adaptations.video)!=null?o:[]],l=c.every(I=>I.supportStatus.hasCodecWithUndefinedSupport);if(c.length>0&&l)continue;let f=pt(u,"audio")[0];d.audio.storedSettings=f===void 0?null:{adaptation:f,switchingMode:this._defaultAudioTrackSwitchingMode,lockedRepresentations:new G(null)};let p=pt(u,"video")[0],g=Va(p,this._isTrickModeTrackEnabled);d.video.storedSettings=g===void 0?null:{adaptation:g,adaptationBase:p,switchingMode:e,lockedRepresentations:new G(null)};let b=null,h=((a=u.adaptations.text)!=null?a:[]).filter(I=>I.isForcedSubtitles===!0);if(h.length>0){if(f!=null){let I=Q(h,T=>T.normalizedLanguage===f.normalizedLanguage);I!==void 0&&(b=I)}b===null&&(b=(s=Q(h,I=>I.normalizedLanguage===void 0))!=null?s:null)}d.text.storedSettings=b===null?null:{adaptation:b,switchingMode:"direct",lockedRepresentations:new G(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 c of u){let l=d[c];if(l.dispatcher!==null&&l.storedSettings!==void 0&&!l.dispatcher.hasSetTrack()&&(l.dispatcher.updateTrack(l.storedSettings),this._isDisposed))return}}}_shouldAdvertisePeriod(e){return!e.isPeriodAdvertised&&e.text.dispatcher!==null&&e.video.dispatcher!==null&&e.audio.dispatcher!==null}};function ft(n,e){for(let t=0;t<n.length;t++){let r=n[t];if(r.period.id===e)return r}}function Vl(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 Va(n,e){var t;return e&&((t=n.trickModeTracks)==null?void 0:t[0])!==void 0?n.trickModeTracks[0]:n}function zl(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 Kt(n){return{start:n.start,end:n.end,id:n.id}}var hp=ho;function yp(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:c,DEFAULT_MAX_VIDEO_BUFFER_SIZE:l,DEFAULT_THROTTLE_VIDEO_BITRATE_WHEN_HIDDEN:f,DEFAULT_WANTED_BUFFER_AHEAD:p}=L.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=c;else if(t=Number(n.maxBufferBehind),isNaN(t))throw new Error("Invalid maxBufferBehind parameter. Should be a number.");if(_(n.wantedBufferAhead))r=p;else if(r=Number(n.wantedBufferAhead),isNaN(r))throw new Error("Invalid wantedBufferAhead parameter. Should be a number.");if(_(n.maxVideoBufferSize))i=l;else if(i=Number(n.maxVideoBufferSize),isNaN(i))throw new Error("Invalid maxVideoBufferSize parameter. Should be a number.");let g=_(n.videoResolutionLimit)?d:n.videoResolutionLimit,b=_(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:g,videoElement:o,wantedBufferAhead:r,maxVideoBufferSize:i,throttleVideoBitrateWhenHidden:b,baseBandwidth:a}}function Ip(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 bp(n){var E,v,k,x;let e,t,r,i,o,a,s,{DEFAULT_AUTO_PLAY:d,DEFAULT_CODEC_SWITCHING_BEHAVIOR:u,DEFAULT_ENABLE_FAST_SWITCHING:c,DEFAULT_TEXT_TRACK_MODE:l}=L.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 P of r)if(typeof P.type!="string"||typeof P.getLicense!="function")throw new Error("Invalid key system given: Missing type string or getLicense callback")}let p=n.lowLatencyMode===void 0?!1:!!n.lowLatencyMode,g=n.initialManifest,b=(E=n.minimumManifestUpdateInterval)!=null?E:0,h=(v=n.defaultAudioTrackSwitchingMode)!=null?v:void 0;h!==void 0&&!X(["seamless","direct","reload"],h)&&(m.warn("The `defaultAudioTrackSwitchingMode` loadVideo option must match one of the following strategy name:\n- `seamless`\n- `direct`\n- `reload`"),h=void 0);let I=_(n.onCodecSwitch)?u:n.onCodecSwitch;if(X(["continue","reload"],I)||(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"),I=u),_(n.textTrackMode))i=l;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(!X(["auto","multithread","main"],n.mode))throw new Error("Invalid `mode` option.");o=n.mode}let T=_(n.enableFastSwitching)?c:n.enableFastSwitching;if(!_(n.startAt))if("wallClockTime"in n.startAt&&n.startAt.wallClockTime instanceof Date){let P=n.startAt.wallClockTime.getTime()/1e3;s=Y({},n.startAt,{wallClockTime:P})}else s=n.startAt;let R=(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:h,enableFastSwitching:T,initialManifest:g,keySystems:r,lowLatencyMode:p,manifestLoader:n.manifestLoader,minimumManifestUpdateInterval:b,requestConfig:R,onCodecSwitch:I,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,experimentalOptions:{enableRepresentationAvoidance:((x=n.experimentalOptions)==null?void 0:x.enableRepresentationAvoidance)===!0}}}function Sp(n,e,t,r){if(r.isCancelled())return;let i=n.getReference().getValue().seeking===2;i&&(e(),r.isCancelled())||n.listen(o=>{o.event==="seeking"?(i=!0,e()):i&&o.event==="seeked"&&(i=!1,t())},{includeLastObservation:!0,clearSignal:r})}function Tp(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 _p(n,e,t,r){let i=new G("LOADING",r);n.addEventListener("loaded",()=>{if(i.getValue()==="LOADING"){if(i.setValue("LOADED"),!r.isCancelled()){let s=Hl(e,null);s!=="PAUSED"&&i.setValue(s)}}else i.getValue()==="RELOADING"?i.setValue(Hl(e,null)):a(null)},r),n.addEventListener("reloadingMediaSource",()=>{fr(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=>{X(["seeking","ended","play","pause"],s.event)&&a(o)},{clearSignal:r}),i;function a(s){if(!fr(i.getValue()))return;let d=Hl(e,s);i.getValue()==="LOADED"&&d==="PAUSED"||i.setValueIfChanged(d)}}function Hl(n,e){let{FORCED_ENDED_THRESHOLD:t}=L.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 fr(n){return n!=="LOADING"&&n!=="RELOADING"&&n!=="STOPPED"}var Kb=et(),Vb=["manifestLoader","segmentLoader"],Vt=class Vt extends ae{static get ErrorTypes(){return Ze}static get ErrorCodes(){return ls}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){ca(e)}static _priv_registerVideoElement(e){Vt._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.`),Vt._priv_currentlyUsedVideoElements.add(e)}static _priv_deregisterVideoElement(e){Vt._priv_currentlyUsedVideoElements.has(e)&&Vt._priv_currentlyUsedVideoElements.delete(e)}constructor(e={}){super();let{baseBandwidth:t,videoResolutionLimit:r,maxBufferAhead:i,maxBufferBehind:o,throttleVideoBitrateWhenHidden:a,videoElement:s,wantedBufferAhead:d,maxVideoBufferSize:u}=yp(e);s.preload="auto",this.version="4.3.1-dev.2025040700",this.log=m,this.state="STOPPED",this.videoElement=s,Vt._priv_registerVideoElement(this.videoElement);let c=new U;this._destroyCanceller=c,this._priv_pictureInPictureRef=Mc(s,c.signal),this._priv_speed=new G(s.playbackRate,this._destroyCanceller.signal),this._priv_preferTrickModeTracks=!1,this._priv_contentLock=new G(!1,this._destroyCanceller.signal),this._priv_bufferOptions={wantedBufferAhead:new G(d,this._destroyCanceller.signal),maxBufferAhead:new G(i,this._destroyCanceller.signal),maxBufferBehind:new G(o,this._destroyCanceller.signal),maxVideoBufferSize:new G(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;let l=()=>{this.trigger("volumeChange",{volume:s.volume,muted:s.muted})};s.addEventListener("volumechange",l),c.signal.register(()=>{s.removeEventListener("volumechange",l)})}attachWorker(e){return new Promise((t,r)=>{var a;if(!Fl())return m.warn("API: Cannot rely on a WebWorker: Worker API unavailable"),r(new Nn("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 Nn("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 Nn("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:Un(),date:Date.now(),timestamp:V(),hasVideo:((a=this.videoElement)==null?void 0:a.nodeName.toLowerCase())==="video",hasMseInWorker:cm}}),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:Un()}}))},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}))};L.updated&&o(L.getCurrent()),L.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&&(Vt._priv_deregisterVideoElement(this.videoElement),Vn(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=bp(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 c,l,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.");Ip(e);let a;if(((c=e==null?void 0:e.reloadAt)==null?void 0:c.position)!==void 0)a={position:e.reloadAt.position};else if(((l=e==null?void 0:e.reloadAt)==null?void 0:l.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=de(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(fe.createDebugElement===null)throw new Error("Feature `DEBUG_ELEMENT` not added to the RxPlayer");let t=new U;return fe.createDebugElement(e,this,t.signal),{dispose(){t.cancel()}}}getAvailableThumbnailTracks({time:e,periodId:t}={}){if(this._priv_contentInfos===null||this._priv_contentInfos.manifest===null)return[];let{manifest:r}=this._priv_contentInfos,i;if(e!==void 0){if(i=Kn(this._priv_contentInfos.manifest,e),i===void 0||i.thumbnailTracks.length===0)return[]}else if(t!==void 0){if(i=Q(r.periods,o=>o.id===t),i===void 0)return m.error("API: getAvailableThumbnailTracks: periodId not found"),[]}else{let{currentPeriod:o}=this._priv_contentInfos;if(o===null)return[];i=o}return i.thumbnailTracks.map(o=>({id:o.id,width:Math.floor(o.width/o.horizontalTiles),height:Math.floor(o.height/o.verticalTiles),mimeType:o.mimeType}))}async renderThumbnail(e){if(_(e.time))throw new Error("You have to provide a `time` property to `renderThumbnail`, indicating the wanted thumbnail time in seconds.");if(_(e.container))throw new Error("You have to provide a `container` property to `renderThumbnail`, specifying the HTML Element in which the thumbnail should be inserted.");return Kl(this._priv_contentInfos,e)}_priv_initializeContentPlayback(e){var q,ie,ne,le,be,me;let{autoPlay:t,cmcd:r,defaultAudioTrackSwitchingMode:i,enableFastSwitching:o,initialManifest:a,keySystems:s,lowLatencyMode:d,minimumManifestUpdateInterval:u,requestConfig:c,onCodecSwitch:l,startAt:f,transport:p,checkMediaSegmentIntegrity:g,checkManifestIntegrity:b,manifestLoader:h,referenceDateTime:I,segmentLoader:T,serverSyncInfos:R,mode:E,experimentalOptions:v,__priv_manifestUpdateUrl:k,__priv_patchLastSegmentInSidx:x,url:P}=e;if(this.videoElement===null)throw new Error("the attached video element is disposed");let M=p==="directfile",O=new U,B=this.videoElement,D,F=!1,A=null;if(M){if(fe.directfile===null)throw this.stop(),this._priv_currentError=null,new Error("DirectFile feature not activated in your build.");if(_(P))throw new Error("No URL for a DirectFile content");if(m.info("API: Initializing DirectFile mode in the main thread"),A=this._priv_initializeMediaElementTracksStore(O.signal),O.isUsed())return;D=new fe.directfile.initDirectFile({autoPlay:t,keySystems:s,speed:this._priv_speed,startAt:f,url:P})}else{let W={lowLatencyMode:d,maxRetry:(q=c.manifest)==null?void 0:q.maxRetry,requestTimeout:(ie=c.manifest)==null?void 0:ie.timeout,connectionTimeout:(ne=c.manifest)==null?void 0:ne.connectionTimeout,minimumManifestUpdateInterval:u,initialManifest:a},Ce=Bl(),nt={throttleBitrate:{},limitResolution:{}};this._priv_throttleVideoBitrateWhenHidden&&(Ce?nt.throttleBitrate={video:cn(Ac(this._priv_pictureInPictureRef,O.signal),Ht=>Ht?1/0:0,O.signal)}:m.warn("API: Can't apply throttleVideoBitrateWhenHidden because browser can't be trusted for visibility.")),this._priv_videoResolutionLimit==="videoElement"?Ce?nt.limitResolution={video:wc(B,this._priv_pictureInPictureRef,O.signal)}:m.warn("API: Can't apply videoResolutionLimit because browser can't be trusted for video size."):this._priv_videoResolutionLimit==="screen"&&(nt.limitResolution={video:xc(O.signal)});let Ae={initialBitrates:this._priv_bitrateInfos.lastBitrates,lowLatencyMode:d,throttlers:nt},zt=e.textTrackMode==="native"?{textTrackMode:"native"}:{textTrackMode:"html",textTrackElement:e.textTrackElement},ln=Y({enableFastSwitching:o,onCodecSwitch:l},this._priv_bufferOptions),mt={lowLatencyMode:d,maxRetry:(le=c.segment)==null?void 0:le.maxRetry,requestTimeout:(be=c.segment)==null?void 0:be.timeout,connectionTimeout:(me=c.segment)==null?void 0:me.connectionTimeout},bt=fe.multithread!==null&&this._priv_worker!==null&&p==="dash"&&Vb.every(Ht=>_(e[Ht]))&&typeof e.representationFilter!="function";if(E==="main"||E==="auto"&&!bt){if(fe.mainThreadMediaSourceInit===null)throw new Error("Cannot load video, neither in a WebWorker nor with the `MEDIA_SOURCE_MAIN` feature");let Ht=fe.transports[p];if(typeof Ht!="function")throw this.stop(),this._priv_currentError=null,new Error(`transport "${p}" not supported`);let vp=typeof e.representationFilter=="string"?kc(e.representationFilter):e.representationFilter;m.info("API: Initializing MediaSource mode in the main thread");let Rp=Ht({lowLatencyMode:d,checkMediaSegmentIntegrity:g,checkManifestIntegrity:b,manifestLoader:h,referenceDateTime:I,representationFilter:vp,segmentLoader:T,serverSyncInfos:R,__priv_manifestUpdateUrl:k,__priv_patchLastSegmentInSidx:x});D=new fe.mainThreadMediaSourceInit({adaptiveOptions:Ae,autoPlay:t,bufferOptions:ln,cmcd:r,enableRepresentationAvoidance:v.enableRepresentationAvoidance,keySystems:s,lowLatencyMode:d,transport:Rp,manifestRequestSettings:W,segmentRequestOptions:mt,speed:this._priv_speed,startAt:f,textTrackOptions:zt,url:P})}else{if(fe.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 Ht={lowLatencyMode:d,checkMediaSegmentIntegrity:g,checkManifestIntegrity:b,referenceDateTime:I,serverSyncInfos:R,manifestLoader:void 0,segmentLoader:void 0,representationFilter:e.representationFilter,__priv_manifestUpdateUrl:k,__priv_patchLastSegmentInSidx:x};D=new fe.multithread.init({adaptiveOptions:Ae,autoPlay:t,bufferOptions:ln,cmcd:r,enableRepresentationAvoidance:v.enableRepresentationAvoidance,keySystems:s,lowLatencyMode:d,transportOptions:Ht,manifestRequestSettings:W,segmentRequestOptions:mt,speed:this._priv_speed,startAt:f,textTrackOptions:zt,worker:this._priv_worker,url:P})}}let C={contentId:Kb(),originalUrl:P,currentContentCanceller:O,defaultAudioTrackSwitchingMode:i,initializer:D,isDirectFile:M,manifest:null,currentPeriod:null,activeAdaptations:null,activeRepresentations:null,tracksStore:null,mediaElementTracksStore:A,useWorker:F,segmentSinkMetricsCallback:null,fetchThumbnailDataCallback:null,thumbnailRequestsInfo:{pendingRequests:new WeakMap,lastResponse:null}};D.addEventListener("error",W=>{this._priv_onFatalError(W,C)}),D.addEventListener("warning",W=>{let Ce=Ee(W,{defaultCode:"NONE",defaultReason:"An unknown error happened."});m.warn("API: Sending warning:",Ce),this.trigger("warning",Ce)}),D.addEventListener("reloadingMediaSource",W=>{C.tracksStore!==null&&C.tracksStore.resetPeriodObjects(),this._priv_contentInfos!==null&&(this._priv_contentInfos.segmentSinkMetricsCallback=null),this._priv_lastAutoPlay=W.autoPlay}),D.addEventListener("inbandEvents",W=>this.trigger("inbandEvents",W)),D.addEventListener("streamEvent",W=>this.trigger("streamEvent",W)),D.addEventListener("streamEventSkip",W=>this.trigger("streamEventSkip",W)),D.addEventListener("activePeriodChanged",W=>this._priv_onActivePeriodChanged(C,W)),D.addEventListener("periodStreamReady",W=>this._priv_onPeriodStreamReady(C,W)),D.addEventListener("periodStreamCleared",W=>this._priv_onPeriodStreamCleared(C,W)),D.addEventListener("representationChange",W=>this._priv_onRepresentationChange(C,W)),D.addEventListener("adaptationChange",W=>this._priv_onAdaptationChange(C,W)),D.addEventListener("bitrateEstimateChange",W=>this._priv_onBitrateEstimateChange(W)),D.addEventListener("manifestReady",W=>this._priv_onManifestReady(C,W)),D.addEventListener("manifestUpdate",W=>this._priv_onManifestUpdate(C,W)),D.addEventListener("codecSupportUpdate",()=>this._priv_onCodecSupportUpdate(C)),D.addEventListener("decipherabilityUpdate",W=>this._priv_onDecipherabilityUpdate(C,W)),D.addEventListener("loaded",W=>{this._priv_contentInfos!==null&&(this._priv_contentInfos.segmentSinkMetricsCallback=W.getSegmentSinkMetrics,this._priv_contentInfos.fetchThumbnailDataCallback=W.getThumbnailData)}),D.prepare(),this.stop();let N=new po(B,{withMediaSource:!M,lowLatencyMode:d});O.signal.register(()=>{N.stop()});let K=_p(D,B,N,O.signal);O.signal.register(()=>{D.dispose()});let j=W=>{switch(W){case"STOPPED":case"RELOADING":case"LOADING":break;case"ENDED":this._priv_reloadingMetadata.reloadInPause=!0,this._priv_reloadingMetadata.reloadPosition=N.getReference().getValue().position.getPolled();break;default:{let Ce=N.getReference().getValue();this._priv_reloadingMetadata.reloadInPause=Ce.paused,this._priv_reloadingMetadata.reloadPosition=Ce.position.getWanted();break}}},$=null,z=W=>{$!==null&&($.cancel(),$=null),K.onUpdate((Ce,nt)=>{fr(Ce)&&(nt(),$!==null&&$.cancel(),$=new U,$.linkToSignal(O.signal),W!==!B.paused&&(B.paused?this.trigger("pause",null):this.trigger("play",null)),Tp(B,()=>this.trigger("play",null),()=>this.trigger("pause",null),O.signal))},{emitCurrentValue:!1,clearSignal:O.signal})};z(t),D.addEventListener("reloadingMediaSource",W=>{z(W.autoPlay)}),this._priv_currentError=null,this._priv_contentInfos=C;let H=null;K.onUpdate(W=>{j(W),this._priv_setPlayerState(W),!O.isUsed()&&(H!==null?fr(this.state)||(H.cancel(),H=null):fr(this.state)&&(H=new U,H.linkToSignal(O.signal),Sp(N,()=>this.trigger("seeking",null),()=>this.trigger("seeked",null),H.signal)))},{emitCurrentValue:!0,clearSignal:O.signal}),N.listen(W=>{j(this.state),this._priv_triggerPositionUpdate(C,W)},{clearSignal:O.signal}),O.signal.register(()=>{D.removeEventListener()}),this._priv_contentLock.onUpdate((W,Ce)=>{W||(Ce(),D.start(B,N))},{emitCurrentValue:!0,clearSignal:O.signal})}getError(){return this._priv_currentError}getVideoElement(){return this.videoElement}getPlayerState(){return this.state}isContentLoaded(){return!X(["LOADING","RELOADING","STOPPED"],this.state)}isBuffering(){return X(["BUFFERING","SEEKING","LOADING","RELOADING"],this.state)}isPaused(){return this.videoElement!==null?X(["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=uc(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=mo(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=mo(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=Yn(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 c;return(c=d.getAvailableAudioTracks(u,o))!=null?c:[]})}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 c;return(c=d.getAvailableVideoTracks(u,o))!=null?c:[]})}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 c=typeof e=="string"?e:e.trackId;r==null||r.setAudioTrackById(c);return}catch(c){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,(c,l)=>c.setAudioTrack({periodRef:l,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 c=typeof e=="string"?e:e.trackId;r==null||r.setVideoTrackById(c);return}catch(c){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,(c,l)=>c.setVideoTrack({periodRef:l,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:Tt(t):null}async __priv_getSegmentSinkMetrics(){var e,t;return(t=(e=this._priv_contentInfos)==null?void 0:e.segmentSinkMetricsCallback)==null?void 0:t.call(e)}__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_contentEventsMemory={};let e=()=>{this.videoElement!==null&&(m.debug("Unlocking `contentLock`. Next content can begin."),this._priv_contentLock.setValue(!1))};_(this.videoElement)?e():wo(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 hp({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(!(Q(i,c=>c[0].id===o.period.id&&c[1]===o.adaptation.type)!==void 0)){let c=e.tracksStore;if(c===null)return i;let l=!1,f=c.getPeriodObjectFromPeriod(o.period);if(f===void 0)return i;switch(o.adaptation.type){case"audio":l=((s=c.getChosenAudioTrack(f,!1))==null?void 0:s.id)===o.adaptation.id;break;case"video":l=((d=c.getChosenVideoTrack(f,!1))==null?void 0:d.id)===o.adaptation.id;break;case"text":l=((u=c.getChosenTextTrack(f))==null?void 0:u.id)===o.adaptation.id;break}l&&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,c,l,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 p=i.getPeriodObjectFromPeriod(t);if(p!==void 0){let g=i.getChosenAudioTrack(p,!0);this._priv_triggerEventIfNotStopped("audioTrackChange",g,r);let b=i.getChosenTextTrack(p);this._priv_triggerEventIfNotStopped("textTrackChange",b,r);let h=i.getChosenVideoTrack(p,!0);this._priv_triggerEventIfNotStopped("videoTrackChange",h,r)}}let o=(c=(u=this.__priv_getCurrentRepresentations())==null?void 0:u.audio)!=null?c:null;this._priv_triggerEventIfNotStopped("audioRepresentationChange",o,r);let a=(f=(l=this.__priv_getCurrentRepresentations())==null?void 0:l.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:He(r)}}_priv_onPeriodStreamCleared(e,t){var d;if(e.contentId!==((d=this._priv_contentInfos)==null?void 0:d.contentId))return;let{type:r,periodId: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])){let u=a[i];delete u[r],Object.keys(u).length===0&&delete a[i]}if(!_(s)&&!_(s[i])){let u=s[i];delete u[r],Object.keys(u).length===0&&delete s[i]}}_priv_onAdaptationChange(e,{type:t,adaptation:r,period:i}){var c;if(e.contentId!==((c=this._priv_contentInfos)==null?void 0:c.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 l=d.getPeriodObjectFromPeriod(i);if(l===void 0)return;switch(t){case"audio":{let f=d.getChosenAudioTrack(l,!0);this._priv_triggerEventIfNotStopped("audioTrackChange",f,u);break}case"text":{let f=d.getChosenTextTrack(l);this._priv_triggerEventIfNotStopped("textTrackChange",f,u);break}case"video":{let f=d.getChosenVideoTrack(l,!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?Tt(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 c=In(i);c!==void 0&&(a.liveGap=c-t.position.getPolled())}else if(r&&this.videoElement!==null){let u=mo(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(fe.directfile!==null,"Initializing `MediaElementTracksStore` without Directfile feature"),ee(this.videoElement!==null,"Initializing `MediaElementTracksStore` on a disposed RxPlayer");let t=new fe.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:He(e)}}_priv_onFatalError(e,t){let r=Ee(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)}};Vt._priv_currentlyUsedVideoElements=new WeakSet;var za=Vt;za.version="4.3.1-dev.2025040700";var Ep=za;var Ha=Ep;Wa();Ha.addFeatures([Ul,_u,Pu,Cu,vl,bl,Cl,Tl,rl,Ou,gl,Nu]);Un()?m.setLevel("DEBUG","full"):y.CURRENT_ENV===y.DEV&&m.setLevel(S.CURRENT_LEVEL,"standard");var use=Ha;J.RxPlayer=Ha;})();