rx-player 4.5.0-dev.2026060401 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -14
- package/VERSION +1 -1
- package/dist/commonjs/__GENERATED_CODE/embedded_dash_wasm.d.ts.map +1 -1
- package/dist/commonjs/__GENERATED_CODE/embedded_dash_wasm.js +1 -1
- package/dist/commonjs/__GENERATED_CODE/embedded_worker.d.ts.map +1 -1
- package/dist/commonjs/__GENERATED_CODE/embedded_worker.js +1 -1
- package/dist/commonjs/core/fetchers/utils/schedule_request.d.ts.map +1 -1
- package/dist/commonjs/core/fetchers/utils/schedule_request.js +5 -2
- package/dist/commonjs/main_thread/api/public_api.js +2 -2
- package/dist/commonjs/main_thread/core_interface/monothread.d.ts.map +1 -1
- package/dist/commonjs/main_thread/core_interface/monothread.js +3 -2
- package/dist/commonjs/main_thread/render_thumbnail.d.ts.map +1 -1
- package/dist/commonjs/main_thread/render_thumbnail.js +7 -4
- package/dist/es2017/__GENERATED_CODE/embedded_dash_wasm.d.ts.map +1 -1
- package/dist/es2017/__GENERATED_CODE/embedded_dash_wasm.js +1 -1
- package/dist/es2017/__GENERATED_CODE/embedded_worker.d.ts.map +1 -1
- package/dist/es2017/__GENERATED_CODE/embedded_worker.js +1 -1
- package/dist/es2017/core/fetchers/utils/schedule_request.d.ts.map +1 -1
- package/dist/es2017/core/fetchers/utils/schedule_request.js +5 -2
- package/dist/es2017/main_thread/api/public_api.js +2 -2
- package/dist/es2017/main_thread/core_interface/monothread.d.ts.map +1 -1
- package/dist/es2017/main_thread/core_interface/monothread.js +3 -2
- package/dist/es2017/main_thread/render_thumbnail.d.ts.map +1 -1
- package/dist/es2017/main_thread/render_thumbnail.js +7 -4
- package/dist/mpd-parser.wasm +0 -0
- package/dist/worker.js +1 -1
- package/package.json +2 -2
- package/src/__GENERATED_CODE/embedded_dash_wasm.ts +1 -1
- package/src/__GENERATED_CODE/embedded_worker.ts +1 -1
- package/src/core/fetchers/utils/schedule_request.ts +4 -2
- package/src/main_thread/__tests__/render_thumbnail.test.ts +193 -0
- package/src/main_thread/api/public_api.ts +2 -2
- package/src/main_thread/core_interface/monothread.ts +3 -2
- package/src/main_thread/render_thumbnail.ts +7 -4
- package/src/parsers/manifest/dash/wasm-parser/rs/lib.rs +1 -0
package/dist/worker.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";(()=>{var kd=Object.defineProperty,Md=Object.defineProperties;var Od=Object.getOwnPropertyDescriptors;var io=Object.getOwnPropertySymbols;var wd=Object.prototype.hasOwnProperty,Dd=Object.prototype.propertyIsEnumerable;var ao=(n,e,t)=>e in n?kd(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,J=(n,e)=>{for(var t in e||(e={}))wd.call(e,t)&&ao(n,t,e[t]);if(io)for(var t of io(e))Dd.call(e,t)&&ao(n,t,e[t]);return n},de=(n,e)=>Md(n,Od(e));var I={PRODUCTION:0,DEV:1,CURRENT_ENV:0};var oo={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_AUDIO_TRACKS_NOT_PLAYABLE_BEHAVIOR:"error",DEFAULT_VIDEO_TRACKS_NOT_PLAYABLE_BEHAVIOR:"error",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,PREVENT_PSSH_PATCHING:!1,FORCE_CANNOT_RELY_ON_REQUEST_MEDIA_KEY_SYSTEM_ACCESS:!1,FORCE_CANNOT_REUSE_MEDIA_KEYS:!1,FORCE_HAS_ISSUES_WITH_HIGH_MEDIA_SOURCE_DURATION:!1,FORCE_IS_SEEKING_APPROXIMATE:!1,FORCE_MEDIA_ELEMENT_FAIL_ON_UNDECIPHERABLE_DATA:!1,FORCE_SHOULD_AWAIT_SET_MEDIA_KEYS:!1,FORCE_SHOULD_FAVOUR_CUSTOM_SAFARI_EME:!1,FORCE_SHOULD_RELOAD_MEDIA_SOURCE_ON_DECIPHERABILITY_UPDATE:!1,FORCE_SHOULD_RENEW_MEDIA_KEY_SYSTEM_ACCESS:!1,FORCE_SHOULD_UNSET_MEDIA_KEYS:!1,FORCE_SHOULD_VALIDATE_METADATA:!1,FORCE_DONT_WAIT_FOR_DATA_BEFORE_LOADED:!1,FORCE_WAIT_FOR_HAVE_ENOUGH_DATA:!1,FORCE_INITIAL_SEEK_TO_ZERO:!1},so=oo;function Nd(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 H=typeof Object.assign=="function"?Object.assign:Nd;function ai(n){return n!=null&&!Array.isArray(n)&&typeof n=="object"}function Jt(n,...e){if(e.length===0)return n;let t=e.shift();if(ai(n)&&ai(t))for(let r in t)if(ai(t[r])){let i=n[r];i===void 0&&(i={},n[r]=i),Jt(i,t[r])}else H(n,{[r]:t[r]});return Jt(n,...e)}function v(n){return n==null}function O(){}var ce=class{constructor(){this._listeners={}}addEventListener(e,t,r){let i=O;if(r!==void 0){if(r.isCancelled())return;i=r.register(()=>this.removeEventListener(e,t))}let a=this._listeners[e];Array.isArray(a)?a.push({cb:t,onRemove:i}):this._listeners[e]=[{cb:t,onRemove:i}]}removeEventListener(e,t){if(v(e)){for(let i of Object.keys(this._listeners)){let a=this._listeners[i];Array.isArray(a)&&a.forEach(o=>o.onRemove())}this._listeners={};return}let r=this._listeners[e];if(Array.isArray(r)){if(v(t)){r.forEach(i=>i.onRemove()),delete this._listeners[e];return}for(let i=0;i<r.length;i++)if(r[i].cb===t){r[i].onRemove(),r.splice(i,1);break}r.length===0&&delete this._listeners[e]}}trigger(e,t){let r=this._listeners[e];Array.isArray(r)&&r.slice().forEach(i=>{try{i.cb(t)}catch(a){if(I.CURRENT_ENV===I.DEV)throw a instanceof Error?a:new Error("EventEmitter: listener error");console.error("RxPlayer: EventEmitter error",a instanceof Error?a:null)}})}};var oi=class extends ce{constructor(){super(...arguments);this.updated=!1;this._config=so}update(t){let r=Jt(this._config,t);this._config=r,this.updated=!0,this.trigger("update",t)}getCurrent(){return this._config}},Ud=new oi,L=Ud;var $e=class n extends Error{constructor(e,t,r){super(e),Object.setPrototypeOf(this,n.prototype),this.name="CustomLoaderError",this.canRetry=t,this.xhr=r}};function ae(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}var fr=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){I.CURRENT_ENV===I.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 a=this._listeners.indexOf(i);a>=0&&this._listeners.splice(a,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 O;let r=()=>{let o=ae(this._onFinishCbs,s=>s.trigger===i);o>=0&&(this._onFinishCbs[o].hasBeenCleared=!0,this._onFinishCbs.splice(o,1))},i=()=>{r(),e()},a=t.register(r);return this._onFinishCbs.push({trigger:i,hasBeenCleared:!1}),a}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 en(n,e,t){let r=new fr(e(n.getValue()),t);return n.onUpdate(function(a){r.setValue(e(a))},{clearSignal:t}),n._onFinished(()=>{r.finish()},t),r}var $=fr;var si=new $(0);function uo({date:n,timestamp:e}){let t=n-e,r=typeof performance!="undefined"?Date.now()-performance.now():0;si.setValueIfChanged(r-t)}var Ld=typeof performance!="undefined"?()=>performance.now()+si.getValue():()=>Date.now()+si.getValue(),F=Ld;var Fd="NONE",tn=class extends ce{constructor(){super(),this.error=O,this.warn=O,this.info=O,this.debug=O,this._levels={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4},this._currentFormat="standard",this._currentLevel=Fd}setLevel(e,t,r){let i,a=this._levels[e];typeof a=="number"?(i=a,this._currentLevel=e):(i=0,this._currentLevel="NONE");let o;if(t==="standard"||t==="full"?o=t:o="standard",o==="full"&&o!==this._currentFormat){let d=F();console.log(String(d.toFixed(2)),"[Init]",`Local-Date: ${Date.now()}`)}this._currentFormat=o;let s=this._currentFormat==="full"?(d,u)=>(f,...l)=>{let m=F();return u(String(m.toFixed(2)),`[${d}]`,f+":",...l.map(g=>typeof g=="object"&&g!==null&&!(g instanceof Error)?lo(g):g))}:(d,u)=>(f,...l)=>u(f+":",...l.map(m=>typeof m=="object"&&m!==null&&!(m instanceof Error)?lo(m):m));if(r===void 0)this.error=i>=this._levels.ERROR?s("error",console.error.bind(console)):O,this.warn=i>=this._levels.WARNING?s("warn",console.warn.bind(console)):O,this.info=i>=this._levels.INFO?s("info",console.info.bind(console)):O,this.debug=i>=this._levels.DEBUG?s("log",console.log.bind(console)):O;else{let d=u=>i>=this._levels[u]?(f,...l)=>r(u,f,l):O;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]}};function lo(n){let e="";for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)){e.length>0&&(e+=" ");let r=n[t];r instanceof Error?e+=`${t}="${JSON.stringify(r==null?void 0:r.toString())}"`:e+=`${t}=${typeof r=="string"?`${JSON.stringify(r)}`:String(r)}`}return e}var zd=new tn,c=zd;var mr=typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope;var Wd=typeof window=="undefined"&&!mr,cr=Wd;var pr;mr?pr=self:cr?pr=global:pr=window;var ne=pr;var le=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}}},Pe={TIMEOUT:"TIMEOUT",ERROR_EVENT:"ERROR_EVENT",ERROR_HTTP_CODE:"ERROR_HTTP_CODE",PARSE_ERROR:"PARSE_ERROR"};var di=typeof Headers=="function"?Headers:null,gr=typeof AbortController=="function"?AbortController:null;function hr(n){var m,g;let e;if(!v(n.headers))if(v(di))e=n.headers;else{e=new di;let h=Object.keys(n.headers);for(let b=0;b<h.length;b++){let p=h[b];e.append(p,n.headers[p])}}c.debug("utils","Fetch",{url:n.url});let t=null,r=!1,i=!1,a=F(),o=v(gr)?null:new gr;function s(){if(v(o)){c.warn("utils","Fetch: AbortController API not available.");return}o.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 f=n.cancelSignal.register(function(b){t=b,s()}),l={method:"GET"};if(e!==void 0&&(l.headers=e),l.signal=v(o)?null:o.signal,c.hasLevel("DEBUG")){let h="fetch GET "+n.url;n.timeout!==void 0&&(h+=" to="+String(n.timeout/1e3)),n.connectionTimeout!==void 0&&(h+=" cto="+String(n.connectionTimeout/1e3)),((m=n.headers)==null?void 0:m.Range)!==void 0&&(h+=" Range="+((g=n.headers)==null?void 0:g.Range)),c.debug("utils",h)}return fetch(n.url,l).then(h=>{if(u!==void 0&&clearTimeout(u),h.status>=300)throw c.warn("utils","Fetch: Request HTTP Error",{status:h.status,responseUrl:h.url}),new le(h.url,h.status,Pe.ERROR_HTTP_CODE);if(v(h.body))throw new le(h.url,h.status,Pe.PARSE_ERROR);let b=h.headers.get("Content-Length"),p=!v(b)&&!isNaN(+b)?+b:void 0,S=h.body.getReader(),T=0;return R();async function R(){let E=await S.read();if(!E.done&&!v(E.value)){T+=E.value.byteLength;let C=F(),P={url:h.url,currentTime:C,duration:C-a,sendingTime:a,chunkSize:E.value.byteLength,chunk:E.value.buffer,size:T,totalSize:p};return n.onData(P),R()}else if(E.done){d!==void 0&&clearTimeout(d),f();let C=F();return{requestDuration:C-a,receivedTime:C,sendingTime:a,size:T,status:h.status,url:h.url}}return R()}}).catch(h=>{throw t!==null?t:(f(),r?(c.warn("utils","Fetch: Request timed out.",{url:n.url,timeout:n.timeout}),new le(n.url,0,Pe.TIMEOUT)):i?(c.warn("utils","Fetch: Request connection timed out.",{url:n.url,connectionTimeout:n.connectionTimeout}),new le(n.url,0,Pe.TIMEOUT)):h instanceof le?h:(c.warn("utils","Fetch: Request Error",{error:h instanceof Error?h.toString():"Unkwown Error"}),new le(n.url,0,Pe.ERROR_EVENT)))})}function nn(){let n=/\[\s*native\s+code\s*\]/;return typeof ne.fetch=="function"&&!v(gr)&&n.test(gr.toString())&&!v(di)}function Y(n){return typeof n=="string"&&n.length>0}var Vd="json";function rn(n){let e={url:n.url,headers:n.headers,responseType:v(n.responseType)?Vd:n.responseType,timeout:n.timeout,connectionTimeout:n.connectionTimeout};return new Promise((t,r)=>{let{onProgress:i,cancelSignal:a}=n,{url:o,headers:s,responseType:d,timeout:u,connectionTimeout:f}=e,l=new XMLHttpRequest;l.open("GET",o,!0);let m;u!==void 0&&(l.timeout=u,m=setTimeout(()=>{p(),r(new le(o,l.status,Pe.TIMEOUT))},u+3e3));let g;if(f!==void 0&&(g=setTimeout(()=>{p(),l.readyState!==XMLHttpRequest.DONE&&l.abort(),r(new le(o,l.status,Pe.TIMEOUT))},f)),l.responseType=d,l.responseType==="document"&&l.overrideMimeType("text/xml"),!v(s)){let S=s;for(let T in S)Object.prototype.hasOwnProperty.call(S,T)&&l.setRequestHeader(T,S[T])}let h=F(),b=null;if(a!==void 0&&(b=a.register(function(T){p(),l.readyState!==XMLHttpRequest.DONE&&l.abort(),r(T)}),a.isCancelled()))return;if(l.onerror=function(){p(),r(new le(o,l.status,Pe.ERROR_EVENT))},l.ontimeout=function(){p(),r(new le(o,l.status,Pe.TIMEOUT))},f!==void 0&&(l.onreadystatechange=function(){l.readyState>=XMLHttpRequest.HEADERS_RECEIVED&&clearTimeout(g)}),i!==void 0&&(l.onprogress=function(T){let R=F();i({url:o,duration:R-h,sendingTime:h,currentTime:R,size:T.loaded,totalSize:T.total})}),l.onload=function(T){if(l.readyState===XMLHttpRequest.DONE)if(p(),l.status>=200&&l.status<300){let R=F(),E=l.response instanceof ArrayBuffer?l.response.byteLength:T.total,C=l.status,P=l.responseType,x=Y(l.responseURL)?l.responseURL:o,A;if(P==="json"?A=typeof l.response=="object"?l.response:qd(l.responseText):A=l.response,v(A)){r(new le(o,l.status,Pe.PARSE_ERROR));return}t({status:C,url:x,responseType:P,sendingTime:h,receivedTime:R,requestDuration:R-h,size:E,responseData:A})}else r(new le(o,l.status,Pe.ERROR_HTTP_CODE))},c.hasLevel("DEBUG")){let S="XHR GET "+o;n.responseType!==void 0&&(S+=" type="+n.responseType),u!==void 0&&(S+=" to="+String(u/1e3)),f!==void 0&&(S+=" cto="+String(f/1e3)),(s==null?void 0:s.Range)!==void 0&&(S+=" Range="+(s==null?void 0:s.Range)),c.debug("utils",S)}l.send();function p(){m!==void 0&&clearTimeout(m),g!==void 0&&clearTimeout(g),b!==null&&b()}})}function qd(n){try{return JSON.parse(n)}catch(e){return null}}var be=rn;var Pt=Pe,qe={NETWORK_ERROR:"NETWORK_ERROR",MEDIA_ERROR:"MEDIA_ERROR",ENCRYPTED_MEDIA_ERROR:"ENCRYPTED_MEDIA_ERROR",OTHER_ERROR:"OTHER_ERROR"};function et(n,e){return`${n}: ${e}`}var an=class n extends Error{constructor(e,t,r){super(et(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="EncryptedMediaError",this.type=qe.ENCRYPTED_MEDIA_ERROR,this.code=e,this._originalMessage=t,this.fatal=!1,this.keyStatuses=r.keyStatuses,this.keySystemConfiguration=r.keySystemConfiguration,this.keySystem=r.keySystem}serialize(){return{isSerializedError:!0,name:this.name,code:this.code,reason:this._originalMessage,keyStatuses:this.keyStatuses,keySystemConfiguration:this.keySystemConfiguration,keySystem:this.keySystem}}};var Ir=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype),this.name="AssertionError"}};function Se(n,e){if(I.DEV===I.CURRENT_ENV&&!n)throw new Ir(e===void 0?"invalid assertion":e)}function Ne(n){throw new Ir("Unreachable path taken")}var ee=class n extends Error{constructor(e,t,r){super(et(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="MediaError",this.type=qe.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),(r==null?void 0:r.timeInfo)!==void 0&&(this.timeInfo=r.timeInfo)}serialize(){return{isSerializedError:!0,name:this.name,code:this.code,reason:this._originalMessage,tracks:this.tracksInfo,timeInfo:this.timeInfo}}};var Xe=class n extends Error{constructor(e,t){super(et(e,t.message)),Object.setPrototypeOf(this,n.prototype),this.name="NetworkError",this.type=qe.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===Pt.ERROR_HTTP_CODE&&this.status===e}serialize(){return{isSerializedError:!0,name:this.name,code:this.code,baseError:this._baseError.serialize()}}};var _e=class n extends Error{constructor(e,t){super(et(e,t)),Object.setPrototypeOf(this,n.prototype),this.name="OtherError",this.type=qe.OTHER_ERROR,this.code=e,this.fatal=!1,this._originalMessage=t}serialize(){return{isSerializedError:!0,name:this.name,code:this.code,reason:this._originalMessage}}};function Ut(n){return(n instanceof an||n instanceof ee||n instanceof _e||n instanceof Xe)&&Object.keys(qe).indexOf(n.type)>=0}function ge(n,{defaultCode:e,defaultReason:t}){if(Ut(n))return n;let r=n instanceof Error?n.toString():t;return new _e(e,r)}var xe=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 Gd={dashParsers:{wasm:null,js:null},createDebugElement:null,directfile:null,decrypt:null,htmlTextDisplayer:null,htmlTextTracksParsers:{},monothread:null,multithread:null,nativeTextDisplayer:null,nativeTextTracksParsers:{},transports:{}},fo=Gd;var ke=fo;function j(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 a=n[i];if(e.call(t,a,i,n))return a}}var Hd={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"},mo=Hd;var Kd={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"},co=Kd;function jd(n){if(v(n)||n==="")return"und";let t=(""+n).toLowerCase().split("-")[0],r=Yd(t);return Y(r)?r:n}function Yd(n){let e;switch(n.length){case 2:e=mo[n];break;case 3:e=co[n];break}return e}var po=jd;var go=po;function br(n,e){if(n.length!==e.length)return!1;if(n===e)return!0;for(let t=n.length-1;t>=0;t--)if(n[t]!==e[t])return!1;return!0}function Me(){let n="",e=-1;return function(){return e++,e>=Number.MAX_SAFE_INTEGER&&(n+="0",e=0),n+String(e)}}var Qd=typeof ne=="object"&&typeof ne.TextDecoder=="function",$d=typeof ne=="object"&&typeof ne.TextEncoder=="function";function on(n){if($d)try{return new TextEncoder().encode(n)}catch(i){let a=i instanceof Error?i:"Unknown Error";c.warn("utils","Could not use TextEncoder to encode string into UTF-8, fallbacking to another implementation",a)}let e,t=encodeURIComponent(n);if(typeof unescape=="function")e=unescape(t);else{let i=/[0-9a-fA-F]/,a=t.length;e="";for(let o=0;o<t.length;o++){let s=!1;if(t[o]==="%"){if(o<=a-6&&t[o+1]==="u"&&i.test(t[o+2])&&i.test(t[o+3])&&i.test(t[o+4])&&i.test(t[o+5])){let d=parseInt(t.substring(o+1,o+6),16);e+=String.fromCharCode(d),s=!0,o+=5}else if(o<=a-3&&i.test(t[o+1])&&i.test(t[o+2])){let d=parseInt(t.substring(o+1,o+3),16);e+=String.fromCharCode(d),s=!0,o+=2}}s||(e+=t[o])}}let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e.charCodeAt(i)&255;return r}function Xd(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 ho(n,e){let t=n.toString(16);return t.length>=e?t:new Array(e-t.length+1).join("0")+t}function Ge(n){if(Qd)try{return new TextDecoder().decode(n)}catch(i){let a=i instanceof Error?i:"Unknown Error";c.warn("utils","could not use TextDecoder to parse UTF-8, fallbacking to another implementation",a)}let e=n;e[0]===239&&e[1]===187&&e[2]===191&&(e=e.subarray(3));let t=Xd(e),r;if(typeof escape=="function")r=escape(t);else{let i=/[A-Za-z0-9*_+-./]/;r="";for(let a=0;a<t.length;a++)if(i.test(t[a]))r+=t[a];else{let o=t.charCodeAt(a);r+=o>=256?"%u"+ho(o,4):"%"+ho(o,2)}}return decodeURIComponent(r)}function sn(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 Sr(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 ui(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:Ge(r)}}function li(n){return Object.keys(n).map(e=>n[e])}var yr=typeof Object.values=="function"?Object.values:li;var Lt=["audio","video","text"];function bo(n){var a,o;let e=n.timeBounds;if(e.timeshiftDepth===null)return(a=e.minimumSafePosition)!=null?a:0;let{maximumTimeData:t}=e,r;if(!e.maximumTimeData.isLinear)r=t.maximumSafePosition;else{let s=F()-t.time;r=t.maximumSafePosition+s/1e3}let i=r-e.timeshiftDepth;return Math.max((o=e.minimumSafePosition)!=null?o:0,i)}function So(n){let{maximumTimeData:e}=n.timeBounds;if(!n.isLive||e.livePosition===void 0)return;if(!e.isLinear)return e.livePosition;let t=F()-e.time;return e.livePosition+t/1e3}function yo(n){let{maximumTimeData:e}=n.timeBounds;if(!e.isLinear)return e.maximumSafePosition;let t=F()-e.time;return e.maximumSafePosition+t/1e3}function To(n,e){if(e===void 0)return mi(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 Eo(n,e){let t=null;for(let r=n.periods.length-1;r>=0;r--){let i=n.periods[r];if(fi(i,e,t))return i;t=i}}function _o(n,e){let t=e.end;if(t===void 0)return null;let r=j(n.periods,i=>i.end===void 0||t<i.end);return r===void 0?null:r}function fi(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 mi(n){let e=n.adaptations;return li(e).reduce((t,r)=>v(r)?t:t.concat(r),[])}function Zd(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(a=>dn(a)===!0):n.representations).map(tu),label:n.label};return n.isDub===!0&&(t.dub=!0),t}function Jd(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 eu(n,e){let t=n.trickModeTracks!==void 0?n.trickModeTracks.map(i=>{let a=(e?i.representations.filter(s=>dn(s)===!0):i.representations).map(Io),o={id:i.id,representations:a,isTrickModeTrack:!0};return i.isSignInterpreted===!0&&(o.signInterpreted=!0),o}):void 0,r={id:n.id,representations:(e?n.representations.filter(i=>dn(i)===!0):n.representations).map(Io),label:n.label};return n.isSignInterpreted===!0&&(r.signInterpreted=!0),n.isTrickModeTrack===!0&&(r.isTrickModeTrack=!0),t!==void 0&&(r.trickModeTracks=t),r}function tu(n){let{id:e,bitrate:t,chosenCodec:r,isSpatialAudio:i,isSupported:a,decipherable:o}=n;return{id:e,bitrate:t,codec:r,isSpatialAudio:i,isCodecSupported:a,decipherable:o}}function Io(n){let{id:e,bitrate:t,frameRate:r,width:i,height:a,chosenCodec:o,hdrInfo:s,isSupported:d,decipherable:u,contentProtections:f}=n;return{id:e,bitrate:t,frameRate:r,width:i,height:a,codec:o,hdrInfo:s,isCodecSupported:d,decipherable:u,contentProtections:f!==void 0?{keyIds:f.keyIds}:void 0}}function vt(n){switch(n.type){case"audio":return{type:"audio",track:Zd(n,!1)};case"video":return{type:"video",track:eu(n,!1)};case"text":return{type:"text",track:Jd(n)}}}function dn(n){return n.decipherable===!1?!1:n.isSupported}function Ro(n){return new Function(`return (${n}(arguments[0], arguments[1]))`)}var nu=Me(),ci=class{constructor(e,t,r){var a,o,s,d;this.id=e.id,this.uniqueId=nu(),this.shouldBeAvoided=!1,this.bitrate=e.bitrate,this.baseCodecs=[],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"){let u=!1;e.supplementalCodecs!==void 0&&(this.baseCodecs.push(e.supplementalCodecs),u=r.isSupported((a=this.mimeType)!=null?a:"",(o=e.supplementalCodecs)!=null?o:"",i),u===!0&&(c.debug("manifest","supplementalCodec is supported as per the cache",{codec:e.supplementalCodecs}),this.chosenCodec=e.supplementalCodecs)),e.codecs!==void 0&&this.baseCodecs.push(e.codecs),u===!1&&(u=r.isSupported((s=this.mimeType)!=null?s:"",(d=e.codecs)!=null?d:"",i),c.debug("manifest","codec is supported as per the cache",{codec:e.codecs}),this.chosenCodec=e.codecs),this.isSupported=u}else e.codecs!==void 0&&(this.baseCodecs.push(e.codecs),this.chosenCodec=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:"",a=(d=this.baseCodecs)!=null?d:[];a.length===0&&(a=[""]);let o=!1;for(let u of a){if(r=e.isSupported(i,u,t),r===!0){c.debug("manifest","codec is found to be supported",{codec:u}),this.chosenCodec=u;break}r===void 0&&(o=!0)}r===!0?this.isSupported=!0:o?this.isSupported=void 0:this.isSupported=!1}getMimeTypeString(){var t;let e=this.chosenCodec;return e===void 0&&(c.warn("manifest","Asked for mimetype string when codec support is yet unknown, attempting with first known linked codec"),this.baseCodecs!==void 0&&(e=this.baseCodecs[0])),`${(t=this.mimeType)!=null?t:""};codecs="${e!=null?e:""}"`}getEncryptionData(e){var i;let t=this.getAllEncryptionData(),r=[];for(let a=0;a<t.length;a++){let o=!1,s=t[a];for(let d=0;d<s.values.length;d++)if(s.values[d].systemId.toLowerCase()===e.toLowerCase())if(o)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]]}),o=!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 o=this.contentProtections.keyIds;if(o===void 0)this.contentProtections.keyIds=[t];else{let s=!1;for(let d of o)br(d,t)&&(s=!0);s||(c.warn("manifest","found unanounced key id.",{keyId:Sr(t)}),o.push(t))}}let a=this.contentProtections.initData;for(let o=0;o<a.length;o++)if(a[o].type===e){let s=a[o].values;for(let d=0;d<r.length;d++){let u=r[d],f;for(f=0;f<s.length;f++)if(u.systemId===s[f].systemId){if(br(u.data,s[f].data))break;c.warn("manifest","different init data for the same system ID",{systemId:u.systemId})}f===s.length&&(s.push(u),i=!0)}return i}return this.contentProtections.initData.push({type:e,values:r}),!0}isPlayable(){return dn(this)}getMetadataSnapshot(){return{id:this.id,uniqueId:this.uniqueId,bitrate:this.bitrate,baseCodecs:this.baseCodecs,chosenCodec:this.chosenCodec,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}}},un=ci;var ct=class n{constructor(e,t,r={}){let{trickModeTracks:i}=e,{representationFilter:a,isManuallyAdded:o}=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=go(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 f=new un(s[u],this.type,t),l=!0;if(!v(a)){let m={id:f.id,bitrate:f.bitrate,codecs:f.chosenCodec!==void 0?[f.chosenCodec]:f.baseCodecs,height:f.height,width:f.width,frameRate:f.frameRate,hdrInfo:f.hdrInfo};if(f.contentProtections!==void 0&&(m.contentProtections={},f.contentProtections.keyIds!==void 0)){let g=f.contentProtections.keyIds;m.contentProtections.keyIds=g}l=a(m,{trackType:this.type,language:this.language,normalizedLanguage:this.normalizedLanguage,isClosedCaption:this.isClosedCaption,isDub:this.isDub,isAudioDescription:this.isAudioDescription,isSignInterpreted:this.isSignInterpreted})}l?(d.push(f),f.isSupported===void 0?(this.supportStatus.hasCodecWithUndefinedSupport=!0,this.supportStatus.hasSupportedCodec===!1&&(this.supportStatus.hasSupportedCodec=void 0)):f.isSupported&&(this.supportStatus.hasSupportedCodec=!0),f.decipherable===void 0?this.supportStatus.isDecipherable===!1&&(this.supportStatus.isDecipherable=void 0):f.decipherable&&(this.supportStatus.isDecipherable=!0)):c.debug("manifest","Filtering Representation due to representationFilter",this.type,`Adaptation: ${this.id}`,`Representation: ${f.id}`,`(${f.bitrate})`)}d.sort((u,f)=>u.bitrate-f.bitrate),this.representations=d,this.manuallyAdded=o===!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 j(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}}};var ye=ne,Po,vo,Co,Ao,xo,pi=(xo=(Ao=(Co=(vo=(Po=ye==null?void 0:ye.MediaSource)!=null?Po:ye==null?void 0:ye.MozMediaSource)!=null?vo:ye==null?void 0:ye.WebKitMediaSource)!=null?Co:ye==null?void 0:ye.MSMediaSource)!=null?Ao:ye==null?void 0:ye.ManagedMediaSource)!=null?xo:void 0,ru=pi!==void 0&&pi===(ye==null?void 0:ye.ManagedMediaSource),iu={HAVE_NOTHING:0,HAVE_METADATA:1,HAVE_CURRENT_DATA:2,HAVE_FUTURE_DATA:3,HAVE_ENOUGH_DATA:4},au={MediaSource_:pi,isManagedMediaSource:ru,READY_STATES:iu},ln=au;var pt={EdgeChromium:0,Firefox:1,Ie11:2,OtherIeOrEdgePreEdgeChromium:3,SafariDesktop:4,SafariMobile:5,Other:6},De={A1KStb40xx:100,Panasonic:101,PhilipsNetTv:102,PlayStation4:103,PlayStation5:104,Tizen:105,WebOs2021:106,WebOs2022:107,WebOsOther:108,Xbox:109,Other:110,StreamaMdp1001S:111},he={DEVICES:De,BROWSERS:pt,browser:pt.Other,device:De.Other,isSamsungBrowser:!1};ou();function ou(){var n,e,t;cr||(typeof ne.MSInputMethodContext!="undefined"&&typeof document.documentMode!="undefined"?he.browser=pt.Ie11:navigator.appName==="Microsoft Internet Explorer"||navigator.appName==="Netscape"&&/(Trident|Edge)\//.test(navigator.userAgent)?he.browser=pt.OtherIeOrEdgePreEdgeChromium:navigator.userAgent.toLowerCase().indexOf("edg/")!==-1?he.browser=pt.EdgeChromium:navigator.userAgent.toLowerCase().indexOf("firefox")!==-1?he.browser=pt.Firefox:typeof navigator.platform=="string"&&/iPad|iPhone|iPod/.test(navigator.platform)?he.browser=pt.SafariMobile:(Object.prototype.toString.call(ne.HTMLElement).indexOf("Constructor")>=0||((e=(n=ne.safari)==null?void 0:n.pushNotification)==null?void 0:e.toString())==="[object SafariRemoteNotification]"||/Safari\/(\d+)/.test(navigator.userAgent)&&/Version\/(\d+)/.test(navigator.userAgent)&&((t=navigator.vendor)==null?void 0:t.indexOf("Apple"))!==-1&&!/Chrome\/(\d+)/.test(navigator.userAgent)&&!/Chromium\/(\d+)/.test(navigator.userAgent))&&(he.browser=pt.SafariDesktop),/SamsungBrowser/.test(navigator.userAgent)&&(he.isSamsungBrowser=!0),navigator.userAgent.indexOf("PlayStation 4")!==-1?he.device=De.PlayStation4:navigator.userAgent.indexOf("PlayStation 5")!==-1?he.device=De.PlayStation5:navigator.userAgent.indexOf("DStv Streama, MDMP1001S")!==-1?he.device=De.StreamaMdp1001S:/Tizen/.test(navigator.userAgent)?he.device=De.Tizen:/[Ww]eb[O0]S/.test(navigator.userAgent)?/[Ww]eb[O0]S.TV-2022/.test(navigator.userAgent)||/[Cc]hr[o0]me\/87/.test(navigator.userAgent)?he.device=De.WebOs2022:/[Ww]eb[O0]S.TV-2021/.test(navigator.userAgent)||/[Cc]hr[o0]me\/79/.test(navigator.userAgent)?he.device=De.WebOs2021:he.device=De.WebOsOther:navigator.userAgent.indexOf("NETTV")!==-1&&navigator.userAgent.indexOf("Philips")!==-1?he.device=De.PhilipsNetTv:/[Pp]anasonic/.test(navigator.userAgent)?he.device=De.Panasonic:navigator.userAgent.indexOf("Xbox")!==-1?he.device=De.Xbox:navigator.userAgent.indexOf("Model/a1-kstb40xx")!==-1&&(he.device=De.A1KStb40xx))}var tt=he;function gi(n){return new Promise(e=>{setTimeout(e,n)})}function Ct(n,e){let t;return new Promise((r,i)=>{if(n.cancellationError!==null)return i(n.cancellationError);let a=!1;t=e(function(d){n.deregister(o),a=!0,r(d)},function(d){n.deregister(o),a=!0,i(d)}),a||n.register(o);function o(s){t!==void 0&&t(),i(s)}})}function fn(n,e){return Ct(e,t=>{let r=setTimeout(()=>t(),n);return()=>clearTimeout(r)})}var z=class{constructor(e){let[t,r]=su();this._isUsed=!1,this._trigger=t,this._taskName=e,this.signal=new hi(r)}isUsed(){return this._isUsed}linkToSignal(e){let t=e.register(r=>{this.cancel(r.reason)});return this.signal.register(t),t}cancel(e){if(this._isUsed)return;this._isUsed=!0;let t=new ue(this._taskName,e);this._trigger(t)}static isCancellationError(e){return e instanceof ue}},hi=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){c.error("utils","Error while calling clean up listener",r instanceof Error?r:"Unknown Error")}})}isCancelled(){return this._isCancelled}register(e){return this._isCancelled?(Se(this.cancellationError!==null),e(this.cancellationError),O):(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)}},ue=class n extends Error{constructor(e,t){let r=e!==void 0?`"${e}" task cancelled.`:"This task was cancelled.";t!==void 0&&(r+=" Reason: "+t),super(r),Object.setPrototypeOf(this,n.prototype),this.name="CancellationError",this.reason=t,e!==void 0&&c.debug("utils",`task cancellation: "${e}"`+(t===void 0?"":` - Reason: "${t}"`))}};function su(){let n=O;return[function(t){n(t)},function(t){n=t}]}var du=["","webkit","moz","ms"];function uu(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 lu(n,e){return e.filter(t=>uu(n,t))[0]}function fu(n,e){return n.reduce((t,r)=>t.concat((e===void 0?du:e).map(i=>i+r)),[])}function ve(n,e){let t,r=fu(n,e);return(i,a,o)=>{if(!o.isCancelled()){if(typeof HTMLElement!="undefined"&&i instanceof HTMLElement)if(typeof t=="undefined"&&(t=lu(i,r)),Y(t))i.addEventListener(t,a),o.register(()=>{t!==void 0&&i.removeEventListener(t,a)});else{c.warn("utils",`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,a):(d=!0,i["on"+s]=a),o.register(()=>{typeof i.removeEventListener=="function"&&i.removeEventListener(s,a),d&&delete i["on"+s]})})}}}var Ch=ve(["loadedmetadata"]),Ah=ve(["timeupdate"]),xh=ve(["addtrack"]),kh=ve(["removetrack"]),Ft=ve(["sourceopen","webkitsourceopen"]),Tr=ve(["sourceclose","webkitsourceclose"]),Er=ve(["sourceended","webkitsourceended"]),ko=ve(["update"]),Mo=ve(["removesourcebuffer"]),Mh=ve(["keymessage","message"]),Oh=ve(["keyadded","ready"]),wh=ve(["keyerror","error"]),Dh=ve(["keystatuseschange"]),Bh=ve(["seeking"]),Nh=ve(["seeked"]),Uh=ve(["ended"]);var Oo=[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 _r(n){if(n>=Oo.length)throw new Error("Unable to parse base64 string.");let e=Oo[n];if(e===255)throw new Error("Unable to parse base64 string.");return e}function Rr(n){if(typeof Uint8Array.fromBase64=="function")return Uint8Array.fromBase64(n);let e=n.length%4,t=n;e!==0&&(c.warn("utils","base64ToBytes: base64 given miss padding",{padding:e}),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,a=t.length,o=new Uint8Array(a/4*3),s;for(let d=0,u=0;d<a;d+=4,u+=3)s=_r(t.charCodeAt(d))<<18|_r(t.charCodeAt(d+1))<<12|_r(t.charCodeAt(d+2))<<6|_r(t.charCodeAt(d+3)),o[u]=s>>16,o[u+1]=s>>8&255,o[u+2]=s&255;return o.subarray(0,o.length-i)}function At(...n){let e=n.length,t=-1,r=0,i;for(;++t<e;)i=n[t],r+=typeof i=="number"?i:i.length;let a=new Uint8Array(r),o=0;for(t=-1;++t<e;)i=n[t],typeof i=="number"?o+=i:i.length>0&&(a.set(i,o),o+=i.length);return a}function wo(n,e){return(n[e+0]<<8)+(n[e+1]<<0)}function Ii(n,e){return n[e+0]*65536+n[e+1]*256+n[e+2]}function te(n,e){return n[e+0]*16777216+n[e+1]*65536+n[e+2]*256+n[e+3]}function gt(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 Do(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer)}function Ie(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}function Ze(n,e){let t=n.length,r=0;for(;r+8<=t;){let i=te(n,r);if(i===0)i=t-r;else if(i===1){if(r+16>t)return-1;i=gt(n,r+8)}if(isNaN(i)||i<=0)return-1;if(te(n,r+4)===e)return r+i<=t?r:-1;r+=i}return-1}function Pr(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=Ze(r,1836019558);if(i<0)break;let a=te(n,i+e),o=e+i+a;if(o>n.length)break;let s=Ze(r,1835295092);if(s<0)break;let d=te(n,s+e),u=e+s+d;if(u>n.length)break;let f=Math.max(o,u),l=n.subarray(e,f);t.push(l),e=f}return t.length===0?[null,r]:[t,r]}function bi(){let{PREVENT_PSSH_PATCHING:n}=L.getCurrent();return!(n||tt.device===tt.DEVICES.StreamaMdp1001S)}function mu(n,e,t){return new Uint8Array(Array.prototype.slice.call(n,e,t))}function cu(n,e,t){return n.slice(e,t)}var Si=typeof Uint8Array.prototype.slice=="function"?cu:mu;function yi(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=nt(n,e);return t!==null?n.subarray(t[1],t[2]):null}function Bo(n,e){let t=[],r=n;for(;;){let i=nt(r,e);if(i===null)return t;Se(i[2]!==0&&r.length!==0),t.push(r.subarray(i[1],i[2])),r=r.subarray(i[2])}}function nt(n,e){let t=n.length,r=0,i,a=0,o;for(;r+8<=t;){if(o=r,a=te(n,o),o+=4,i=te(n,o),o+=4,a===0)a=t-r;else if(a===1){if(o+8>t)return null;a=gt(n,o),o+=8}if(a<0)throw new Error("ISOBMFF: Size out of range");if(i===e)return e===1970628964&&(o+=16),[r,o,r+a];r+=a}return null}function Ti(n){return[n>>>24&255,n>>>16&255,n>>>8&255,n&255].map(e=>String.fromCharCode(e)).join("")}function vr(n){let e=re(n,1836019574);if(e===null)return[];let t=[],r=e;for(;r.length>0;){let i;try{i=nt(r,1886614376)}catch(s){let d=s instanceof Error?s:new Error("Unknown ISOBMFF box reading error");return c.warn("isobmff","Error while removing PSSH from ISOBMFF",d),t}if(i===null)return t;let a=Si(r,i[0],i[2]),o=No(a,i[1]-i[0]);o!==void 0&&t.push({systemId:o,data:a}),bi()&&(r[i[0]+4]=102,r[i[0]+5]=114,r[i[0]+6]=101,r[i[0]+7]=101),r=r.subarray(i[2])}return t}function No(n,e){if(n[e]>1){c.warn("isobmff","un-handled PSSH version");return}let t=e+4;if(t+16>n.length)return;let r=Si(n,t,t+16);return Sr(r)}function Cr(n){let e=re(n,1836019574);if(e===null)return;let t=0;for(;t<e.length;){let r;try{r=nt(e.subarray(t),1953653099)}catch(a){let o=a instanceof Error?a:"";c.warn("isobmff","Error while iterating trak boxes in ISOBMFF",o);return}if(r===null)break;let i=re(e.subarray(t),1953653099);i!==null&&pu(i),t+=r[2]}}function pu(n){let e=[1685480259,1685485123,1685485379],t=re(n,1835297121);if(t===null)return;let r=re(t,1835626086);if(r===null)return;let i=re(r,1937007212);if(i===null)return;let a=re(i,1937011556);if(a===null)return;let o=a.subarray(8),s=0;for(;s<o.length&&!(s+8>o.length);){let d=te(o,s),u=te(o,s+4);if(d<8||s+d>o.length)break;let f=o.subarray(s,s+d),l=gu(f);if(l===null){s+=d;continue}let m=f.subarray(l);for(let g of e){let h=0;for(;h<m.length;){let b;try{b=nt(m.subarray(h),g)}catch(S){let T=S instanceof Error?S:"";c.warn("isobmff","Error while patching out dvcC/dvvC/dvwC from ISOBMFF",T);break}if(b===null)break;c.hasLevel("DEBUG")&&c.debug("isobmff",`Found '${Ti(g)}' inside '${Ti(u)}', overwriting with 'free'`);let p=h+b[0]+4;m[p]=102,m[p+1]=114,m[p+2]=101,m[p+3]=101,h+=b[2]-b[0]}}s+=d}}function gu(n){for(let e=16;e+8<=n.length;e++){let t=te(n,e);if(t<8||e+t>n.length)continue;let r=!0;for(let i=e+4;i<e+8;i++)if(n[i]<32||n[i]>126){r=!1;break}if(r)return e}return null}function Ei(n){let e=re(n,1836019558);return e===null?null:re(e,1953653094)}function Uo(n){return Bo(n,1836019558).reduce((t,r)=>{let i=re(r,1953653094);return i!==null&&t.push(i),t},[])}function _i(n){return re(n,1835295092)}function Ri(n){let e=re(n,1836019574);if(e===null)return null;let t=re(e,1953653099);return t===null?null:re(t,1835297121)}function Lo(n,e=0){return re(n.subarray(e),1701671783)}function mn(n,e){let t=nt(n,1936286840);if(t===null)return null;let r=e,i=t[2]-t[0],a=t[1],o=n[a];a+=8;let s=te(n,a);a+=4;let d;if(o===0)d=te(n,a),a+=4,r+=te(n,a)+i,a+=4;else if(o===1)d=gt(n,a),a+=8,r+=gt(n,a)+i,a+=8;else return null;let u=[];a+=2;let f=wo(n,a);for(a+=2;--f>=0;){let l=te(n,a);a+=4;let m=(l&2147483648)>>>31,g=l&2147483647;if(m===1)throw new Error("sidx with reference_type `1` not yet implemented");let h=te(n,a);a+=4,a+=4,u.push({time:d,duration:h,timescale:s,range:[r,r+g-1]}),d+=h,r+=g}return u}function Pi(n){let e=Ei(n);if(e===null)return;let t=re(e,1952867444);if(t===null)return;let r=t[0];if(r===1)return gt(t,4);if(r===0)return te(t,4)}function hu(n){let e=re(n,1952868452);if(e===null)return;let t=1,r=Ii(e,t);t+=3;let i=(r&1)>0,a=(r&2)>0;return(r&8)>0?(t+=4,i&&(t+=8),a&&(t+=4),te(e,t)):void 0}function vi(n){let e=Uo(n);if(e.length===0)return;let t=0;for(let r of e){let i=re(r,1953658222);if(i===null)return;let a=0,o=i[a];if(a+=1,o>1)return;let s=Ii(i,a);a+=3;let d=(s&256)>0,u=0;if(!d&&(u=hu(r),u===void 0))return;let f=(s&1)>0,l=(s&4)>0,m=(s&512)>0,g=(s&1024)>0,h=(s&2048)>0,b=te(i,a);a+=4,f&&(a+=4),l&&(a+=4);let p=b,S=0;for(;p-- >0;)d?(S+=te(i,a),a+=4):S+=u,m&&(a+=4),g&&(a+=4),h&&(a+=4);t+=S}return t}function cn(n){let e=Ri(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 te(t,r+16);if(i===0)return te(t,r+8)}function Fo(n){let e=[],t=0;for(;t<n.length;){let r=Lo(n,t);if(r===null)break;let i=r.length;t+=i;let a=r[0];if(a!==0)c.warn("isobmff","EMSG version "+a.toString()+" not supported.");else{let o=4,{end:s,string:d}=ui(r,o);o=s;let{end:u,string:f}=ui(r,o);o=u;let l=te(r,o);o+=4;let m=te(r,o);o+=4;let g=te(r,o);o+=4;let h=te(r,o);o+=4;let b=r.subarray(o,i),p={schemeIdUri:d,value:f,timescale:l,presentationTimeDelta:m,eventDuration:g,id:h,messageData:b};e.push(p)}}if(e.length!==0)return e}function zo(n){let e=yi(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 a=yi(r.subarray(i),[1936289382,1935894633,1952804451]);if(a===null||a.byteLength<24)return null;let o=a.subarray(8,24);return o.every(s=>s===0)?null:o}function fe(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,a=i>=0?Math.min(i,r-1):Math.max(r+i,0),o=(s,d)=>s===d||typeof s=="number"&&typeof d=="number"&&isNaN(s)&&isNaN(d);for(;a<r;){if(o(n[a],e))return!0;a++}return!1}function Iu(n,e){let{mimeType:t,codecs:r}=Wo(n),{mimeType:i,codecs:a}=Wo(e);if(t!==i||r===""||a==="")return!1;let o=r.split(".")[0];o=o==="hev1"?"hvc1":o;let s=a.split(".")[0];return s=s==="hev1"?"hvc1":s,o===s}var bu=7;function Wo(n){var i;let[e,...t]=n.split(";"),r=(i=j(t,a=>Ie(a,"codecs=")))!=null?i:"";return r=r.substring(bu),r[0]==='"'&&(r=r.substring(1,r.length-1)),{mimeType:e,codecs:r}}var Vo=Iu;function Ci(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 Ai(n){let e=(Math.random()*2-1)*.3;return n*(e+1)}function qo(n){var t,r,i,a;let e=[];for(let o of n.periods){let s=[...(t=o.adaptations.video)!=null?t:[],...(r=o.adaptations.audio)!=null?r:[]];for(let d of s)if(d.supportStatus.hasCodecWithUndefinedSupport){for(let u of d.representations)if(u.isSupported===void 0)for(let f of(i=u.baseCodecs)!=null?i:[])e.push({mimeType:(a=u.mimeType)!=null?a:"",codec:f})}}return e}var Go=[];function rt(n){fe(Go,n)||(console.warn(n),Go.push(n))}var pn=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 a=i.get(t);if(a!==void 0)return r?a.supportedIfEncrypted:a.supported}};var ht=class{constructor(e,t,r){if(this.id=e.id,this.adaptations=Su(e.adaptations,t,r),Ho(this.adaptations.video)&&Ho(this.adaptations.audio))throw new ee("MANIFEST_PARSE_ERROR","The manifest has no video nor audio tracks.");this.thumbnailTracks=e.thumbnailTracks.map(i=>({id:i.id,mimeType:i.mimeType,index:i.index,cdnMetadata:i.cdnMetadata,height:i.height,width:i.width,horizontalTiles:i.horizontalTiles,verticalTiles:i.verticalTiles,start:i.start,end:i.end,tileDuration:i.tileDuration})),this.duration=e.duration,this.start=e.start,!v(this.duration)&&!v(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)for(let a of i){if(!a.supportStatus.hasCodecWithUndefinedSupport)continue;let o=a.supportStatus.hasSupportedCodec;a.refreshCodecSupport(t),o!==!1&&a.supportStatus.hasSupportedCodec===!1&&e.push(a)}},{})}getAdaptations(){return mi(this)}getAdaptationsForType(e){let t=this.adaptations[e];return t!=null?t:[]}getAdaptation(e){return j(this.getAdaptations(),({id:t})=>e===t)}getSupportedAdaptations(e){return To(this,e)}containsTime(e,t){return fi(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 Ho(n){return Array.isArray(n)?n.length===0:!0}function Su(n,e,t){let r={};for(let[i,a]of Object.entries(n))v(a)||(r[i]=a.map(o=>new ct(o,e,{representationFilter:t})).filter(o=>o.representations.length>0));return r}function gn(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,a=e.thumbnailTracks;for(let d=0;d<i.length;d++){let u=i[d],f=ae(a,l=>l.id===u.id);if(f===-1){c.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]=a.splice(f,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})}}a.length>0&&(c.warn("manifest",`${a.length} new Thumbnail tracks found when merging.`),r.addedThumbnailTracks.push(...a.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(...a));let o=n.getAdaptations(),s=e.getAdaptations();for(let d=0;d<o.length;d++){let u=o[d],f=ae(s,l=>l.id===u.id);if(f===-1){c.warn("manifest",'Adaptation "'+o[d].id+'" not found when merging.');let[l]=o.splice(d,1);d--,r.removedAdaptations.push({id:l.id,trackType:l.type})}else{let[l]=s.splice(f,1),m=[],g=[],h=[];r.updatedAdaptations.push({adaptation:u.id,trackType:u.type,updatedRepresentations:m,addedRepresentations:g,removedRepresentations:h});let b=u.representations,p=l.representations.slice();for(let S=0;S<b.length;S++){let T=b[S],R=ae(p,E=>E.id===T.id);if(R===-1){c.warn("manifest",`Representation "${b[S].id}" not found when merging.`);let[E]=b.splice(S,1);S--,h.push(E.id)}else{let[E]=p.splice(R,1);m.push(T.getMetadataSnapshot()),T.cdnMetadata=E.cdnMetadata,t===0?T.index._replace(E.index):T.index._update(E.index)}}p.length>0&&(c.warn("manifest",`${p.length} new Representations found when merging.`),u.representations.push(...p),g.push(...p.map(S=>S.getMetadataSnapshot())))}}if(s.length>0){c.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 Ko(n,e){let t={updatedPeriods:[],addedPeriods:[],removedPeriods:[]},r=0;for(let a=0;a<e.length;a++){let o=e[a],s=r,d=n[s];for(;d!==void 0&&d.id!==o.id;)s++,d=n[s];if(d!==void 0){let u=gn(d,o,0);t.updatedPeriods.push({period:{id:d.id,start:d.start,end:d.end,duration:d.duration,streamEvents:d.streamEvents},result:u});let f=e.slice(r,a),l=s-r,m=n.splice(r,l,...f);t.removedPeriods.push(...m.map(g=>({id:g.id,start:g.start,end:g.end}))),t.addedPeriods.push(...f.map(g=>g.getMetadataSnapshot())),r=a+1}}if(r>n.length)return c.error("manifest","error when updating Periods"),t;if(r<n.length){let a=n.splice(r,n.length-r);t.removedPeriods.push(...a.map(o=>({id:o.id,start:o.start,end:o.end})))}let i=e.slice(r,e.length);return i.length>0&&(n.push(...i),t.addedPeriods.push(...i.map(a=>a.getMetadataSnapshot()))),t}function jo(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 ee("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=ae(n,({id:s})=>s===e[0].id);if(i<0)throw new ee("MANIFEST_UPDATE_ERROR","Cannot perform partial update: incoherent data");let a=gn(n[i],e[0],1);t.updatedPeriods.push({period:H(n[i].getMetadataSnapshot(),{adaptations:void 0}),result:a});let o=i+1;for(let s=1;s<e.length;s++){let d=e[s],u=-1;for(let f=o;f<n.length;f++)if(d.id===n[f].id){u=f;break}if(u<0){let f=-1;for(let g=o;g<n.length;g++)if(d.start<n[g].start){f=g;break}let l=f-o,m=n.splice(o,l,d);t.addedPeriods.push(d.getMetadataSnapshot()),t.removedPeriods.push(...m.map(g=>({id:g.id,start:g.start,end:g.end})))}else{if(u>o){c.warn("manifest","old Periods not found in new when updating, removing");let l=n.splice(o,u-o);t.removedPeriods.push(...l.map(m=>({id:m.id,start:m.start,end:m.end}))),u=o}let f=gn(n[u],d,0);t.updatedPeriods.push({period:H(n[u].getMetadataSnapshot(),{adaptations:void 0}),result:f})}o++}if(o<n.length){c.warn("manifest","Ending Periods not found in new when updating, removing");let s=n.splice(o,n.length-o);t.removedPeriods.push(...s.map(d=>({id:d.id,start:d.start,end:d.end})))}return t}var yu=Me(),hn=class extends ce{constructor(e,t){var a;super();let{representationFilter:r,manifestUpdateUrl:i}=t;this.manifestFormat=0,this.id=yu(),this.expired=(a=e.expired)!=null?a:null,this.transport=e.transportType,this.clockOffset=e.clockOffset,this._cachedCodecSupport=new pn([]),this.periods=e.periods.map(o=>new ht(o,this._cachedCodecSupport,r)).sort((o,s)=>o.start-s.start),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=i,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 ee("MANIFEST_INCOMPATIBLE_CODECS_ERROR","An Adaptation contains only incompatible codecs.",{tracks:t.map(vt)}):null}getPeriod(e){return j(this.periods,t=>e===t.id)}getPeriodForTime(e){return Eo(this,e)}getNextPeriod(e){return j(this.periods,t=>t.start>e)}getPeriodAfter(e){return _o(this,e)}getUrls(){return this.uris}replace(e){this._performUpdate(e,0)}update(e){this._performUpdate(e,1)}getMinimumSafePosition(){return bo(this)}getLivePosition(){return So(this)}getMaximumSafePosition(){return yo(this)}updateCodecSupportList(e){this._cachedCodecSupport=e}updateRepresentationsDeciperability(e){let t=Tu(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 a=i.getAdaptation(r.adaptation.id);if(a===void 0)continue;let o=a.getRepresentation(r.representation.id);o!==void 0&&(o.shouldBeAvoided=!0,t.push({manifest:this,period:i,adaptation:a,representation:o}))}t.length>0&&this.trigger("representationAvoidanceUpdate",t)}getAdaptations(){rt("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 a=t[i];r.push(...a)}return r}getAdaptationsForType(e){rt("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 rt("manifest.getAdaptation(id) is deprecated. Please use manifest.period[].getAdaptation(id) instead"),j(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 qo(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=Ko(this.periods,e.periods);else{this.timeBounds.maximumTimeData=e.timeBounds.maximumTimeData,this.updateUrl=e.uris[0],r=jo(this.periods,e.periods);let i=this.getMinimumSafePosition();for(;this.periods.length>0;){let a=this.periods[0];if(a.end===void 0||a.end>i)break;this.periods.shift()}}this.updateCodecSupport(),this.adaptations=this.periods[0]===void 0?{}:this.periods[0].adaptations,this.trigger("manifestUpdate",r)}};function Tu(n,e){let t=[];for(let r of n.periods)for(let i of r.getAdaptations()){let a=!0;for(let o of i.representations){let s={manifest:n,period:r,adaptation:i,representation:o},d=e(s);d!==!1&&(a=!1),d!==o.decipherable&&(t.push(s),o.decipherable=d,d===!0?i.supportStatus.isDecipherable=!0:d===void 0&&i.supportStatus.isDecipherable===!1&&(i.supportStatus.isDecipherable=void 0),c.debug("manifest",`Decipherability changed for "${o.id}"`,`(${o.bitrate})`,String(o.decipherable)))}a&&(i.supportStatus.isDecipherable=!1)}return t}function it(n,e){return n.segment.id===e.segment.id&&n.representation.uniqueId===e.representation.uniqueId}function He(n){if(v(n))return null;let{period:e,adaptation:t,representation:r,segment:i}=n;return{t:t.type[0],p:e.id,a:t.id,r:r.id,ss:i.isInit?null:i.time,se:i.isInit||!i.complete?null:i.end}}var It=hn;var xt=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 Ar(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,a){t.isCancelled()||a.clearSignal.isCancelled()||r.onUpdate(i,{clearSignal:a.clearSignal,emitCurrentValue:a.includeLastObservation})},deriveReadOnlyObserver(i){return Ar(this,i,t)}}}var In=class{constructor(e,t,r,i){this._src=e,this._contentId=t,this._messageSender=r,this._cancelSignal=i}getCurrentTime(){}getReadyState(){}getIsPaused(){}getReference(){return this._src}setPlaybackRate(e){this._messageSender({type:"update-playback-rate",contentId:this._contentId,value:e})}getPlaybackRate(){}listen(e,t){this._cancelSignal.isCancelled()||t.clearSignal.isCancelled()||this._src.onUpdate(e,{clearSignal:t.clearSignal,emitCurrentValue:t.includeLastObservation})}deriveReadOnlyObserver(e){return Ar(this,e,this._cancelSignal)}};var at=typeof queueMicrotask=="function"?queueMicrotask:function(e){Promise.resolve().then(e,()=>e())};var kt=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],a=!1;for(;!a&&t<this._array.length;)this._sortingFn(i,this._array[t])<0?(this._array.splice(t,0,i),a=!0):t++;a||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 j(this._array,e)}has(e){return fe(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 bn=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)}};var Eu=.016666666666666666;function Yo(n,e){return Math.abs(n-e)<Eu}function $o(n,e){let t=Math.min(n.start,e.start),r=Math.max(n.end,e.end);return{start:t,end:r}}function _u(n){for(let e=0;e<n.length;e++){let t=n[e];t.start===t.end&&n.splice(e--,1)}return n}function Ru(n){for(let e=1;e<n.length;e++){let t=n[e-1],r=n[e];if(Zo(t,r)){let i=$o(t,r);n.splice(--e,2,i)}}return n}function xi(n,e){return n.end<=e.start}function Qo({start:n,end:e},t){return n<=t&&t<e}function Xo(n,e){return Qo(n,e.start)||n.start<e.end&&e.end<n.end||Qo(e,n.start)}function Zo(n,e){return Yo(e.start,n.end)||Yo(e.end,n.start)}function ki(n){let e=[];for(let t=0;t<n.length;t++)e.push({start:n.start(t),end:n.end(t)});return e}function Pu(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 Jo(n,e){let t=null,r=[];for(let i=0;i<n.length;i++){let a=n[i].start,o=n[i].end;e<a||e>=o?r.push({start:a,end:o}):t={start:a,end:o}}return{outerRanges:r,innerRange:t}}function xr(n,e){let t=Pu(n,e);return t!==null?t.end-e:1/0}function bt(n,e){if(e.start===e.end)return n;let t=e,r=0;for(;r<n.length;r++){let i=n[r],a=Xo(t,i),o=Zo(t,i);if(a||o)t=$o(t,i),n.splice(r--,1);else if(r===0){if(xi(t,n[0]))break}else if(xi(n[r-1],t)&&xi(t,i))break}return n.splice(r,0,t),Ru(_u(n))}function vu(n,e){let t=[];for(let r=0;r<e.length;r++)Xo(n,e[r])&&t.push(e[r]);return t}function kr(n,e){let t=[];for(let r=0;r<n.length;r++){let i=n[r],a=[],o=vu(i,e);if(o.length>0)for(let s=0;s<o.length;s++){let d=o[s];a.push({start:Math.max(i.start,d.start),end:Math.min(i.end,d.end)})}if(a.length===0)t.push(i);else{let s=i.start;for(let d=0;d<a.length;d++)a[d].start>s&&t.push({start:s,end:a[d].start}),s=a[d].end;s<i.end&&t.push({start:s,end:i.end})}}return t}function Mr({segmentSink:n,playbackObserver:e,maxBufferBehind:t,maxBufferAhead:r},i){let a,o=[];e.listen(d=>{a=d.position.getWanted(),o=d.buffered[n.bufferType],s()},{includeLastObservation:!0,clearSignal:i});function s(){o!==null&&Cu(n,a,o,t.getValue(),r.getValue(),i).catch(d=>{if(i.isCancelled()&&z.isCancellationError(d))return;let u=d instanceof Error?d.message:"Unknown error";c.error("Stream","Could not run BufferGarbageCollector:",u)})}t.onUpdate(s,{clearSignal:i}),r.onUpdate(s,{clearSignal:i})}async function Cu(n,e,t,r,i,a){if(!isFinite(r)&&!isFinite(i))return Promise.resolve();let o=[],{innerRange:s,outerRanges:d}=Jo(t,e),u=()=>{if(isFinite(r)){for(let l of d)e-r>=l.end?o.push(l):e>=l.end&&e-r>l.start&&e-r<l.end&&o.push({start:l.start,end:e-r});v(s)||e-r>s.start&&o.push({start:s.start,end:e-r})}},f=()=>{if(isFinite(i)){for(let l of d)e+i<=l.start?o.push(l):e<=l.start&&e+i<l.end&&e+i>l.start&&o.push({start:e+i,end:l.end});v(s)||e+i<s.end&&o.push({start:e+i,end:s.end})}};u(),f();for(let l of o)if(l.start<l.end){if(c.debug("Stream","cleaning range from SegmentSink",{start:l.start,end:l.end}),a.cancellationError!==null)throw a.cancellationError;await n.removeBuffer(l.start,l.end)}}var Sn=class{constructor(e,t){this._history=[],this._lifetime=e,this._maxHistoryLength=t}addBufferedSegment(e,t){let r=F();this._history.push({date:r,buffered:t,context:e}),this._cleanHistory(r)}getHistoryFor(e){return this._history.filter(t=>it(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 yn=class{constructor(){let{BUFFERED_HISTORY_RETENTION_TIME:e,BUFFERED_HISTORY_MAXIMUM_ENTRIES:t}=L.getCurrent();this._inventory=[],this._bufferedHistory=new Sn(e,t)}reset(){this._inventory.length=0}synchronizeBuffered(e){var d,u,f,l,m,g,h;let t=this._inventory,r=0,i=t[0],{MINIMUM_SEGMENT_SIZE:a}=L.getCurrent(),o=i==null?void 0:i.infos.adaptation.type;if(c.hasLevel("DEBUG")){let b=e.map(p=>`${p.start}-${p.end}`).join(",");c.debug("SI",`synchronizing ${o!=null?o:"unknown"} buffered ranges:`,b)}let s=e.length;for(let b=0;b<s;b++){if(i===void 0)return;let p=e[b].start,S=e[b].end;if(S-p<a){c.warn("SI","skipped range when synchronizing because it was too small",{t:o,rangeStart:p,rangeEnd:S});continue}let T=r;for(;i!==void 0&&((d=i.bufferedEnd)!=null?d:i.end)-p<a;)i=t[++r];let R=null,E=r-T;if(E>0){let P=t[T+E-1];R={end:(u=P.bufferedEnd)!=null?u:P.end,precizeEnd:P.precizeEnd},c.debug("SI",`${E} segments GCed.`,{t:o});let x=t.splice(T,E);for(let A of x)A.bufferedStart===void 0&&A.bufferedEnd===void 0&&A.status!==2&&this._bufferedHistory.addBufferedSegment(A.infos,null);r=T}if(i===void 0)return;if(S-((f=i.bufferedStart)!=null?f:i.start)>=a){if(Au(i,p,R,o),r===t.length-1){ts(i,S,o);return}i=t[++r];let P=(l=i.bufferedStart)!=null?l:i.start,x=(m=i.bufferedEnd)!=null?m:i.end,A=b<s-1?e[b+1].start:void 0;for(;i!==void 0&&!(S<P||S-P<a&&x-S>=a||A!==void 0&&S-P<x-A);){let k=t[r-1];k.bufferedEnd===void 0&&(i.precizeStart?k.bufferedEnd=i.start:k.infos.segment.complete?k.bufferedEnd=k.end:k.bufferedEnd=i.start,c.debug("SI","calculating buffered end of contiguous segment",{t:o,prevSegmentBufferedEnd:k.bufferedEnd,pse:k.end})),i.bufferedStart=k.bufferedEnd,i=t[++r],i!==void 0&&(P=(g=i.bufferedStart)!=null?g:i.start,x=(h=i.bufferedEnd)!=null?h:i.end)}}let C=t[r-1];C!==void 0&&ts(C,S,o)}if(!v(i)){let{SEGMENT_SYNCHRONIZATION_DELAY:b}=L.getCurrent(),p=F();for(let S=r;S<t.length;S++){let T=t[S];p-T.insertionTs>=b&&(c.debug("SI","A segment at the end has been completely GCed",He(T.infos)),T.bufferedStart===void 0&&T.bufferedEnd===void 0&&T.status!==2&&this._bufferedHistory.addBufferedSegment(T.infos,null),t.splice(S,1),S--)}}o!==void 0&&c.hasLevel("DEBUG")&&c.debug("SI",`current ${o} inventory timeline:
|
|
2
2
|
`+xu(this._inventory))}insertChunk({period:e,adaptation:t,representation:r,segment:i,chunkSize:a,start:o,end:s},d,u){if(i.isInit)return;let f=t.type;if(o>=s){c.warn("SI","Invalid chunked inserted: starts before it ends",{t:f,start:o,end:s});return}let l=this._inventory,m={status:d?0:2,insertionTs:u,chunkSize:a,splitted:!1,start:o,end:s,precizeStart:!1,precizeEnd:!1,bufferedStart:void 0,bufferedEnd:void 0,infos:{segment:i,period:e,adaptation:t,representation:r}};for(let h=l.length-1;h>=0;h--){let b=l[h];if(b.start<=o)if(b.end<=o){for(c.debug("SI","Pushing segment strictly after previous one.",{t:f,pse:b.end,ss:o}),this._inventory.splice(h+1,0,m),h+=2;h<l.length&&l[h].start<m.end;){if(l[h].end>m.end){c.debug("SI","Segment pushed updates the start of the next one",{t:f,pss:l[h].start,ss:o,se:s}),l[h].start=m.end,l[h].bufferedStart=void 0,l[h].precizeStart=l[h].precizeStart&&m.precizeEnd;return}c.debug("SI","Segment pushed removes the next one",{t:f,ss:o,se:s,pss:l[h].start,pse:l[h].end}),l.splice(h,1)}return}else if(b.start===o)if(b.end<=s){for(c.debug("SI","Segment pushed replace another one",{t:f,ss:o,se:s,pss:b.start,pse:b.end}),this._inventory.splice(h,1,m),h+=1;h<l.length&&l[h].start<m.end;){if(l[h].end>m.end){c.debug("SI","Segment pushed updates the start of the next one",{t:f,ss:o,se:s,pss:l[h].start,pse:l[h].end}),l[h].start=m.end,l[h].bufferedStart=void 0,l[h].precizeStart=l[h].precizeStart&&m.precizeEnd;return}c.debug("SI","Segment pushed removes the next one",{t:f,ss:o,se:s,pss:l[h].start,pse:l[h].end}),l.splice(h,1)}return}else{c.debug("SI","Segment pushed ends before another with the same start",{t:f,ss:o,se:s,pse:b.end}),l.splice(h,0,m),b.start=m.end,b.bufferedStart=void 0,b.precizeStart=b.precizeStart&&m.precizeEnd;return}else if(b.end<=m.end){for(c.debug("SI","Segment pushed updates end of previous one",{t:f,ss:o,se:s,pss:b.start,pse:b.end}),this._inventory.splice(h+1,0,m),b.end=m.start,b.bufferedEnd=void 0,b.precizeEnd=b.precizeEnd&&m.precizeStart,h+=2;h<l.length&&l[h].start<m.end;){if(l[h].end>m.end){c.debug("SI","Segment pushed updates the start of the next one",{t:f,ss:o,se:s,pss:l[h].start}),l[h].start=m.end,l[h].bufferedStart=void 0,l[h].precizeStart=l[h].precizeStart&&m.precizeEnd;return}c.debug("SI","Segment pushed removes the next one",{t:f,ss:o,se:s,pss:l[h].start,pse:l[h].end}),l.splice(h,1)}return}else{c.warn("SI","Segment pushed is contained in a previous one",{t:f,ss:o,se:s,pss:b.start,pse:b.end});let p={status:b.status,insertionTs:b.insertionTs,chunkSize:b.chunkSize,splitted:!0,start:m.end,end:b.end,precizeStart:b.precizeStart&&b.precizeEnd&&m.precizeEnd,precizeEnd:b.precizeEnd,bufferedStart:void 0,bufferedEnd:b.end,infos:b.infos};b.end=m.start,b.splitted=!0,b.bufferedEnd=void 0,b.precizeEnd=b.precizeEnd&&m.precizeStart,l.splice(h+1,0,m),l.splice(h+2,0,p);return}}let g=this._inventory[0];if(g===void 0){c.debug("SI","first segment pushed",{t:f,ss:o,se:s}),this._inventory.push(m);return}if(g.start>=s)c.debug("SI","Segment pushed comes before all previous ones",{t:f,ss:o,se:s,pss:g.start}),this._inventory.splice(0,0,m);else if(g.end<=s){for(c.debug("SI","Segment pushed starts before and completely recovers the previous first one",{t:f,ss:o,se:s,pss:g.start,pse:g.end}),this._inventory.splice(0,1,m);l.length>1&&l[1].start<m.end;){if(l[1].end>m.end){c.debug("SI","Segment pushed updates the start of the next one",{t:f,ss:o,se:s,pss:l[1].start,pse:l[1].end}),l[1].start=m.end,l[1].bufferedStart=void 0,l[1].precizeStart=m.precizeEnd;return}c.debug("SI","Segment pushed removes the next one",{t:f,ss:o,se:s,pss:l[1].start,pse:l[1].end}),l.splice(1,1)}return}else{c.debug("SI","Segment pushed start of the next one",f,{ss:o,se:s,pss:g.start,pse:g.end}),g.start=s,g.bufferedStart=void 0,g.precizeStart=m.precizeEnd,this._inventory.splice(0,0,m);return}}completeSegment(e){if(e.segment.isInit)return;let t=this._inventory,r=[];for(let i=0;i<t.length;i++)if(it(t[i].infos,e)){let a=!1;r.length>0&&(a=!0,r.length===1&&(c.warn("SI","Completed Segment is splitted.",He(e)),r[0].splitted=!0));let o=i,s=t[i].chunkSize;for(i+=1;i<t.length&&it(t[i].infos,e);){let m=t[i].chunkSize;s!==void 0&&m!==void 0&&(s+=m),i++}let d=i-1,u=d-o,f=t[d].end,l=t[d].bufferedEnd;u>0&&(this._inventory.splice(o+1,u),i-=u),this._inventory[o].status===0&&(this._inventory[o].status=1),this._inventory[o].chunkSize=s,this._inventory[o].end=f,this._inventory[o].bufferedEnd=l,this._inventory[o].splitted=a,r.push(this._inventory[o])}if(r.length===0)c.warn("SI","Completed Segment not found",He(e));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}):c.debug("SI","buffered range not known after sync. Skipping history.",{ss:i.start,se:i.end})}getInventory(){return this._inventory}getHistoryFor(e){return this._bufferedHistory.getHistoryFor(e)}};function Mi(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:a}=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(a,r/3))}function es(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:a}=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(a,r/3)}function Au(n,e,t,r){let{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:i,MISSING_DATA_TRIGGER_SYNC_DELAY:a,SEGMENT_SYNCHRONIZATION_DELAY:o}=L.getCurrent();if(n.bufferedStart!==void 0)n.bufferedStart<e&&(c.debug("SI","Segment partially GCed at the start",{t:r,firstsbs:n.bufferedStart,rs:e}),n.bufferedStart=e),!n.precizeStart&&Mi(n)&&(n.start=n.bufferedStart,n.precizeStart=!0);else if(n.precizeStart)c.debug("SI","buffered start is precize start",{t:r,firstss:n.start}),n.bufferedStart=n.start;else if(t!==null&&t.end>e&&(t.precizeEnd||n.start-t.end<=i))c.debug("SI","buffered start is end of previous segment",{t:r,rs:e,firstss:n.start,lastdelse:t.end}),n.bufferedStart=t.end,Mi(n)&&(n.start=t.end,n.precizeStart=!0);else if(n.start-e<=i){let s=F();if(n.start-e>=a&&s-n.insertionTs<o){c.debug("SI","Ignored bufferedStart synchronization",{t:r,rs:e,firstss:n.start,delta:s-n.insertionTs});return}c.debug("SI","found true buffered start",{t:r,rs:e,firstss:n.start}),n.bufferedStart=e,Mi(n)&&(n.start=e,n.precizeStart=!0)}else if(e<n.start)c.debug("SI","range start too far from expected start",{t:r,rs:e,firstss:n.start}),n.bufferedStart=n.start;else{let s=F();if(n.start-e>=a&&s-n.insertionTs<o){c.debug("SI","Ignored bufferedStart synchronization",{t:r,rs:e,firstss:n.start,delta:s-n.insertionTs});return}c.debug("SI","Segment appears immediately garbage collected at the start",{t:r,rs:e,firstss:n.start}),n.bufferedStart=e}}function ts(n,e,t){let{MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE:r,MISSING_DATA_TRIGGER_SYNC_DELAY:i,SEGMENT_SYNCHRONIZATION_DELAY:a}=L.getCurrent();if(n.bufferedEnd!==void 0)n.bufferedEnd>e&&(c.debug("SI","Segment partially GCed at the end",{t,lastsbe:n.bufferedEnd,re:e}),n.bufferedEnd=e),!n.precizeEnd&&e-n.end<=r&&es(n)&&(n.precizeEnd=!0,n.end=e);else if(n.precizeEnd)c.debug("SI","buffered end is precize end",{t,lastse:n.end}),n.bufferedEnd=n.end;else if(e-n.end<=r||!n.infos.segment.complete){let o=F();if(e-n.end>=i&&o-n.insertionTs<a){c.debug("SI","Ignored bufferedEnd synchronization",{t,re:e,lastse:n.end,delta:o-n.insertionTs});return}c.debug("SI","found true buffered end",{t,re:e,lastse:n.end}),n.bufferedEnd=e,es(n)&&(n.end=e,n.precizeEnd=!0)}else if(e>n.end)c.debug("SI","range end too far from expected end",{t,re:e,lastse:n.end}),n.bufferedEnd=n.end;else{let o=F();if(e-n.end>=i&&o-n.insertionTs<a){c.debug("SI","Ignored bufferedEnd synchronization",{t,re:e,lastse:n.end,delta:o-n.insertionTs});return}c.debug("SI","Segment appears immediately garbage collected at the end",{t,lastsbe:n.bufferedEnd,re:e}),n.bufferedEnd=e}}function xu(n){let e=.016666666666666666,t={},r=[],i=null,a=null;function o(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,f=d.infos.representation.id,l=t[u],m;if(l===void 0)m=o(d.infos),t[u]={[f]:m};else{let g=l[f];g===void 0?(m=o(d.infos),l[f]=m):m=g}i===null?s+=`${d.bufferedStart.toFixed(2)}|${m}|`:a===m?i.bufferedEnd+e<d.bufferedStart&&(s+=`${i.bufferedEnd.toFixed(2)} ~ ${d.bufferedStart.toFixed(2)}|${m}|`):s+=`${i.bufferedEnd.toFixed(2)} ~ ${d.bufferedStart.toFixed(2)}|${m}|`,i=d,a=m}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 zt(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 Wt(n,e){for(let t of n)if(t.infos.period.start>e.start)return t;return null}var ns=yn;var Vt=class{constructor(){this._segmentInventory=new ns}synchronizeInventory(e){this._segmentInventory.synchronizeBuffered(e)}getLastKnownInventory(){return this._segmentInventory.getInventory()}getSegmentHistory(e){return this._segmentInventory.getHistoryFor(e)}};var Tn=class extends Vt{constructor(e,t,r){super(),c.info("Stream","calling `mediaSource.addSourceBuffer`",{codec: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){rs(t),this._initSegmentsMap.set(e,t)}freeInitSegment(e){this._initSegmentsMap.delete(e)}async pushChunk(e){rs(e.data.chunk),c.debug("Stream","queuing push order",He(e.inventoryInfos));let t=this._getActualDataToPush(e.data);t.length===0&&t.push(new Uint8Array);let r=Promise.all(t.map(o=>{let{codec:s,timestampOffset:d,appendWindow:u}=e.data;return c.debug("Stream","now pushing",He(e.inventoryInfos)),this._sourceBuffer.appendBuffer(o,{codec:s,timestampOffset:d,appendWindow:u})}));this._addToOperationQueue(r,{type:0,value:e});let i;try{i=await r}catch(o){throw this._segmentInventory.insertChunk(e.inventoryInfos,!1,F()),o}e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,F());let a=i[i.length-1];return this._segmentInventory.synchronizeBuffered(a),a}async removeBuffer(e,t){c.debug("Stream","queuing remove order",{bufferType:this.bufferType,start:e,end: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(e){try{c.debug("Stream","Calling `dispose` on the SourceBufferInterface"),this._sourceBuffer.dispose(e)}catch(t){c.debug("Stream",`Failed to dispose a ${this.bufferType} SourceBufferInterface:`,t instanceof Error?t:"Unknown Error")}}_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),a=new Uint8Array(i);a.set(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer)),r=a,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 a=this._pendingOperations.indexOf(r);a>=0&&this._pendingOperations.splice(a,1)};e.then(i,i)}};function rs(n){if(I.CURRENT_ENV!==I.PRODUCTION&&(typeof n!="object"||n!==null&&!(n instanceof ArrayBuffer)&&!(n.buffer instanceof ArrayBuffer)))throw new Error("Invalid data given to the AudioVideoSegmentSink")}var wr=Tn;var En=class extends Vt{constructor(e){c.debug("Stream","Creating TextSegmentSink"),super(),this.bufferType="text",this._sender=e,this._pendingOperations=[],this._sender.reset()}declareInitSegment(e){c.warn("Stream","Declaring initialization segment for Text SegmentSink",{uniqueId:e})}freeInitSegment(e){c.warn("Stream","Freeing initialization segment for Text SegmentSink",{uniqueId:e})}async pushChunk(e){let{data:t}=e;Mu(t.chunk);let r=this._sender.pushTextData(de(J({},t),{chunk:t.chunk}));this._addToOperationQueue(r,{type:0,value:e});let i=await r;return e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,F()),this._segmentInventory.synchronizeBuffered(i),i}async removeBuffer(e,t){let r=this._sender.remove(e,t);this._addToOperationQueue(r,{type:1,value:{start:e,end:t}});let i=await r;return this._segmentInventory.synchronizeBuffered(i),i}async signalSegmentComplete(e){if(this._pendingOperations.length>0){let{promise:t}=this._pendingOperations[this._pendingOperations.length-1];this._addToOperationQueue(t,{type:2,value:e});try{await t}catch(r){}}this._segmentInventory.completeSegment(e)}getPendingOperations(){return this._pendingOperations.map(e=>e.operation)}dispose(e){c.debug("Stream","Disposing TextSegmentSink"),this._sender.stop(e)}_addToOperationQueue(e,t){let r={operation:t,promise:e};this._pendingOperations.push(r);let i=()=>{let a=this._pendingOperations.indexOf(r);a>=0&&this._pendingOperations.splice(a,1)};e.then(i,i)}};function Mu(n){if(I.CURRENT_ENV!==I.PRODUCTION){if(typeof n!="object"||n===null||v(n.data))throw new Error("Invalid format given to a TextSegmentSink");if(!Ou(n))throw new Error("Invalid format given to a TextSegmentSink");if(typeof n.data!="string"&&typeof n.data.byteLength!="number")throw new Error("Invalid format given to a TextSegmentSink")}}function Ou(n){return!(typeof n!="object"||n===null||typeof n.type!="string"||n.language!==void 0&&typeof n.language!="string"||n.initTimescale!==null&&typeof n.initTimescale!="number"||n.start!==void 0&&typeof n.start!="number"||n.end!==void 0&&typeof n.end!="number")}I.CURRENT_ENV===I.DEV&&(wu=function(e){function t(r){}});var wu;var is=En;var Du=["audio","video","text"],_n=class n{static isNative(e){return as(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():Ct(e,t=>{let r=O,i=()=>{let a=this._onNativeBufferAddedOrDisabled.indexOf(r);a>=0&&this._onNativeBufferAddedOrDisabled.splice(a,1)};return r=()=>{this._areNativeBuffersUsable()&&(i(),t())},this._onNativeBufferAddedOrDisabled.push(r),i})}disableSegmentSink(e){let t=this._initializedSegmentSinks[e];if(t===null){c.warn("Stream",`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()),Se(this._onNativeBufferAddedOrDisabled.length===0))}createSegmentSink(e,t){let r=this._initializedSegmentSinks[e];if(as(e)){if(!v(r))return r instanceof wr&&r.codec!==t?c.warn("Stream","Reusing native SegmentSink with codec",r.codec,"for codec",t):c.info("Stream","Reusing native SegmentSink with codec",t),r;c.info("Stream","Adding native SegmentSink with codec",t);let a=e==="audio"?"audio":"video",o=new wr(a,t,this._mediaSource);return this._initializedSegmentSinks[e]=o,this._onNativeBufferAddedOrDisabled.slice().forEach(s=>s()),Se(this._onNativeBufferAddedOrDisabled.length===0),o}if(!v(r))return c.info("Stream","Reusing a previous custom SegmentSink",{bufferType:e}),r;let i;if(e==="text"){if(c.info("Stream","Creating a new text SegmentSink"),this._textInterface===null)throw new Error("HTML Text track feature not activated");return i=new is(this._textInterface),this._initializedSegmentSinks.text=i,i}throw c.error("Stream","Unknown buffer type:",{bufferType:e}),new ee("BUFFER_TYPE_UNKNOWN","The player wants to create a SegmentSink of an unknown type.")}disposeSegmentSink(e,t){let r=this._initializedSegmentSinks[e];if(v(r)){c.warn("Stream","Trying to dispose a SegmentSink that does not exist",{bufferType:e});return}c.info("Stream","Aborting SegmentSink",{bufferType:e}),r.dispose(t),delete this._initializedSegmentSinks[e]}disposeAll(e){Du.forEach(t=>{this.getStatus(t).type==="initialized"&&this.disposeSegmentSink(t,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,a;let t=(i=this._initializedSegmentSinks[e])==null?void 0:i.getLastKnownInventory(),r;if(t!==void 0){r=0;for(let o of t){if(o.chunkSize===void 0||r===void 0){r=void 0;break}r+=o.chunkSize}}return{bufferType:e,sizeEstimate:r,codec:(a=this._initializedSegmentSinks[e])==null?void 0:a.codec,segmentInventory:t==null?void 0:t.map(o=>de(J({},o),{infos:Bu(o.infos)}))}}getSegmentSinksMetrics(){return{segmentSinks:{audio:this.createSegmentSinkMetricsForType("audio"),video:this.createSegmentSinkMetricsForType("video"),text:this.createSegmentSinkMetricsForType("text")}}}};function as(n){return n==="audio"||n==="video"}function Bu(n){return{adaptation:n.adaptation.getMetadataSnapshot(),period:n.period.getMetadataSnapshot(),representation:n.representation.getMetadataSnapshot()}}var St=_n;var Rn=class{constructor({drmSystemId:e,representation:t,notify:r}){if(this._hasSentEncryptionData=!1,this._representation=t,this._notify=r,e!==void 0){let i=t.getEncryptionData(e);i.length>0&&i.every(a=>a.keyIds!==void 0)&&(this._hasSentEncryptionData=!0,r(i))}}onNewProtectionData(e){for(let t of e)this._representation.addProtectionData(t.initDataType,t.keyId,t.initData);if(!this._hasSentEncryptionData){let t=this._representation.getAllEncryptionData();t.length>0&&(this._notify(t),this._hasSentEncryptionData=!0)}}};function Oi(n,e,t,r,i){let{period:a,adaptation:o,representation:s}=n,d=Nu(i,e);if(d===null){if(t===null){if(r&&a.end!==void 0&&e.end>=a.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:(c.debug("Stream","current discontinuity encountered",{bufferType:o.type,nextSegmentTime:u.bufferedStart,checkStartTime:e.start}),{start:void 0,end:l})}let f=Uu(i,e,d+1);if(f!==null){let l=i[f-1],m=i[f];if(t===null||m.infos.segment.end<=t){if(!r&&s.index.awaitSegmentBetween(l.infos.segment.end,m.infos.segment.time)!==!1)return null;let g=l.bufferedEnd,h=m.bufferedStart;return c.debug("Stream","future discontinuity encountered",{bufferType:o.type,discontinuityStart:g,discontinuityEnd:h}),{start:g,end:h}}}if(t===null){if(r&&a.end!==void 0){if(e.end<a.end)return null;let l=Lu(i,a.end);if(l!==null){let m=i[l];if(m.bufferedEnd!==void 0&&m.bufferedEnd<a.end)return c.debug("Stream","discontinuity encountered at the end of the current period",{bufferType:o.type,segmentsEndTimeFromPeriod:m.bufferedEnd,periodEnd:a.end}),{start:m.bufferedEnd,end:null}}}if(a.end!==void 0&&e.end>=a.end)return null;for(let l=i.length-1;l>=0;l--){let m=i[l];if(m.bufferedStart===void 0)break;if(m.bufferedStart<e.end){if(m.bufferedEnd!==void 0&&m.bufferedEnd<e.end){let g=s.index.checkDiscontinuity(e.end);if(g!==null)return{start:m.bufferedEnd,end:g}}return null}}}return null}function Nu(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 Uu(n,e,t){if(t<=0)return c.error("Stream","Asked to check a discontinuity before the first chunk."),null;for(let r=t;r<n.length;r++){let i=n[r],a=n[r-1];if(i.bufferedStart===void 0||a.bufferedEnd===void 0||i.bufferedStart>=e.end)return null;if(i.bufferedStart-a.bufferedEnd>0)return r}return null}function Lu(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 wi({bufferedSegments:n,content:e,currentPlaybackTime:t,fastSwitchThreshold:r,getBufferedHistory:i,neededRange:a,segmentsBeingPushed:o,maxBufferSize:s}){let{adaptation:d,representation:u}=e,f=Fu(n,o,s),l=u.index.getSegments(a.start,a.end-a.start),m=n.filter(C=>!os(C.infos,e,t,r)),g=Ku(m,a,i),{MINIMUM_SEGMENT_SIZE:h,MIN_BUFFER_AHEAD:b}=L.getCurrent(),p=!1,S=Math.min(1/60,h),T=!1,R=[];return{segmentsToLoad:l.filter(C=>{let P=H({segment:C},e);if(o.length>0&&o.some(B=>it(P,B)))return!1;let{duration:x,time:A,end:k}=C;if(C.isInit)return!0;if(p)return R.push(C),!1;if(C.complete&&x<h||o.length>0&&o.some(B=>{if(B.period.id!==e.period.id||B.adaptation.id!==e.adaptation.id)return!1;let{segment:_}=B;if(_.time-S>A)return!1;if(_.complete){if(_.end+S<k)return!1}else if(Math.abs(A-_.time)>A)return!1;return!os(B,P,t,r)}))return!1;for(let W of g){let B=W.infos.period.id===e.period.id;if(W.status===1&&B){let _=W.infos.segment;if(A-_.time>-S){if(_.complete){if(_.end-k>-S)return!1}else if(Math.abs(A-_.time)<S)return!1}}}let N=x*e.representation.bitrate;if(f-N<0&&(T=!0,A>a.start+b))return p=!0,R.push(C),!1;let w=i(P);if(w.length>1){let W=w[w.length-1],B=w[w.length-2];if(W.buffered===null&&B.buffered===null)return c.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.",{bufferType:d.type,representationId:u.id,segmentTime:C.time}),!1}for(let W=0;W<g.length;W++){let B=g[W];if(B.end+S>A){let _=B.start>A+S||zu(g,W).end<k-S;return _&&(f-=N),_}}return f-=N,!0}),segmentsOnHold:R,isBufferFull:T}}function Fu(n,e,t){let r=t*8e3;return r-=e.reduce((i,a)=>{let{bitrate:o}=a.representation,{duration:s}=a.segment;return i+o*s},0),n.reduce((i,a)=>a.chunkSize!==void 0?i-a.chunkSize*8:i,r)}function zu(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 os(n,e,t,r){let{CONTENT_REPLACEMENT_PADDING:i}=L.getCurrent();if(n.period.id!==e.period.id)return!1;let{segment:a}=n;return a.time<t+i?!1:n.adaptation.id!==e.adaptation.id?!0:Wu(n.representation,e.representation,r)}function Wu(n,e,t){let r=n.bitrate,{BITRATE_REBUFFERING_RATIO:i}=L.getCurrent();if(t===void 0){let a=r*i;return e.bitrate>a}return r<t&&e.bitrate>r}function Vu(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?(c.info("Stream","The start of the wanted segment has been garbage collected",{segmentStart:n.start,currentStartInBuffer:n.bufferedStart}),!0):!1}function qu(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?(c.info("Stream","The end of the wanted segment has been garbage collected",{segmentEnd:n.end,currentEndInBuffer:n.bufferedEnd}),!0):!1}function Gu(n,e){var o,s;if(n.length<2)return!0;let r=(o=n[n.length-1].buffered)==null?void 0:o.start;if(e!==void 0&&r!==void 0&&e-r>.05)return!0;let a=(s=n[n.length-2].buffered)==null?void 0:s.start;return a===void 0||r===void 0?!0:Math.abs(a-r)>.01}function Hu(n,e){var o,s;if(n.length<2)return!0;let r=(o=n[n.length-1].buffered)==null?void 0:o.end;if(e!==void 0&&r!==void 0&&r-e>.05)return!0;let a=(s=n[n.length-2].buffered)==null?void 0:s.end;return a===void 0||r===void 0?!0:Math.abs(a-r)>.01}function Ku(n,e,t){return n.filter((r,i,a)=>{let o=i===0?null:a[i-1],s=i>=a.length-1?null:a[i+1],d=null;if(Vu(r,o,e.start)){if(d=t(r.infos),Gu(d,r.bufferedStart))return!1;c.debug("Stream","skipping segment gc-ed at the start",{segmentStart:r.start,currentStartInBuffer:r.bufferedStart})}if(qu(r,s,e.end)){if(d=d!=null?d:t(r.infos),Hu(d,r.bufferedEnd))return!1;c.debug("Stream","skipping segment gc-ed at the end",{segmentEnd:r.end,currentEndInBuffer:r.bufferedEnd})}return!0})}function Pn(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 Di(n,e,t,r,i,a,o){var A,k,N;let{representation:s}=n,d=(k=(A=t.getIsPaused())!=null?A:t.getReference().getValue().paused.pending)!=null?k:t.getReference().getValue().paused.last,u=(N=t.getPlaybackRate())!=null?N:t.getReference().getValue().speed,f=e;(d===void 0||u===void 0||d||u<=0)&&(f-=.1);let l=ju(n,f,i),m=s.index.shouldRefresh(l.start,l.end),g=o.getPendingOperations().filter(w=>w.type===2).map(w=>w.value),h=o.getLastKnownInventory(),b=t.getCurrentTime();b===void 0&&(b=t.getReference().getValue().position.getWanted());let p=o.getSegmentHistory.bind(o),{segmentsToLoad:S,segmentsOnHold:T,isBufferFull:R}=wi({content:n,bufferedSegments:h,currentPlaybackTime:b,fastSwitchThreshold:r,getBufferedHistory:p,neededRange:l,segmentsBeingPushed:g,maxBufferSize:a}),E=S.map(w=>({priority:Pn(w.time,f),segment:w})),C=s.index.isInitialized()&&!s.index.isStillAwaitingFutureSegments()&&l.hasReachedPeriodEnd&&E.length===0&&T.length===0,P=null;return g.length>0&&(P=Math.min(...g.map(w=>w.segment.time))),T.length>0&&(P=P!==null?Math.min(P,T[0].time):T[0].time),E.length>0&&(P=P!==null?Math.min(P,E[0].segment.time):E[0].segment.time),{imminentDiscontinuity:Oi(n,l,P,C,h),hasFinishedLoading:C,neededSegments:E,isBufferFull:R,shouldRefreshManifest:m}}function ju(n,e,t){var l;let r,{manifest:i,period:a,representation:o}=n,s=o.index.getLastAvailablePosition(),d=o.index;!v(s)&&St.isNative(n.adaptation.type)&&e>=s&&d.isInitialized()&&!d.isStillAwaitingFutureSegments()&&Yu(i,a,e)?r=s-1:r=e-.1;let u=r+t,f;return!o.index.isInitialized()||o.index.isStillAwaitingFutureSegments()||a.end===void 0?f=!1:s===void 0?f=u>=a.end:s===null?f=!0:f=u>=s,{start:Math.max(r,a.start),end:Math.min(u,(l=a.end)!=null?l:1/0),hasReachedPeriodEnd:f}}function Yu(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 vn(n,e,t,r,i){try{return await e.pushChunk(t)}catch(a){if(i.isCancelled()&&a instanceof ue)throw a;if(!(a instanceof xe)||!a.isBufferFull){let d=a instanceof Error?a.toString():"An unknown error happened when pushing content";throw new ee("BUFFER_APPEND_ERROR",d,{tracks:[vt(t.inventoryInfos.adaptation)]})}let{position:o}=n.getReference().getValue(),s=o.getWanted();try{c.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 gi(200),i.cancellationError!==null)throw i.cancellationError;return await e.pushChunk(t)}catch(d){if(d instanceof ue)throw d;let u=d instanceof Error?d.toString():"Could not clean the buffer";throw new ee("BUFFER_FULL_ERROR",u,{tracks:[vt(t.inventoryInfos.adaptation)]})}}}async function Bi({playbackObserver:n,content:e,initSegmentUniqueId:t,segment:r,segmentSink:i,bufferGoal:a},o){let s=e.representation.getMimeTypeString(),d={initSegmentUniqueId:t,chunk:null,timestampOffset:0,appendWindow:[void 0,void 0],codec:s},u=H({segment:r,chunkSize:void 0,start:0,end:0},e),f=await vn(n,i,{data:d,inventoryInfos:u},a,o);return{content:e,segment:r,buffered:f}}async function Ni({playbackObserver:n,bufferGoal:e,content:t,initSegmentUniqueId:r,parsedSegment:i,segment:a,segmentSink:o},s){var P,x;if(i.chunkData===null)return null;let{chunkData:d,chunkInfos:u,chunkOffset:f,chunkSize:l,appendWindow:m}=i,g=t.representation.getMimeTypeString(),{APPEND_WINDOW_SECURITIES:h}=L.getCurrent(),b=[m[0]!==void 0?Math.max(0,m[0]-h.START):void 0,m[1]!==void 0?m[1]+h.END:void 0],p={initSegmentUniqueId:r,chunk:d,timestampOffset:f,appendWindow:b,codec:g},S=(P=u==null?void 0:u.time)!=null?P:a.time,T=(x=u==null?void 0:u.duration)!=null?x:a.duration,R=S+T;b[0]!==void 0&&(S=Math.max(S,b[0])),b[1]!==void 0&&(R=Math.min(R,b[1]));let E=H({segment:a,chunkSize:l,start:S,end:R},t),C=await vn(n,o,{data:p,inventoryInfos:E},e,s);return{content:t,segment:a,buffered:C}}function Ui({content:n,options:e,playbackObserver:t,segmentSink:r,segmentQueue:i,terminate:a},o,s){c.debug("Stream","Creating RepresentationStream",{periodStart:n.period.start,bufferType:n.adaptation.type,adaptationId:n.adaptation.id,representationBitrate:n.representation.bitrate,mimeType:n.representation.getMimeTypeString()});let{period:d,adaptation:u,representation:f}=n,{bufferGoal:l,maxBufferSize:m,drmSystemId:g,fastSwitchThreshold:h}=e,b=u.type,p=new z("RepresentationStream "+b);p.linkToSignal(s);let S={segment:f.index.getInitSegment(),uniqueId:null,isLoaded:!1};p.signal.register(()=>{S.uniqueId!==null&&r.freeInitSegment(S.uniqueId)});let T=S.segment!==null;T||(S.isLoaded=!0);let R=new Rn({drmSystemId:g,representation:f,notify:A=>o.encryptionDataEncountered(A.map(k=>H({content:n},k)))});if(p.isUsed())return;i.addEventListener("error",A=>{p.signal.isCancelled()||(p.cancel("RepresentationStream: SegmentQueue err"),o.error(A))},p.signal),i.addEventListener("parsedInitSegment",P,p.signal),i.addEventListener("parsedMediaSegment",P,p.signal),i.addEventListener("emptyQueue",C,p.signal),i.addEventListener("requestRetry",A=>{if(o.warning(A.error),p.signal.isCancelled())return;let k=A.segment,{index:N}=f;N.isSegmentStillAvailable(k)===!1?C():N.canBeOutOfSyncError(A.error,k)&&o.manifestMightBeOufOfSync()},p.signal),i.addEventListener("fullyLoadedSegment",A=>{r.signalSegmentComplete(H({segment:A},n)).catch(x)},p.signal);let E=i.resetForContent(n,T,"new RepresentationStream linked to SegmentQueue");p.signal.register(A=>{i.stop(A.reason)}),t.listen(C,{includeLastObservation:!1,clearSignal:p.signal}),n.manifest.addEventListener("manifestUpdate",C,p.signal),l.onUpdate(C,{emitCurrentValue:!1,clearSignal:p.signal}),m.onUpdate(C,{emitCurrentValue:!1,clearSignal:p.signal}),a.onUpdate(C,{emitCurrentValue:!1,clearSignal:p.signal}),C();return;function C(){if(p.isUsed())return;let A=t.getReference().getValue(),k=A.position.getWanted(),N=Di(n,k,t,h.getValue(),l.getValue(),m.getValue(),r),{neededSegments:w}=N,W=null;if(f.index.isInitialized()){if(w.length>0&&!S.isLoaded&&S.segment!==null){let M=w[0].priority;W={segment:S.segment,priority:M}}}else if(S.segment===null)c.warn("Stream","Uninitialized index without an initialization segment",{bufferType:b,representationBitrate:n.representation.bitrate});else if(S.isLoaded)c.warn("Stream","Uninitialized index with an already loaded initialization segment",{bufferType:b,representationBitrate:n.representation.bitrate});else{let M=A.position.getWanted();W={segment:S.segment,priority:Pn(d.start,M)}}let B=a.getValue();if(B===null)E.setValue({initSegment:W,segmentQueue:w});else if(B.urgent){c.debug("Stream","Urgent switch, terminate now.",{bufferType:b,representationBitrate:n.representation.bitrate}),E.setValue({initSegment:null,segmentQueue:[]}),E.finish(),p.cancel(B.reason),o.terminating();return}else{let M=w[0],D=i.getRequestedInitSegment(),U=i.getRequestedMediaSegment(),G=U===null||M===void 0||U.id!==M.segment.id?[]:[M],Q=D===null?null:W;if(E.setValue({initSegment:Q,segmentQueue:G}),G.length===0&&Q===null){c.debug("Stream","No request left, terminate",{bufferType:b,representationBitrate:n.representation.bitrate}),E.finish(),p.cancel(B.reason),o.terminating();return}}if(o.streamStatusUpdate({period:d,position:A.position.getWanted(),bufferType:b,imminentDiscontinuity:N.imminentDiscontinuity,isEmptyStream:!1,hasFinishedLoading:N.hasFinishedLoading,neededSegments:N.neededSegments}),p.signal.isCancelled())return;let{UPTO_CURRENT_POSITION_CLEANUP:_}=L.getCurrent();if(N.isBufferFull){let M=Math.max(0,k-_);M>0&&r.removeBuffer(0,M).catch(x)}N.shouldRefreshManifest&&o.needsManifestRefresh()}function P(A){if(R.onNewProtectionData(A.protectionData),A.segmentType==="init"){if(!f.index.isInitialized()&&A.segmentList!==void 0&&f.index.initialize(A.segmentList),S.isLoaded=!0,A.initializationData!==null){let k=f.uniqueId;S.uniqueId=k,r.declareInitSegment(k,A.initializationData),Bi({playbackObserver:t,bufferGoal:l,content:n,initSegmentUniqueId:k,segment:A.segment,segmentData:A.initializationData,segmentSink:r},p.signal).then(N=>{N!==null&&o.addedSegment(N)}).catch(x)}C();return}else{let{inbandEvents:k,predictedSegments:N,needsManifestRefresh:w}=A;if(N!==void 0&&f.index.addPredictedSegments(N,A.segment),w===!0&&(o.needsManifestRefresh(),p.isUsed())||k!==void 0&&k.length>0&&(o.inbandEvent(k),p.isUsed()))return;let W=S.uniqueId;Ni({playbackObserver:t,bufferGoal:l,content:n,initSegmentUniqueId:W,parsedSegment:A,segment:A.segment,segmentSink:r},p.signal).then(B=>{B!==null&&o.addedSegment(B)}).catch(x)}}function x(A){p.isUsed()&&A instanceof ue||(c.warn("Stream","Received fatal buffer error",{bufferType:b,representationBitrate:n.representation.bitrate},A instanceof Error?A:null),p.cancel("RepresentationStream: fatal buffer err"),o.error(A))}}var ss=Ui;function Li(n,e,t,r,i){var m,g,h,b;if(t.switchingMode==="lazy")return{type:"continue",value:void 0};let a=r.getLastKnownInventory(),o=[];for(let p of a)p.infos.period.id===n.id&&(p.infos.adaptation.id!==e.id||!fe(t.representationIds,p.infos.representation.id))&&bt(o,{start:(m=p.bufferedStart)!=null?m:p.start,end:(g=p.bufferedEnd)!=null?g:p.end});let s=r.getPendingOperations();for(let p of s)if(p.type===0){let S=p.value.inventoryInfos;if(S.period.id===n.id&&(S.adaptation.id!==e.id||!fe(t.representationIds,S.representation.id))){let T=S.segment.time,R=T+S.segment.duration;bt(o,{start:T,end:R})}}if(o.length===0)return{type:"continue",value:void 0};if(t.switchingMode==="reload"){let p=i.getReadyState();if(p===void 0||p>1)return{type:"needs-reload",value:void 0}}let d=t.switchingMode==="direct",u=[],f=zt(a,n);if(f!==null&&(f.bufferedEnd===void 0||n.start-f.bufferedEnd<1)&&u.push({start:0,end:n.start+1}),!d){let{ADAP_REP_SWITCH_BUFFER_PADDINGS:p}=L.getCurrent(),S=e.type,T=(h=p[S].before)!=null?h:0,R=(b=p[S].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 p=Wt(a,n);p!==null&&(p.bufferedStart===void 0||p.bufferedStart-n.end<1)&&u.push({start:n.end-1,end:Number.MAX_VALUE})}let l=kr(o,u);return l.length===0?{type:"continue",value:void 0}:d?{type:"flush-buffer",value:l}:{type:"clean-buffer",value:l}}function Fi({playbackObserver:n,content:e,options:t,representationEstimator:r,segmentSink:i,segmentQueueCreator:a,wantedBufferAhead:o,maxVideoBufferSize:s},d,u){let{manifest:f,period:l,adaptation:m}=e,g=new z("AdaptationStream "+m.type);g.linkToSignal(u);let h=new Map,b=new $(null,g.signal),p,S=e.representations.getValue().representationIds,T=ds(e.adaptation.representations,S),R=new $(T,g.signal),{estimates:E,callbacks:C}=r({manifest:f,period:l,adaptation:m},b,R,n,g.signal),P=new $(!1);n.listen(_=>{var D;let M=(D=_.canStream)!=null?D:!0;P.getValue()===M&&(c.debug("Stream","isMediaSegmentQueueInterrupted updated to",!M),P.setValue(!M))},{clearSignal:g.signal});let x=a.createSegmentQueue(m.type,{onRequestBegin:C.requestBegin,onRequestEnd:C.requestEnd,onProgress:C.requestProgress,onMetrics:C.metrics},P),A=new $(0);E.onUpdate(({bitrate:_,knownStableBitrate:M})=>{t.enableFastSwitching&&A.setValueIfChanged(M),!(_===void 0||_===p)&&(p=_,c.debug("Stream",`new ${m.type} bitrate estimate received from ABR`,{bitrate:_}),d.bitrateEstimateChange({type:m.type,bitrate:_}))},{emitCurrentValue:!0,clearSignal:g.signal});let k;e.representations.onUpdate(_=>{k!==void 0&&k.cancel("locked representations changed");let M=e.representations.getValue().representationIds,D=ds(e.adaptation.representations,M);R.setValueIfChanged(D);let U=new z("AdaptationStream: RepresentationStream Group "+m.type);k=U,U.linkToSignal(g.signal),N(_,U.signal).catch(G=>{U.isUsed()&&z.isCancellationError(G)||(g.cancel("RepresentationStream err"),d.error(G))})},{clearSignal:g.signal,emitCurrentValue:!0});return;async function N(_,M){let D=Li(l,m,_,i,n);switch(D.type){case"continue":break;case"needs-reload":return at(()=>{n.listen(()=>{if(M.isCancelled())return;let{DELTA_POSITION_AFTER_RELOAD:U}=L.getCurrent(),G=U.bitrateSwitch;return d.waitingMediaSourceReload({bufferType:m.type,period:l,timeOffset:G,stayInPeriod:!0})},{includeLastObservation:!0,clearSignal:M})});case"flush-buffer":case"clean-buffer":for(let U of D.value)if(await i.removeBuffer(U.start,U.end),M.isCancelled())return;if(D.type==="flush-buffer"&&(d.needsBufferFlush(),M.isCancelled()))return;break;default:Ne(D)}w(M)}function w(_){let M=new z("AdaptationStream: RepresentationStream creation "+m.type);M.linkToSignal(_);let{representation:D}=E.getValue();if(D===null)return;let U=new $(null,M.signal);E.onUpdate(K=>{if(!(K.representation===null||K.representation.id===D.id))return K.urgent?(c.info("Stream","urgent Representation switch",{bufferType:m.type,estimateBitrate:K.bitrate,prevRepresentationBitrate:D.bitrate,newRepresentationBitrate:K.representation.bitrate}),U.setValue({urgent:!0,reason:"Urgent Representation switch"})):(c.info("Stream","slow Representation switch",{bufferType:m.type,estimateBitrate:K.bitrate,prevRepresentationBitrate:D.bitrate,newRepresentationBitrate:K.representation.bitrate}),U.setValue({urgent:!1,reason:"Non-urgent Representation switch"}))},{clearSignal:M.signal,emitCurrentValue:!0});let G={type:m.type,adaptation:m,period:l,representation:D};if(b.setValue(D),_.isCancelled()||(d.representationChange(G),_.isCancelled()))return;let Q={streamStatusUpdate:d.streamStatusUpdate,encryptionDataEncountered:d.encryptionDataEncountered,manifestMightBeOufOfSync:d.manifestMightBeOufOfSync,needsManifestRefresh:d.needsManifestRefresh,inbandEvent:d.inbandEvent,warning:d.warning,error(K){g.cancel("RepresentationStream err cb"),d.error(K)},addedSegment(K){C.addedSegment(K)},terminating(){if(!M.isUsed())return M.cancel("RepresentationStream terminating"),w(_)}};W(D,U,Q,_)}function W(_,M,D,U){let G=!1,Q=new z(`RepresentationStream-linked listeners in AdaptationStream - periodStart=${l.start} type=${m.type}`);Q.linkToSignal(U);let K=en(o,X=>B(_,X),Q.signal),q=m.type==="video"?s:new $(1/0);c.info("Stream","changing representation",{bufferType:m.type,representationId:_.id,representationBitrate:_.bitrate});let Z=H({},D,{error(X){var pe;if(G){c.warn("Stream","Ignoring RepresentationStream error",X);return}G=!0;let me=ge(X,{defaultCode:"NONE",defaultReason:"Unknown `RepresentationStream` error"});if(me.code!=="BUFFER_FULL_ERROR")D.error(X);else{c.warn("Stream","received BUFFER_FULL_ERROR",{bufferType:m.type,representationBitrate:_.bitrate});let Qe=o.getValue(),se=((pe=h.get(_.id))!=null?pe:1)*.7;if(h.set(_.id,se),se<=.05||B(_,Qe)<=2){D.error(me);return}fn(4e3,Q.signal).then(()=>W(_,M,D,U)).catch(O)}},terminating(){Q.cancel("Representation terminating"),D.terminating()}});ss({playbackObserver:n,content:{representation:_,adaptation:m,period:l,manifest:f},segmentSink:i,segmentQueue:x,terminate:M,options:{bufferGoal:K,maxBufferSize:q,drmSystemId:t.drmSystemId,fastSwitchThreshold:A}},Z,U),f.addEventListener("manifestUpdate",X=>{for(let me of X.updatedPeriods)if(me.period.id===l.id){for(let pe of me.result.updatedAdaptations)if(pe.adaptation===m.id){for(let Qe of pe.removedRepresentations)if(Qe===_.id)return Q.isUsed()?void 0:d.waitingMediaSourceReload({bufferType:m.type,period:l,timeOffset:0,stayInPeriod:!0})}}else if(me.period.start>l.start)break},Q.signal)}function B(_,M){let D=h.get(_.id),U=D!==void 0?D:1;return D===void 0&&h.set(_.id,U),U<1&&M===1/0?300*U:M*U}}function ds(n,e){let t=n.filter(r=>fe(e,r.id)&&!r.shouldBeAvoided&&r.isPlayable()!==!1);return t.length>0?t:n.filter(r=>fe(e,r.id)&&r.isPlayable()!==!1)}var us=Fi;function zi(n,e,t,r,i,a){var g,h,b,p;if(n.codec!==void 0&&a.onCodecSwitch==="reload"&&!Qu(t,n.codec))return{type:"needs-reload",value:void 0};let o=n.getLastKnownInventory(),s=[];for(let S of o)S.infos.period.id===e.id&&S.infos.adaptation.id!==t.id&&bt(s,{start:(g=S.bufferedStart)!=null?g:S.start,end:(h=S.bufferedEnd)!=null?h:S.end});let d=n.getPendingOperations();for(let S of d)if(S.type===0){let T=S.value.inventoryInfos;if(T.period.id===e.id&&T.adaptation.id!==t.id){let R=T.segment.time,E=R+T.segment.duration;bt(s,{start:R,end:E})}}if(s.length===0)return{type:"continue",value:void 0};if(r==="reload"){let S=i.getReadyState();if(S===void 0||S>1)return{type:"needs-reload",value:void 0}}let u=r==="direct",f=[],l=zt(o,e);if(l!==null&&(l.bufferedEnd===void 0||e.start-l.bufferedEnd<1)&&f.push({start:0,end:e.start+1}),!u){let S=t.type,{ADAP_REP_SWITCH_BUFFER_PADDINGS:T}=L.getCurrent(),R=(b=T[S].before)!=null?b:0,E=(p=T[S].after)!=null?p:0,C=i.getCurrentTime();C===void 0&&(C=i.getReference().getValue().position.getPolled()),f.push({start:C-R,end:C+E})}if(e.end!==void 0){let S=Wt(o,e);S!==null&&(S.bufferedStart===void 0||S.bufferedStart-e.end<1)&&f.push({start:e.end-1,end:Number.MAX_VALUE})}let m=kr(s,f);return m.length===0?{type:"continue",value:void 0}:u&&t.type!=="text"?{type:"flush-buffer",value:m}:{type:"clean-buffer",value:m}}function Qu(n,e){return n.representations.some(t=>t.isPlayable()===!0&&Vo(t.getMimeTypeString(),e))}function Wi({bufferType:n,content:e,garbageCollectors:t,playbackObserver:r,representationEstimator:i,segmentQueueCreator:a,segmentSinksStore:o,options:s,wantedBufferAhead:d,maxVideoBufferSize:u},f,l){let{manifest:m,period:g}=e,h=new $(void 0,l);if(f.periodStreamReady({type:n,manifest:m,period:g,adaptationRef:h}),l.isCancelled())return;let b,p=!0;h.onUpdate(R=>{(async()=>{var B;if(R===void 0)return;let E=new z("PeriodStream: Adaptation choice "+n);if(E.linkToSignal(l),b==null||b.cancel("PeriodStream: Adaptation update"),b=E,R===null){c.info("Stream","Set no Adaptation",{periodStart:g.start,bufferType:n});let _=o.getStatus(n);if(_.type==="initialized"){if(c.info("Stream","Clearing previous SegmentSink",{periodStart:g.start,bufferType:n}),St.isNative(n))return T(0,!0,E.signal);{let M=(B=g.end)!=null?B:1/0;if(g.start>M)c.warn("Stream","Can't free buffer: period's start is after its end",{periodStart:g.start,periodEnd:M,bufferType:n});else if(await _.value.removeBuffer(g.start,M),E.isUsed())return}}else if(_.type==="uninitialized"&&(o.disableSegmentSink(n),E.isUsed()))return;return f.adaptationChange({type:n,adaptation:null,period:g}),E.isUsed()?void 0:ls(r,d,n,{period:g},f,E.signal)}let C=g.adaptations[n],P=j(C!=null?C:[],_=>_.id===R.adaptationId);if(P===void 0){b.cancel("PeriodStream: Adaptation not found"),c.warn("Stream","Unfound chosen Adaptation choice",{adaptationId:R.adaptationId});return}let{DELTA_POSITION_AFTER_RELOAD:x}=L.getCurrent(),A=!1,k;if(p)k=0;else if(R.relativeResumingPosition!==void 0)k=R.relativeResumingPosition;else switch(A=!0,n){case"audio":k=x.trackSwitch.audio;break;case"video":k=x.trackSwitch.video;break;default:k=x.trackSwitch.other;break}if(p=!1,St.isNative(n)&&o.getStatus(n).type==="disabled")return T(k,!0,E.signal);m.addEventListener("manifestUpdate",_=>{for(let M of _.updatedPeriods)if(M.period.id===g.id){for(let D of M.result.removedAdaptations)if(D.id===P.id)return T(k,!0,E.signal)}else if(M.period.start>g.start)break},b.signal);let{representations:N}=R;if(c.info("Stream","Updating adaptation",{bufferType:P.type,periodStart:g.start,adaptationId:P.id}),f.adaptationChange({type:n,adaptation:P,period:g}),E.isUsed())return;let w=$u(o,n,P),W=zi(w,g,P,R.switchingMode,r,s);if(W.type==="needs-reload")return T(k,!0,E.signal);if(await o.waitForUsableBuffers(E.signal),!E.isUsed()){if(W.type==="flush-buffer"||W.type==="clean-buffer"){for(let{start:_,end:M}of W.value)if(await w.removeBuffer(_,M),E.isUsed())return;if(W.type==="flush-buffer"&&(f.needsBufferFlush({relativeResumingPosition:k,relativePosHasBeenDefaulted:A}),E.isUsed()))return}t.get(w)(E.signal),S(P,N,w,E.signal)}})().catch(E=>{E instanceof ue||(b==null||b.cancel("PeriodStream err"),f.error(E))})},{clearSignal:l,emitCurrentValue:!0});function S(R,E,C,P){let x=Zu(r,R.type);us({content:{manifest:m,period:g,adaptation:R,representations:E},options:s,playbackObserver:x,representationEstimator:i,segmentSink:C,segmentQueueCreator:a,wantedBufferAhead:d,maxVideoBufferSize:u},de(J({},f),{error:A}),P);function A(k){if(!St.isNative(n)){c.error("Stream",`${n} Stream crashed. Aborting it.`,k instanceof Error?k:""),o.disposeSegmentSink(n,"AdaptationStream err");let N=ge(k,{defaultCode:"NONE",defaultReason:"Unknown `AdaptationStream` error"});return f.warning(N),P.isCancelled()?void 0:ls(r,d,n,{period:g},f,P)}c.error("Stream",`${n} Stream crashed. Stopping playback.`,k instanceof Error?k:""),f.error(k)}}function T(R,E,C){at(()=>{r.listen(()=>{C.isCancelled()||f.waitingMediaSourceReload({bufferType:n,period:g,timeOffset:R,stayInPeriod:E})},{includeLastObservation:!0,clearSignal:C})})}}function $u(n,e,t){let r=n.getStatus(e);if(r.type==="initialized")return c.info("Stream","Reusing a previous SegmentSink for the type",{bufferType:e}),r.value;let i=Xu(t);return n.createSegmentSink(e,i)}function Xu(n){let e=n.representations.filter(t=>t.isPlayable()!==!1);if(e.length>0)return e[0].getMimeTypeString();if(n.representations.length>0)return n.representations[0].getMimeTypeString();throw new ee("NO_PLAYABLE_REPRESENTATION","No Representation in the chosen "+n.type+" Adaptation can be played",{tracks:[vt(n)]})}function Zu(n,e){return n.deriveReadOnlyObserver(function(r,i){let a=new $(o(),i);return r.onUpdate(s,{clearSignal:i,emitCurrentValue:!1}),a;function o(){let d=r.getValue(),u=d.buffered[e],f=u!==null?xr(u,d.position.getWanted()):0;return H({},d,{bufferGap:f,buffered:u})}function s(){a.setValue(o())}})}function ls(n,e,t,r,i,a){let{period:o}=r,s=!1;e.onUpdate(d,{emitCurrentValue:!1,clearSignal:a}),n.listen(d,{includeLastObservation:!1,clearSignal:a}),d();function d(){let u=n.getReference().getValue(),f=e.getValue(),l=u.position.getWanted();o.end!==void 0&&l+f>=o.end&&(c.debug("Stream",'full "empty" AdaptationStream',{bufferType:t,periodEnd:o.end,position:l,wantedBufferAhead:f}),s=!0),i.streamStatusUpdate({period:o,bufferType:t,imminentDiscontinuity:null,position:l,isEmptyStream:!0,hasFinishedLoading:s,neededSegments:[]})}}var fs=Wi;function Dr(n,e){if(e.length===0)return[];let t=[],r=n.getLastKnownInventory(),i=n.getPendingOperations();for(let a of r)if(e.some(s=>a.infos.period.id===s.period.id&&a.infos.adaptation.id===s.adaptation.id&&a.infos.representation.id===s.representation.id)){let{bufferedStart:s,bufferedEnd:d}=a;if(s===void 0||d===void 0)return c.warn("Stream","No buffered start or end found from a segment.",{bufferType:a.infos.adaptation.type,segmentStart:a.infos.segment.time}),[{start:0,end:Number.MAX_VALUE}];let u=t[t.length-1];u!==void 0&&u.end===s?u.end=d:t.push({start:s,end:d})}for(let a of i){if(a.type!==0)continue;let o=a.value;e.some(d=>o.inventoryInfos.period.id===d.period.id&&o.inventoryInfos.adaptation.id===d.adaptation.id&&o.inventoryInfos.representation.id===d.representation.id)&&bt(t,{start:o.inventoryInfos.start,end:o.inventoryInfos.end})}return t}function Vi(n,e,t,r,i,a,o,s){let{manifest:d,initialPeriod:u}=n,{maxBufferAhead:f,maxBufferBehind:l,wantedBufferAhead:m,maxVideoBufferSize:g}=a,{MINIMUM_MAX_BUFFER_AHEAD:h,MAXIMUM_MAX_BUFFER_AHEAD:b,MAXIMUM_MAX_BUFFER_BEHIND:p}=L.getCurrent(),S=new bn(E=>{var A,k;let{bufferType:C}=E,P=(A=p[C])!=null?A:1/0,x=(k=b[C])!=null?k:1/0;return N=>{Mr({segmentSink:E,playbackObserver:e,maxBufferBehind:en(l,w=>Math.min(w,P),N),maxBufferAhead:en(f,w=>{var B;let W=Math.max(w,(B=h[C])!=null?B:0);return Math.min(W,x)},N)},N)}});for(let E of r.getBufferTypes())T(E,u);function T(E,C){let P=new kt((W,B)=>W.start-B.start),x=!1,A=new z("StreamOrchestrator Streams for "+E);return A.linkToSignal(s),e.listen(({position:W})=>{let B=W.getWanted();if(!x||!N(B))return;let _=()=>{var D;return(D=d.getPeriodForTime(B))!=null?D:d.getNextPeriod(B)},M=_();if(!(!v(M)&&P.has(M))){for(c.info("Stream","Destroying all PeriodStreams due to out of bounds situation",{bufferType:E,time:B}),x=!1;P.length()>0;){let D=P.get(P.length()-1);P.removeElement(D),o.periodStreamCleared({type:E,manifest:d,period:D})}if(A.cancel("PeriodStream is out of bounds"),A=new z("StreamOrchestrator Streams for "+E),A.linkToSignal(s),M=_(),M===void 0){c.warn("Stream","The wanted position is not found in the Manifest."),x=!0;return}k(M)}},{clearSignal:s,includeLastObservation:!0}),d.addEventListener("decipherabilityUpdate",W=>{s.isCancelled()||w(W).catch(B=>{s.isCancelled()||(A.cancel("decipherabilityUpdate event"),o.error(B))})},s),k(C);function k(W){let B=de(J({},o),{waitingMediaSourceReload(_){let M=P.head();M===void 0||M.id!==_.period.id?o.lockedStream({bufferType:_.bufferType,period:_.period}):o.needsMediaSourceReload({timeOffset:_.timeOffset,minimumPosition:_.stayInPeriod?_.period.start:void 0,maximumPosition:_.stayInPeriod?_.period.end:void 0})},periodStreamReady(_){x=!0,P.add(_.period),o.periodStreamReady(_)},periodStreamCleared(_){P.removeElement(_.period),o.periodStreamCleared(_)},error(_){A.cancel("PeriodStream err callback"),o.error(_)}});R(E,W,B,A.signal)}function N(W){let B=P.head(),_=P.last();return B===void 0||_===void 0?!0:B.start>W||(v(_.end)?1/0:_.end)<W}async function w(W){let B=r.getStatus(E),_=W.filter(q=>q.adaptation.type===E);if(_.length===0||B.type!=="initialized"||_.every(q=>q.representation.decipherable===!0))return;let M=B.value,D=_.filter(q=>q.representation.decipherable===void 0),U=_.filter(q=>q.representation.decipherable===!1),G=Dr(M,U),Q=Dr(M,D);for(c.info("Stream","Destroying all PeriodStreams for decipherability matters",{bufferType:E}),x=!1;P.length()>0;){let q=P.get(P.length()-1);P.removeElement(q),o.periodStreamCleared({type:E,manifest:d,period:q})}A.cancel("decipherability update"),A=new z("StreamOrchestrator Streams for "+E),A.linkToSignal(s);let K=A;for(let{start:q,end:Z}of[...G,...Q]){if(K.isUsed())return;q<Z&&await M.removeBuffer(q,Z)}at(()=>{if(K.signal.isCancelled())return;let q=e.getReference().getValue();if(ms(q,G)){if(o.needsDecipherabilityFlush(),K.isUsed())return}else if(ms(q,Q)&&(o.needsBufferFlush(),K.isUsed()))return;let Z=q.position.getWanted(),X=d.getPeriodForTime(Z);if(X===void 0&&(X=d.getNextPeriod(Z),c.warn("Stream","No Period found for the reloading position, selecting next one instead",{reloadPosition:Z,nextPeriodStart:X==null?void 0:X.start})),X===void 0&&(X=d.periods[d.periods.length-1],c.warn("Stream","No Period found for of after the reloading position, selecting the last one",{reloadPosition:Z,nextPeriodStart:X==null?void 0:X.start,nextPeriodEnd:X==null?void 0:X.end})),X===void 0){o.error(new ee("MEDIA_TIME_NOT_FOUND","The wanted position is not found in the Manifest."));return}k(X)})}}function R(E,C,P,x){c.info("Stream","Creating new PeriodStream",{bufferType:E,periodStart:C.start});let A=null,k=new z("StreamOrchestrator current consecutive Streams "+E);k.linkToSignal(x),e.listen(({position:_},M)=>{if(C.end!==void 0&&_.getWanted()>=C.end){let D=d.getPeriodAfter(C);if(C.containsTime(_.getWanted(),D))return;c.info("Stream","Destroying PeriodStream as the current playhead moved above it",{bufferType:E,periodStart:C.start,periodEnd:C.end,position:_.getWanted()}),M(),P.periodStreamCleared({type:E,manifest:d,period:C}),k.cancel("Position ahead of PeriodStream")}},{clearSignal:x,includeLastObservation:!0});let N={bufferType:E,content:{manifest:d,period:C},garbageCollectors:S,maxVideoBufferSize:g,segmentQueueCreator:i,segmentSinksStore:r,options:a,playbackObserver:e,representationEstimator:t,wantedBufferAhead:m},w=de(J({},P),{streamStatusUpdate(_){if(_.hasFinishedLoading){let M=d.getPeriodAfter(C);M!==null&&W(M)}else A!==null&&(c.info("Stream","Destroying next PeriodStream due to current one being active",{bufferType:E,periodStart:C.start,nextPeriodStart:A.period.start}),P.periodStreamCleared({type:E,manifest:d,period:A.period}),A.canceller.cancel("previous PeriodStream is active"),A=null);P.streamStatusUpdate(_)},error(_){A!==null&&(A.canceller.cancel("previous PeriodStream err"),A=null),k.cancel("PeriodStream err"),P.error(_)}});fs(N,w,k.signal),B(k.signal);function W(_){if(A!==null){if(A.period.id===_.id)return;c.warn("Stream","Creating next `PeriodStream` while one was already created.",{bufferType:E,nextPeriodStart:_.start}),P.periodStreamCleared({type:E,manifest:d,period:A.period}),A.canceller.cancel("PeriodStream recreation")}let M=new z("StreamOrchestrator next PeriodStream "+E);M.linkToSignal(x),A={canceller:M,period:_},R(E,_,P,A.canceller.signal)}function B(_){d.addEventListener("manifestUpdate",M=>{for(let D of M.removedPeriods)if(D.id===C.id){if(d.periods.length>0&&d.periods[0].start<=D.start)return at(()=>{if(!_.isCancelled())return o.needsMediaSourceReload({timeOffset:0,minimumPosition:void 0,maximumPosition:void 0})})}else if(D.start>C.start)break;if(A!==null){let D=d.getPeriodAfter(C);(D===null||A.period.id!==D.id)&&(c.warn("Stream","Destroying next PeriodStream due to manifest update",{bufferType:E,nextPeriodStart:A.period.start}),P.periodStreamCleared({type:E,manifest:d,period:A.period}),A.canceller.cancel("Next Period changed"),A=null)}},_)}}}function ms(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 cs=Vi;var ps=cs;function qi(n,e){if(typeof n.changeType=="function"){try{n.changeType(e)}catch(t){return c.warn("mse","Could not call 'changeType' on the given SourceBuffer:",t instanceof Error?t:""),!1}return!0}return!1}function Ju(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t];r.updating&&e.push(r)}return e}function Cn(n,e){if(c.debug("mse","Trying to call endOfStream"),n.readyState!=="open"){c.debug("mse","MediaSource not open, cancel endOfStream");return}let{sourceBuffers:t}=n,r=Ju(t);if(r.length===0){c.info("mse","Triggering end of stream");try{n.endOfStream()}catch(a){c.error("mse","Unable to call endOfStream",a instanceof Error?a:new Error("Unknown error"))}return}c.debug("mse","Waiting SourceBuffers to be updated before calling endOfStream.");let i=new z("EndOfStream current iteration");i.linkToSignal(e);for(let a of r)ko(a,()=>{i.cancel("SourceBuffer update"),Cn(n,e)},i.signal);Mo(t,()=>{i.cancel("SourceBuffer remove"),Cn(n,e)},i.signal)}function gs(n,e){let t=new z("EndOfStream");t.linkToSignal(e),Ft(n,()=>{c.debug("mse","MediaSource re-opened while end-of-stream is active"),t.cancel("MediaSource re-opened"),t=new z("EndOfStream"),t.linkToSignal(e),Cn(n,t.signal)},e),Cn(n,t.signal)}function Gi(){let{FORCE_HAS_ISSUES_WITH_HIGH_MEDIA_SOURCE_DURATION:n}=L.getCurrent();return n||tt.device===tt.DEVICES.PlayStation5}var el=365*24*3600,An=class{constructor(e){this._mediaSource=e,this._currentMediaSourceDurationUpdateCanceller=null}updateDuration(e,t){this._currentMediaSourceDurationUpdateCanceller!==null&&this._currentMediaSourceDurationUpdateCanceller.cancel("manual duration update"),this._currentMediaSourceDurationUpdateCanceller=new z("MediaSource Duration Update");let r=this._mediaSource,i=this._currentMediaSourceDurationUpdateCanceller.signal,a=rl(r,i),o=new z(void 0);o.linkToSignal(i),a.onUpdate(s,{emitCurrentValue:!0,clearSignal:i});function s(){if(o.cancel("MediaSource open status changed"),!a.getValue())return;o=new z(void 0),o.linkToSignal(i);let d=nl(r.sourceBuffers,o.signal),u=new z(void 0);return u.linkToSignal(o.signal),d.onUpdate(f=>{u.cancel("SourceBuffer status update"),u=new z(void 0),u.linkToSignal(o.signal),!f&&Is(r,e,t,u.signal)},{clearSignal:o.signal,emitCurrentValue:!0})}}stopUpdating(e){this._currentMediaSourceDurationUpdateCanceller!==null&&(this._currentMediaSourceDurationUpdateCanceller.cancel(e!=null?e:"stop MSDU"),this._currentMediaSourceDurationUpdateCanceller=null)}};function tl(n,e,t){let r=e;t||(r=Gi()?1/0:hs(e));let i=0;for(let a=0;a<n.sourceBuffers.length;a++){let o=n.sourceBuffers[a],s=o.buffered.length;s>0&&(i=Math.max(i,o.buffered.end(s-1)))}if(r===n.duration)return"success";if(i>r){if(i<n.duration)try{c.info("mse","Updating duration to what is currently buffered",{maxBufferedEnd:i}),n.duration=i}catch(a){return c.warn("mse","Can't update duration on the MediaSource.",a instanceof Error?a:""),"failed"}return"partial"}else{let a=n.duration;try{if(c.info("mse","Updating duration",{newDuration:r}),n.duration=r,n.readyState==="open"&&!isFinite(r)){let s=hs(e);c.info("mse","calling `mediaSource.setLiveSeekableRange`",{maxSeekable:s}),n.setLiveSeekableRange(0,s)}}catch(s){return c.warn("mse","Can't update duration on the MediaSource.",s instanceof Error?s:""),"failed"}let o=Math.abs(n.duration-r);if(o>=.1){let s=Math.abs(n.duration-a);return o<s?"partial":"failed"}return"success"}}function nl(n,e){if(n.length===0){let i=new $(!1);return i.finish(),i}let t=new $(!1,e);r();for(let i=0;i<n.length;i++){let a=n[i];a.addEventListener("updatestart",r),a.addEventListener("update",r),e.register(()=>{a.removeEventListener("updatestart",r),a.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 rl(n,e){let t=new $(n.readyState==="open",e);return Ft(n,()=>{c.debug("mse","Reacting to MediaSource open in duration updater"),t.setValueIfChanged(!0)},e),Er(n,()=>{c.debug("mse","Reacting to MediaSource ended in duration updater"),t.setValueIfChanged(!1)},e),Tr(n,()=>{c.debug("mse","Reacting to MediaSource close in duration updater"),t.setValueIfChanged(!1)},e),t}function Is(n,e,t,r){if(tl(n,e,t)==="success")return;let a=setTimeout(()=>{o(),Is(n,e,t,r)},2e3),o=r.register(()=>{clearTimeout(a)})}function hs(n){return Math.max(Math.pow(2,32),n+el)}var xn=class extends ce{constructor(e,t){super(),this.id=e,this.sourceBuffers=[],this._canceller=new z("MainMediaSourceInterface");let{MediaSource_:r}=ln;if(v(r))throw new ee("MEDIA_SOURCE_NOT_SUPPORTED","No MediaSource Object was found in the current browser.");c.info("mse","Creating MediaSource");let i=t!==void 0?new t:new r,a=i.handle;this.handle=v(a)?{type:"media-source",value:i}:{type:"handle",value:a},this._mediaSource=i,this.readyState=i.readyState,this._durationUpdater=new An(i),this._endOfStreamCanceller=null,Ft(i,()=>{this.readyState=i.readyState,this.trigger("mediaSourceOpen",null)},this._canceller.signal),Er(i,()=>{this.readyState=i.readyState,this.trigger("mediaSourceEnded",null)},this._canceller.signal),Tr(i,()=>{this.readyState=i.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 Hi(e,t,r);return this.sourceBuffers.push(i),i}setDuration(e,t){this._durationUpdater.updateDuration(e,t)}interruptDurationSetting(e){this._durationUpdater.stopUpdating(e)}maintainEndOfStream(){this._endOfStreamCanceller===null&&(this._endOfStreamCanceller=new z("MainMediaSourceInterface EndOfStream"),this._endOfStreamCanceller.linkToSignal(this._canceller.signal),c.debug("mse","end-of-stream order received."),gs(this._mediaSource,this._endOfStreamCanceller.signal))}stopEndOfStream(){this._endOfStreamCanceller!==null&&(c.debug("mse","resume-stream order received."),this._endOfStreamCanceller.cancel("MediaSourceInterface stopEndOfStream"),this._endOfStreamCanceller=null)}dispose(e){this.sourceBuffers.forEach(t=>t.dispose(e)),this._canceller.cancel(e!=null?e:"MainMediaSourceInterface dispose"),il(this._mediaSource)}},Hi=class{constructor(e,t,r){this.type=e,this.codec=t,this._canceller=new z("MainSourceBufferInterface "+e),this._sourceBuffer=r,this._operationQueue=[],this._currentOperations=[];let i=this._onError.bind(this),a=this._onUpdateEnd.bind(this);r.addEventListener("updateend",a),r.addEventListener("error",i),this._canceller.signal.register(()=>{r.removeEventListener("updateend",a),r.removeEventListener("error",i)})}appendBuffer(...e){return c.debug("mse","receiving order to push data to the SourceBuffer",{type:this.type}),this._addToQueue({operationName:0,params:e})}remove(e,t){return c.debug("mse","receiving order to remove data from the SourceBuffer",{type:this.type,start:e,end:t}),this._addToQueue({operationName:1,params:[e,t]})}getBuffered(){try{return ki(this._sourceBuffer.buffered)}catch(e){return c.error("mse","Failed to get buffered time range of SourceBuffer",{type:this.type},e instanceof Error?e:"Unknown Error"),[]}}abort(e){try{this._sourceBuffer.abort()}catch(t){c.debug("mse","Failed to abort SourceBuffer:",t instanceof Error?t:"Unknown Error")}this._emptyCurrentQueue(e)}dispose(e){try{this._sourceBuffer.abort()}catch(t){}this._emptyCurrentQueue(e)}_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)c.error("mse","error for an unknown operation",t);else{let i=new xe(t.name,t.message,t.name==="QuotaExceededError");for(let a of r)a.reject(i)}}_onUpdateEnd(){let e=this._currentOperations;this._currentOperations=[];try{for(let t of e)t.resolve(ki(this._sourceBuffer.buffered))}catch(t){for(let r of e)t instanceof Error&&t.name==="InvalidStateError"?r.resolve([]):r.reject(t)}this._performNextOperation()}_emptyCurrentQueue(e){let t=new ue("MainSourceBufferInterface queue "+this.type,e);this._currentOperations.length>0&&(this._currentOperations.forEach(r=>{r.reject(t)}),this._currentOperations=[]),this._operationQueue.length>0&&(this._operationQueue.forEach(r=>{r.reject(t)}),this._operationQueue=[])}_addToQueue(e){return new Promise((t,r)=>{let i=this._operationQueue.length===0&&this._currentOperations.length===0,a=H({resolve:t,reject:r},e);this._operationQueue.push(a),i&&this._performNextOperation()})}_performNextOperation(){var t,r,i,a,o;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 f;s instanceof ArrayBuffer?f=new Uint8Array(s):s instanceof Uint8Array?f=s:f=new Uint8Array(s.buffer);let l=[f];for(;((t=this._operationQueue[0])==null?void 0:t.operationName)===0;){let m=this._operationQueue[0],g=(r=d.appendWindow)!=null?r:[void 0,void 0],h=(i=m.params[1].appendWindow)!=null?i:[void 0,void 0],b=(a=d.timestampOffset)!=null?a:0,p=(o=m.params[1].timestampOffset)!=null?o:0;if(g[0]===h[0]&&g[1]===h[1]&&d.codec===m.params[1].codec&&b===p){let S=m.params[0],T;S instanceof ArrayBuffer?T=new Uint8Array(S):S instanceof Uint8Array?T=S:T=new Uint8Array(S.buffer),l.push(T),this._operationQueue.splice(0,1),this._currentOperations.push({operationName:0,resolve:m.resolve,reject:m.reject})}else break}l.length>1&&(c.info("mse",`: Merging ${l.length} segments together for perf`,{type:this.type}),u=At(...l).buffer)}try{this._appendBufferNow(u,d)}catch(f){let l=f instanceof Error?new xe(f.name,f.message,f.name==="QuotaExceededError"):new xe("Error","Unknown SourceBuffer Error during appendBuffer",!1);this._currentOperations.forEach(m=>{m.reject(l)}),this._currentOperations=[],this._performNextOperation()}}else{this._currentOperations=[e];let[s,d]=e.params;c.debug("mse","removing data from SourceBuffer",{type:this.type,start:s,end:d});try{this._sourceBuffer.remove(s,d)}catch(u){let f=u instanceof Error?new xe(u.name,u.message,!1):new xe("Error","Unknown SourceBuffer Error during remove",!1);e.reject(f),this._currentOperations.forEach(l=>{l.reject(f)}),this._currentOperations=[],this._performNextOperation()}}}_appendBufferNow(e,t){let r=this._sourceBuffer,{codec:i,timestampOffset:a,appendWindow:o=[]}=t;if(i!==void 0&&i!==this.codec&&(c.debug("mse","updating codec",{type:this.type,prevCodec:this.codec,newCodec:i}),qi(r,i)?this.codec=i:c.debug("mse","could not update codec",{type:this.type,prevCodec:this.codec,newCodec:i})),a!==void 0&&r.timestampOffset!==a){let s=a;c.debug("mse","updating timestampOffset",{type:this.type,codec:i,prevTimestampOffset:r.timestampOffset,newTimestampOffset:s}),r.timestampOffset=s}if(o[0]===void 0)r.appendWindowStart>0&&(c.debug("mse","re-setting `appendWindowStart`",{type:this.type,prevWindowStart:r.appendWindowStart}),r.appendWindowStart=0);else if(o[0]!==r.appendWindowStart){if(o[0]>=r.appendWindowEnd){let s=o[0]+1;c.debug("mse","pre-updating `appendWindowEnd`",{type:this.type,prevWindowEnd:r.appendWindowEnd,newWindowEnd:s}),r.appendWindowEnd=s}c.debug("mse","setting `appendWindowStart`",{type:this.type,appendWindowStart:o[0]}),r.appendWindowStart=o[0]}o[1]===void 0?r.appendWindowEnd!==1/0&&(c.debug("mse","re-setting `appendWindowEnd`",{type:this.type,prevWindowStart:r.appendWindowStart}),r.appendWindowEnd=1/0):o[1]!==r.appendWindowEnd&&(c.debug("mse","setting `appendWindowEnd`",{type:this.type,prevWindowEnd:r.appendWindowEnd,newWindowEnd:o[1]}),r.appendWindowEnd=o[1]),c.debug("mse","pushing segment",{type:this.type}),r.appendBuffer(e)}};function il(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"){c.info("mse","Aborting SourceBuffer before removing");try{i.abort()}catch(a){}}c.info("mse","Removing SourceBuffer from mediaSource"),n.removeSourceBuffer(i)}catch(a){}}t.length>0&&c.info("mse","Not all SourceBuffers could have been removed.")}}var al=Me(),Br=Me(),bs=1/0,kn=class extends ce{constructor(e,t,r){super(),this.id=e,this.sourceBuffers=[],this._canceller=new z("WorkerMediaSourceInterface"),this.readyState="closed",this._messageSender=r;let i=al();this._messageSender({type:"create-media-source",contentId:t,mediaSourceId:i})}onMediaSourceReadyStateChanged(e){switch(e){case"closed":this.readyState="closed",this.trigger("mediaSourceClose",null);break;case"open":this.readyState="open",this.trigger("mediaSourceOpen",null);break;case"ended":this.readyState="ended",this.trigger("mediaSourceEnded",null);break}}addSourceBuffer(e,t){this._messageSender({type:"add-source-buffer",mediaSourceId:this.id,value:{sourceBufferType:e,codec:t}});let r=new Ki(e,t,this.id,this._messageSender);return this.sourceBuffers.push(r),r}setDuration(e,t){this._messageSender({type:"update-media-source-duration",mediaSourceId:this.id,value:{duration:e,isRealEndKnown:t}})}interruptDurationSetting(){this._messageSender({type:"stop-media-source-duration",mediaSourceId:this.id,value:null})}maintainEndOfStream(){this._messageSender({type:"end-of-stream",mediaSourceId:this.id,value:null})}stopEndOfStream(){this._messageSender({type:"stop-end-of-stream",mediaSourceId:this.id,value:null})}dispose(e){this.sourceBuffers.forEach(t=>t.dispose(e)),this._canceller.cancel("WorkerMediaSourceInterface dispose"),this._messageSender({type:"dispose-media-source",mediaSourceId:this.id,value:null})}},Ki=class{constructor(e,t,r,i){this.type=e,this.codec=t,this._canceller=new z("WorkerSourceBufferInterface "+e),this._mediaSourceId=r,this._queuedOperations=[],this._pendingOperations=new Map,this._messageSender=i}onOperationSuccess(e,t){let r=this._pendingOperations.get(e);r===void 0?c.warn("mse","unknown SourceBuffer operation succeeded",{type:this.type}):(this._pendingOperations.delete(e),r.resolve(t)),this._performNextQueuedOperationIfItExists()}onOperationFailure(e,t){let r=t.errorName==="CancellationError"?new ue("Pending SBI Operation "+this.type,"SBI Failure"):new xe(t.errorName,t.message,t.isBufferFull),i=this._pendingOperations.get(e);i===void 0?c.info("mse","unknown SourceBuffer operation failed",{type:this.type},r):(this._pendingOperations.delete(e),i.reject(r));let a=new ue("Queued SBI Operation "+this.type,"SBI failure");for(let o of this._queuedOperations)o.reject(a);this._queuedOperations=[]}appendBuffer(e,t){return new Promise((r,i)=>{if(this._queuedOperations.length>0||this._pendingOperations.size>=bs){this._queuedOperations.push({operationName:0,params:[e,t],resolve:r,reject:i});return}try{let a;e instanceof ArrayBuffer?a=e:e.byteLength===e.buffer.byteLength?a=e.buffer:a=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);let o=Br();this._messageSender({type:"source-buffer-append",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,operationId:o,value:{data:a,params:t}},[a]),this._addOperationToQueue(o,r,i)}catch(a){i(a)}})}remove(e,t){return new Promise((r,i)=>{if(this._queuedOperations.length>0||this._pendingOperations.size>=bs){this._queuedOperations.push({operationName:1,params:[e,t],resolve:r,reject:i});return}try{let a=Br();this._messageSender({type:"source-buffer-remove",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,operationId:a,value:{start:e,end:t}}),this._addOperationToQueue(a,r,i)}catch(a){i(a)}})}abort(){this._messageSender({type:"abort-source-buffer",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,value:null})}dispose(e){this.abort(),this._canceller.cancel(e!=null?e:"WorkerSourceBufferInterface dispose")}getBuffered(){}_addOperationToQueue(e,t,r){this._pendingOperations.set(e,{resolve:a,reject:o});let i=this._canceller.signal.register(s=>{this._pendingOperations.delete(e),r(s)});function a(s){i(),t(s)}function o(s){i(),r(s)}}_performNextQueuedOperationIfItExists(){let e=this._queuedOperations.shift();if(e!==void 0)try{if(e.operationName===0){let[t,r]=e.params,i;t instanceof ArrayBuffer?i=t:t.byteLength===t.buffer.byteLength?i=t.buffer:i=t.buffer.slice(t.byteOffset,t.byteLength+t.byteOffset);let a=Br();this._messageSender({type:"source-buffer-append",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,operationId:a,value:{data:i,params:r}},[i]),this._addOperationToQueue(a,e.resolve,e.reject)}else{let[t,r]=e.params,i=Br();this._messageSender({type:"source-buffer-remove",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,operationId:i,value:{start:t,end:r}}),this._addOperationToQueue(i,e.resolve,e.reject)}}catch(t){e.reject(t)}}};function ji(n){let e=n.map(o=>Math.log(o/n[0])),t=e.map(o=>o-e[0]+1),r=(t[t.length-1]-1)/(n.length*2+10),i=1/r;return n.map((o,s)=>a(s));function a(o){if(o===0)return 0;let s=Math.min(Math.max(1,o),n.length-1);return n[s]===n[s-1]?a(o-1):i*(r+(n[s]*t[s-1]-n[s-1]*t[s])/(n[s]-n[s-1]))+4}}var Ue=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 Mn=class{constructor(){this._currentRepresentationData=null,this._lastRepresentationWithGoodScore=null}addSample(e,t,r){let i=r/t,a=this._currentRepresentationData,o;a!==null&&a.representation.id===e.id?(o=a.ewma,a.ewma.addSample(t,i),a.loadedDuration+=r,a.loadedSegments++):(o=new Ue(5),o.addSample(t,i),this._currentRepresentationData={representation:e,ewma:o,loadedDuration:r,loadedSegments:1}),o.getEstimate()>1&&this._lastRepresentationWithGoodScore!==e&&(c.debug("ABR","New last stable representation",{bitrate: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,a=t.getEstimate(),o=r>=6&&i>=10?1:0;return{score:a,confidenceLevel:o}}getLastStableRepresentation(){return this._lastRepresentationWithGoodScore}};var Ss=6e3,ol=15e3,sl=3e3,dl=1e3,ul=9e3,On=class{constructor(e){this._levelsMap=ji(e).map(t=>t+4),this._bitrates=e,this._lastUnsuitableQualityTimestamp=void 0,this._blockRaiseDelay=Ss,c.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:a,currentScore:o,speed:s}=e;if(v(a)){this._currentEstimate=r[0];return}let d=-1;for(let h=0;h<r.length;h++){let b=r[h];if(b===a)d=h;else if(b>a)break}if(d<0||r.length!==t.length){c.info("ABR","Current Bitrate not found in the calculated levels"),this._currentEstimate=r[0];return}let u;o!==void 0&&(u=s===0?o.score:o.score/s);let f=isFinite(i)?i:0,l=F();if(f<t[d]||u!==void 0&&u<1&&(o==null?void 0:o.confidenceLevel)===1){if((this._lastUnsuitableQualityTimestamp===void 0?-1:l-this._lastUnsuitableQualityTimestamp)<this._blockRaiseDelay+ul){let p=this._blockRaiseDelay+sl;c.debug("ABR","Incrementing blocking raise in BufferBasedChooser due to unstable quality",{prevDelay:this._blockRaiseDelay,newDelay:p}),this._blockRaiseDelay=Math.min(p,ol)}else{let p=this._blockRaiseDelay-dl;c.debug("ABR","Lowering quality in BufferBasedChooser",{prevDelay:this._blockRaiseDelay,newDelay:p}),this._blockRaiseDelay=Math.max(Ss,p)}this._lastUnsuitableQualityTimestamp=l;let b=ae(r,p=>p===a);for(let p=b-1;p>=0;p--)if(f>=t[p]){this._currentEstimate=r[p];return}this._currentEstimate=r[0];return}if(this._lastUnsuitableQualityTimestamp!==void 0&&l-this._lastUnsuitableQualityTimestamp<this._blockRaiseDelay||u===void 0||u<1.15||(o==null?void 0:o.confidenceLevel)!==1){this._currentEstimate=a;return}let m=t[d],g=(()=>{for(let h=d+1;h<t.length;h++)if(t[h]>m)return h})();if(g!==void 0){let h=t[g];if(i>=h){c.debug("ABR","Raising quality in BufferBasedChooser",{bitrate:r[g]}),this._currentEstimate=r[g];return}}this._currentEstimate=a}getLastEstimate(){return this._currentEstimate}};function ll(n,e){let t=-1;for(let o=0;o<n.length;o++){let{segment:s}=n[o].content;if(s.duration<=0)continue;let d=s.time+s.duration;if(!s.complete&&o===n.length-1&&e-s.time>-1.2){t=o;break}if(d>e&&e-s.time>-1.2){t=o;break}}if(t<0)return[];let r=n[t],i=r.content.segment.time,a=[r];for(let o=t+1;o<n.length&&n[o].content.segment.time===i;o++)a.push(n[o]);return a}function Nr(n){if(n.progress.length<5)return;let e=new Ue(2),{progress:t}=n;for(let r=1;r<t.length;r++){let i=t[r].size-t[r-1].size,a=t[r].timestamp-t[r-1].timestamp,o=i*8/(a/1e3);e.addSample(a/1e3,o)}return e.getEstimate()}function ys(n,e){let t=(n.totalSize-n.size)*8;return Math.max(t/e,0)}function fl(n,e,t,r,i){if(r)return;let{bufferGap:a,speed:o,position:s}=e,d=isFinite(a)?a:0,u=s.getWanted()+d,f=ll(n,u);if(f.length!==1)return;let l=f[0],m=F(),g=l.content.segment.duration*1500;if(g=Math.max(g,3e3),g=Math.min(g,12e3),m-l.requestTimestamp<g)return;let h=l.progress.length>0?l.progress[l.progress.length-1]:void 0,b=Nr(l);if(h!==void 0&&b!==void 0){let C=ys(h,b);if((m-h.timestamp)/1e3<=C&&C-d/o>2500)return b}if(!l.content.segment.complete)return;let p=l.content.segment.duration,S=(m-l.requestTimestamp)/1e3,T=S<=(p*1.5+2)/o;if(v(t)||T)return;let R=p/S,E=t.bitrate*Math.min(.7,R);if(i===void 0||E<i)return E}function ml(n,e,t){if(t)return!0;let r=isFinite(n.bufferGap)?n.bufferGap:0,i=n.position.getWanted()+r,a=j(e,({content:l})=>l.segment.duration>0&&l.segment.time+l.segment.duration>i);if(a===void 0)return!0;let o=F(),s=a.progress.length>0?a.progress[a.progress.length-1]:void 0,d=Nr(a);if(s===void 0||d===void 0)return!0;let u=ys(s,d);return(o-s.timestamp)/1e3>u*1.2?!0:u-r/n.speed>-1.5}var wn=class{constructor(e,t){let{ABR_STARVATION_GAP:r,OUT_OF_STARVATION_GAP:i,ABR_STARVATION_FACTOR:a,ABR_REGULAR_FACTOR:o}=L.getCurrent();this._initialBitrate=e,this._inStarvationMode=!1,this._lowLatencyMode=t,t?this._config={starvationGap:r.LOW_LATENCY,outOfStarvationGap:i.LOW_LATENCY,starvationBitrateFactor:a.LOW_LATENCY,regularBitrateFactor:o.LOW_LATENCY}:this._config={starvationGap:r.DEFAULT,outOfStarvationGap:i.DEFAULT,starvationBitrateFactor:a.DEFAULT,regularBitrateFactor:o.DEFAULT}}getBandwidthEstimate(e,t,r,i,a){let o,s,d=this._config,{bufferGap:u,position:f,duration:l}=e,m=isFinite(u)?u:0,{ABR_STARVATION_DURATION_DELTA:g}=L.getCurrent();return isNaN(l)||m+f.getWanted()<l-g?!this._inStarvationMode&&m<=d.starvationGap?(c.info("ABR","enter starvation mode.",{buffergap:m,enterStarvation:d.starvationGap}),this._inStarvationMode=!0):this._inStarvationMode&&m>=d.outOfStarvationGap&&(c.info("ABR","exit starvation mode.",{bufferGap:m,outOfStarvation:d.starvationGap}),this._inStarvationMode=!1):this._inStarvationMode&&(c.info("ABR","exit starvation mode.",{bufferGap:m}),this._inStarvationMode=!1),this._inStarvationMode&&(s=fl(i,e,r,this._lowLatencyMode,a),s!==void 0&&(c.info("ABR","starvation mode emergency estimate:",{bandwidth:s}),t.reset(),o=v(r)?s:Math.min(s,r.bitrate))),v(o)&&(s=t.getEstimate(),s!==void 0?o=s*(this._inStarvationMode?d.starvationBitrateFactor:d.regularBitrateFactor):a!==void 0?o=a*(this._inStarvationMode?d.starvationBitrateFactor:d.regularBitrateFactor):o=this._initialBitrate),e.speed>1&&(o/=e.speed),{bandwidthEstimate:s,bitrateChosen:o}}isUrgent(e,t,r,i){return t===null?!0:e>=t.bitrate?!1:ml(i,r,this._lowLatencyMode)}};var Dn=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 Bn=class{constructor(e,t){this._scoreCalculator=e,this._lastAbrEstimate=t,this._consecutiveWrongGuesses=0,this._blockGuessesUntil=0,this._lastMaintanableBitrate=null}getGuess(e,t,r,i,a){let{bufferGap:o,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(o,s,u)){let l=Ts(e,r);if(l!==null)return l}return null}if(this._isLastGuessValidated(d,i,u)&&(c.debug("ABR","Guessed Representation validated",{chosenBitrate:d.bitrate,otherAbrAlgosBitrate:i,scoreData:u==null?void 0:u.score,scoreConfidence:u==null?void 0:u.confidenceLevel}),this._lastMaintanableBitrate=d.bitrate,this._consecutiveWrongGuesses=0),r.id!==d.id)return d;if(this._shouldStopGuess(r,u,o,a))return this._consecutiveWrongGuesses++,this._blockGuessesUntil=F()+Math.min(this._consecutiveWrongGuesses*15e3,12e4),cl(e,r);if(u===void 0)return r;if(this._canGuessHigher(o,s,u)){let l=Ts(e,r);if(l!==null)return l}return r}_canGuessHigher(e,t,{score:r,confidenceLevel:i}){return isFinite(e)&&e>=2.5&&F()>this._blockGuessesUntil&&i===1&&r/t>1.01}_shouldStopGuess(e,t,r,i){if(t!==void 0&&t.score<1.01)return!0;if((t===void 0||t.score<1.2)&&r<.6)return!0;let a=i.filter(s=>s.content.representation.id===e.id),o=F();for(let s of a){let d=o-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=Nr(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 Ts(n,e){let t=n.length,r=ae(n,({id:i})=>i===e.id);if(r<0)return c.error("ABR","Current Representation not found."),null;for(;++r<t;)if(n[r].bitrate>e.bitrate)return n[r];return null}function cl(n,e){let t=ae(n,({id:r})=>r===e.id);if(t<0)return c.error("ABR","Current Representation not found."),null;for(;--t>=0;)if(n[t].bitrate<e.bitrate)return n[t];return null}var Nn=class{constructor(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=L.getCurrent();this._fastEWMA=new Ue(e),this._slowEWMA=new Ue(t),this._bytesSampled=0}addSample(e,t){let{ABR_MINIMUM_CHUNK_SIZE:r}=L.getCurrent();if(t<r)return;let i=t*8e3/e,a=e/1e3;this._bytesSampled+=t,this._fastEWMA.addSample(a,i),this._slowEWMA.addSample(a,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 Ue(e),this._slowEWMA=new Ue(t),this._bytesSampled=0}};function Yi(n,e){if(n.length===0)return[];n.sort((a,o)=>a.bitrate-o.bitrate);let t=n[0].bitrate,r=Math.max(e,t),i=ae(n,a=>a.bitrate>r);return i===-1?n:n.slice(0,i)}function Qi(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,f;return((u=s.width)!=null?u:0)-((f=d.width)!=null?f:0)}),a=j(i,s=>typeof s.width=="number"&&s.width>=t&&typeof s.height=="number"&&s.height>=r);if(a===void 0)return n;let o=typeof a.width=="number"?a.width:0;return n.filter(s=>typeof s.width=="number"?s.width<=o:!0)}var Un=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(v(t)){if(I.CURRENT_ENV===I.DEV)throw new Error("ABR: progress for a request not added");c.warn("ABR","progress for a request not added",{requestId:e.id});return}t.progress.push(e)}remove(e){if(v(this._currentRequests[e])){if(I.CURRENT_ENV===I.DEV)throw new Error("ABR: can't remove unknown request");c.warn("ABR","can't remove unknown request",{requestId:e})}delete this._currentRequests[e]}getRequests(){return yr(this._currentRequests).filter(e=>!v(e)).sort((e,t)=>e.content.segment.time-t.content.segment.time)}};function Ur(n,e){let t=ae(n,r=>r.bitrate>e);return t===-1?n[n.length-1]:t===0?n[0]:n[t-1]}var Es=new $(void 0);Es.finish();var _s=new $(1/0);_s.finish();function $i(n){let e={},{initialBitrates:t,throttlers:r,lowLatencyMode:i}=n;return function(s,d,u,f,l){var p,S,T;let{type:m}=s.adaptation,g=a(m),h=(p=t[m])!=null?p:0,b={limitResolution:(S=r.limitResolution[m])!=null?S:Es,throttleBitrate:(T=r.throttleBitrate[m])!=null?T:_s};return pl({bandwidthEstimator:g,context:s,currentRepresentation:d,filters:b,initialBitrate:h,playbackObserver:f,representations:u,lowLatencyMode:i},l)};function a(o){let s=e[o];if(v(s)){c.debug("ABR","Creating new BandwidthEstimator",{bufferType:o});let d=new Nn;return e[o]=d,d}return s}}function pl({bandwidthEstimator:n,context:e,currentRepresentation:t,filters:r,initialBitrate:i,lowLatencyMode:a,playbackObserver:o,representations:s},d){let u=new Mn,f=new wn(i!=null?i:0,a),l=new Un,m=O,g={metrics:T,requestBegin:R,requestProgress:E,requestEnd:C,addedSegment(P){m(P)}},h=new z("ABR "+e.adaptation.type);h.linkToSignal(d);let b=p(s.getValue(),h.signal);return s.onUpdate(S,{clearSignal:d}),{estimates:b,callbacks:g};function p(P,x){if(P.length<=1)return new $({bitrate:void 0,representation:P[0],urgent:!0,knownStableBitrate:void 0});let A=!1,k=P.sort((U,G)=>U.bitrate-G.bitrate),N=new On(k.map(U=>U.bitrate)),w=new Dn,W=new Bn(u,w),B=o.getReference().getValue(),_=new $(D());return o.listen(U=>{B=U,M()},{includeLastObservation:!1,clearSignal:x}),m=function(U){if(B===null)return;let{position:G,speed:Q}=B,K=U.buffered,q=xr(K,G.getWanted()),{representation:Z}=U.content,X=u.getEstimate(Z),me=Z.bitrate,pe={bufferGap:q,currentBitrate:me,currentScore:X,speed:Q};N.onAddedSegment(pe),M()},x.register(()=>{m=O}),r.throttleBitrate.onUpdate(M,{clearSignal:x}),r.limitResolution.onUpdate(M,{clearSignal:x}),_;function M(){_.setValue(D())}function D(){let{bufferGap:U,position:G,maximumPosition:Q}=B,K=r.limitResolution.getValue(),q=r.throttleBitrate.getValue(),Z=t.getValue(),X=gl(k,K,q),me=l.getRequests(),{bandwidthEstimate:pe,bitrateChosen:Qe}=f.getBandwidthEstimate(B,n,Z,me,w.bandwidth),ie=u.getLastStableRepresentation(),se=ie===null?void 0:ie.bitrate/(B.speed>0?B.speed:1),{ABR_ENTER_BUFFER_BASED_ALGO:$t,ABR_EXIT_BUFFER_BASED_ALGO:Xt}=L.getCurrent();A&&U<=Xt?A=!1:!A&&isFinite(U)&&U>=$t&&(A=!0);let Re=Ur(X,Qe),Zt=N.getLastEstimate(),lr=Re.bitrate,ft=null;A&&Zt!==void 0&&Zt>lr&&(ft=Ur(X,Zt),lr=ft.bitrate);let mt=null;return a&&Z!==null&&e.manifest.isDynamic&&Q-G.getWanted()<40&&(mt=W.getGuess(k,B,Z,lr,me)),mt!==null&&mt.bitrate>lr?(c.debug("ABR","new guess-based estimate",{bitrate:mt.bitrate,representation:mt.id}),w.update(mt,pe,2),{bitrate:pe,representation:mt,urgent:Z===null||mt.bitrate<Z.bitrate,knownStableBitrate:se}):ft!==null?(c.debug("ABR","new buffer-based estimate",{bitrate:ft.bitrate,representation:ft.id}),w.update(ft,pe,0),{bitrate:pe,representation:ft,urgent:f.isUrgent(ft.bitrate,Z,me,B),knownStableBitrate:se}):(c.debug("ABR","new bandwidth estimate",{bitrate:Re.bitrate,representation:Re.id}),w.update(Re,pe,1),{bitrate:pe,representation:Re,urgent:f.isUrgent(Re.bitrate,Z,me,B),knownStableBitrate:se})}}function S(){let P=s.getValue();h.cancel("restart"),h=new z("ABR "+e.adaptation.type),h.linkToSignal(d),p(P,h.signal).onUpdate(function(k){b.setValue(k)},{clearSignal:h.signal,emitCurrentValue:!0})}function T(P){let{requestDuration:x,segmentDuration:A,size:k,content:N}=P;if(n.addSample(x,k),!N.segment.isInit){let{segment:w,representation:W}=N;if(A===void 0&&!w.complete)return;let B=A!=null?A:w.duration;u.addSample(W,x/1e3,B)}}function R(P){l.add(P)}function E(P){l.addProgress(P)}function C(P){l.remove(P.id)}}function gl(n,e,t){let r=n;return t!==void 0&&t<1/0&&(r=Yi(r,t)),e!==void 0&&(r=Qi(r,e)),r}var Rs=$i;function Lr(){var t;if(typeof((t=ne.crypto)==null?void 0:t.randomUUID)=="function")return ne.crypto.randomUUID();let n=new Date().getTime(),e=F();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let i=Math.random()*16;return n>0?(i=(n+i)%16|0,n=Math.floor(n/16)):(i=(e+i)%16|0,e=Math.floor(e/16)),(r==="x"?i:i&3|8).toString(16)})}var hl=/^(?:[a-z]+:)?\/\//i,Il=/^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/;function Zi(n){let e=n.lastIndexOf("/");if(e<0)return n.length;if(hl.test(n)){let r=n.indexOf("/");if(r>=0&&e===r+1)return n.length}let t=n.indexOf("?");return t>=0&&t<e?Zi(n.substring(0,t)):e+1}function Ps(n,e){let t=Fr(n),r=Fr(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=Fn(t.path),a=Fn(r.path),o;if(i===a)o="";else{let d=i.split("/");d.pop();let u=a.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 f=u.join("/");(f.endsWith("../")||f.endsWith("./"))&&(f=f.slice(0,f.length-1)),o=f===""?".":f}let s=o;return o===""&&r.query===t.query||Y(r.query)&&(s+="?",s+=r.query),Y(r.fragment)&&(s+="#",s+=r.fragment),s}function bl(n,e){let t=Fr(n),r=Fr(e);if(Y(r.scheme))return Xi(r);let i={scheme:t.scheme,authority:t.authority,path:"",query:r.query,fragment:r.fragment};return Y(r.authority)?(i.authority=r.authority,i.path=Fn(r.path),Xi(i)):(r.path===""?(i.path=t.path,Y(r.query)||(i.query=t.query)):Ie(r.path,"/")?i.path=Fn(r.path):i.path=Fn(yl(t,r.path)),Xi(i))}var Ln=new Map,Sl=200;function Fr(n){var r,i,a,o,s;if(Ln.has(n))return Ln.get(n);let e=n.match(Il),t;return e===null?t={scheme:"",authority:"",path:"",query:"",fragment:""}:t={scheme:(r=e[1])!=null?r:"",authority:(i=e[2])!=null?i:"",path:(a=e[3])!=null?a:"",query:(o=e[4])!=null?o:"",fragment:(s=e[5])!=null?s:""},Ln.size>=Sl&&Ln.clear(),Ln.set(n,t),t}function Xi(n){let e="";return Y(n.scheme)&&(e+=n.scheme+":"),Y(n.authority)&&(e+="//"+n.authority),e+=n.path,Y(n.query)&&(e+="?"+n.query),Y(n.fragment)&&(e+="#"+n.fragment),e}function Fn(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 yl(n,e){if(Y(n.authority)&&n.path==="")return"/"+e;let t=n.path;return t.substring(0,t.lastIndexOf("/")+1)+e}function zn(...n){var r,i,a;let e=n.filter(o=>o!==""),t=e.length;if(t===0)return"";if(t===1)return(r=e[0])!=null?r:"";{let o=(i=e[0])!=null?i:"",s=(a=e[1])!=null?a:"",d=bl(o,s),u=e.slice(2);return zn(d,...u)}}var Tl=4,Wn=class{constructor(e){var t,r;this._sessionId=(t=e.sessionId)!=null?t:Lr(),this._contentId=(r=e.contentId)!=null?r:Lr(),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("CmcdDataBuilder start"),this._canceller=new z("CMCD monitoring"),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("CmcdDataBuilder stop"),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||!isFinite(r.speed)||r.speed<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 o,s,d,u;let t=(o=this._playbackObserver)==null?void 0:o.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"),!v(e.nextSegment)&&e.segment.url!==null&&e.nextSegment.url!==null&&(!e.nextSegment.isInit||e.nextSegment.indexRange===void 0)){let f=e.segment.url,l=e.nextSegment.url,m=Ps(f,l);m!==null&&(m!=="."&&(r.nor=encodeURIComponent(m)),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 f=t.buffered[e.adaptation.type];if(!v(f)){let l=(u=(d=(s=this._playbackObserver)==null?void 0:s.getCurrentTime())!=null?d:t.position.getWanted())!=null?u:t.position.getPolled();for(let m of f)if(l>=m.start&&l<m.end){i=(m.end-l)*1e3,r.bl=Math.floor(Math.round(i/100)*100);break}}}let a=i===void 0||t===void 0||!isFinite(t.speed)||t.speed<=0?void 0:i/t.speed;if(r.dl=a===void 0?void 0:Math.floor(Math.round(a/100)*100),a!==void 0){let l=e.representation.bitrate*e.segment.duration/1e3/(a/1e3);r.rtp=Math.floor(Math.round(l*Tl/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((f,l)=>l.isPlayable()!==!0?f:f===void 0?Math.round(l.bitrate/1e3):Math.max(f,Math.round(l.bitrate/1e3)),void 0),this._producePayload(r)}_producePayload(e){let t={object:"",request:"",session:"",status:""},r="",i=(u,f)=>{this._typePreference===0?t[f]+=u:r+=u},a=(u,f)=>{let l=e[u];if(l!==void 0){let m=`${u}=${String(l)},`;i(m,f)}},o=(u,f)=>{if(e[u]===!0){let l=`${u},`;i(l,f)}},s=(u,f)=>{let l=e[u];if(l!==void 0){let m=`"${l.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,g=`${u}=${m},`;i(g,f)}},d=(u,f)=>{let l=e[u];if(l!==void 0){let m=`${u}=${l},`;i(m,f)}};return a("bl","request"),a("br","object"),o("bs","status"),s("cid","session"),a("d","object"),a("dl","request"),a("mtp","request"),s("nor","request"),s("nrr","request"),d("ot","object"),a("pr","session"),a("rtp","status"),d("sf","session"),s("sid","session"),d("st","session"),o("su","request"),a("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)),c.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),c.debug("CMCD","proposing query string payload",{queryString:r}),{type:"query",value:[["CMCD",r]]})}};var vs=Wn;var Vn=class extends ce{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=Cs(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 a=setTimeout(()=>{let o=Cs(this._downgradedCdnList.metadata,e);o>=0&&this._removeIndexFromDowngradeList(o),this.trigger("priorityChange",null)},i);this._downgradedCdnList.timeouts.push(a),this.trigger("priorityChange",null)}_innerGetCdnPreferenceForResource(e){let[t,r]=e.reduce((i,a)=>(this._downgradedCdnList.metadata.some(o=>o.id===a.id&&o.baseUrl===a.baseUrl)?i[1].push(a):i[0].push(a),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 Cs(n,e){return n.length===0?-1:e.id!==void 0?ae(n,t=>t.id===e.id):ae(n,t=>t.baseUrl===e.baseUrl)}function Le(n){return n instanceof le?new Xe("PIPELINE_LOAD_ERROR",n):ge(n,{defaultCode:"PIPELINE_LOAD_ERROR",defaultReason:"Unknown error when fetching the Manifest"})}function El(n){return n instanceof le?n.type===Pt.ERROR_HTTP_CODE?n.status>=500||n.status===404||n.status===415||n.status===412:n.type===Pt.TIMEOUT||n.type===Pt.ERROR_EVENT:n instanceof $e?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:Ut(n)&&n.code==="INTEGRITY_ERROR"}async function qn(n,e,t,r,i){if(i.cancellationError!==null)return Promise.reject(i.cancellationError);let{baseDelay:a,maxDelay:o,maxRetry:s,onRetry:d}=r;n!==null&&n.length===0&&c.warn("utils","No CDN given to `scheduleRequestWithCdns`.");let u=new Map,f=l();if(f===void 0)throw new Error("No CDN to request");return m(f);function l(){if(n===null){let p=u.get(null);return p!==void 0&&p.isBlacklisted?void 0:null}else{if(e===null)return b(n);{let p=e.getCdnPreferenceForResource(n);return b(p)}}}async function m(p){try{return await t(p,i)}catch(S){if(z.isCancellationError(S))throw S;p!==null&&e!==null&&e.downgradeCdn(p);let T=u.get(p);if(T===void 0?(T={errorCounter:1,blockedUntil:void 0,isBlacklisted:!1},u.set(p,T)):T.errorCounter++,!El(S))return T.blockedUntil=void 0,T.isBlacklisted=!0,g(S);if(T.errorCounter>s)T.blockedUntil=void 0,T.isBlacklisted=!0;else{let R=T.errorCounter,E=Math.min(a*Math.pow(2,R-1),o),C=Ai(E);T.blockedUntil=F()+C}return g(S)}}async function g(p){let S=l();if(i.isCancelled())throw i.cancellationError;if(S===void 0)throw p;if(d(p),i.isCancelled())throw i.cancellationError;return h(S,p)}function h(p,S){let T=u.get(p);if(T===void 0||T.blockedUntil===void 0)return m(p);let R=F(),E=T.blockedUntil-R;if(E<=0)return m(p);let C=new z("Request Backoff"),P=C.linkToSignal(i);return new Promise((x,A)=>{e==null||e.addEventListener("priorityChange",()=>{let w=l();if(!i.isCancelled()){if(w===void 0)return N(S);w!==p&&(C.cancel("new prioritized CDN"),h(w,S).then(k,N))}},C.signal),fn(E,C.signal).then(()=>m(p).then(k,N),w=>N(i.isCancelled()?i.cancellationError:w));function k(w){P(),x(w)}function N(w){P(),A(w)}})}function b(p){var T;if(u.size===0)return p[0];let S=F();return(T=p.filter(R=>{var E;return((E=u.get(R))==null?void 0:E.isBlacklisted)!==!0}).reduce((R,E)=>{var P;let C=(P=u.get(E))==null?void 0:P.blockedUntil;return C!==void 0&&C<=S&&(C=void 0),R===void 0?[E,C]:R[1]===void 0?R:C===void 0?[E,void 0]:C<R[1]?[E,C]:R},void 0))==null?void 0:T[0]}}function Ji(n,e,t){return qn(null,null,n,e,t)}var Gn=class extends ce{constructor(e,t,r){super(),this.scheduleManualRefresh=O,this._manifestUrls=e,this._pipelines=t.manifest,this._transportName=t.transportName,this._settings=r,this._canceller=new z("ManifestFetcher"),this._isStarted=!1,this._isRefreshPending=!1,this._consecutiveUnsafeMode=0,this._prioritizedContentUrl=null}dispose(e){this._canceller.cancel(e!=null?e:"ManifestFetcher dispose"),this.removeEventListener()}start(){if(this._isStarted)return;this._isStarted=!0;let e,t=this._settings.initialManifest;t instanceof It?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._manifestUrls=e,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,a=this._pipelines,o=e!=null?e:(u=this._manifestUrls)==null?void 0:u[0],s=this._getBackoffSetting(f=>{this.trigger("warning",Le(f))});try{let f=await d(o);return{parse:l=>this._parseLoadedManifest(f,l,o)}}catch(f){throw Le(f)}function d(f){var p;let{loadManifest:l}=a,m=r.requestTimeout===void 0?L.getCurrent().DEFAULT_REQUEST_TIMEOUT:r.requestTimeout,g=r.connectionTimeout===void 0?L.getCurrent().DEFAULT_CONNECTION_TIMEOUT:r.connectionTimeout;m<0&&(m=void 0),g<0&&(g=void 0);let h={timeout:m,connectionTimeout:g,cmcdPayload:(p=r.cmcdDataBuilder)==null?void 0:p.getCmcdDataForManifest(i)};return Ji(()=>l(f,h,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=F(),a=this._canceller.signal,o=this.trigger.bind(this),{sendingTime:s,receivedTime:d}=e,u=this._getBackoffSetting(p=>{this.trigger("warning",Le(p))}),f=r!=null?r:(b=this._manifestUrls)==null?void 0:b[0],l={externalClockOffset:t.externalClockOffset,unsafeMode:t.unsafeMode,previousManifest:t.previousManifest,originalUrl:f};try{let p=this._pipelines.parseManifest(e,l,g,a,m);if(_l(p)){let{manifest:S}=await p;return h(S)}else return h(p.manifest)}catch(p){throw ge(p,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"})}async function m(p){try{return await Ji(p,u,a)}catch(S){throw Le(S)}}function g(p){for(let S of p){if(a.isCancelled())return;let T=ge(S,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"});o("warning",T)}}function h(p){let S=F()-i;return c.info("MF",`Manifest parsed in ${S}ms`),{manifest:p,sendingTime:s,receivedTime:d,parsingTime:S}}}_getBackoffSetting(e){let{DEFAULT_MAX_MANIFEST_REQUEST_RETRY:t,INITIAL_BACKOFF_DELAY_BASE:r,MAX_BACKOFF_DELAY_BASE:i}=L.getCurrent(),{lowLatencyMode:a,maxRetry:o}=this._settings,s=a?r.LOW_LATENCY:r.REGULAR,d=a?i.LOW_LATENCY:i.REGULAR,u=o!=null?o: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:a,MIN_MANIFEST_PARSING_TIME_TO_ENTER_UNSAFE_MODE:o}=L.getCurrent(),s=r!==void 0?r+(i!=null?i:0):void 0,d=!1;this._consecutiveUnsafeMode>0?d=this._consecutiveUnsafeMode<a:s!==void 0&&(d=s>=o);let u=t===void 0?0:F()-t,f=Math.max(this._settings.minimumManifestUpdateInterval-u,0),l=new z("ManifestFetcher refresh handling");if(l.linkToSignal(this._canceller.signal),this.scheduleManualRefresh=m=>{let{enablePartialRefresh:g,delay:h,canUseUnsafeMode:b}=m,p=b&&d,S=t===void 0?0:F()-t,T=Math.max(this._settings.minimumManifestUpdateInterval-S,0),R=setTimeout(()=>{l.cancel("manifest request timeout"),this._triggerNextManifestRefresh(e,{enablePartialRefresh:g,unsafeMode:p})},Math.max((h!=null?h:0)-S,T));l.signal.register(()=>{clearTimeout(R)})},e.expired!==null){let m=setTimeout(()=>{var g;(g=e.expired)==null||g.then(()=>{l.cancel("manifest expiration"),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},O)},f);l.signal.register(()=>{clearTimeout(m)})}if(e.lifetime!==void 0&&e.lifetime>=0){let m=e.lifetime*1e3-u,g;s===void 0?g=m:e.lifetime<3&&s>=100?(g=Math.min(Math.max(3e3-u,Math.max(m,0)+s),m*6),c.info("MF","Manifest update rythm is too frequent. Postponing next request.",{regularRefreshDelay:m,newRefreshDelay:g})):s>=e.lifetime*1e3/10?(g=Math.min(Math.max(m,0)+s,m*6),c.info("MF","Manifest took too long to parse. Postponing next request",{regularRefreshDelay:m,newRefreshDelay:g})):g=m;let h=setTimeout(()=>{l.cancel("manifest request timeout"),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},Math.max(g,f));l.signal.register(()=>{clearTimeout(h)})}}_triggerNextManifestRefresh(e,{enablePartialRefresh:t,unsafeMode:r}){let i=e.updateUrl,a,o;this._prioritizedContentUrl!==null?(a=!0,o=this._prioritizedContentUrl,this._prioritizedContentUrl=null):(a=!t||i===void 0,o=a?e.getUrls()[0]:i);let s=e.clockOffset;r?(this._consecutiveUnsafeMode+=1,c.info("MF",'Refreshing the Manifest in "unsafeMode" for the '+String(this._consecutiveUnsafeMode)+" consecutive time.")):this._consecutiveUnsafeMode>0&&(c.info("MF",'Not parsing the Manifest in "unsafeMode" anymore after '+String(this._consecutiveUnsafeMode)+" consecutive times."),this._consecutiveUnsafeMode=0),!this._isRefreshPending&&(this._isRefreshPending=!0,this._fetchManifest(o).then(d=>d.parse({externalClockOffset:s,previousManifest:e,unsafeMode:r})).then(d=>{this._isRefreshPending=!1;let{manifest:u,sendingTime:f,parsingTime:l}=d,m=F();if(a)e.replace(u);else try{e.update(u)}catch(h){let b=h instanceof Error?h.message:"unknown error";c.warn("MF",`Attempt to update Manifest failed: ${b}`,"Re-downloading the Manifest fully");let{FAILED_PARTIAL_UPDATE_MANIFEST_REFRESH_DELAY:p}=L.getCurrent(),S=f===void 0?0:F()-f,T=Math.max(this._settings.minimumManifestUpdateInterval-S,0),R=O,E=setTimeout(()=>{R(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:!1})},Math.max(p-S,T));R=this._canceller.signal.register(()=>{clearTimeout(E)});return}let g=F()-m;this._recursivelyRefreshManifest(e,{sendingTime:f,parsingTime:l,updatingTime:g})}).catch(d=>{this._isRefreshPending=!1,this._onFatalError(d)}))}_onFatalError(e){this._canceller.isUsed()||(this.trigger("error",e),this.dispose("ManifestFetcher fatal err"))}};function _l(n){return n instanceof Promise}var ea=Gn;function ta(n,e){let t=new WeakMap;return{createRequest(r,i,a,o){let s=u=>e(r,a,u),d=n.create(s,i,a,o);return t.set(d,s),d},updatePriority(r,i){let a=t.get(r);if(a===void 0){c.warn("SF","Cannot update the priority of a request: task not found.");return}n.updatePriority(a,i)}}}var na=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}},As=na;var Rl=Me();function ra({bufferType:n,pipeline:e,cdnPrioritizer:t,cmcdDataBuilder:r,eventListeners:i,requestOptions:a}){let o;a.connectionTimeout===void 0||a.connectionTimeout<0?o=void 0:o=a.connectionTimeout;let s={timeout:a.requestTimeout<0?void 0:a.requestTimeout,connectionTimeout:o,cmcdPayload:void 0},d=fe(["audio","video"],n)?new As:void 0,{loadSegment:u,parseSegment:f}=e;return async function(m,g,h){var G,Q,K;let{segment:b,adaptation:p,representation:S,manifest:T,period:R}=m,E=He(m),C=Rl(),P,x=[],A=0,k=!1,N={segment:b,type:p.type,language:p.language,isLive:T.isLive,periodStart:R.start,periodEnd:R.end,mimeType:S.mimeType,baseCodecs:S.baseCodecs,chosenCodec:S.chosenCodec,manifestPublishTime:T.publishTime},w={onProgress(q){var Z;P===void 0&&q.totalSize!==void 0&&q.size<q.totalSize&&((Z=i.onProgress)==null||Z.call(i,{duration:q.duration,size:q.size,totalSize:q.totalSize,timestamp:F(),id:C}))},onNewChunk(q){g.onChunk(M(q,!0))}},W=d!==void 0?d.get(m):null;if(W!==null)return c.debug("SF","Found wanted segment in cache",E),g.onChunk(M(W,!1)),Promise.resolve();c.debug("SF","Beginning request",E),(G=i.onRequestBegin)==null||G.call(i,{requestTimestamp:F(),id:C,content:m}),h.register(B);try{let q=await qn(m.representation.cdnMetadata,t,_,H({onRetry:D},a),h);if(q.resultType==="segment-loaded"){let Z=q.resultData.responseData;d!==void 0&&d.add(m,q.resultData.responseData),g.onChunk(M(Z,!1))}else q.resultType==="segment-created"&&g.onChunk(M(q.resultData,!1));c.debug("SF","Segment request ended with success",E),g.onAllChunksReceived(),q.resultType!=="segment-created"?(P=q.resultData,U()):P=null,h.isCancelled()||(Q=i.onRequestEnd)==null||Q.call(i,{id:C}),h.deregister(B)}catch(q){throw h.deregister(B),P=null,q instanceof ue?(c.debug("SF","Segment request aborted",E),q):(c.debug("SF","Segment request failed",E),(K=i.onRequestEnd)==null||K.call(i,{id:C}),Le(q))}function B(){var q;P===void 0&&(c.debug("SF","Segment request cancelled",E),P=null,(q=i.onRequestEnd)==null||q.call(i,{id:C}))}function _(q){return s.cmcdPayload=r==null?void 0:r.getCmcdDataForSegmentRequest(m),u(q,N,s,h,w)}function M(q,Z){x.push(!1);let X=x.length-1;return function(pe){let Qe={data:q,isChunked:Z};try{let ie=f(Qe,N,pe);return x[X]||(A=A!==void 0&&ie.segmentType==="media"&&ie.chunkInfos!==null&&ie.chunkInfos.duration!==void 0?A+ie.chunkInfos.duration:void 0,x[X]=!0,U()),ie}catch(ie){throw ge(ie,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}}}function D(q){g.onRetry(Le(q))}function U(){var q;k||!v(P)&&P.size!==void 0&&P.requestDuration!==void 0&&x.length>0&&x.every(Z=>Z)&&(k=!0,(q=i.onMetrics)==null||q.call(i,{size:P.size,requestDuration:P.requestDuration,content:m,segmentDuration:A}))}}}function xs({maxRetry:n,lowLatencyMode:e,requestTimeout:t,connectionTimeout:r}){let{DEFAULT_MAX_REQUESTS_RETRY_ON_ERROR:i,DEFAULT_REQUEST_TIMEOUT:a,DEFAULT_CONNECTION_TIMEOUT:o,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?a:t,connectionTimeout:r===void 0?o:r}}var Hn=class extends ce{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,r){var s;(s=this._currentContentInfo)==null||s.currentCanceller.cancel(r!=null?r:"SegmentQueue reset");let i=new $({initSegment:null,segmentQueue:[]}),a=new z("SegmentQueue "+e.adaptation.type);a.signal.register(()=>{i.finish()});let o={content:e,downloadQueue:i,initSegmentInfoRef:t?new $(void 0):new $(null),currentCanceller:a,initSegmentRequest:null,mediaSegmentRequest:null,mediaSegmentAwaitingInitMetadata:null};return this._currentContentInfo=o,this.isMediaSegmentQueueInterrupted.onUpdate(d=>{d||(c.debug("SF","Media segment can be loaded again, restarting queue.",{type:e.adaptation.type}),this._restartMediaSegmentDownloadingQueue(o,"interrupt end"))},{clearSignal:a.signal}),i.onUpdate(d=>{let{segmentQueue:u}=d;if(u.length>0&&u[0].segment.id===o.mediaSegmentAwaitingInitMetadata)return;let f=o.mediaSegmentRequest;if(u.length===0){if(f===null)return;c.debug("SF","no more media segment to request. Cancelling queue.",{type:e.adaptation.type}),this._restartMediaSegmentDownloadingQueue(o,"media segment queue empty");return}else if(f===null){c.debug("SF","Media segments now need to be requested. Starting queue.",{type:e.adaptation.type,queueLength:u.length}),this._restartMediaSegmentDownloadingQueue(o,"media segment queue start");return}else{let l=u[0];if(f.segment.id!==l.segment.id){c.debug("SF","Next media segment changed, cancelling previous",{type:e.adaptation.type}),this._restartMediaSegmentDownloadingQueue(o,"next media segment changed");return}f.priority!==l.priority&&(c.debug("SF","Priority of next media segment changed, updating",{type:e.adaptation.type,prevPriority:f.priority,newPriority:l.priority}),this._segmentFetcher.updatePriority(f.request,l.priority));return}},{emitCurrentValue:!0,clearSignal:a.signal}),i.onUpdate(d=>{var f;let u=o.initSegmentRequest;if(d.initSegment!==null&&u!==null){d.initSegment.priority!==u.priority&&this._segmentFetcher.updatePriority(u.request,d.initSegment.priority);return}else if(((f=d.initSegment)==null?void 0:f.segment.id)===(u==null?void 0:u.segment.id))return;d.initSegment===null&&c.debug("SF","no more init segment to request. Cancelling queue.",{type:e.adaptation.type}),this._restartInitSegmentDownloadingQueue(o,d.initSegment,"init segment queue empty")},{emitCurrentValue:!0,clearSignal:a.signal}),i}stop(e){var t;(t=this._currentContentInfo)==null||t.currentCanceller.cancel(e!=null?e:"SegmentQueue stop"),this._currentContentInfo=null}_restartMediaSegmentDownloadingQueue(e,t){e.mediaSegmentRequest!==null&&e.mediaSegmentRequest.canceller.cancel(t!=null?t:"SegmentQueue media restart");let{downloadQueue:r,content:i,initSegmentInfoRef:a,currentCanceller:o}=e,s=()=>{var E;if(this.isMediaSegmentQueueInterrupted.getValue()){c.debug("SF","Segment fetching postponed because it cannot stream now.");return}let{segmentQueue:d}=r.getValue(),u=d[0];if(o!==null&&o.isUsed()){e.mediaSegmentRequest=null;return}if(u===void 0){e.mediaSegmentRequest=null,this.trigger("emptyQueue",null);return}let f=new z("SegmentQueue media segments queue "+i.adaptation.type),l=o===null?O:f.linkToSignal(o.signal),{segment:m,priority:g}=u,h=H({segment:m,nextSegment:(E=d[1])==null?void 0:E.segment},i),b=!1,p=!1;f.signal.register(()=>{e.mediaSegmentRequest=null,!b&&(e.mediaSegmentAwaitingInitMetadata===m.id&&(e.mediaSegmentAwaitingInitMetadata=null),b=!0,p=!1)});let S=C=>{Se(C.segmentType==="media","Should have loaded a media segment."),this.trigger("parsedMediaSegment",H({},C,{segment:m}))},T=()=>{let C=r.getValue().segmentQueue;if(C.length===0){b=!0,this.trigger("emptyQueue",null);return}else C[0].segment.id===m.id&&C.shift();b=!0,s()},R=this._segmentFetcher.createRequest(h,g,{onRetry:C=>{this.trigger("requestRetry",{segment:m,error:C})},beforeInterrupted(){c.info("SF","segment request interrupted temporarly.",{segmentId:m.id,segmentTime:m.time})},onChunk:C=>{let P=a.getValue();P!==void 0?S(C(P!=null?P:void 0)):(p=!0,a.waitUntilDefined(x=>{S(C(x!=null?x:void 0))},{clearSignal:f.signal}))},onAllChunksReceived:()=>{p?(e.mediaSegmentAwaitingInitMetadata=m.id,a.waitUntilDefined(()=>{e.mediaSegmentAwaitingInitMetadata=null,p=!1,this.trigger("fullyLoadedSegment",m)},{clearSignal:f.signal})):this.trigger("fullyLoadedSegment",m)},beforeEnded:()=>{l(),e.mediaSegmentRequest=null,p?a.waitUntilDefined(T,{clearSignal:f.signal}):T()}},f.signal);R.catch(C=>{l(),b||(b=!0,this.stop("request err"),this.trigger("error",C))}),e.mediaSegmentRequest={segment:m,priority:g,request:R,canceller:f}};s()}_restartInitSegmentDownloadingQueue(e,t,r){let{content:i,initSegmentInfoRef:a}=e;if(e.initSegmentRequest!==null&&e.initSegmentRequest.canceller.cancel(r!=null?r:"SegmentQueue init restart"),t===null)return;let o=new z("SegmentQueue init segment "+i.adaptation.type),s=e.currentCanceller===null?O:o.linkToSignal(e.currentCanceller.signal),{segment:d,priority:u}=t,f=H({segment:d,nextSegment:void 0},i),l=!1,m=this._segmentFetcher.createRequest(f,u,{onRetry:g=>{this.trigger("requestRetry",{segment:d,error:g})},beforeInterrupted:()=>{c.info("SF","init segment request interrupted temporarly.",{segmentId:d.id})},beforeEnded:()=>{s(),e.initSegmentRequest=null,l=!0},onChunk:g=>{var b;let h=g(void 0);Se(h.segmentType==="init","Should have loaded an init segment."),this.trigger("parsedInitSegment",H({},h,{segment:d})),h.segmentType==="init"&&a.setValue((b=h.initTimescale)!=null?b:null)},onAllChunksReceived:()=>{this.trigger("fullyLoadedSegment",d)}},o.signal);m.catch(g=>{s(),l||(l=!0,this.stop("request err"),this.trigger("error",g))}),o.signal.register(()=>{e.initSegmentRequest=null,!l&&(l=!0)}),e.initSegmentRequest={segment:d,priority:u,request:m,canceller:o}}};var jn=class{constructor({prioritySteps:e}){if(this._minPendingPriority=null,this._waitingQueue=[],this._pendingTasks=[],this._prioritySteps=e,this._prioritySteps.high>=this._prioritySteps.low)throw new Error("The max high level priority should be given a lowerpriority number than the min low priority.")}create(e,t,r,i){let a;return Ct(i,(o,s)=>(a={hasEnded:!1,priority:t,trigger:()=>{if(a.hasEnded)return;let u=()=>{g(),this._endTask(a)},f=h=>{r.beforeEnded(),u(),o(h)},l=h=>{u(),s(h)},m=new z(void 0),g=m.linkToSignal(i);a.interrupter=m,m.signal.register(()=>{a.interrupter=null,i.isCancelled()||r.beforeInterrupted()}),this._minPendingPriority=this._minPendingPriority===null?a.priority:Math.min(this._minPendingPriority,a.priority),this._pendingTasks.push(a),a.taskFn(m.signal).then(f).catch(h=>{!i.isCancelled()&&m.isUsed()&&h instanceof ue||l(h)})},taskFn:e,interrupter:null},this._canBeStartedNow(a)?(a.trigger(),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks()):this._waitingQueue.push(a),()=>this._endTask(a)))}_endTask(e){e.hasEnded=!0;let t=Kn(e.taskFn,this._waitingQueue);if(t>=0)this._waitingQueue.splice(t,1);else{let r=Kn(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=Kn(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=Kn(e,this._pendingTasks);if(i<0){c.warn("SF","request to update the priority of a non-existent task");return}let a=this._pendingTasks[i];if(a.priority===t)return;let o=a.priority;a.priority=t,this._minPendingPriority===null||t<this._minPendingPriority?this._minPendingPriority=t:this._minPendingPriority===o&&(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?(c.warn("SF","Tried to start a non existing task"),!1):(this._waitingQueue.splice(e,1)[0].trigger(),!0)}_interruptPendingTask(e){var r;let t=Kn(e.taskFn,this._pendingTasks);if(t<0){c.warn("SF","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("TaskPrioritizer interrupt")}_canBeStartedNow(e){return this._minPendingPriority===null||e.priority<=this._minPendingPriority}_isRunningHighPriorityTasks(){return this._minPendingPriority!==null&&this._minPendingPriority<=this._prioritySteps.high}};function Kn(n,e){return ae(e,t=>t.taskFn===n)}var Yn=class{constructor(e,t,r,i){let{MIN_CANCELABLE_PRIORITY:a,MAX_HIGH_PRIORITY_LEVEL:o}=L.getCurrent();this._transport=e,this._prioritizer=new jn({prioritySteps:{high:o,low:a}}),this._cdnPrioritizer=t,this._backoffOptions=i,this._cmcdDataBuilder=r}createSegmentQueue(e,t,r){let i=xs(this._backoffOptions),a=this._transport[e],o=ra({bufferType:e,pipeline:a,cdnPrioritizer:this._cdnPrioritizer,cmcdDataBuilder:this._cmcdDataBuilder,eventListeners:t,requestOptions:i}),s=ta(this._prioritizer,o);return new Hn(s,r)}};var ia=Yn;function aa(n,e){let{loadThumbnail:t}=n,r=[];return async function(a,o){o.register(E);let{segment:s,track:d}=a,u,f=j(r,({thumbnailContext:x})=>x.period.id===a.period.id&&x.track.id===a.track.id&&x.segment.id===a.segment.id);if(f!==void 0){c.debug("Thumbnails","Requesting same thumbnail than the pending one",{time:a.segment.time}),u=f,u.referenceCount++;let x;try{x=await u.promise}catch(A){throw o.deregister(E),A}if(o.deregister(E),o.isCancelled())throw o.cancellationError;return R(x)}let l=Pl({}),m;l.connectionTimeout===void 0||l.connectionTimeout<0?m=void 0:m=l.connectionTimeout;let g={timeout:l.requestTimeout<0?void 0:l.requestTimeout,connectionTimeout:m,cmcdPayload:void 0},h=new z("Thumbnail request"),b=T();u={thumbnailContext:a,promise:b,referenceCount:1},r.push(u);let p=()=>{let x=r.indexOf(u);x>=0&&r.splice(x,1)},S;try{S=await b}catch(x){throw p(),o.deregister(E),x}if(p(),o.deregister(E),o.isCancelled())throw o.cancellationError;return R(S);async function T(){c.debug("Thumbnails","Beginning thumbnail request",{time:s.time});try{let x=await qn(d.cdnMetadata,e,C,H({onRetry:P},l),h.signal);return c.debug("Thumbnails","Thumbnail request ended with success",{time:s.time}),x}catch(x){throw x instanceof ue?(c.debug("Thumbnails","Thumbnail request aborted",{time:s.time}),x):(c.debug("Thumbnails","Thumbnail request failed",{time:s.time}),Le(x))}}function R(x){try{return n.parseThumbnail(x.responseData,{thumbnail:s,thumbnailTrack:d})}catch(A){throw ge(A,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}}function E(){c.debug("Thumbnails","Thumbnail request cancelled",{time:s.time});let x=r.indexOf(u);x<0||(r[x].referenceCount--,r[x].referenceCount<=0&&(h.cancel("Thumbnail request aborted"),r.splice(x,1)))}function C(x){return t(x,s,g,h.signal)}function P(x){let A=Le(x);c.warn("Thumbnails","Thumbnail request retry ",{time:s.time},A)}}}function Pl({maxRetry:n,requestTimeout:e,connectionTimeout:t}){let{DEFAULT_MAX_THUMBNAIL_REQUESTS_RETRY_ON_ERROR:r,DEFAULT_THUMBNAIL_REQUEST_TIMEOUT:i,DEFAULT_THUMBNAIL_CONNECTION_TIMEOUT:a,INITIAL_BACKOFF_DELAY_BASE:o,MAX_BACKOFF_DELAY_BASE:s}=L.getCurrent();return{maxRetry:n!=null?n:r,baseDelay:o.REGULAR,maxDelay:s.REGULAR,requestTimeout:e===void 0?i:e,connectionTimeout:t===void 0?a:t}}var Qn=class{constructor(e,t){this._contentId=e,this._messageSender=t,this._queues={pushTextData:[],remove:[]}}pushTextData(e){return new Promise((t,r)=>{this._queues.pushTextData.push({resolve:t,reject:r}),this._messageSender({type:"push-text-data",contentId:this._contentId,value:e})})}remove(e,t){return new Promise((r,i)=>{this._queues.remove.push({resolve:r,reject:i}),this._messageSender({type:"remove-text-data",contentId:this._contentId,value:{start:e,end:t}})})}reset(){this._messageSender({type:"reset-text-displayer",contentId:this._contentId,value:null}),this._resetCurrentQueue("WorkerTextDisplayerInterface reset")}stop(e){this._messageSender({type:"stop-text-displayer",contentId:this._contentId,value:null}),this._resetCurrentQueue(e)}_resetCurrentQueue(e){let t=new ue("WorkerTextDisplayerInterface queue",e!=null?e:"reset");this._queues.pushTextData.forEach(r=>{r.reject(t)}),this._queues.pushTextData.length=0,this._queues.remove.forEach(r=>{r.reject(t)}),this._queues.remove.length=0}onPushedTrackSuccess(e){let t=this._queues.pushTextData.shift();if(t===void 0){c.error("text","pushTextData success for inexistant operation");return}t.resolve(e)}onPushedTrackError(e){let t=this._queues.pushTextData.shift();if(t===void 0){c.error("text","pushTextData error for inexistant operation");return}t.reject(e)}onRemoveSuccess(e){let t=this._queues.remove.shift();if(t===void 0){c.error("text","remove success for inexistant operation");return}t.resolve(e)}onRemoveError(e){let t=this._queues.remove.shift();if(t===void 0){c.error("text","remove error for inexistant operation");return}t.reject(e)}};var ks=6,oa=4e3,zr=6e3,vl=6e4,qt=class{constructor(e){this._segmentSinksStore=e,this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=null,this._lastFlushAttempt=null,this._lastSegmentInfo={audio:[],video:[]}}onNewObservation(e){var p,S;let t=F();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:a}=L.getCurrent(),{readyState:o,rebuffering:s,freezing:d,fullyLoaded:u}=e,f=e.position.getPolled(),l=Ms(e.bufferGap);if(!(d!==null||o===1&&(l>=ks||u)))return this._decipherabilityFreezeStartingTimestamp=null,null;let g=(S=(p=d==null?void 0:d.timestamp)!=null?p:s==null?void 0:s.timestamp)!=null?S:null;if(c.info("Freeze","Freeze detected",{freezeStart:g,timeFrozen:t-(g!=null?g:t)}),this._lastFlushAttempt!==null&&t-this._lastFlushAttempt.timestamp<a.MAXIMUM&&t-this._lastFlushAttempt.timestamp>=a.MINIMUM&&Math.abs(f-this._lastFlushAttempt.position)<a.POSITION_DELTA){let T=this._getStrategyIfFlushingFails(f);return this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+zr,T}let b=this._checkForDecipherabilityRelatedFreeze(e,t);return b!==null?b:g!==null&&t-g>r?(this._lastFlushAttempt={timestamp:t,position:f+i},c.debug("Freeze","Trying to flush to un-freeze"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+zr,{type:"flush",value:{relativeSeek:i}}):null}_checkForDecipherabilityRelatedFreeze(e,t){let{readyState:r,rebuffering:i,freezing:a,fullyLoaded:o}=e,s=Ms(e.bufferGap),d=i!==null&&t-i.timestamp>oa,{hasUndecipherableData:u,hasEncryptedData:f}=Cl(this._segmentSinksStore);if(u===!0)return c.warn("Freeze","we have undecipherable segments left in the buffer, reloading"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+zr,{type:"reload",value:null};let l=a!==null&&t-a.timestamp>oa;return(d||l)&&(s>=ks||o)&&r<=1?this._decipherabilityFreezeStartingTimestamp===null&&(c.debug("Freeze","Start of a potential decipherability freeze detected"),this._decipherabilityFreezeStartingTimestamp=t):this._decipherabilityFreezeStartingTimestamp=null,this._decipherabilityFreezeStartingTimestamp!==null&&F()-this._decipherabilityFreezeStartingTimestamp>oa&&f&&u===!1?(c.warn("Freeze","we are frozen despite only having decipherable segments left in the buffer, reloading"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+zr,{type:"reload",value:null}):null}_getStrategyIfFlushingFails(e){c.warn("Freeze","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 a=i[i.length-1];if(a.segment===null)continue;let o=a.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!==o.infos.representation.uniqueId&&a.timestamp-u.timestamp<5e3){s=u;break}else u.segment.start===o.start&&e-u.position<3e3&&(a=u)}if(s===void 0||s.segment===null)c.debug("Freeze","Freeze when beginning to play a content, try avoiding this quality"),t.push({adaptation:o.infos.adaptation,period:o.infos.period,representation:o.infos.representation});else{if(o.infos.period.id!==s.segment.infos.period.id)return c.debug("Freeze","Freeze when switching Period, reloading"),{type:"reload",value:null};o.infos.representation.uniqueId!==s.segment.infos.representation.uniqueId&&(c.warn("Freeze","Freeze when switching Representation, avoiding",{bitrate:o.infos.representation.bitrate}),t.push({adaptation:o.infos.adaptation,period:o.infos.period,representation:o.infos.representation}))}}return t.length>0?{type:"avoid-representations",value:t}:(c.debug("Freeze","Reloading because flush doesn't work"),{type:"reload",value:null})}_addPositionToHistory(e,t){var i,a;let r=e.position.getPolled();for(let o of["audio","video"]){let s=this._segmentSinksStore.getStatus(o);if(s.type==="initialized")for(let f of s.value.getLastKnownInventory())((i=f.bufferedStart)!=null?i:f.start)<=r&&((a=f.bufferedEnd)!=null?a:f.end)>r&&this._lastSegmentInfo[o].push({segment:f,position:r,timestamp:t});else this._lastSegmentInfo[o].push({segment:null,position:r,timestamp:t});if(this._lastSegmentInfo[o].length>100){let f=this._lastSegmentInfo[o].length-100;this._lastSegmentInfo[o].splice(0,f)}let d=t-vl,u;for(u=0;u<this._lastSegmentInfo[o].length&&!(this._lastSegmentInfo[o][u].timestamp>d);u++);u>0&&this._lastSegmentInfo[o].splice(0,u)}}};function Cl(n){let e=!0,t=!0;for(let r of["audio","video"]){let i=n.getStatus(r);if(i.type==="initialized")for(let a of i.value.getLastKnownInventory()){let{representation:o}=a.infos;if(o.decipherable===!1)return{hasUndecipherableData:!0,hasEncryptedData:!0};o.contentProtections!==void 0&&(t=!1,o.decipherable!==!0&&(e=!1))}}return{hasEncryptedData:!t,hasUndecipherableData:e?!1:void 0}}function Ms(n){return n!==void 0&&isFinite(n)?n:0}var $n=class{constructor(){this._refs=new Map}reset(){var e,t,r,i,a,o,s,d,u,f,l,m;for(let g of this._refs.keys())(t=(e=this._refs.get(g))==null?void 0:e.audio)==null||t.trackReference.finish(),(i=(r=this._refs.get(g))==null?void 0:r.audio)==null||i.representations.finish(),(o=(a=this._refs.get(g))==null?void 0:a.video)==null||o.trackReference.finish(),(d=(s=this._refs.get(g))==null?void 0:s.video)==null||d.representations.finish(),(f=(u=this._refs.get(g))==null?void 0:u.text)==null||f.trackReference.finish(),(m=(l=this._refs.get(g))==null?void 0:l.text)==null||m.representations.finish();this._refs=new Map}addTrackSetter(e,t,r){var s,d;let i=this._refs.get(e);i===void 0&&(i={},this._refs.set(e,i)),i[t]!==void 0&&(c.warn("Track","Track for periodId already declared",{periodId:e,bufferType:t}),(s=i[t])==null||s.trackReference.finish(),(d=i[t])==null||d.representations.finish());let a=r.getValue(),o;v(a)?o=new $({representationIds:[],switchingMode:"lazy"}):(o=new $(a.representations.getValue()),r.setValue(H({},a,{representations:o}))),i[t]={trackReference:r,representations:o}}setTrack(e,t,r){var a;let i=(a=this._refs.get(e))==null?void 0:a[t];return i===void 0?(c.debug("Track","Setting track for inexistent periodId",{periodId:e,bufferType:t}),!1):(v(r)?(i.representations=new $({representationIds:[],switchingMode:"lazy"}),i.trackReference.setValue(r)):(i.representations=new $(r.initialRepresentations),i.trackReference.setValue({adaptationId:r.adaptationId,switchingMode:r.switchingMode,representations:i.representations,relativeResumingPosition:r.relativeResumingPosition})),!0)}updateRepresentations(e,t,r,i){var s;let a=(s=this._refs.get(e))==null?void 0:s[r];if(a===void 0)return c.debug("Track","Setting track for inexistent periodId",{periodId:e,bufferType:r}),!1;let o=a.trackReference.getValue();return v(o)||o.adaptationId!==t?(c.debug("Track","Desynchronized Adaptation id",{oldId:o==null?void 0:o.adaptationId,newId:t}),!1):(a.representations.setValue(i),!0)}removeTrackSetter(e,t){let r=this._refs.get(e),i=r==null?void 0:r[t];return r===void 0||i===void 0?(c.debug("Track","Removing track setter for inexistent periodId",{periodId:e,bufferType:t}),!1):(i.trackReference.finish(),i.representations.finish(),delete r[t],Object.keys(r).length===0&&this._refs.delete(e),!0)}};function Oe(n){return ge(n,{defaultCode:"NONE",defaultReason:"An unknown error stopped content playback."}).serialize()}function Os(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 ws(n){var t,r;if(v(ln.MediaSource_))return;let e=new Map;for(let i of n.periods){let a=[...(t=i.adaptations.video)!=null?t:[],...(r=i.adaptations.audio)!=null?r:[]];for(let o of a)for(let s of o.representations){let d=s.getMimeTypeString();if(e.has(d))s.isCodecSupportedInWebWorker=e.get(d);else{let u=ln.MediaSource_.isTypeSupported(d);s.isCodecSupportedInWebWorker=u,e.set(d,u)}}}}function Ds(n,e){var a,o,s,d,u,f,l;let t,r,i;return typeof((a=n.representationFilter)==null?void 0:a.fn)=="function"?i=n.representationFilter.fn:typeof((o=n.representationFilter)==null?void 0:o.eval)=="string"?i=Ro(n.representationFilter.eval):typeof((s=n.representationFilter)==null?void 0:s.workerId)=="string"&&(i=e.representationFilters.get(n.representationFilter.workerId)),typeof((d=n.manifestLoader)==null?void 0:d.fn)=="function"?t=n.manifestLoader.fn:typeof((u=n.manifestLoader)==null?void 0:u.workerId)=="string"&&(t=e.manifestLoaders.get(n.manifestLoader.workerId)),typeof((f=n.segmentLoader)==null?void 0:f.fn)=="function"?r=n.segmentLoader.fn:typeof((l=n.segmentLoader)==null?void 0:l.workerId)=="string"&&(r=e.segmentLoaders.get(n.segmentLoader.workerId)),{manifestLoader:t,segmentLoader:r,representationFilter:i}}var Bs=Me(),Gt=class{constructor({hasVideo:e}){this._currentContent=null,this._currentMediaSourceCanceller=new z("ContentPreparer MediaSource"),this._hasVideo=e;let t=new z("ContentPreparer");this._contentCanceller=t}initializeNewContent(e,t,r,i){return new Promise((a,o)=>{var D,U;this.disposeCurrentContent("new init");let s=this._contentCanceller,d=new z("ContentPreparer MediaSource");this._currentMediaSourceCanceller=d,d.linkToSignal(s.signal);let{contentId:u,url:f,hasText:l,transportOptions:m,useMseInWorker:g,enableRepresentationAvoidance:h,transport:b}=t,p=null,S=ke.transports[b];if(typeof S!="function"){o(new Error(`transport "${b}" not supported. Did you add the corresponding feature?`));return}let T=S(J(J({},m),Ds(m,i))),R=t.cmcd===void 0?null:new vs(t.cmcd),E=new ea(f===void 0?void 0:[f],T,J({cmcdDataBuilder:R},t.manifestRetryOptions)),C=Rs({initialBitrates:{audio:(D=t.initialAudioBitrate)!=null?D:0,video:(U=t.initialVideoBitrate)!=null?U:0},lowLatencyMode:m.lowLatencyMode,throttlers:r}),P=d.signal.register(G=>{o(G)}),x=new Vn(s.signal),A=new ia(T,x,R,t.segmentRetryOptions),k=aa(T.thumbnails,x),N=new $n,[w,W,B]=Ns(e,u,{useMseInWorker:g,hasVideo:this._hasVideo,hasText:l},d.signal),_=new qt(W);this._currentContent={cmcdDataBuilder:R,contentId:u,enableRepresentationAvoidance:h,freezeResolver:_,mediaSource:w,manifest:null,manifestFetcher:E,representationEstimator:C,segmentSinksStore:W,segmentQueueCreator:A,fetchThumbnailData:k,coreTextSender:B,trackChoiceSetter:N,useMseInWorker:g},w.addEventListener("mediaSourceOpen",function(){M()},d.signal),s.signal.register(G=>{E.dispose(G.reason)}),E.addEventListener("warning",G=>{e({type:"warning",contentId:u,value:Oe(G)})},s.signal),E.addEventListener("manifestReady",G=>{if(p!==null){c.warn("Core","Multiple `manifestReady` events, ignoring");return}p=G,this._currentContent!==null&&(this._currentContent.manifest=p),M()},d.signal),E.addEventListener("error",G=>{o(G)},s.signal),E.start();function M(){p===null||w.readyState==="closed"||d.isUsed()||(ws(p),p.addEventListener("manifestUpdate",G=>{p!==null&&e({type:"manifest-update",contentId:u,value:{manifest:p,updates:G}})},s.signal),P(),a(p))}})}getCurrentContent(){return this._currentContent}scheduleManifestRefresh(e){var t;(t=this._currentContent)==null||t.manifestFetcher.scheduleManualRefresh(e)}reloadMediaSource(e){var a;if(this._currentMediaSourceCanceller.cancel("ContentPreparer MediaSource reload"),this._currentContent===null)return Promise.reject(new Error("CP: No content anymore"));this._currentContent.trackChoiceSetter.reset(),(a=this._currentContent.coreTextSender)==null||a.stop("ContentPreparer MediaSource reload"),this._currentMediaSourceCanceller=new z("ContentPreparer MediaSource"),this._currentMediaSourceCanceller.linkToSignal(this._contentCanceller.signal);let[t,r,i]=Ns(e,this._currentContent.contentId,{useMseInWorker:this._currentContent.useMseInWorker,hasVideo:this._hasVideo,hasText:this._currentContent.coreTextSender!==null},this._currentMediaSourceCanceller.signal);return this._currentContent.mediaSource=t,this._currentContent.segmentSinksStore=r,this._currentContent.freezeResolver=new qt(r),this._currentContent.coreTextSender=i,new Promise((o,s)=>{t.addEventListener("mediaSourceOpen",function(){o()},this._currentMediaSourceCanceller.signal),t.addEventListener("mediaSourceClose",function(){s(new Error("MediaSource ReadyState changed to close during init."))},this._currentMediaSourceCanceller.signal),this._currentMediaSourceCanceller.signal.register(d=>{s(d)})})}disposeCurrentContent(e){this._contentCanceller.cancel(e),this._contentCanceller=new z("ContentPreparer")}};function Ns(n,e,t,r){let i;if(t.useMseInWorker){let d=new xn(Bs());i=d;let u,f=d.handle;if(f.type==="handle")u={type:"handle",value:f.value};else{let l=URL.createObjectURL(f.value);u={type:"url",value:l},r.register(()=>{URL.revokeObjectURL(l)})}n({type:"attach-media-source",contentId:e,value:u,mediaSourceId:i.id},[f.value])}else i=new kn(Bs(),e,n);let a=t.hasText?new Qn(e,n):null,{hasVideo:o}=t,s=new St(i,o,a);return r.register(d=>{s.disposeAll(d.reason),a==null||a.stop(d.reason),i.dispose(d.reason)}),[i,s,a]}var Us=.001,Xn=class extends ce{constructor(e,t,r){super(),this._canceller=new z("Boundaries Observation"),this._manifest=e,this._activeStreams=new Map,this._allBufferTypes=r,this._lastCurrentPeriodId=null;let i=new sa(e);fe(this._allBufferTypes,"video")||i.updateLastVideoAdaptation(null),fe(this._allBufferTypes,"audio")||i.updateLastAudioAdaptation(null),this._maximumPositionCalculator=i;let a=this._canceller.signal;at(()=>{t.listen(({position:o})=>{let s=o.getWanted(),d=e.getMinimumSafePosition(),u=i.getMaximumAvailablePosition();if(s<d-Us){let f=new ee("MEDIA_TIME_BEFORE_MANIFEST","The current position is behind the earliest time announced in the Manifest.",{timeInfo:{position:s,minPosition:d,maxPosition:u}});this.trigger("warning",f)}else if(s>u+Us){let f=new ee("MEDIA_TIME_AFTER_MANIFEST","The current position is after the latest time announced in the Manifest.",{timeInfo:{position:s,minPosition:d,maxPosition:u}});this.trigger("warning",f)}},{includeLastObservation:!1,clearSignal:a})}),e.addEventListener("manifestUpdate",()=>{this.trigger("endingPositionChange",this._getManifestEndTime()),!a.isCancelled()&&this._checkEndOfStream()},a)}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 a=this._maximumPositionCalculator.getEndingPosition(),o=a!==void 0?{isEnd:!0,endingPosition:a}:{isEnd:!1,endingPosition:this._maximumPositionCalculator.getMaximumAvailablePosition()};this.trigger("endingPositionChange",o)}}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(e){this.removeEventListener(),this._canceller.cancel(e!=null?e:"ContentTimeBoundariesObserver dispose")}_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 a=this._activeStreams.get(i);if(a===void 0)return;if(!a.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 kt((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)}},sa=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=Wr(this._lastVideoAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}}else if(this._lastVideoAdaptation===null){let e=Wr(this._lastAudioAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}else{let e=Wr(this._lastAudioAdaptation),t=Wr(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=Vr(this._lastVideoAdaptation))!=null?e:void 0;if(this._lastVideoAdaptation===null)return(t=Vr(this._lastAudioAdaptation))!=null?t:void 0;{let r=Vr(this._lastAudioAdaptation),i=Vr(this._lastVideoAdaptation);return typeof r!="number"||typeof i!="number"?void 0:Math.min(r,i)}}}};function Wr(n){let{representations:e}=n,t=null,r;for(let i of e)if(i.index!==r){r=i.index;let a=i.index.getLastAvailablePosition();if(a===void 0)return;a!==null&&(t=v(t)?a:Math.min(t,a))}return t}function Vr(n){let{representations:e}=n,t=null,r;for(let i of e)if(i.index!==r){r=i.index;let a=i.index.getEnd();if(a===void 0)return;a!==null&&(t=v(t)?a:Math.min(t,a))}return t}function da(n,e,t,r,i,a){a.register(d=>{e.interruptDurationSetting(d.reason)});let o=new Xn(n,t,r.getBufferTypes());a.register(d=>{o.dispose(d.reason)}),o.addEventListener("warning",d=>i.onWarning(d)),o.addEventListener("periodChange",d=>i.onPeriodChanged(d)),o.addEventListener("endingPositionChange",d=>{e.setDuration(d.endingPosition,d.isEnd)}),o.addEventListener("endOfStream",()=>{c.debug("mse","Start applying end-of-stream order."),e.maintainEndOfStream()}),o.addEventListener("resumeStream",()=>{e.stopEndOfStream()});let s=o.getCurrentEndingTime();return e.setDuration(s.endingPosition,s.isEnd),o}function ua(n,e){let t={audio:null,video:null,text:null};if(e!==null&&(t.text=e.getBufferedRanges()),n===null)return t;let r=j(n.sourceBuffers,s=>s.type==="audio"),i=j(n.sourceBuffers,s=>s.type==="video"),a=r==null?void 0:r.getBuffered();a!==void 0&&(t.audio=a);let o=i==null?void 0:i.getBuffered();return o!==void 0&&(t.video=o),t}async function la(n,e,t,r,i){let a=e.getPeriod(t);if(a===void 0)throw new Error("Wanted Period not found.");let o=j(a.thumbnailTracks,d=>d.id===r);if(o===void 0)throw new Error("Wanted Period has no thumbnail track.");let s=o.index.getSegments(i,1)[0];if(s===void 0)throw new Error("No thumbnail for the given timestamp");return n({segment:s,track:o,period:a},new z(void 0).signal)}function fa(n,e,t){let{DEFAULT_WANTED_BUFFER_AHEAD:r,DEFAULT_MAX_VIDEO_BUFFER_SIZE:i,DEFAULT_MAX_BUFFER_AHEAD:a,DEFAULT_MAX_BUFFER_BEHIND:o}=L.getCurrent(),s={wantedBufferAhead:new $(r),maxVideoBufferSize:new $(i),maxBufferAhead:new $(a),maxBufferBehind:new $(o),limitVideoResolution:new $({height:void 0,width:void 0,pixelRatio:1}),throttleVideoBitrate:new $(1/0)},d=!1,u=new Gt({hasVideo:!0}),f=null,l=null;n(m=>{var h,b;c.debug("Core","received message",{name:m.data.type});let g=m.data;switch(g.type){case"init":{if(Se(!d),d=!0,uo(g.value),Ls(g.value.logLevel,g.value.logFormat,g.value.sendBackLogs),!v(g.value.dashWasmUrl)){let p=ke.dashParsers.wasm;p===null?c.error("Core","Could not initialize DASH_WASM parser: DASH_WASM feature not added"):p.isCompatible()?p.initialize({wasmUrl:g.value.dashWasmUrl}).catch(S=>{let T=S instanceof Error?S.toString():"Unknown Error";c.error("Core","Could not initialize DASH_WASM parser",T)}):c.warn("Core","Could not initialize DASH_WASM parser: Browser not compatible")}g.value.hasVideo||(u.disposeCurrentContent("Received Init msg"),u=new Gt({hasVideo:g.value.hasVideo})),e({type:"init-success",value:null})}break;case"log-level-update":Ls(g.value.logLevel,g.value.logFormat,g.value.sendBackLogs);break;case"prepare":Al(e,u,g.value,s,t);break;case"start":{let p=u.getCurrentContent();if(g.contentId!==(p==null?void 0:p.contentId))return;f==null||f.stop(),l==null||l.finish();let S=new $(H(g.value.initialObservation,{position:new xt(...g.value.initialObservation.position)}));l=S,f=kl(e,g.value,u,S,s);break}case"observation":{let p=u.getCurrentContent();if(g.contentId!==(p==null?void 0:p.contentId))return;let S=g.value,{buffered:T}=S,R=ua(p.mediaSource,null);R.audio!==null&&(T.audio=R.audio),R.video!==null&&(T.video=R.video),l==null||l.setValue(H(S,{position:new xt(...g.value.position)}));break}case"ref-update":xl(g,s);break;case"stop":if(g.contentId!==((h=u.getCurrentContent())==null?void 0:h.contentId))return;u.disposeCurrentContent("StopContent message"),f==null||f.stop(),f=null,l==null||l.finish(),l=null;break;case"ms-reload":{let p=u.getCurrentContent();if(g.mediaSourceId!==(p==null?void 0:p.mediaSource.id))return;f==null||f.signalMediaSourceReload()}break;case"sb-success":{let p=u.getCurrentContent();if(g.mediaSourceId!==(p==null?void 0:p.mediaSource.id))return;let{sourceBuffers:S}=p.mediaSource,T=j(S,R=>R.type===g.sourceBufferType);if(T===void 0){c.info("Core","Success for an unknown SourceBuffer",{sourceBufferType:g.sourceBufferType});return}if(T.onOperationSuccess===void 0){c.warn("Core","A SourceBufferInterface with MSE performed a cross-thread operation",{sourceBufferType:g.sourceBufferType});return}T.onOperationSuccess(g.operationId,g.value.buffered);break}case"sb-error":{let p=u.getCurrentContent();if(g.mediaSourceId!==(p==null?void 0:p.mediaSource.id))return;let{sourceBuffers:S}=p.mediaSource,T=j(S,R=>R.type===g.sourceBufferType);if(T===void 0){c.info("Core","Error for an unknown SourceBuffer",{sourceBufferType:g.sourceBufferType});return}if(T.onOperationFailure===void 0){c.warn("Core","A SourceBufferInterface with MSE performed a cross-thread operation",{sourceBufferType:g.sourceBufferType});return}T.onOperationFailure(g.operationId,g.value);break}case"media-source-ready-state-change":{let p=u.getCurrentContent();if(g.mediaSourceId!==(p==null?void 0:p.mediaSource.id))return;if(p.mediaSource.onMediaSourceReadyStateChanged===void 0){c.warn("Core","A MediaSourceInterface with MSE performed a cross-thread operation");return}p.mediaSource.onMediaSourceReadyStateChanged(g.value);break}case"decipherability-update":{if(g.contentId!==((b=u.getCurrentContent())==null?void 0:b.contentId))return;let p=u.getCurrentContent();if(p===null||p.manifest===null)return;let S=g.value;p.manifest.updateRepresentationsDeciperability(T=>{for(let R of S)if(T.representation.uniqueId===R.representationUniqueId)return R.decipherable;return T.representation.decipherable});break}case"codec-support-update":{let p=u.getCurrentContent();if(p===null||p.manifest===null)return;let S=g.value;try{let T=p.manifest.updateCodecSupport(S);T!==null&&e({type:"warning",contentId:p.contentId,value:Oe(T)})}catch(T){e({type:"error",contentId:p.contentId,value:Oe(T)})}break}case"urls-update":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;p.manifestFetcher.updateContentUrls(g.value.urls,g.value.refreshNow);break}case"track-update":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;p.trackChoiceSetter.setTrack(g.value.periodId,g.value.bufferType,g.value.choice);break}case"rep-update":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;p.trackChoiceSetter.updateRepresentations(g.value.periodId,g.value.adaptationId,g.value.bufferType,g.value.choice);break}case"add-text-success":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;if(p.coreTextSender===null){c.error("Core","Added text track but text track aren't enabled");return}p.coreTextSender.onPushedTrackSuccess(g.value.ranges);break}case"push-text-error":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;if(p.coreTextSender===null){c.error("Core","Added text track but text track aren't enabled");return}p.coreTextSender.onPushedTrackError(new Error(g.value.message));break}case"remove-text-success":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;if(p.coreTextSender===null){c.error("Core","Removed text track but text track aren't enabled");return}p.coreTextSender.onRemoveSuccess(g.value.ranges);break}case"remove-text-error":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;if(p.coreTextSender===null){c.error("Core","Removed text track but text track aren't enabled");return}p.coreTextSender.onRemoveError(new Error(g.value.message));break}case"pull-segment-sink-store-infos":{Ml(e,u,g.value.requestId);break}case"thumbnail-request":{wl(e,u,g);break}case"config-update":{L.update(g.value);break}case"app-defined":break;default:Ne(g)}})}function Al(n,e,t,r,i){e.initializeNewContent(n,t,{limitResolution:{video:r.limitVideoResolution},throttleBitrate:{video:r.throttleVideoBitrate}},i).then(a=>{n({type:"manifest-ready",contentId:t.contentId,value:{manifest:a}})},a=>{n({type:"error",contentId:t.contentId,value:Oe(a)})})}function xl(n,e){switch(n.value.name){case"wantedBufferAhead":e.wantedBufferAhead.setValueIfChanged(n.value.newVal);break;case"maxVideoBufferSize":e.maxVideoBufferSize.setValueIfChanged(n.value.newVal);break;case"maxBufferBehind":e.maxBufferBehind.setValueIfChanged(n.value.newVal);break;case"maxBufferAhead":e.maxBufferAhead.setValueIfChanged(n.value.newVal);break;case"limitVideoResolution":e.limitVideoResolution.setValueIfChanged(n.value.newVal);break;case"throttleVideoBitrate":e.throttleVideoBitrate.setValueIfChanged(n.value.newVal);break;default:Ne(n.value)}}function kl(n,e,t,r,i){c.debug("Core","Loading pepared content.");let a=new z("Start Content Worker"),o=null;return s(e.initialTime),{signalMediaSourceReload:()=>u(),stop:()=>{a.cancel("ContentHandle stop")}};function s(f){var B;o==null||o.cancel("Reloading content worker"),o=new z("(Re)Loading Content Worker"),o.linkToSignal(a.signal);let l=new Map,m=t.getCurrentContent();if(m===null||m.manifest===null){let _=new _e("NONE","Loading content when none is prepared");throw n({type:"error",contentId:void 0,value:Oe(_)}),_}let{contentId:g,cmcdDataBuilder:h,enableRepresentationAvoidance:b,manifest:p,mediaSource:S,representationEstimator:T,segmentSinksStore:R,segmentQueueCreator:E}=m,{drmSystemId:C,enableFastSwitching:P,onCodecSwitch:x}=e;r.onUpdate(_=>{Os(_,R);let M=m.freezeResolver.onNewObservation(_);M!==null&&Ol(n,M,{contentId:g,manifest:p,handleMediaSourceReload:d,enableRepresentationAvoidance:b})},{clearSignal:o.signal});let A=(B=p.getPeriodForTime(f))!=null?B:p.getNextPeriod(f);if(A===void 0){let _=new ee("MEDIA_STARTING_TIME_NOT_FOUND","Wanted starting time not found in the Manifest.");throw n({type:"error",contentId:g,value:Oe(_)}),_}let k=new In(r,g,n,o.signal);h==null||h.startMonitoringPlayback(k),o.signal.register(()=>{h==null||h.stopMonitoringPlayback()});let N=da(p,S,k,R,{onWarning:_=>n({type:"warning",contentId:g,value:Oe(_)}),onPeriodChanged:_=>{n({type:"active-period-changed",contentId:g,value:{periodId:_.id}})}},o.signal);ps({initialPeriod:A,manifest:p},k,T,R,E,{wantedBufferAhead:i.wantedBufferAhead,maxVideoBufferSize:i.maxVideoBufferSize,maxBufferAhead:i.maxBufferAhead,maxBufferBehind:i.maxBufferBehind,drmSystemId:C,enableFastSwitching:P,onCodecSwitch:x},w(),o.signal);function w(){return{needsBufferFlush(_){n({type:"needs-buffer-flush",contentId:g,value:_})},streamStatusUpdate(_){W(_),p.isLastPeriodKnown&&_.period.id===p.periods[p.periods.length-1].id&&(_.hasFinishedLoading||_.isEmptyStream?N.onLastSegmentFinishedLoading(_.bufferType):N.onLastSegmentLoadingResume(_.bufferType))},needsManifestRefresh(){t.scheduleManifestRefresh({enablePartialRefresh:!0,canUseUnsafeMode:!0})},manifestMightBeOufOfSync(){let{OUT_OF_SYNC_MANIFEST_REFRESH_DELAY:_}=L.getCurrent();t.scheduleManifestRefresh({enablePartialRefresh:!1,canUseUnsafeMode:!1,delay:_})},lockedStream(_){n({type:"locked-stream",contentId:g,value:{periodId:_.period.id,bufferType:_.bufferType}})},adaptationChange(_){var M,D;n({type:"adaptation-changed",contentId:g,value:{adaptationId:(D=(M=_.adaptation)==null?void 0:M.id)!=null?D:null,periodId:_.period.id,type:_.type}}),N.onAdaptationChange(_.type,_.period,_.adaptation)},representationChange(_){var M,D;N.onRepresentationChange(_.type,_.period),!(o===null||o.signal.isCancelled())&&n({type:"representation-changed",contentId:g,value:{adaptationId:_.adaptation.id,representationId:(D=(M=_.representation)==null?void 0:M.id)!=null?D:null,periodId:_.period.id,type:_.type}})},inbandEvent(_){n({type:"inband-event",contentId:g,value:_})},warning(_){n({type:"warning",contentId:g,value:Oe(_)})},periodStreamReady(_){m!==null&&(m.trackChoiceSetter.addTrackSetter(_.period.id,_.type,_.adaptationRef),n({type:"period-stream-ready",contentId:g,value:{periodId:_.period.id,bufferType:_.type}}))},periodStreamCleared(_){if(m===null)return;let M=l.get(_.period);M!==void 0&&(M.delete(_.type),M.size===0&&l.delete(_.period)),N.onPeriodCleared(_.type,_.period),m.trackChoiceSetter.removeTrackSetter(_.period.id,_.type),n({type:"period-stream-cleared",contentId:g,value:{periodId:_.period.id,bufferType:_.type}})},bitrateEstimateChange(_){var M;m!==null&&((M=m.cmcdDataBuilder)==null||M.updateThroughput(_.type,_.bitrate)),n({type:"bitrate-estimate-change",contentId:g,value:{bitrate:_.bitrate,bufferType:_.type}})},needsMediaSourceReload(_){d(_)},needsDecipherabilityFlush(){n({type:"needs-decipherability-flush",contentId:g,value:null})},encryptionDataEncountered(_){for(let M of _){let D=M.content,U=J({},D);U.manifest instanceof It&&(U.manifest=U.manifest.getMetadataSnapshot()),U.period instanceof ht&&(U.period=U.period.getMetadataSnapshot()),U.adaptation instanceof ct&&(U.adaptation=U.adaptation.getMetadataSnapshot()),U.representation instanceof un&&(U.representation=U.representation.getMetadataSnapshot()),n({type:"encryption-data-encountered",contentId:g,value:{keyIds:M.keyIds,values:M.values,content:U,type:M.type}})}},error(_){n({type:"error",contentId:g,value:Oe(_)})}}}function W(_){let{imminentDiscontinuity:M}=_,D=l.get(_.period),U=D==null?void 0:D.get(_.bufferType);if(U!==void 0){if(U.discontinuity===null){if(M===null)return}else if(M!==null&&U.discontinuity.start===M.start&&U.discontinuity.end===M.end)return}D===void 0&&(D=new Map,l.set(_.period,D));let G={periodId:_.period.id,bufferType:_.bufferType,discontinuity:_.imminentDiscontinuity,position:_.position};D.set(_.bufferType,G),n({type:"discontinuity-update",contentId:g,value:G})}}function d(f){var m;o!==null&&(o.cancel("WorkerMain MediaSource reload"),o=null);let l=(m=t.getCurrentContent())==null?void 0:m.mediaSource.id;if(l===void 0){c.warn("Core","Cannot reload MediaSource: no MediaSource currently.");return}c.debug("Core","Reloading MediaSource",{timeOffset:f.timeOffset,minimumPosition:f.minimumPosition,maximumPosition:f.maximumPosition}),n({type:"reloading-media-source",mediaSourceId:l,value:f},[]),u()}function u(){var g;let l=r.getValue().position.getWanted();o!==null&&(o.cancel("MediaSource reload"),o=null);let m=(g=t.getCurrentContent())==null?void 0:g.contentId;t.reloadMediaSource(n).then(()=>{c.info("Core","MediaSource Reloaded, loading content again",{newInitialTime:l}),s(l)},h=>{if(z.isCancellationError(h)){c.info("Core","A reloading operation was cancelled");return}n({type:"error",contentId:m,value:Oe(h)})})}}function Ls(n,e,t){t?c.setLevel(n,"standard",(r,i,a)=>{let o=a.map(s=>s instanceof Error?Oe(s):s);postMessage({type:"log",value:{namespace:i,logLevel:r,logs:o}})}):c.setLevel(n,e)}function Ml(n,e,t){let r=e.getCurrentContent();if(r===null)return;let i=r.segmentSinksStore.getSegmentSinksMetrics();n({type:"segment-sink-store-update",contentId:r.contentId,value:{segmentSinkMetrics:i,requestId:t}})}function Ol(n,e,{contentId:t,manifest:r,handleMediaSourceReload:i,enableRepresentationAvoidance:a}){switch(e.type){case"reload":{c.info("Core","Planning reload due to freeze"),i({timeOffset:0,minimumPosition:0,maximumPosition:1/0});break}case"flush":{c.info("Core","Flushing buffer due to freeze"),n({type:"needs-buffer-flush",contentId:t,value:{relativeResumingPosition:e.value.relativeSeek,relativePosHasBeenDefaulted:!1}});break}case"avoid-representations":{c.info("Core","Planning Representation avoidance due to freeze");let o=e.value;a&&r.addRepresentationsToAvoid(o),i({timeOffset:0,minimumPosition:0,maximumPosition:1/0});break}default:Ne(e)}}function wl(n,e,t){let r=e.getCurrentContent(),i=a=>{n({type:"thumbnail-response",contentId:t.contentId,value:{status:"error",requestId:t.value.requestId,error:Oe(a)}})};if(r===null||r.manifest===null||r.contentId!==t.contentId)return i(new Error("Content changed"));la(r.fetchThumbnailData,r.manifest,t.value.periodId,t.value.thumbnailTrackId,t.value.time).then(a=>{let o=a.data.slice(0);n({type:"thumbnail-response",contentId:t.contentId,value:{status:"success",requestId:t.value.requestId,data:de(J({},a),{data:o})}},[o])},a=>i(a))}var Fs=fa;var Dl="<",Bl=60,zs=">",qr=62,ma=45,Ws=47,Nl=33,Vs=39,qs=34,ca=91,Ul=93,Ll=`\r
|
|
3
|
+
[${d.letter}] P: ${d.periodId} || R: ${d.representationId}(${(u=d.bitrate)!=null?u:"unknown bitrate"})`}),s}function zt(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 Wt(n,e){for(let t of n)if(t.infos.period.start>e.start)return t;return null}var ns=yn;var Vt=class{constructor(){this._segmentInventory=new ns}synchronizeInventory(e){this._segmentInventory.synchronizeBuffered(e)}getLastKnownInventory(){return this._segmentInventory.getInventory()}getSegmentHistory(e){return this._segmentInventory.getHistoryFor(e)}};var Tn=class extends Vt{constructor(e,t,r){super(),c.info("Stream","calling `mediaSource.addSourceBuffer`",{codec: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){rs(t),this._initSegmentsMap.set(e,t)}freeInitSegment(e){this._initSegmentsMap.delete(e)}async pushChunk(e){rs(e.data.chunk),c.debug("Stream","queuing push order",He(e.inventoryInfos));let t=this._getActualDataToPush(e.data);t.length===0&&t.push(new Uint8Array);let r=Promise.all(t.map(o=>{let{codec:s,timestampOffset:d,appendWindow:u}=e.data;return c.debug("Stream","now pushing",He(e.inventoryInfos)),this._sourceBuffer.appendBuffer(o,{codec:s,timestampOffset:d,appendWindow:u})}));this._addToOperationQueue(r,{type:0,value:e});let i;try{i=await r}catch(o){throw this._segmentInventory.insertChunk(e.inventoryInfos,!1,F()),o}e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,F());let a=i[i.length-1];return this._segmentInventory.synchronizeBuffered(a),a}async removeBuffer(e,t){c.debug("Stream","queuing remove order",{bufferType:this.bufferType,start:e,end: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(e){try{c.debug("Stream","Calling `dispose` on the SourceBufferInterface"),this._sourceBuffer.dispose(e)}catch(t){c.debug("Stream",`Failed to dispose a ${this.bufferType} SourceBufferInterface:`,t instanceof Error?t:"Unknown Error")}}_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),a=new Uint8Array(i);a.set(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer)),r=a,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 a=this._pendingOperations.indexOf(r);a>=0&&this._pendingOperations.splice(a,1)};e.then(i,i)}};function rs(n){if(I.CURRENT_ENV!==I.PRODUCTION&&(typeof n!="object"||n!==null&&!(n instanceof ArrayBuffer)&&!(n.buffer instanceof ArrayBuffer)))throw new Error("Invalid data given to the AudioVideoSegmentSink")}var wr=Tn;var En=class extends Vt{constructor(e){c.debug("Stream","Creating TextSegmentSink"),super(),this.bufferType="text",this._sender=e,this._pendingOperations=[],this._sender.reset()}declareInitSegment(e){c.warn("Stream","Declaring initialization segment for Text SegmentSink",{uniqueId:e})}freeInitSegment(e){c.warn("Stream","Freeing initialization segment for Text SegmentSink",{uniqueId:e})}async pushChunk(e){let{data:t}=e;Mu(t.chunk);let r=this._sender.pushTextData(de(J({},t),{chunk:t.chunk}));this._addToOperationQueue(r,{type:0,value:e});let i=await r;return e.inventoryInfos!==null&&this._segmentInventory.insertChunk(e.inventoryInfos,!0,F()),this._segmentInventory.synchronizeBuffered(i),i}async removeBuffer(e,t){let r=this._sender.remove(e,t);this._addToOperationQueue(r,{type:1,value:{start:e,end:t}});let i=await r;return this._segmentInventory.synchronizeBuffered(i),i}async signalSegmentComplete(e){if(this._pendingOperations.length>0){let{promise:t}=this._pendingOperations[this._pendingOperations.length-1];this._addToOperationQueue(t,{type:2,value:e});try{await t}catch(r){}}this._segmentInventory.completeSegment(e)}getPendingOperations(){return this._pendingOperations.map(e=>e.operation)}dispose(e){c.debug("Stream","Disposing TextSegmentSink"),this._sender.stop(e)}_addToOperationQueue(e,t){let r={operation:t,promise:e};this._pendingOperations.push(r);let i=()=>{let a=this._pendingOperations.indexOf(r);a>=0&&this._pendingOperations.splice(a,1)};e.then(i,i)}};function Mu(n){if(I.CURRENT_ENV!==I.PRODUCTION){if(typeof n!="object"||n===null||v(n.data))throw new Error("Invalid format given to a TextSegmentSink");if(!Ou(n))throw new Error("Invalid format given to a TextSegmentSink");if(typeof n.data!="string"&&typeof n.data.byteLength!="number")throw new Error("Invalid format given to a TextSegmentSink")}}function Ou(n){return!(typeof n!="object"||n===null||typeof n.type!="string"||n.language!==void 0&&typeof n.language!="string"||n.initTimescale!==null&&typeof n.initTimescale!="number"||n.start!==void 0&&typeof n.start!="number"||n.end!==void 0&&typeof n.end!="number")}I.CURRENT_ENV===I.DEV&&(wu=function(e){function t(r){}});var wu;var is=En;var Du=["audio","video","text"],_n=class n{static isNative(e){return as(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():Ct(e,t=>{let r=O,i=()=>{let a=this._onNativeBufferAddedOrDisabled.indexOf(r);a>=0&&this._onNativeBufferAddedOrDisabled.splice(a,1)};return r=()=>{this._areNativeBuffersUsable()&&(i(),t())},this._onNativeBufferAddedOrDisabled.push(r),i})}disableSegmentSink(e){let t=this._initializedSegmentSinks[e];if(t===null){c.warn("Stream",`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()),Se(this._onNativeBufferAddedOrDisabled.length===0))}createSegmentSink(e,t){let r=this._initializedSegmentSinks[e];if(as(e)){if(!v(r))return r instanceof wr&&r.codec!==t?c.warn("Stream","Reusing native SegmentSink with codec",r.codec,"for codec",t):c.info("Stream","Reusing native SegmentSink with codec",t),r;c.info("Stream","Adding native SegmentSink with codec",t);let a=e==="audio"?"audio":"video",o=new wr(a,t,this._mediaSource);return this._initializedSegmentSinks[e]=o,this._onNativeBufferAddedOrDisabled.slice().forEach(s=>s()),Se(this._onNativeBufferAddedOrDisabled.length===0),o}if(!v(r))return c.info("Stream","Reusing a previous custom SegmentSink",{bufferType:e}),r;let i;if(e==="text"){if(c.info("Stream","Creating a new text SegmentSink"),this._textInterface===null)throw new Error("HTML Text track feature not activated");return i=new is(this._textInterface),this._initializedSegmentSinks.text=i,i}throw c.error("Stream","Unknown buffer type:",{bufferType:e}),new ee("BUFFER_TYPE_UNKNOWN","The player wants to create a SegmentSink of an unknown type.")}disposeSegmentSink(e,t){let r=this._initializedSegmentSinks[e];if(v(r)){c.warn("Stream","Trying to dispose a SegmentSink that does not exist",{bufferType:e});return}c.info("Stream","Aborting SegmentSink",{bufferType:e}),r.dispose(t),delete this._initializedSegmentSinks[e]}disposeAll(e){Du.forEach(t=>{this.getStatus(t).type==="initialized"&&this.disposeSegmentSink(t,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,a;let t=(i=this._initializedSegmentSinks[e])==null?void 0:i.getLastKnownInventory(),r;if(t!==void 0){r=0;for(let o of t){if(o.chunkSize===void 0||r===void 0){r=void 0;break}r+=o.chunkSize}}return{bufferType:e,sizeEstimate:r,codec:(a=this._initializedSegmentSinks[e])==null?void 0:a.codec,segmentInventory:t==null?void 0:t.map(o=>de(J({},o),{infos:Bu(o.infos)}))}}getSegmentSinksMetrics(){return{segmentSinks:{audio:this.createSegmentSinkMetricsForType("audio"),video:this.createSegmentSinkMetricsForType("video"),text:this.createSegmentSinkMetricsForType("text")}}}};function as(n){return n==="audio"||n==="video"}function Bu(n){return{adaptation:n.adaptation.getMetadataSnapshot(),period:n.period.getMetadataSnapshot(),representation:n.representation.getMetadataSnapshot()}}var St=_n;var Rn=class{constructor({drmSystemId:e,representation:t,notify:r}){if(this._hasSentEncryptionData=!1,this._representation=t,this._notify=r,e!==void 0){let i=t.getEncryptionData(e);i.length>0&&i.every(a=>a.keyIds!==void 0)&&(this._hasSentEncryptionData=!0,r(i))}}onNewProtectionData(e){for(let t of e)this._representation.addProtectionData(t.initDataType,t.keyId,t.initData);if(!this._hasSentEncryptionData){let t=this._representation.getAllEncryptionData();t.length>0&&(this._notify(t),this._hasSentEncryptionData=!0)}}};function Oi(n,e,t,r,i){let{period:a,adaptation:o,representation:s}=n,d=Nu(i,e);if(d===null){if(t===null){if(r&&a.end!==void 0&&e.end>=a.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:(c.debug("Stream","current discontinuity encountered",{bufferType:o.type,nextSegmentTime:u.bufferedStart,checkStartTime:e.start}),{start:void 0,end:l})}let f=Uu(i,e,d+1);if(f!==null){let l=i[f-1],m=i[f];if(t===null||m.infos.segment.end<=t){if(!r&&s.index.awaitSegmentBetween(l.infos.segment.end,m.infos.segment.time)!==!1)return null;let g=l.bufferedEnd,h=m.bufferedStart;return c.debug("Stream","future discontinuity encountered",{bufferType:o.type,discontinuityStart:g,discontinuityEnd:h}),{start:g,end:h}}}if(t===null){if(r&&a.end!==void 0){if(e.end<a.end)return null;let l=Lu(i,a.end);if(l!==null){let m=i[l];if(m.bufferedEnd!==void 0&&m.bufferedEnd<a.end)return c.debug("Stream","discontinuity encountered at the end of the current period",{bufferType:o.type,segmentsEndTimeFromPeriod:m.bufferedEnd,periodEnd:a.end}),{start:m.bufferedEnd,end:null}}}if(a.end!==void 0&&e.end>=a.end)return null;for(let l=i.length-1;l>=0;l--){let m=i[l];if(m.bufferedStart===void 0)break;if(m.bufferedStart<e.end){if(m.bufferedEnd!==void 0&&m.bufferedEnd<e.end){let g=s.index.checkDiscontinuity(e.end);if(g!==null)return{start:m.bufferedEnd,end:g}}return null}}}return null}function Nu(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 Uu(n,e,t){if(t<=0)return c.error("Stream","Asked to check a discontinuity before the first chunk."),null;for(let r=t;r<n.length;r++){let i=n[r],a=n[r-1];if(i.bufferedStart===void 0||a.bufferedEnd===void 0||i.bufferedStart>=e.end)return null;if(i.bufferedStart-a.bufferedEnd>0)return r}return null}function Lu(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 wi({bufferedSegments:n,content:e,currentPlaybackTime:t,fastSwitchThreshold:r,getBufferedHistory:i,neededRange:a,segmentsBeingPushed:o,maxBufferSize:s}){let{adaptation:d,representation:u}=e,f=Fu(n,o,s),l=u.index.getSegments(a.start,a.end-a.start),m=n.filter(C=>!os(C.infos,e,t,r)),g=Ku(m,a,i),{MINIMUM_SEGMENT_SIZE:h,MIN_BUFFER_AHEAD:b}=L.getCurrent(),p=!1,S=Math.min(1/60,h),T=!1,R=[];return{segmentsToLoad:l.filter(C=>{let P=H({segment:C},e);if(o.length>0&&o.some(B=>it(P,B)))return!1;let{duration:x,time:A,end:k}=C;if(C.isInit)return!0;if(p)return R.push(C),!1;if(C.complete&&x<h||o.length>0&&o.some(B=>{if(B.period.id!==e.period.id||B.adaptation.id!==e.adaptation.id)return!1;let{segment:_}=B;if(_.time-S>A)return!1;if(_.complete){if(_.end+S<k)return!1}else if(Math.abs(A-_.time)>A)return!1;return!os(B,P,t,r)}))return!1;for(let W of g){let B=W.infos.period.id===e.period.id;if(W.status===1&&B){let _=W.infos.segment;if(A-_.time>-S){if(_.complete){if(_.end-k>-S)return!1}else if(Math.abs(A-_.time)<S)return!1}}}let N=x*e.representation.bitrate;if(f-N<0&&(T=!0,A>a.start+b))return p=!0,R.push(C),!1;let w=i(P);if(w.length>1){let W=w[w.length-1],B=w[w.length-2];if(W.buffered===null&&B.buffered===null)return c.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.",{bufferType:d.type,representationId:u.id,segmentTime:C.time}),!1}for(let W=0;W<g.length;W++){let B=g[W];if(B.end+S>A){let _=B.start>A+S||zu(g,W).end<k-S;return _&&(f-=N),_}}return f-=N,!0}),segmentsOnHold:R,isBufferFull:T}}function Fu(n,e,t){let r=t*8e3;return r-=e.reduce((i,a)=>{let{bitrate:o}=a.representation,{duration:s}=a.segment;return i+o*s},0),n.reduce((i,a)=>a.chunkSize!==void 0?i-a.chunkSize*8:i,r)}function zu(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 os(n,e,t,r){let{CONTENT_REPLACEMENT_PADDING:i}=L.getCurrent();if(n.period.id!==e.period.id)return!1;let{segment:a}=n;return a.time<t+i?!1:n.adaptation.id!==e.adaptation.id?!0:Wu(n.representation,e.representation,r)}function Wu(n,e,t){let r=n.bitrate,{BITRATE_REBUFFERING_RATIO:i}=L.getCurrent();if(t===void 0){let a=r*i;return e.bitrate>a}return r<t&&e.bitrate>r}function Vu(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?(c.info("Stream","The start of the wanted segment has been garbage collected",{segmentStart:n.start,currentStartInBuffer:n.bufferedStart}),!0):!1}function qu(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?(c.info("Stream","The end of the wanted segment has been garbage collected",{segmentEnd:n.end,currentEndInBuffer:n.bufferedEnd}),!0):!1}function Gu(n,e){var o,s;if(n.length<2)return!0;let r=(o=n[n.length-1].buffered)==null?void 0:o.start;if(e!==void 0&&r!==void 0&&e-r>.05)return!0;let a=(s=n[n.length-2].buffered)==null?void 0:s.start;return a===void 0||r===void 0?!0:Math.abs(a-r)>.01}function Hu(n,e){var o,s;if(n.length<2)return!0;let r=(o=n[n.length-1].buffered)==null?void 0:o.end;if(e!==void 0&&r!==void 0&&r-e>.05)return!0;let a=(s=n[n.length-2].buffered)==null?void 0:s.end;return a===void 0||r===void 0?!0:Math.abs(a-r)>.01}function Ku(n,e,t){return n.filter((r,i,a)=>{let o=i===0?null:a[i-1],s=i>=a.length-1?null:a[i+1],d=null;if(Vu(r,o,e.start)){if(d=t(r.infos),Gu(d,r.bufferedStart))return!1;c.debug("Stream","skipping segment gc-ed at the start",{segmentStart:r.start,currentStartInBuffer:r.bufferedStart})}if(qu(r,s,e.end)){if(d=d!=null?d:t(r.infos),Hu(d,r.bufferedEnd))return!1;c.debug("Stream","skipping segment gc-ed at the end",{segmentEnd:r.end,currentEndInBuffer:r.bufferedEnd})}return!0})}function Pn(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 Di(n,e,t,r,i,a,o){var A,k,N;let{representation:s}=n,d=(k=(A=t.getIsPaused())!=null?A:t.getReference().getValue().paused.pending)!=null?k:t.getReference().getValue().paused.last,u=(N=t.getPlaybackRate())!=null?N:t.getReference().getValue().speed,f=e;(d===void 0||u===void 0||d||u<=0)&&(f-=.1);let l=ju(n,f,i),m=s.index.shouldRefresh(l.start,l.end),g=o.getPendingOperations().filter(w=>w.type===2).map(w=>w.value),h=o.getLastKnownInventory(),b=t.getCurrentTime();b===void 0&&(b=t.getReference().getValue().position.getWanted());let p=o.getSegmentHistory.bind(o),{segmentsToLoad:S,segmentsOnHold:T,isBufferFull:R}=wi({content:n,bufferedSegments:h,currentPlaybackTime:b,fastSwitchThreshold:r,getBufferedHistory:p,neededRange:l,segmentsBeingPushed:g,maxBufferSize:a}),E=S.map(w=>({priority:Pn(w.time,f),segment:w})),C=s.index.isInitialized()&&!s.index.isStillAwaitingFutureSegments()&&l.hasReachedPeriodEnd&&E.length===0&&T.length===0,P=null;return g.length>0&&(P=Math.min(...g.map(w=>w.segment.time))),T.length>0&&(P=P!==null?Math.min(P,T[0].time):T[0].time),E.length>0&&(P=P!==null?Math.min(P,E[0].segment.time):E[0].segment.time),{imminentDiscontinuity:Oi(n,l,P,C,h),hasFinishedLoading:C,neededSegments:E,isBufferFull:R,shouldRefreshManifest:m}}function ju(n,e,t){var l;let r,{manifest:i,period:a,representation:o}=n,s=o.index.getLastAvailablePosition(),d=o.index;!v(s)&&St.isNative(n.adaptation.type)&&e>=s&&d.isInitialized()&&!d.isStillAwaitingFutureSegments()&&Yu(i,a,e)?r=s-1:r=e-.1;let u=r+t,f;return!o.index.isInitialized()||o.index.isStillAwaitingFutureSegments()||a.end===void 0?f=!1:s===void 0?f=u>=a.end:s===null?f=!0:f=u>=s,{start:Math.max(r,a.start),end:Math.min(u,(l=a.end)!=null?l:1/0),hasReachedPeriodEnd:f}}function Yu(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 vn(n,e,t,r,i){try{return await e.pushChunk(t)}catch(a){if(i.isCancelled()&&a instanceof ue)throw a;if(!(a instanceof xe)||!a.isBufferFull){let d=a instanceof Error?a.toString():"An unknown error happened when pushing content";throw new ee("BUFFER_APPEND_ERROR",d,{tracks:[vt(t.inventoryInfos.adaptation)]})}let{position:o}=n.getReference().getValue(),s=o.getWanted();try{c.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 gi(200),i.cancellationError!==null)throw i.cancellationError;return await e.pushChunk(t)}catch(d){if(d instanceof ue)throw d;let u=d instanceof Error?d.toString():"Could not clean the buffer";throw new ee("BUFFER_FULL_ERROR",u,{tracks:[vt(t.inventoryInfos.adaptation)]})}}}async function Bi({playbackObserver:n,content:e,initSegmentUniqueId:t,segment:r,segmentSink:i,bufferGoal:a},o){let s=e.representation.getMimeTypeString(),d={initSegmentUniqueId:t,chunk:null,timestampOffset:0,appendWindow:[void 0,void 0],codec:s},u=H({segment:r,chunkSize:void 0,start:0,end:0},e),f=await vn(n,i,{data:d,inventoryInfos:u},a,o);return{content:e,segment:r,buffered:f}}async function Ni({playbackObserver:n,bufferGoal:e,content:t,initSegmentUniqueId:r,parsedSegment:i,segment:a,segmentSink:o},s){var P,x;if(i.chunkData===null)return null;let{chunkData:d,chunkInfos:u,chunkOffset:f,chunkSize:l,appendWindow:m}=i,g=t.representation.getMimeTypeString(),{APPEND_WINDOW_SECURITIES:h}=L.getCurrent(),b=[m[0]!==void 0?Math.max(0,m[0]-h.START):void 0,m[1]!==void 0?m[1]+h.END:void 0],p={initSegmentUniqueId:r,chunk:d,timestampOffset:f,appendWindow:b,codec:g},S=(P=u==null?void 0:u.time)!=null?P:a.time,T=(x=u==null?void 0:u.duration)!=null?x:a.duration,R=S+T;b[0]!==void 0&&(S=Math.max(S,b[0])),b[1]!==void 0&&(R=Math.min(R,b[1]));let E=H({segment:a,chunkSize:l,start:S,end:R},t),C=await vn(n,o,{data:p,inventoryInfos:E},e,s);return{content:t,segment:a,buffered:C}}function Ui({content:n,options:e,playbackObserver:t,segmentSink:r,segmentQueue:i,terminate:a},o,s){c.debug("Stream","Creating RepresentationStream",{periodStart:n.period.start,bufferType:n.adaptation.type,adaptationId:n.adaptation.id,representationBitrate:n.representation.bitrate,mimeType:n.representation.getMimeTypeString()});let{period:d,adaptation:u,representation:f}=n,{bufferGoal:l,maxBufferSize:m,drmSystemId:g,fastSwitchThreshold:h}=e,b=u.type,p=new z("RepresentationStream "+b);p.linkToSignal(s);let S={segment:f.index.getInitSegment(),uniqueId:null,isLoaded:!1};p.signal.register(()=>{S.uniqueId!==null&&r.freeInitSegment(S.uniqueId)});let T=S.segment!==null;T||(S.isLoaded=!0);let R=new Rn({drmSystemId:g,representation:f,notify:A=>o.encryptionDataEncountered(A.map(k=>H({content:n},k)))});if(p.isUsed())return;i.addEventListener("error",A=>{p.signal.isCancelled()||(p.cancel("RepresentationStream: SegmentQueue err"),o.error(A))},p.signal),i.addEventListener("parsedInitSegment",P,p.signal),i.addEventListener("parsedMediaSegment",P,p.signal),i.addEventListener("emptyQueue",C,p.signal),i.addEventListener("requestRetry",A=>{if(o.warning(A.error),p.signal.isCancelled())return;let k=A.segment,{index:N}=f;N.isSegmentStillAvailable(k)===!1?C():N.canBeOutOfSyncError(A.error,k)&&o.manifestMightBeOufOfSync()},p.signal),i.addEventListener("fullyLoadedSegment",A=>{r.signalSegmentComplete(H({segment:A},n)).catch(x)},p.signal);let E=i.resetForContent(n,T,"new RepresentationStream linked to SegmentQueue");p.signal.register(A=>{i.stop(A.reason)}),t.listen(C,{includeLastObservation:!1,clearSignal:p.signal}),n.manifest.addEventListener("manifestUpdate",C,p.signal),l.onUpdate(C,{emitCurrentValue:!1,clearSignal:p.signal}),m.onUpdate(C,{emitCurrentValue:!1,clearSignal:p.signal}),a.onUpdate(C,{emitCurrentValue:!1,clearSignal:p.signal}),C();return;function C(){if(p.isUsed())return;let A=t.getReference().getValue(),k=A.position.getWanted(),N=Di(n,k,t,h.getValue(),l.getValue(),m.getValue(),r),{neededSegments:w}=N,W=null;if(f.index.isInitialized()){if(w.length>0&&!S.isLoaded&&S.segment!==null){let M=w[0].priority;W={segment:S.segment,priority:M}}}else if(S.segment===null)c.warn("Stream","Uninitialized index without an initialization segment",{bufferType:b,representationBitrate:n.representation.bitrate});else if(S.isLoaded)c.warn("Stream","Uninitialized index with an already loaded initialization segment",{bufferType:b,representationBitrate:n.representation.bitrate});else{let M=A.position.getWanted();W={segment:S.segment,priority:Pn(d.start,M)}}let B=a.getValue();if(B===null)E.setValue({initSegment:W,segmentQueue:w});else if(B.urgent){c.debug("Stream","Urgent switch, terminate now.",{bufferType:b,representationBitrate:n.representation.bitrate}),E.setValue({initSegment:null,segmentQueue:[]}),E.finish(),p.cancel(B.reason),o.terminating();return}else{let M=w[0],D=i.getRequestedInitSegment(),U=i.getRequestedMediaSegment(),G=U===null||M===void 0||U.id!==M.segment.id?[]:[M],Q=D===null?null:W;if(E.setValue({initSegment:Q,segmentQueue:G}),G.length===0&&Q===null){c.debug("Stream","No request left, terminate",{bufferType:b,representationBitrate:n.representation.bitrate}),E.finish(),p.cancel(B.reason),o.terminating();return}}if(o.streamStatusUpdate({period:d,position:A.position.getWanted(),bufferType:b,imminentDiscontinuity:N.imminentDiscontinuity,isEmptyStream:!1,hasFinishedLoading:N.hasFinishedLoading,neededSegments:N.neededSegments}),p.signal.isCancelled())return;let{UPTO_CURRENT_POSITION_CLEANUP:_}=L.getCurrent();if(N.isBufferFull){let M=Math.max(0,k-_);M>0&&r.removeBuffer(0,M).catch(x)}N.shouldRefreshManifest&&o.needsManifestRefresh()}function P(A){if(R.onNewProtectionData(A.protectionData),A.segmentType==="init"){if(!f.index.isInitialized()&&A.segmentList!==void 0&&f.index.initialize(A.segmentList),S.isLoaded=!0,A.initializationData!==null){let k=f.uniqueId;S.uniqueId=k,r.declareInitSegment(k,A.initializationData),Bi({playbackObserver:t,bufferGoal:l,content:n,initSegmentUniqueId:k,segment:A.segment,segmentData:A.initializationData,segmentSink:r},p.signal).then(N=>{N!==null&&o.addedSegment(N)}).catch(x)}C();return}else{let{inbandEvents:k,predictedSegments:N,needsManifestRefresh:w}=A;if(N!==void 0&&f.index.addPredictedSegments(N,A.segment),w===!0&&(o.needsManifestRefresh(),p.isUsed())||k!==void 0&&k.length>0&&(o.inbandEvent(k),p.isUsed()))return;let W=S.uniqueId;Ni({playbackObserver:t,bufferGoal:l,content:n,initSegmentUniqueId:W,parsedSegment:A,segment:A.segment,segmentSink:r},p.signal).then(B=>{B!==null&&o.addedSegment(B)}).catch(x)}}function x(A){p.isUsed()&&A instanceof ue||(c.warn("Stream","Received fatal buffer error",{bufferType:b,representationBitrate:n.representation.bitrate},A instanceof Error?A:null),p.cancel("RepresentationStream: fatal buffer err"),o.error(A))}}var ss=Ui;function Li(n,e,t,r,i){var m,g,h,b;if(t.switchingMode==="lazy")return{type:"continue",value:void 0};let a=r.getLastKnownInventory(),o=[];for(let p of a)p.infos.period.id===n.id&&(p.infos.adaptation.id!==e.id||!fe(t.representationIds,p.infos.representation.id))&&bt(o,{start:(m=p.bufferedStart)!=null?m:p.start,end:(g=p.bufferedEnd)!=null?g:p.end});let s=r.getPendingOperations();for(let p of s)if(p.type===0){let S=p.value.inventoryInfos;if(S.period.id===n.id&&(S.adaptation.id!==e.id||!fe(t.representationIds,S.representation.id))){let T=S.segment.time,R=T+S.segment.duration;bt(o,{start:T,end:R})}}if(o.length===0)return{type:"continue",value:void 0};if(t.switchingMode==="reload"){let p=i.getReadyState();if(p===void 0||p>1)return{type:"needs-reload",value:void 0}}let d=t.switchingMode==="direct",u=[],f=zt(a,n);if(f!==null&&(f.bufferedEnd===void 0||n.start-f.bufferedEnd<1)&&u.push({start:0,end:n.start+1}),!d){let{ADAP_REP_SWITCH_BUFFER_PADDINGS:p}=L.getCurrent(),S=e.type,T=(h=p[S].before)!=null?h:0,R=(b=p[S].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 p=Wt(a,n);p!==null&&(p.bufferedStart===void 0||p.bufferedStart-n.end<1)&&u.push({start:n.end-1,end:Number.MAX_VALUE})}let l=kr(o,u);return l.length===0?{type:"continue",value:void 0}:d?{type:"flush-buffer",value:l}:{type:"clean-buffer",value:l}}function Fi({playbackObserver:n,content:e,options:t,representationEstimator:r,segmentSink:i,segmentQueueCreator:a,wantedBufferAhead:o,maxVideoBufferSize:s},d,u){let{manifest:f,period:l,adaptation:m}=e,g=new z("AdaptationStream "+m.type);g.linkToSignal(u);let h=new Map,b=new $(null,g.signal),p,S=e.representations.getValue().representationIds,T=ds(e.adaptation.representations,S),R=new $(T,g.signal),{estimates:E,callbacks:C}=r({manifest:f,period:l,adaptation:m},b,R,n,g.signal),P=new $(!1);n.listen(_=>{var D;let M=(D=_.canStream)!=null?D:!0;P.getValue()===M&&(c.debug("Stream","isMediaSegmentQueueInterrupted updated to",!M),P.setValue(!M))},{clearSignal:g.signal});let x=a.createSegmentQueue(m.type,{onRequestBegin:C.requestBegin,onRequestEnd:C.requestEnd,onProgress:C.requestProgress,onMetrics:C.metrics},P),A=new $(0);E.onUpdate(({bitrate:_,knownStableBitrate:M})=>{t.enableFastSwitching&&A.setValueIfChanged(M),!(_===void 0||_===p)&&(p=_,c.debug("Stream",`new ${m.type} bitrate estimate received from ABR`,{bitrate:_}),d.bitrateEstimateChange({type:m.type,bitrate:_}))},{emitCurrentValue:!0,clearSignal:g.signal});let k;e.representations.onUpdate(_=>{k!==void 0&&k.cancel("locked representations changed");let M=e.representations.getValue().representationIds,D=ds(e.adaptation.representations,M);R.setValueIfChanged(D);let U=new z("AdaptationStream: RepresentationStream Group "+m.type);k=U,U.linkToSignal(g.signal),N(_,U.signal).catch(G=>{U.isUsed()&&z.isCancellationError(G)||(g.cancel("RepresentationStream err"),d.error(G))})},{clearSignal:g.signal,emitCurrentValue:!0});return;async function N(_,M){let D=Li(l,m,_,i,n);switch(D.type){case"continue":break;case"needs-reload":return at(()=>{n.listen(()=>{if(M.isCancelled())return;let{DELTA_POSITION_AFTER_RELOAD:U}=L.getCurrent(),G=U.bitrateSwitch;return d.waitingMediaSourceReload({bufferType:m.type,period:l,timeOffset:G,stayInPeriod:!0})},{includeLastObservation:!0,clearSignal:M})});case"flush-buffer":case"clean-buffer":for(let U of D.value)if(await i.removeBuffer(U.start,U.end),M.isCancelled())return;if(D.type==="flush-buffer"&&(d.needsBufferFlush(),M.isCancelled()))return;break;default:Ne(D)}w(M)}function w(_){let M=new z("AdaptationStream: RepresentationStream creation "+m.type);M.linkToSignal(_);let{representation:D}=E.getValue();if(D===null)return;let U=new $(null,M.signal);E.onUpdate(K=>{if(!(K.representation===null||K.representation.id===D.id))return K.urgent?(c.info("Stream","urgent Representation switch",{bufferType:m.type,estimateBitrate:K.bitrate,prevRepresentationBitrate:D.bitrate,newRepresentationBitrate:K.representation.bitrate}),U.setValue({urgent:!0,reason:"Urgent Representation switch"})):(c.info("Stream","slow Representation switch",{bufferType:m.type,estimateBitrate:K.bitrate,prevRepresentationBitrate:D.bitrate,newRepresentationBitrate:K.representation.bitrate}),U.setValue({urgent:!1,reason:"Non-urgent Representation switch"}))},{clearSignal:M.signal,emitCurrentValue:!0});let G={type:m.type,adaptation:m,period:l,representation:D};if(b.setValue(D),_.isCancelled()||(d.representationChange(G),_.isCancelled()))return;let Q={streamStatusUpdate:d.streamStatusUpdate,encryptionDataEncountered:d.encryptionDataEncountered,manifestMightBeOufOfSync:d.manifestMightBeOufOfSync,needsManifestRefresh:d.needsManifestRefresh,inbandEvent:d.inbandEvent,warning:d.warning,error(K){g.cancel("RepresentationStream err cb"),d.error(K)},addedSegment(K){C.addedSegment(K)},terminating(){if(!M.isUsed())return M.cancel("RepresentationStream terminating"),w(_)}};W(D,U,Q,_)}function W(_,M,D,U){let G=!1,Q=new z(`RepresentationStream-linked listeners in AdaptationStream - periodStart=${l.start} type=${m.type}`);Q.linkToSignal(U);let K=en(o,X=>B(_,X),Q.signal),q=m.type==="video"?s:new $(1/0);c.info("Stream","changing representation",{bufferType:m.type,representationId:_.id,representationBitrate:_.bitrate});let Z=H({},D,{error(X){var pe;if(G){c.warn("Stream","Ignoring RepresentationStream error",X);return}G=!0;let me=ge(X,{defaultCode:"NONE",defaultReason:"Unknown `RepresentationStream` error"});if(me.code!=="BUFFER_FULL_ERROR")D.error(X);else{c.warn("Stream","received BUFFER_FULL_ERROR",{bufferType:m.type,representationBitrate:_.bitrate});let Qe=o.getValue(),se=((pe=h.get(_.id))!=null?pe:1)*.7;if(h.set(_.id,se),se<=.05||B(_,Qe)<=2){D.error(me);return}fn(4e3,Q.signal).then(()=>W(_,M,D,U)).catch(O)}},terminating(){Q.cancel("Representation terminating"),D.terminating()}});ss({playbackObserver:n,content:{representation:_,adaptation:m,period:l,manifest:f},segmentSink:i,segmentQueue:x,terminate:M,options:{bufferGoal:K,maxBufferSize:q,drmSystemId:t.drmSystemId,fastSwitchThreshold:A}},Z,U),f.addEventListener("manifestUpdate",X=>{for(let me of X.updatedPeriods)if(me.period.id===l.id){for(let pe of me.result.updatedAdaptations)if(pe.adaptation===m.id){for(let Qe of pe.removedRepresentations)if(Qe===_.id)return Q.isUsed()?void 0:d.waitingMediaSourceReload({bufferType:m.type,period:l,timeOffset:0,stayInPeriod:!0})}}else if(me.period.start>l.start)break},Q.signal)}function B(_,M){let D=h.get(_.id),U=D!==void 0?D:1;return D===void 0&&h.set(_.id,U),U<1&&M===1/0?300*U:M*U}}function ds(n,e){let t=n.filter(r=>fe(e,r.id)&&!r.shouldBeAvoided&&r.isPlayable()!==!1);return t.length>0?t:n.filter(r=>fe(e,r.id)&&r.isPlayable()!==!1)}var us=Fi;function zi(n,e,t,r,i,a){var g,h,b,p;if(n.codec!==void 0&&a.onCodecSwitch==="reload"&&!Qu(t,n.codec))return{type:"needs-reload",value:void 0};let o=n.getLastKnownInventory(),s=[];for(let S of o)S.infos.period.id===e.id&&S.infos.adaptation.id!==t.id&&bt(s,{start:(g=S.bufferedStart)!=null?g:S.start,end:(h=S.bufferedEnd)!=null?h:S.end});let d=n.getPendingOperations();for(let S of d)if(S.type===0){let T=S.value.inventoryInfos;if(T.period.id===e.id&&T.adaptation.id!==t.id){let R=T.segment.time,E=R+T.segment.duration;bt(s,{start:R,end:E})}}if(s.length===0)return{type:"continue",value:void 0};if(r==="reload"){let S=i.getReadyState();if(S===void 0||S>1)return{type:"needs-reload",value:void 0}}let u=r==="direct",f=[],l=zt(o,e);if(l!==null&&(l.bufferedEnd===void 0||e.start-l.bufferedEnd<1)&&f.push({start:0,end:e.start+1}),!u){let S=t.type,{ADAP_REP_SWITCH_BUFFER_PADDINGS:T}=L.getCurrent(),R=(b=T[S].before)!=null?b:0,E=(p=T[S].after)!=null?p:0,C=i.getCurrentTime();C===void 0&&(C=i.getReference().getValue().position.getPolled()),f.push({start:C-R,end:C+E})}if(e.end!==void 0){let S=Wt(o,e);S!==null&&(S.bufferedStart===void 0||S.bufferedStart-e.end<1)&&f.push({start:e.end-1,end:Number.MAX_VALUE})}let m=kr(s,f);return m.length===0?{type:"continue",value:void 0}:u&&t.type!=="text"?{type:"flush-buffer",value:m}:{type:"clean-buffer",value:m}}function Qu(n,e){return n.representations.some(t=>t.isPlayable()===!0&&Vo(t.getMimeTypeString(),e))}function Wi({bufferType:n,content:e,garbageCollectors:t,playbackObserver:r,representationEstimator:i,segmentQueueCreator:a,segmentSinksStore:o,options:s,wantedBufferAhead:d,maxVideoBufferSize:u},f,l){let{manifest:m,period:g}=e,h=new $(void 0,l);if(f.periodStreamReady({type:n,manifest:m,period:g,adaptationRef:h}),l.isCancelled())return;let b,p=!0;h.onUpdate(R=>{(async()=>{var B;if(R===void 0)return;let E=new z("PeriodStream: Adaptation choice "+n);if(E.linkToSignal(l),b==null||b.cancel("PeriodStream: Adaptation update"),b=E,R===null){c.info("Stream","Set no Adaptation",{periodStart:g.start,bufferType:n});let _=o.getStatus(n);if(_.type==="initialized"){if(c.info("Stream","Clearing previous SegmentSink",{periodStart:g.start,bufferType:n}),St.isNative(n))return T(0,!0,E.signal);{let M=(B=g.end)!=null?B:1/0;if(g.start>M)c.warn("Stream","Can't free buffer: period's start is after its end",{periodStart:g.start,periodEnd:M,bufferType:n});else if(await _.value.removeBuffer(g.start,M),E.isUsed())return}}else if(_.type==="uninitialized"&&(o.disableSegmentSink(n),E.isUsed()))return;return f.adaptationChange({type:n,adaptation:null,period:g}),E.isUsed()?void 0:ls(r,d,n,{period:g},f,E.signal)}let C=g.adaptations[n],P=j(C!=null?C:[],_=>_.id===R.adaptationId);if(P===void 0){b.cancel("PeriodStream: Adaptation not found"),c.warn("Stream","Unfound chosen Adaptation choice",{adaptationId:R.adaptationId});return}let{DELTA_POSITION_AFTER_RELOAD:x}=L.getCurrent(),A=!1,k;if(p)k=0;else if(R.relativeResumingPosition!==void 0)k=R.relativeResumingPosition;else switch(A=!0,n){case"audio":k=x.trackSwitch.audio;break;case"video":k=x.trackSwitch.video;break;default:k=x.trackSwitch.other;break}if(p=!1,St.isNative(n)&&o.getStatus(n).type==="disabled")return T(k,!0,E.signal);m.addEventListener("manifestUpdate",_=>{for(let M of _.updatedPeriods)if(M.period.id===g.id){for(let D of M.result.removedAdaptations)if(D.id===P.id)return T(k,!0,E.signal)}else if(M.period.start>g.start)break},b.signal);let{representations:N}=R;if(c.info("Stream","Updating adaptation",{bufferType:P.type,periodStart:g.start,adaptationId:P.id}),f.adaptationChange({type:n,adaptation:P,period:g}),E.isUsed())return;let w=$u(o,n,P),W=zi(w,g,P,R.switchingMode,r,s);if(W.type==="needs-reload")return T(k,!0,E.signal);if(await o.waitForUsableBuffers(E.signal),!E.isUsed()){if(W.type==="flush-buffer"||W.type==="clean-buffer"){for(let{start:_,end:M}of W.value)if(await w.removeBuffer(_,M),E.isUsed())return;if(W.type==="flush-buffer"&&(f.needsBufferFlush({relativeResumingPosition:k,relativePosHasBeenDefaulted:A}),E.isUsed()))return}t.get(w)(E.signal),S(P,N,w,E.signal)}})().catch(E=>{E instanceof ue||(b==null||b.cancel("PeriodStream err"),f.error(E))})},{clearSignal:l,emitCurrentValue:!0});function S(R,E,C,P){let x=Zu(r,R.type);us({content:{manifest:m,period:g,adaptation:R,representations:E},options:s,playbackObserver:x,representationEstimator:i,segmentSink:C,segmentQueueCreator:a,wantedBufferAhead:d,maxVideoBufferSize:u},de(J({},f),{error:A}),P);function A(k){if(!St.isNative(n)){c.error("Stream",`${n} Stream crashed. Aborting it.`,k instanceof Error?k:""),o.disposeSegmentSink(n,"AdaptationStream err");let N=ge(k,{defaultCode:"NONE",defaultReason:"Unknown `AdaptationStream` error"});return f.warning(N),P.isCancelled()?void 0:ls(r,d,n,{period:g},f,P)}c.error("Stream",`${n} Stream crashed. Stopping playback.`,k instanceof Error?k:""),f.error(k)}}function T(R,E,C){at(()=>{r.listen(()=>{C.isCancelled()||f.waitingMediaSourceReload({bufferType:n,period:g,timeOffset:R,stayInPeriod:E})},{includeLastObservation:!0,clearSignal:C})})}}function $u(n,e,t){let r=n.getStatus(e);if(r.type==="initialized")return c.info("Stream","Reusing a previous SegmentSink for the type",{bufferType:e}),r.value;let i=Xu(t);return n.createSegmentSink(e,i)}function Xu(n){let e=n.representations.filter(t=>t.isPlayable()!==!1);if(e.length>0)return e[0].getMimeTypeString();if(n.representations.length>0)return n.representations[0].getMimeTypeString();throw new ee("NO_PLAYABLE_REPRESENTATION","No Representation in the chosen "+n.type+" Adaptation can be played",{tracks:[vt(n)]})}function Zu(n,e){return n.deriveReadOnlyObserver(function(r,i){let a=new $(o(),i);return r.onUpdate(s,{clearSignal:i,emitCurrentValue:!1}),a;function o(){let d=r.getValue(),u=d.buffered[e],f=u!==null?xr(u,d.position.getWanted()):0;return H({},d,{bufferGap:f,buffered:u})}function s(){a.setValue(o())}})}function ls(n,e,t,r,i,a){let{period:o}=r,s=!1;e.onUpdate(d,{emitCurrentValue:!1,clearSignal:a}),n.listen(d,{includeLastObservation:!1,clearSignal:a}),d();function d(){let u=n.getReference().getValue(),f=e.getValue(),l=u.position.getWanted();o.end!==void 0&&l+f>=o.end&&(c.debug("Stream",'full "empty" AdaptationStream',{bufferType:t,periodEnd:o.end,position:l,wantedBufferAhead:f}),s=!0),i.streamStatusUpdate({period:o,bufferType:t,imminentDiscontinuity:null,position:l,isEmptyStream:!0,hasFinishedLoading:s,neededSegments:[]})}}var fs=Wi;function Dr(n,e){if(e.length===0)return[];let t=[],r=n.getLastKnownInventory(),i=n.getPendingOperations();for(let a of r)if(e.some(s=>a.infos.period.id===s.period.id&&a.infos.adaptation.id===s.adaptation.id&&a.infos.representation.id===s.representation.id)){let{bufferedStart:s,bufferedEnd:d}=a;if(s===void 0||d===void 0)return c.warn("Stream","No buffered start or end found from a segment.",{bufferType:a.infos.adaptation.type,segmentStart:a.infos.segment.time}),[{start:0,end:Number.MAX_VALUE}];let u=t[t.length-1];u!==void 0&&u.end===s?u.end=d:t.push({start:s,end:d})}for(let a of i){if(a.type!==0)continue;let o=a.value;e.some(d=>o.inventoryInfos.period.id===d.period.id&&o.inventoryInfos.adaptation.id===d.adaptation.id&&o.inventoryInfos.representation.id===d.representation.id)&&bt(t,{start:o.inventoryInfos.start,end:o.inventoryInfos.end})}return t}function Vi(n,e,t,r,i,a,o,s){let{manifest:d,initialPeriod:u}=n,{maxBufferAhead:f,maxBufferBehind:l,wantedBufferAhead:m,maxVideoBufferSize:g}=a,{MINIMUM_MAX_BUFFER_AHEAD:h,MAXIMUM_MAX_BUFFER_AHEAD:b,MAXIMUM_MAX_BUFFER_BEHIND:p}=L.getCurrent(),S=new bn(E=>{var A,k;let{bufferType:C}=E,P=(A=p[C])!=null?A:1/0,x=(k=b[C])!=null?k:1/0;return N=>{Mr({segmentSink:E,playbackObserver:e,maxBufferBehind:en(l,w=>Math.min(w,P),N),maxBufferAhead:en(f,w=>{var B;let W=Math.max(w,(B=h[C])!=null?B:0);return Math.min(W,x)},N)},N)}});for(let E of r.getBufferTypes())T(E,u);function T(E,C){let P=new kt((W,B)=>W.start-B.start),x=!1,A=new z("StreamOrchestrator Streams for "+E);return A.linkToSignal(s),e.listen(({position:W})=>{let B=W.getWanted();if(!x||!N(B))return;let _=()=>{var D;return(D=d.getPeriodForTime(B))!=null?D:d.getNextPeriod(B)},M=_();if(!(!v(M)&&P.has(M))){for(c.info("Stream","Destroying all PeriodStreams due to out of bounds situation",{bufferType:E,time:B}),x=!1;P.length()>0;){let D=P.get(P.length()-1);P.removeElement(D),o.periodStreamCleared({type:E,manifest:d,period:D})}if(A.cancel("PeriodStream is out of bounds"),A=new z("StreamOrchestrator Streams for "+E),A.linkToSignal(s),M=_(),M===void 0){c.warn("Stream","The wanted position is not found in the Manifest."),x=!0;return}k(M)}},{clearSignal:s,includeLastObservation:!0}),d.addEventListener("decipherabilityUpdate",W=>{s.isCancelled()||w(W).catch(B=>{s.isCancelled()||(A.cancel("decipherabilityUpdate event"),o.error(B))})},s),k(C);function k(W){let B=de(J({},o),{waitingMediaSourceReload(_){let M=P.head();M===void 0||M.id!==_.period.id?o.lockedStream({bufferType:_.bufferType,period:_.period}):o.needsMediaSourceReload({timeOffset:_.timeOffset,minimumPosition:_.stayInPeriod?_.period.start:void 0,maximumPosition:_.stayInPeriod?_.period.end:void 0})},periodStreamReady(_){x=!0,P.add(_.period),o.periodStreamReady(_)},periodStreamCleared(_){P.removeElement(_.period),o.periodStreamCleared(_)},error(_){A.cancel("PeriodStream err callback"),o.error(_)}});R(E,W,B,A.signal)}function N(W){let B=P.head(),_=P.last();return B===void 0||_===void 0?!0:B.start>W||(v(_.end)?1/0:_.end)<W}async function w(W){let B=r.getStatus(E),_=W.filter(q=>q.adaptation.type===E);if(_.length===0||B.type!=="initialized"||_.every(q=>q.representation.decipherable===!0))return;let M=B.value,D=_.filter(q=>q.representation.decipherable===void 0),U=_.filter(q=>q.representation.decipherable===!1),G=Dr(M,U),Q=Dr(M,D);for(c.info("Stream","Destroying all PeriodStreams for decipherability matters",{bufferType:E}),x=!1;P.length()>0;){let q=P.get(P.length()-1);P.removeElement(q),o.periodStreamCleared({type:E,manifest:d,period:q})}A.cancel("decipherability update"),A=new z("StreamOrchestrator Streams for "+E),A.linkToSignal(s);let K=A;for(let{start:q,end:Z}of[...G,...Q]){if(K.isUsed())return;q<Z&&await M.removeBuffer(q,Z)}at(()=>{if(K.signal.isCancelled())return;let q=e.getReference().getValue();if(ms(q,G)){if(o.needsDecipherabilityFlush(),K.isUsed())return}else if(ms(q,Q)&&(o.needsBufferFlush(),K.isUsed()))return;let Z=q.position.getWanted(),X=d.getPeriodForTime(Z);if(X===void 0&&(X=d.getNextPeriod(Z),c.warn("Stream","No Period found for the reloading position, selecting next one instead",{reloadPosition:Z,nextPeriodStart:X==null?void 0:X.start})),X===void 0&&(X=d.periods[d.periods.length-1],c.warn("Stream","No Period found for of after the reloading position, selecting the last one",{reloadPosition:Z,nextPeriodStart:X==null?void 0:X.start,nextPeriodEnd:X==null?void 0:X.end})),X===void 0){o.error(new ee("MEDIA_TIME_NOT_FOUND","The wanted position is not found in the Manifest."));return}k(X)})}}function R(E,C,P,x){c.info("Stream","Creating new PeriodStream",{bufferType:E,periodStart:C.start});let A=null,k=new z("StreamOrchestrator current consecutive Streams "+E);k.linkToSignal(x),e.listen(({position:_},M)=>{if(C.end!==void 0&&_.getWanted()>=C.end){let D=d.getPeriodAfter(C);if(C.containsTime(_.getWanted(),D))return;c.info("Stream","Destroying PeriodStream as the current playhead moved above it",{bufferType:E,periodStart:C.start,periodEnd:C.end,position:_.getWanted()}),M(),P.periodStreamCleared({type:E,manifest:d,period:C}),k.cancel("Position ahead of PeriodStream")}},{clearSignal:x,includeLastObservation:!0});let N={bufferType:E,content:{manifest:d,period:C},garbageCollectors:S,maxVideoBufferSize:g,segmentQueueCreator:i,segmentSinksStore:r,options:a,playbackObserver:e,representationEstimator:t,wantedBufferAhead:m},w=de(J({},P),{streamStatusUpdate(_){if(_.hasFinishedLoading){let M=d.getPeriodAfter(C);M!==null&&W(M)}else A!==null&&(c.info("Stream","Destroying next PeriodStream due to current one being active",{bufferType:E,periodStart:C.start,nextPeriodStart:A.period.start}),P.periodStreamCleared({type:E,manifest:d,period:A.period}),A.canceller.cancel("previous PeriodStream is active"),A=null);P.streamStatusUpdate(_)},error(_){A!==null&&(A.canceller.cancel("previous PeriodStream err"),A=null),k.cancel("PeriodStream err"),P.error(_)}});fs(N,w,k.signal),B(k.signal);function W(_){if(A!==null){if(A.period.id===_.id)return;c.warn("Stream","Creating next `PeriodStream` while one was already created.",{bufferType:E,nextPeriodStart:_.start}),P.periodStreamCleared({type:E,manifest:d,period:A.period}),A.canceller.cancel("PeriodStream recreation")}let M=new z("StreamOrchestrator next PeriodStream "+E);M.linkToSignal(x),A={canceller:M,period:_},R(E,_,P,A.canceller.signal)}function B(_){d.addEventListener("manifestUpdate",M=>{for(let D of M.removedPeriods)if(D.id===C.id){if(d.periods.length>0&&d.periods[0].start<=D.start)return at(()=>{if(!_.isCancelled())return o.needsMediaSourceReload({timeOffset:0,minimumPosition:void 0,maximumPosition:void 0})})}else if(D.start>C.start)break;if(A!==null){let D=d.getPeriodAfter(C);(D===null||A.period.id!==D.id)&&(c.warn("Stream","Destroying next PeriodStream due to manifest update",{bufferType:E,nextPeriodStart:A.period.start}),P.periodStreamCleared({type:E,manifest:d,period:A.period}),A.canceller.cancel("Next Period changed"),A=null)}},_)}}}function ms(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 cs=Vi;var ps=cs;function qi(n,e){if(typeof n.changeType=="function"){try{n.changeType(e)}catch(t){return c.warn("mse","Could not call 'changeType' on the given SourceBuffer:",t instanceof Error?t:""),!1}return!0}return!1}function Ju(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t];r.updating&&e.push(r)}return e}function Cn(n,e){if(c.debug("mse","Trying to call endOfStream"),n.readyState!=="open"){c.debug("mse","MediaSource not open, cancel endOfStream");return}let{sourceBuffers:t}=n,r=Ju(t);if(r.length===0){c.info("mse","Triggering end of stream");try{n.endOfStream()}catch(a){c.error("mse","Unable to call endOfStream",a instanceof Error?a:new Error("Unknown error"))}return}c.debug("mse","Waiting SourceBuffers to be updated before calling endOfStream.");let i=new z("EndOfStream current iteration");i.linkToSignal(e);for(let a of r)ko(a,()=>{i.cancel("SourceBuffer update"),Cn(n,e)},i.signal);Mo(t,()=>{i.cancel("SourceBuffer remove"),Cn(n,e)},i.signal)}function gs(n,e){let t=new z("EndOfStream");t.linkToSignal(e),Ft(n,()=>{c.debug("mse","MediaSource re-opened while end-of-stream is active"),t.cancel("MediaSource re-opened"),t=new z("EndOfStream"),t.linkToSignal(e),Cn(n,t.signal)},e),Cn(n,t.signal)}function Gi(){let{FORCE_HAS_ISSUES_WITH_HIGH_MEDIA_SOURCE_DURATION:n}=L.getCurrent();return n||tt.device===tt.DEVICES.PlayStation5}var el=365*24*3600,An=class{constructor(e){this._mediaSource=e,this._currentMediaSourceDurationUpdateCanceller=null}updateDuration(e,t){this._currentMediaSourceDurationUpdateCanceller!==null&&this._currentMediaSourceDurationUpdateCanceller.cancel("manual duration update"),this._currentMediaSourceDurationUpdateCanceller=new z("MediaSource Duration Update");let r=this._mediaSource,i=this._currentMediaSourceDurationUpdateCanceller.signal,a=rl(r,i),o=new z(void 0);o.linkToSignal(i),a.onUpdate(s,{emitCurrentValue:!0,clearSignal:i});function s(){if(o.cancel("MediaSource open status changed"),!a.getValue())return;o=new z(void 0),o.linkToSignal(i);let d=nl(r.sourceBuffers,o.signal),u=new z(void 0);return u.linkToSignal(o.signal),d.onUpdate(f=>{u.cancel("SourceBuffer status update"),u=new z(void 0),u.linkToSignal(o.signal),!f&&Is(r,e,t,u.signal)},{clearSignal:o.signal,emitCurrentValue:!0})}}stopUpdating(e){this._currentMediaSourceDurationUpdateCanceller!==null&&(this._currentMediaSourceDurationUpdateCanceller.cancel(e!=null?e:"stop MSDU"),this._currentMediaSourceDurationUpdateCanceller=null)}};function tl(n,e,t){let r=e;t||(r=Gi()?1/0:hs(e));let i=0;for(let a=0;a<n.sourceBuffers.length;a++){let o=n.sourceBuffers[a],s=o.buffered.length;s>0&&(i=Math.max(i,o.buffered.end(s-1)))}if(r===n.duration)return"success";if(i>r){if(i<n.duration)try{c.info("mse","Updating duration to what is currently buffered",{maxBufferedEnd:i}),n.duration=i}catch(a){return c.warn("mse","Can't update duration on the MediaSource.",a instanceof Error?a:""),"failed"}return"partial"}else{let a=n.duration;try{if(c.info("mse","Updating duration",{newDuration:r}),n.duration=r,n.readyState==="open"&&!isFinite(r)){let s=hs(e);c.info("mse","calling `mediaSource.setLiveSeekableRange`",{maxSeekable:s}),n.setLiveSeekableRange(0,s)}}catch(s){return c.warn("mse","Can't update duration on the MediaSource.",s instanceof Error?s:""),"failed"}let o=Math.abs(n.duration-r);if(o>=.1){let s=Math.abs(n.duration-a);return o<s?"partial":"failed"}return"success"}}function nl(n,e){if(n.length===0){let i=new $(!1);return i.finish(),i}let t=new $(!1,e);r();for(let i=0;i<n.length;i++){let a=n[i];a.addEventListener("updatestart",r),a.addEventListener("update",r),e.register(()=>{a.removeEventListener("updatestart",r),a.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 rl(n,e){let t=new $(n.readyState==="open",e);return Ft(n,()=>{c.debug("mse","Reacting to MediaSource open in duration updater"),t.setValueIfChanged(!0)},e),Er(n,()=>{c.debug("mse","Reacting to MediaSource ended in duration updater"),t.setValueIfChanged(!1)},e),Tr(n,()=>{c.debug("mse","Reacting to MediaSource close in duration updater"),t.setValueIfChanged(!1)},e),t}function Is(n,e,t,r){if(tl(n,e,t)==="success")return;let a=setTimeout(()=>{o(),Is(n,e,t,r)},2e3),o=r.register(()=>{clearTimeout(a)})}function hs(n){return Math.max(Math.pow(2,32),n+el)}var xn=class extends ce{constructor(e,t){super(),this.id=e,this.sourceBuffers=[],this._canceller=new z("MainMediaSourceInterface");let{MediaSource_:r}=ln;if(v(r))throw new ee("MEDIA_SOURCE_NOT_SUPPORTED","No MediaSource Object was found in the current browser.");c.info("mse","Creating MediaSource");let i=t!==void 0?new t:new r,a=i.handle;this.handle=v(a)?{type:"media-source",value:i}:{type:"handle",value:a},this._mediaSource=i,this.readyState=i.readyState,this._durationUpdater=new An(i),this._endOfStreamCanceller=null,Ft(i,()=>{this.readyState=i.readyState,this.trigger("mediaSourceOpen",null)},this._canceller.signal),Er(i,()=>{this.readyState=i.readyState,this.trigger("mediaSourceEnded",null)},this._canceller.signal),Tr(i,()=>{this.readyState=i.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 Hi(e,t,r);return this.sourceBuffers.push(i),i}setDuration(e,t){this._durationUpdater.updateDuration(e,t)}interruptDurationSetting(e){this._durationUpdater.stopUpdating(e)}maintainEndOfStream(){this._endOfStreamCanceller===null&&(this._endOfStreamCanceller=new z("MainMediaSourceInterface EndOfStream"),this._endOfStreamCanceller.linkToSignal(this._canceller.signal),c.debug("mse","end-of-stream order received."),gs(this._mediaSource,this._endOfStreamCanceller.signal))}stopEndOfStream(){this._endOfStreamCanceller!==null&&(c.debug("mse","resume-stream order received."),this._endOfStreamCanceller.cancel("MediaSourceInterface stopEndOfStream"),this._endOfStreamCanceller=null)}dispose(e){this.sourceBuffers.forEach(t=>t.dispose(e)),this._canceller.cancel(e!=null?e:"MainMediaSourceInterface dispose"),il(this._mediaSource)}},Hi=class{constructor(e,t,r){this.type=e,this.codec=t,this._canceller=new z("MainSourceBufferInterface "+e),this._sourceBuffer=r,this._operationQueue=[],this._currentOperations=[];let i=this._onError.bind(this),a=this._onUpdateEnd.bind(this);r.addEventListener("updateend",a),r.addEventListener("error",i),this._canceller.signal.register(()=>{r.removeEventListener("updateend",a),r.removeEventListener("error",i)})}appendBuffer(...e){return c.debug("mse","receiving order to push data to the SourceBuffer",{type:this.type}),this._addToQueue({operationName:0,params:e})}remove(e,t){return c.debug("mse","receiving order to remove data from the SourceBuffer",{type:this.type,start:e,end:t}),this._addToQueue({operationName:1,params:[e,t]})}getBuffered(){try{return ki(this._sourceBuffer.buffered)}catch(e){return c.error("mse","Failed to get buffered time range of SourceBuffer",{type:this.type},e instanceof Error?e:"Unknown Error"),[]}}abort(e){try{this._sourceBuffer.abort()}catch(t){c.debug("mse","Failed to abort SourceBuffer:",t instanceof Error?t:"Unknown Error")}this._emptyCurrentQueue(e)}dispose(e){try{this._sourceBuffer.abort()}catch(t){}this._emptyCurrentQueue(e)}_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)c.error("mse","error for an unknown operation",t);else{let i=new xe(t.name,t.message,t.name==="QuotaExceededError");for(let a of r)a.reject(i)}}_onUpdateEnd(){let e=this._currentOperations;this._currentOperations=[];try{for(let t of e)t.resolve(ki(this._sourceBuffer.buffered))}catch(t){for(let r of e)t instanceof Error&&t.name==="InvalidStateError"?r.resolve([]):r.reject(t)}this._performNextOperation()}_emptyCurrentQueue(e){let t=new ue("MainSourceBufferInterface queue "+this.type,e);this._currentOperations.length>0&&(this._currentOperations.forEach(r=>{r.reject(t)}),this._currentOperations=[]),this._operationQueue.length>0&&(this._operationQueue.forEach(r=>{r.reject(t)}),this._operationQueue=[])}_addToQueue(e){return new Promise((t,r)=>{let i=this._operationQueue.length===0&&this._currentOperations.length===0,a=H({resolve:t,reject:r},e);this._operationQueue.push(a),i&&this._performNextOperation()})}_performNextOperation(){var t,r,i,a,o;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 f;s instanceof ArrayBuffer?f=new Uint8Array(s):s instanceof Uint8Array?f=s:f=new Uint8Array(s.buffer);let l=[f];for(;((t=this._operationQueue[0])==null?void 0:t.operationName)===0;){let m=this._operationQueue[0],g=(r=d.appendWindow)!=null?r:[void 0,void 0],h=(i=m.params[1].appendWindow)!=null?i:[void 0,void 0],b=(a=d.timestampOffset)!=null?a:0,p=(o=m.params[1].timestampOffset)!=null?o:0;if(g[0]===h[0]&&g[1]===h[1]&&d.codec===m.params[1].codec&&b===p){let S=m.params[0],T;S instanceof ArrayBuffer?T=new Uint8Array(S):S instanceof Uint8Array?T=S:T=new Uint8Array(S.buffer),l.push(T),this._operationQueue.splice(0,1),this._currentOperations.push({operationName:0,resolve:m.resolve,reject:m.reject})}else break}l.length>1&&(c.info("mse",`: Merging ${l.length} segments together for perf`,{type:this.type}),u=At(...l).buffer)}try{this._appendBufferNow(u,d)}catch(f){let l=f instanceof Error?new xe(f.name,f.message,f.name==="QuotaExceededError"):new xe("Error","Unknown SourceBuffer Error during appendBuffer",!1);this._currentOperations.forEach(m=>{m.reject(l)}),this._currentOperations=[],this._performNextOperation()}}else{this._currentOperations=[e];let[s,d]=e.params;c.debug("mse","removing data from SourceBuffer",{type:this.type,start:s,end:d});try{this._sourceBuffer.remove(s,d)}catch(u){let f=u instanceof Error?new xe(u.name,u.message,!1):new xe("Error","Unknown SourceBuffer Error during remove",!1);e.reject(f),this._currentOperations.forEach(l=>{l.reject(f)}),this._currentOperations=[],this._performNextOperation()}}}_appendBufferNow(e,t){let r=this._sourceBuffer,{codec:i,timestampOffset:a,appendWindow:o=[]}=t;if(i!==void 0&&i!==this.codec&&(c.debug("mse","updating codec",{type:this.type,prevCodec:this.codec,newCodec:i}),qi(r,i)?this.codec=i:c.debug("mse","could not update codec",{type:this.type,prevCodec:this.codec,newCodec:i})),a!==void 0&&r.timestampOffset!==a){let s=a;c.debug("mse","updating timestampOffset",{type:this.type,codec:i,prevTimestampOffset:r.timestampOffset,newTimestampOffset:s}),r.timestampOffset=s}if(o[0]===void 0)r.appendWindowStart>0&&(c.debug("mse","re-setting `appendWindowStart`",{type:this.type,prevWindowStart:r.appendWindowStart}),r.appendWindowStart=0);else if(o[0]!==r.appendWindowStart){if(o[0]>=r.appendWindowEnd){let s=o[0]+1;c.debug("mse","pre-updating `appendWindowEnd`",{type:this.type,prevWindowEnd:r.appendWindowEnd,newWindowEnd:s}),r.appendWindowEnd=s}c.debug("mse","setting `appendWindowStart`",{type:this.type,appendWindowStart:o[0]}),r.appendWindowStart=o[0]}o[1]===void 0?r.appendWindowEnd!==1/0&&(c.debug("mse","re-setting `appendWindowEnd`",{type:this.type,prevWindowStart:r.appendWindowStart}),r.appendWindowEnd=1/0):o[1]!==r.appendWindowEnd&&(c.debug("mse","setting `appendWindowEnd`",{type:this.type,prevWindowEnd:r.appendWindowEnd,newWindowEnd:o[1]}),r.appendWindowEnd=o[1]),c.debug("mse","pushing segment",{type:this.type}),r.appendBuffer(e)}};function il(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"){c.info("mse","Aborting SourceBuffer before removing");try{i.abort()}catch(a){}}c.info("mse","Removing SourceBuffer from mediaSource"),n.removeSourceBuffer(i)}catch(a){}}t.length>0&&c.info("mse","Not all SourceBuffers could have been removed.")}}var al=Me(),Br=Me(),bs=1/0,kn=class extends ce{constructor(e,t,r){super(),this.id=e,this.sourceBuffers=[],this._canceller=new z("WorkerMediaSourceInterface"),this.readyState="closed",this._messageSender=r;let i=al();this._messageSender({type:"create-media-source",contentId:t,mediaSourceId:i})}onMediaSourceReadyStateChanged(e){switch(e){case"closed":this.readyState="closed",this.trigger("mediaSourceClose",null);break;case"open":this.readyState="open",this.trigger("mediaSourceOpen",null);break;case"ended":this.readyState="ended",this.trigger("mediaSourceEnded",null);break}}addSourceBuffer(e,t){this._messageSender({type:"add-source-buffer",mediaSourceId:this.id,value:{sourceBufferType:e,codec:t}});let r=new Ki(e,t,this.id,this._messageSender);return this.sourceBuffers.push(r),r}setDuration(e,t){this._messageSender({type:"update-media-source-duration",mediaSourceId:this.id,value:{duration:e,isRealEndKnown:t}})}interruptDurationSetting(){this._messageSender({type:"stop-media-source-duration",mediaSourceId:this.id,value:null})}maintainEndOfStream(){this._messageSender({type:"end-of-stream",mediaSourceId:this.id,value:null})}stopEndOfStream(){this._messageSender({type:"stop-end-of-stream",mediaSourceId:this.id,value:null})}dispose(e){this.sourceBuffers.forEach(t=>t.dispose(e)),this._canceller.cancel("WorkerMediaSourceInterface dispose"),this._messageSender({type:"dispose-media-source",mediaSourceId:this.id,value:null})}},Ki=class{constructor(e,t,r,i){this.type=e,this.codec=t,this._canceller=new z("WorkerSourceBufferInterface "+e),this._mediaSourceId=r,this._queuedOperations=[],this._pendingOperations=new Map,this._messageSender=i}onOperationSuccess(e,t){let r=this._pendingOperations.get(e);r===void 0?c.warn("mse","unknown SourceBuffer operation succeeded",{type:this.type}):(this._pendingOperations.delete(e),r.resolve(t)),this._performNextQueuedOperationIfItExists()}onOperationFailure(e,t){let r=t.errorName==="CancellationError"?new ue("Pending SBI Operation "+this.type,"SBI Failure"):new xe(t.errorName,t.message,t.isBufferFull),i=this._pendingOperations.get(e);i===void 0?c.info("mse","unknown SourceBuffer operation failed",{type:this.type},r):(this._pendingOperations.delete(e),i.reject(r));let a=new ue("Queued SBI Operation "+this.type,"SBI failure");for(let o of this._queuedOperations)o.reject(a);this._queuedOperations=[]}appendBuffer(e,t){return new Promise((r,i)=>{if(this._queuedOperations.length>0||this._pendingOperations.size>=bs){this._queuedOperations.push({operationName:0,params:[e,t],resolve:r,reject:i});return}try{let a;e instanceof ArrayBuffer?a=e:e.byteLength===e.buffer.byteLength?a=e.buffer:a=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);let o=Br();this._messageSender({type:"source-buffer-append",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,operationId:o,value:{data:a,params:t}},[a]),this._addOperationToQueue(o,r,i)}catch(a){i(a)}})}remove(e,t){return new Promise((r,i)=>{if(this._queuedOperations.length>0||this._pendingOperations.size>=bs){this._queuedOperations.push({operationName:1,params:[e,t],resolve:r,reject:i});return}try{let a=Br();this._messageSender({type:"source-buffer-remove",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,operationId:a,value:{start:e,end:t}}),this._addOperationToQueue(a,r,i)}catch(a){i(a)}})}abort(){this._messageSender({type:"abort-source-buffer",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,value:null})}dispose(e){this.abort(),this._canceller.cancel(e!=null?e:"WorkerSourceBufferInterface dispose")}getBuffered(){}_addOperationToQueue(e,t,r){this._pendingOperations.set(e,{resolve:a,reject:o});let i=this._canceller.signal.register(s=>{this._pendingOperations.delete(e),r(s)});function a(s){i(),t(s)}function o(s){i(),r(s)}}_performNextQueuedOperationIfItExists(){let e=this._queuedOperations.shift();if(e!==void 0)try{if(e.operationName===0){let[t,r]=e.params,i;t instanceof ArrayBuffer?i=t:t.byteLength===t.buffer.byteLength?i=t.buffer:i=t.buffer.slice(t.byteOffset,t.byteLength+t.byteOffset);let a=Br();this._messageSender({type:"source-buffer-append",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,operationId:a,value:{data:i,params:r}},[i]),this._addOperationToQueue(a,e.resolve,e.reject)}else{let[t,r]=e.params,i=Br();this._messageSender({type:"source-buffer-remove",mediaSourceId:this._mediaSourceId,sourceBufferType:this.type,operationId:i,value:{start:t,end:r}}),this._addOperationToQueue(i,e.resolve,e.reject)}}catch(t){e.reject(t)}}};function ji(n){let e=n.map(o=>Math.log(o/n[0])),t=e.map(o=>o-e[0]+1),r=(t[t.length-1]-1)/(n.length*2+10),i=1/r;return n.map((o,s)=>a(s));function a(o){if(o===0)return 0;let s=Math.min(Math.max(1,o),n.length-1);return n[s]===n[s-1]?a(o-1):i*(r+(n[s]*t[s-1]-n[s-1]*t[s])/(n[s]-n[s-1]))+4}}var Ue=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 Mn=class{constructor(){this._currentRepresentationData=null,this._lastRepresentationWithGoodScore=null}addSample(e,t,r){let i=r/t,a=this._currentRepresentationData,o;a!==null&&a.representation.id===e.id?(o=a.ewma,a.ewma.addSample(t,i),a.loadedDuration+=r,a.loadedSegments++):(o=new Ue(5),o.addSample(t,i),this._currentRepresentationData={representation:e,ewma:o,loadedDuration:r,loadedSegments:1}),o.getEstimate()>1&&this._lastRepresentationWithGoodScore!==e&&(c.debug("ABR","New last stable representation",{bitrate: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,a=t.getEstimate(),o=r>=6&&i>=10?1:0;return{score:a,confidenceLevel:o}}getLastStableRepresentation(){return this._lastRepresentationWithGoodScore}};var Ss=6e3,ol=15e3,sl=3e3,dl=1e3,ul=9e3,On=class{constructor(e){this._levelsMap=ji(e).map(t=>t+4),this._bitrates=e,this._lastUnsuitableQualityTimestamp=void 0,this._blockRaiseDelay=Ss,c.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:a,currentScore:o,speed:s}=e;if(v(a)){this._currentEstimate=r[0];return}let d=-1;for(let h=0;h<r.length;h++){let b=r[h];if(b===a)d=h;else if(b>a)break}if(d<0||r.length!==t.length){c.info("ABR","Current Bitrate not found in the calculated levels"),this._currentEstimate=r[0];return}let u;o!==void 0&&(u=s===0?o.score:o.score/s);let f=isFinite(i)?i:0,l=F();if(f<t[d]||u!==void 0&&u<1&&(o==null?void 0:o.confidenceLevel)===1){if((this._lastUnsuitableQualityTimestamp===void 0?-1:l-this._lastUnsuitableQualityTimestamp)<this._blockRaiseDelay+ul){let p=this._blockRaiseDelay+sl;c.debug("ABR","Incrementing blocking raise in BufferBasedChooser due to unstable quality",{prevDelay:this._blockRaiseDelay,newDelay:p}),this._blockRaiseDelay=Math.min(p,ol)}else{let p=this._blockRaiseDelay-dl;c.debug("ABR","Lowering quality in BufferBasedChooser",{prevDelay:this._blockRaiseDelay,newDelay:p}),this._blockRaiseDelay=Math.max(Ss,p)}this._lastUnsuitableQualityTimestamp=l;let b=ae(r,p=>p===a);for(let p=b-1;p>=0;p--)if(f>=t[p]){this._currentEstimate=r[p];return}this._currentEstimate=r[0];return}if(this._lastUnsuitableQualityTimestamp!==void 0&&l-this._lastUnsuitableQualityTimestamp<this._blockRaiseDelay||u===void 0||u<1.15||(o==null?void 0:o.confidenceLevel)!==1){this._currentEstimate=a;return}let m=t[d],g=(()=>{for(let h=d+1;h<t.length;h++)if(t[h]>m)return h})();if(g!==void 0){let h=t[g];if(i>=h){c.debug("ABR","Raising quality in BufferBasedChooser",{bitrate:r[g]}),this._currentEstimate=r[g];return}}this._currentEstimate=a}getLastEstimate(){return this._currentEstimate}};function ll(n,e){let t=-1;for(let o=0;o<n.length;o++){let{segment:s}=n[o].content;if(s.duration<=0)continue;let d=s.time+s.duration;if(!s.complete&&o===n.length-1&&e-s.time>-1.2){t=o;break}if(d>e&&e-s.time>-1.2){t=o;break}}if(t<0)return[];let r=n[t],i=r.content.segment.time,a=[r];for(let o=t+1;o<n.length&&n[o].content.segment.time===i;o++)a.push(n[o]);return a}function Nr(n){if(n.progress.length<5)return;let e=new Ue(2),{progress:t}=n;for(let r=1;r<t.length;r++){let i=t[r].size-t[r-1].size,a=t[r].timestamp-t[r-1].timestamp,o=i*8/(a/1e3);e.addSample(a/1e3,o)}return e.getEstimate()}function ys(n,e){let t=(n.totalSize-n.size)*8;return Math.max(t/e,0)}function fl(n,e,t,r,i){if(r)return;let{bufferGap:a,speed:o,position:s}=e,d=isFinite(a)?a:0,u=s.getWanted()+d,f=ll(n,u);if(f.length!==1)return;let l=f[0],m=F(),g=l.content.segment.duration*1500;if(g=Math.max(g,3e3),g=Math.min(g,12e3),m-l.requestTimestamp<g)return;let h=l.progress.length>0?l.progress[l.progress.length-1]:void 0,b=Nr(l);if(h!==void 0&&b!==void 0){let C=ys(h,b);if((m-h.timestamp)/1e3<=C&&C-d/o>2500)return b}if(!l.content.segment.complete)return;let p=l.content.segment.duration,S=(m-l.requestTimestamp)/1e3,T=S<=(p*1.5+2)/o;if(v(t)||T)return;let R=p/S,E=t.bitrate*Math.min(.7,R);if(i===void 0||E<i)return E}function ml(n,e,t){if(t)return!0;let r=isFinite(n.bufferGap)?n.bufferGap:0,i=n.position.getWanted()+r,a=j(e,({content:l})=>l.segment.duration>0&&l.segment.time+l.segment.duration>i);if(a===void 0)return!0;let o=F(),s=a.progress.length>0?a.progress[a.progress.length-1]:void 0,d=Nr(a);if(s===void 0||d===void 0)return!0;let u=ys(s,d);return(o-s.timestamp)/1e3>u*1.2?!0:u-r/n.speed>-1.5}var wn=class{constructor(e,t){let{ABR_STARVATION_GAP:r,OUT_OF_STARVATION_GAP:i,ABR_STARVATION_FACTOR:a,ABR_REGULAR_FACTOR:o}=L.getCurrent();this._initialBitrate=e,this._inStarvationMode=!1,this._lowLatencyMode=t,t?this._config={starvationGap:r.LOW_LATENCY,outOfStarvationGap:i.LOW_LATENCY,starvationBitrateFactor:a.LOW_LATENCY,regularBitrateFactor:o.LOW_LATENCY}:this._config={starvationGap:r.DEFAULT,outOfStarvationGap:i.DEFAULT,starvationBitrateFactor:a.DEFAULT,regularBitrateFactor:o.DEFAULT}}getBandwidthEstimate(e,t,r,i,a){let o,s,d=this._config,{bufferGap:u,position:f,duration:l}=e,m=isFinite(u)?u:0,{ABR_STARVATION_DURATION_DELTA:g}=L.getCurrent();return isNaN(l)||m+f.getWanted()<l-g?!this._inStarvationMode&&m<=d.starvationGap?(c.info("ABR","enter starvation mode.",{buffergap:m,enterStarvation:d.starvationGap}),this._inStarvationMode=!0):this._inStarvationMode&&m>=d.outOfStarvationGap&&(c.info("ABR","exit starvation mode.",{bufferGap:m,outOfStarvation:d.starvationGap}),this._inStarvationMode=!1):this._inStarvationMode&&(c.info("ABR","exit starvation mode.",{bufferGap:m}),this._inStarvationMode=!1),this._inStarvationMode&&(s=fl(i,e,r,this._lowLatencyMode,a),s!==void 0&&(c.info("ABR","starvation mode emergency estimate:",{bandwidth:s}),t.reset(),o=v(r)?s:Math.min(s,r.bitrate))),v(o)&&(s=t.getEstimate(),s!==void 0?o=s*(this._inStarvationMode?d.starvationBitrateFactor:d.regularBitrateFactor):a!==void 0?o=a*(this._inStarvationMode?d.starvationBitrateFactor:d.regularBitrateFactor):o=this._initialBitrate),e.speed>1&&(o/=e.speed),{bandwidthEstimate:s,bitrateChosen:o}}isUrgent(e,t,r,i){return t===null?!0:e>=t.bitrate?!1:ml(i,r,this._lowLatencyMode)}};var Dn=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 Bn=class{constructor(e,t){this._scoreCalculator=e,this._lastAbrEstimate=t,this._consecutiveWrongGuesses=0,this._blockGuessesUntil=0,this._lastMaintanableBitrate=null}getGuess(e,t,r,i,a){let{bufferGap:o,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(o,s,u)){let l=Ts(e,r);if(l!==null)return l}return null}if(this._isLastGuessValidated(d,i,u)&&(c.debug("ABR","Guessed Representation validated",{chosenBitrate:d.bitrate,otherAbrAlgosBitrate:i,scoreData:u==null?void 0:u.score,scoreConfidence:u==null?void 0:u.confidenceLevel}),this._lastMaintanableBitrate=d.bitrate,this._consecutiveWrongGuesses=0),r.id!==d.id)return d;if(this._shouldStopGuess(r,u,o,a))return this._consecutiveWrongGuesses++,this._blockGuessesUntil=F()+Math.min(this._consecutiveWrongGuesses*15e3,12e4),cl(e,r);if(u===void 0)return r;if(this._canGuessHigher(o,s,u)){let l=Ts(e,r);if(l!==null)return l}return r}_canGuessHigher(e,t,{score:r,confidenceLevel:i}){return isFinite(e)&&e>=2.5&&F()>this._blockGuessesUntil&&i===1&&r/t>1.01}_shouldStopGuess(e,t,r,i){if(t!==void 0&&t.score<1.01)return!0;if((t===void 0||t.score<1.2)&&r<.6)return!0;let a=i.filter(s=>s.content.representation.id===e.id),o=F();for(let s of a){let d=o-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=Nr(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 Ts(n,e){let t=n.length,r=ae(n,({id:i})=>i===e.id);if(r<0)return c.error("ABR","Current Representation not found."),null;for(;++r<t;)if(n[r].bitrate>e.bitrate)return n[r];return null}function cl(n,e){let t=ae(n,({id:r})=>r===e.id);if(t<0)return c.error("ABR","Current Representation not found."),null;for(;--t>=0;)if(n[t].bitrate<e.bitrate)return n[t];return null}var Nn=class{constructor(){let{ABR_FAST_EMA:e,ABR_SLOW_EMA:t}=L.getCurrent();this._fastEWMA=new Ue(e),this._slowEWMA=new Ue(t),this._bytesSampled=0}addSample(e,t){let{ABR_MINIMUM_CHUNK_SIZE:r}=L.getCurrent();if(t<r)return;let i=t*8e3/e,a=e/1e3;this._bytesSampled+=t,this._fastEWMA.addSample(a,i),this._slowEWMA.addSample(a,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 Ue(e),this._slowEWMA=new Ue(t),this._bytesSampled=0}};function Yi(n,e){if(n.length===0)return[];n.sort((a,o)=>a.bitrate-o.bitrate);let t=n[0].bitrate,r=Math.max(e,t),i=ae(n,a=>a.bitrate>r);return i===-1?n:n.slice(0,i)}function Qi(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,f;return((u=s.width)!=null?u:0)-((f=d.width)!=null?f:0)}),a=j(i,s=>typeof s.width=="number"&&s.width>=t&&typeof s.height=="number"&&s.height>=r);if(a===void 0)return n;let o=typeof a.width=="number"?a.width:0;return n.filter(s=>typeof s.width=="number"?s.width<=o:!0)}var Un=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(v(t)){if(I.CURRENT_ENV===I.DEV)throw new Error("ABR: progress for a request not added");c.warn("ABR","progress for a request not added",{requestId:e.id});return}t.progress.push(e)}remove(e){if(v(this._currentRequests[e])){if(I.CURRENT_ENV===I.DEV)throw new Error("ABR: can't remove unknown request");c.warn("ABR","can't remove unknown request",{requestId:e})}delete this._currentRequests[e]}getRequests(){return yr(this._currentRequests).filter(e=>!v(e)).sort((e,t)=>e.content.segment.time-t.content.segment.time)}};function Ur(n,e){let t=ae(n,r=>r.bitrate>e);return t===-1?n[n.length-1]:t===0?n[0]:n[t-1]}var Es=new $(void 0);Es.finish();var _s=new $(1/0);_s.finish();function $i(n){let e={},{initialBitrates:t,throttlers:r,lowLatencyMode:i}=n;return function(s,d,u,f,l){var p,S,T;let{type:m}=s.adaptation,g=a(m),h=(p=t[m])!=null?p:0,b={limitResolution:(S=r.limitResolution[m])!=null?S:Es,throttleBitrate:(T=r.throttleBitrate[m])!=null?T:_s};return pl({bandwidthEstimator:g,context:s,currentRepresentation:d,filters:b,initialBitrate:h,playbackObserver:f,representations:u,lowLatencyMode:i},l)};function a(o){let s=e[o];if(v(s)){c.debug("ABR","Creating new BandwidthEstimator",{bufferType:o});let d=new Nn;return e[o]=d,d}return s}}function pl({bandwidthEstimator:n,context:e,currentRepresentation:t,filters:r,initialBitrate:i,lowLatencyMode:a,playbackObserver:o,representations:s},d){let u=new Mn,f=new wn(i!=null?i:0,a),l=new Un,m=O,g={metrics:T,requestBegin:R,requestProgress:E,requestEnd:C,addedSegment(P){m(P)}},h=new z("ABR "+e.adaptation.type);h.linkToSignal(d);let b=p(s.getValue(),h.signal);return s.onUpdate(S,{clearSignal:d}),{estimates:b,callbacks:g};function p(P,x){if(P.length<=1)return new $({bitrate:void 0,representation:P[0],urgent:!0,knownStableBitrate:void 0});let A=!1,k=P.sort((U,G)=>U.bitrate-G.bitrate),N=new On(k.map(U=>U.bitrate)),w=new Dn,W=new Bn(u,w),B=o.getReference().getValue(),_=new $(D());return o.listen(U=>{B=U,M()},{includeLastObservation:!1,clearSignal:x}),m=function(U){if(B===null)return;let{position:G,speed:Q}=B,K=U.buffered,q=xr(K,G.getWanted()),{representation:Z}=U.content,X=u.getEstimate(Z),me=Z.bitrate,pe={bufferGap:q,currentBitrate:me,currentScore:X,speed:Q};N.onAddedSegment(pe),M()},x.register(()=>{m=O}),r.throttleBitrate.onUpdate(M,{clearSignal:x}),r.limitResolution.onUpdate(M,{clearSignal:x}),_;function M(){_.setValue(D())}function D(){let{bufferGap:U,position:G,maximumPosition:Q}=B,K=r.limitResolution.getValue(),q=r.throttleBitrate.getValue(),Z=t.getValue(),X=gl(k,K,q),me=l.getRequests(),{bandwidthEstimate:pe,bitrateChosen:Qe}=f.getBandwidthEstimate(B,n,Z,me,w.bandwidth),ie=u.getLastStableRepresentation(),se=ie===null?void 0:ie.bitrate/(B.speed>0?B.speed:1),{ABR_ENTER_BUFFER_BASED_ALGO:$t,ABR_EXIT_BUFFER_BASED_ALGO:Xt}=L.getCurrent();A&&U<=Xt?A=!1:!A&&isFinite(U)&&U>=$t&&(A=!0);let Re=Ur(X,Qe),Zt=N.getLastEstimate(),lr=Re.bitrate,ft=null;A&&Zt!==void 0&&Zt>lr&&(ft=Ur(X,Zt),lr=ft.bitrate);let mt=null;return a&&Z!==null&&e.manifest.isDynamic&&Q-G.getWanted()<40&&(mt=W.getGuess(k,B,Z,lr,me)),mt!==null&&mt.bitrate>lr?(c.debug("ABR","new guess-based estimate",{bitrate:mt.bitrate,representation:mt.id}),w.update(mt,pe,2),{bitrate:pe,representation:mt,urgent:Z===null||mt.bitrate<Z.bitrate,knownStableBitrate:se}):ft!==null?(c.debug("ABR","new buffer-based estimate",{bitrate:ft.bitrate,representation:ft.id}),w.update(ft,pe,0),{bitrate:pe,representation:ft,urgent:f.isUrgent(ft.bitrate,Z,me,B),knownStableBitrate:se}):(c.debug("ABR","new bandwidth estimate",{bitrate:Re.bitrate,representation:Re.id}),w.update(Re,pe,1),{bitrate:pe,representation:Re,urgent:f.isUrgent(Re.bitrate,Z,me,B),knownStableBitrate:se})}}function S(){let P=s.getValue();h.cancel("restart"),h=new z("ABR "+e.adaptation.type),h.linkToSignal(d),p(P,h.signal).onUpdate(function(k){b.setValue(k)},{clearSignal:h.signal,emitCurrentValue:!0})}function T(P){let{requestDuration:x,segmentDuration:A,size:k,content:N}=P;if(n.addSample(x,k),!N.segment.isInit){let{segment:w,representation:W}=N;if(A===void 0&&!w.complete)return;let B=A!=null?A:w.duration;u.addSample(W,x/1e3,B)}}function R(P){l.add(P)}function E(P){l.addProgress(P)}function C(P){l.remove(P.id)}}function gl(n,e,t){let r=n;return t!==void 0&&t<1/0&&(r=Yi(r,t)),e!==void 0&&(r=Qi(r,e)),r}var Rs=$i;function Lr(){var t;if(typeof((t=ne.crypto)==null?void 0:t.randomUUID)=="function")return ne.crypto.randomUUID();let n=new Date().getTime(),e=F();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let i=Math.random()*16;return n>0?(i=(n+i)%16|0,n=Math.floor(n/16)):(i=(e+i)%16|0,e=Math.floor(e/16)),(r==="x"?i:i&3|8).toString(16)})}var hl=/^(?:[a-z]+:)?\/\//i,Il=/^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/;function Zi(n){let e=n.lastIndexOf("/");if(e<0)return n.length;if(hl.test(n)){let r=n.indexOf("/");if(r>=0&&e===r+1)return n.length}let t=n.indexOf("?");return t>=0&&t<e?Zi(n.substring(0,t)):e+1}function Ps(n,e){let t=Fr(n),r=Fr(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=Fn(t.path),a=Fn(r.path),o;if(i===a)o="";else{let d=i.split("/");d.pop();let u=a.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 f=u.join("/");(f.endsWith("../")||f.endsWith("./"))&&(f=f.slice(0,f.length-1)),o=f===""?".":f}let s=o;return o===""&&r.query===t.query||Y(r.query)&&(s+="?",s+=r.query),Y(r.fragment)&&(s+="#",s+=r.fragment),s}function bl(n,e){let t=Fr(n),r=Fr(e);if(Y(r.scheme))return Xi(r);let i={scheme:t.scheme,authority:t.authority,path:"",query:r.query,fragment:r.fragment};return Y(r.authority)?(i.authority=r.authority,i.path=Fn(r.path),Xi(i)):(r.path===""?(i.path=t.path,Y(r.query)||(i.query=t.query)):Ie(r.path,"/")?i.path=Fn(r.path):i.path=Fn(yl(t,r.path)),Xi(i))}var Ln=new Map,Sl=200;function Fr(n){var r,i,a,o,s;if(Ln.has(n))return Ln.get(n);let e=n.match(Il),t;return e===null?t={scheme:"",authority:"",path:"",query:"",fragment:""}:t={scheme:(r=e[1])!=null?r:"",authority:(i=e[2])!=null?i:"",path:(a=e[3])!=null?a:"",query:(o=e[4])!=null?o:"",fragment:(s=e[5])!=null?s:""},Ln.size>=Sl&&Ln.clear(),Ln.set(n,t),t}function Xi(n){let e="";return Y(n.scheme)&&(e+=n.scheme+":"),Y(n.authority)&&(e+="//"+n.authority),e+=n.path,Y(n.query)&&(e+="?"+n.query),Y(n.fragment)&&(e+="#"+n.fragment),e}function Fn(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 yl(n,e){if(Y(n.authority)&&n.path==="")return"/"+e;let t=n.path;return t.substring(0,t.lastIndexOf("/")+1)+e}function zn(...n){var r,i,a;let e=n.filter(o=>o!==""),t=e.length;if(t===0)return"";if(t===1)return(r=e[0])!=null?r:"";{let o=(i=e[0])!=null?i:"",s=(a=e[1])!=null?a:"",d=bl(o,s),u=e.slice(2);return zn(d,...u)}}var Tl=4,Wn=class{constructor(e){var t,r;this._sessionId=(t=e.sessionId)!=null?t:Lr(),this._contentId=(r=e.contentId)!=null?r:Lr(),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("CmcdDataBuilder start"),this._canceller=new z("CMCD monitoring"),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("CmcdDataBuilder stop"),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||!isFinite(r.speed)||r.speed<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 o,s,d,u;let t=(o=this._playbackObserver)==null?void 0:o.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"),!v(e.nextSegment)&&e.segment.url!==null&&e.nextSegment.url!==null&&(!e.nextSegment.isInit||e.nextSegment.indexRange===void 0)){let f=e.segment.url,l=e.nextSegment.url,m=Ps(f,l);m!==null&&(m!=="."&&(r.nor=encodeURIComponent(m)),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 f=t.buffered[e.adaptation.type];if(!v(f)){let l=(u=(d=(s=this._playbackObserver)==null?void 0:s.getCurrentTime())!=null?d:t.position.getWanted())!=null?u:t.position.getPolled();for(let m of f)if(l>=m.start&&l<m.end){i=(m.end-l)*1e3,r.bl=Math.floor(Math.round(i/100)*100);break}}}let a=i===void 0||t===void 0||!isFinite(t.speed)||t.speed<=0?void 0:i/t.speed;if(r.dl=a===void 0?void 0:Math.floor(Math.round(a/100)*100),a!==void 0){let l=e.representation.bitrate*e.segment.duration/1e3/(a/1e3);r.rtp=Math.floor(Math.round(l*Tl/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((f,l)=>l.isPlayable()!==!0?f:f===void 0?Math.round(l.bitrate/1e3):Math.max(f,Math.round(l.bitrate/1e3)),void 0),this._producePayload(r)}_producePayload(e){let t={object:"",request:"",session:"",status:""},r="",i=(u,f)=>{this._typePreference===0?t[f]+=u:r+=u},a=(u,f)=>{let l=e[u];if(l!==void 0){let m=`${u}=${String(l)},`;i(m,f)}},o=(u,f)=>{if(e[u]===!0){let l=`${u},`;i(l,f)}},s=(u,f)=>{let l=e[u];if(l!==void 0){let m=`"${l.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,g=`${u}=${m},`;i(g,f)}},d=(u,f)=>{let l=e[u];if(l!==void 0){let m=`${u}=${l},`;i(m,f)}};return a("bl","request"),a("br","object"),o("bs","status"),s("cid","session"),a("d","object"),a("dl","request"),a("mtp","request"),s("nor","request"),s("nrr","request"),d("ot","object"),a("pr","session"),a("rtp","status"),d("sf","session"),s("sid","session"),d("st","session"),o("su","request"),a("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)),c.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),c.debug("CMCD","proposing query string payload",{queryString:r}),{type:"query",value:[["CMCD",r]]})}};var vs=Wn;var Vn=class extends ce{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=Cs(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 a=setTimeout(()=>{let o=Cs(this._downgradedCdnList.metadata,e);o>=0&&this._removeIndexFromDowngradeList(o),this.trigger("priorityChange",null)},i);this._downgradedCdnList.timeouts.push(a),this.trigger("priorityChange",null)}_innerGetCdnPreferenceForResource(e){let[t,r]=e.reduce((i,a)=>(this._downgradedCdnList.metadata.some(o=>o.id===a.id&&o.baseUrl===a.baseUrl)?i[1].push(a):i[0].push(a),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 Cs(n,e){return n.length===0?-1:e.id!==void 0?ae(n,t=>t.id===e.id):ae(n,t=>t.baseUrl===e.baseUrl)}function Le(n){return n instanceof le?new Xe("PIPELINE_LOAD_ERROR",n):ge(n,{defaultCode:"PIPELINE_LOAD_ERROR",defaultReason:"Unknown error when fetching the Manifest"})}function El(n){return n instanceof le?n.type===Pt.ERROR_HTTP_CODE?n.status>=500||n.status===404||n.status===415||n.status===412||n.status===429:n.type===Pt.TIMEOUT||n.type===Pt.ERROR_EVENT:n instanceof $e?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||n.xhr.status===429:!1:Ut(n)&&n.code==="INTEGRITY_ERROR"}async function qn(n,e,t,r,i){if(i.cancellationError!==null)return Promise.reject(i.cancellationError);let{baseDelay:a,maxDelay:o,maxRetry:s,onRetry:d}=r;n!==null&&n.length===0&&c.warn("utils","No CDN given to `scheduleRequestWithCdns`.");let u=new Map,f=l();if(f===void 0)throw new Error("No CDN to request");return m(f);function l(){if(n===null){let p=u.get(null);return p!==void 0&&p.isBlacklisted?void 0:null}else{if(e===null)return b(n);{let p=e.getCdnPreferenceForResource(n);return b(p)}}}async function m(p){try{return await t(p,i)}catch(S){if(z.isCancellationError(S))throw S;p!==null&&e!==null&&e.downgradeCdn(p);let T=u.get(p);if(T===void 0?(T={errorCounter:1,blockedUntil:void 0,isBlacklisted:!1},u.set(p,T)):T.errorCounter++,!El(S))return T.blockedUntil=void 0,T.isBlacklisted=!0,g(S);if(T.errorCounter>s)T.blockedUntil=void 0,T.isBlacklisted=!0;else{let R=T.errorCounter,E=Math.min(a*Math.pow(2,R-1),o),C=Ai(E);T.blockedUntil=F()+C}return g(S)}}async function g(p){let S=l();if(i.isCancelled())throw i.cancellationError;if(S===void 0)throw p;if(d(p),i.isCancelled())throw i.cancellationError;return h(S,p)}function h(p,S){let T=u.get(p);if(T===void 0||T.blockedUntil===void 0)return m(p);let R=F(),E=T.blockedUntil-R;if(E<=0)return m(p);let C=new z("Request Backoff"),P=C.linkToSignal(i);return new Promise((x,A)=>{e==null||e.addEventListener("priorityChange",()=>{let w=l();if(!i.isCancelled()){if(w===void 0)return N(S);w!==p&&(C.cancel("new prioritized CDN"),h(w,S).then(k,N))}},C.signal),fn(E,C.signal).then(()=>m(p).then(k,N),w=>N(i.isCancelled()?i.cancellationError:w));function k(w){P(),x(w)}function N(w){P(),A(w)}})}function b(p){var T;if(u.size===0)return p[0];let S=F();return(T=p.filter(R=>{var E;return((E=u.get(R))==null?void 0:E.isBlacklisted)!==!0}).reduce((R,E)=>{var P;let C=(P=u.get(E))==null?void 0:P.blockedUntil;return C!==void 0&&C<=S&&(C=void 0),R===void 0?[E,C]:R[1]===void 0?R:C===void 0?[E,void 0]:C<R[1]?[E,C]:R},void 0))==null?void 0:T[0]}}function Ji(n,e,t){return qn(null,null,n,e,t)}var Gn=class extends ce{constructor(e,t,r){super(),this.scheduleManualRefresh=O,this._manifestUrls=e,this._pipelines=t.manifest,this._transportName=t.transportName,this._settings=r,this._canceller=new z("ManifestFetcher"),this._isStarted=!1,this._isRefreshPending=!1,this._consecutiveUnsafeMode=0,this._prioritizedContentUrl=null}dispose(e){this._canceller.cancel(e!=null?e:"ManifestFetcher dispose"),this.removeEventListener()}start(){if(this._isStarted)return;this._isStarted=!0;let e,t=this._settings.initialManifest;t instanceof It?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._manifestUrls=e,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,a=this._pipelines,o=e!=null?e:(u=this._manifestUrls)==null?void 0:u[0],s=this._getBackoffSetting(f=>{this.trigger("warning",Le(f))});try{let f=await d(o);return{parse:l=>this._parseLoadedManifest(f,l,o)}}catch(f){throw Le(f)}function d(f){var p;let{loadManifest:l}=a,m=r.requestTimeout===void 0?L.getCurrent().DEFAULT_REQUEST_TIMEOUT:r.requestTimeout,g=r.connectionTimeout===void 0?L.getCurrent().DEFAULT_CONNECTION_TIMEOUT:r.connectionTimeout;m<0&&(m=void 0),g<0&&(g=void 0);let h={timeout:m,connectionTimeout:g,cmcdPayload:(p=r.cmcdDataBuilder)==null?void 0:p.getCmcdDataForManifest(i)};return Ji(()=>l(f,h,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=F(),a=this._canceller.signal,o=this.trigger.bind(this),{sendingTime:s,receivedTime:d}=e,u=this._getBackoffSetting(p=>{this.trigger("warning",Le(p))}),f=r!=null?r:(b=this._manifestUrls)==null?void 0:b[0],l={externalClockOffset:t.externalClockOffset,unsafeMode:t.unsafeMode,previousManifest:t.previousManifest,originalUrl:f};try{let p=this._pipelines.parseManifest(e,l,g,a,m);if(_l(p)){let{manifest:S}=await p;return h(S)}else return h(p.manifest)}catch(p){throw ge(p,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"})}async function m(p){try{return await Ji(p,u,a)}catch(S){throw Le(S)}}function g(p){for(let S of p){if(a.isCancelled())return;let T=ge(S,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown error when parsing the Manifest"});o("warning",T)}}function h(p){let S=F()-i;return c.info("MF",`Manifest parsed in ${S}ms`),{manifest:p,sendingTime:s,receivedTime:d,parsingTime:S}}}_getBackoffSetting(e){let{DEFAULT_MAX_MANIFEST_REQUEST_RETRY:t,INITIAL_BACKOFF_DELAY_BASE:r,MAX_BACKOFF_DELAY_BASE:i}=L.getCurrent(),{lowLatencyMode:a,maxRetry:o}=this._settings,s=a?r.LOW_LATENCY:r.REGULAR,d=a?i.LOW_LATENCY:i.REGULAR,u=o!=null?o: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:a,MIN_MANIFEST_PARSING_TIME_TO_ENTER_UNSAFE_MODE:o}=L.getCurrent(),s=r!==void 0?r+(i!=null?i:0):void 0,d=!1;this._consecutiveUnsafeMode>0?d=this._consecutiveUnsafeMode<a:s!==void 0&&(d=s>=o);let u=t===void 0?0:F()-t,f=Math.max(this._settings.minimumManifestUpdateInterval-u,0),l=new z("ManifestFetcher refresh handling");if(l.linkToSignal(this._canceller.signal),this.scheduleManualRefresh=m=>{let{enablePartialRefresh:g,delay:h,canUseUnsafeMode:b}=m,p=b&&d,S=t===void 0?0:F()-t,T=Math.max(this._settings.minimumManifestUpdateInterval-S,0),R=setTimeout(()=>{l.cancel("manifest request timeout"),this._triggerNextManifestRefresh(e,{enablePartialRefresh:g,unsafeMode:p})},Math.max((h!=null?h:0)-S,T));l.signal.register(()=>{clearTimeout(R)})},e.expired!==null){let m=setTimeout(()=>{var g;(g=e.expired)==null||g.then(()=>{l.cancel("manifest expiration"),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},O)},f);l.signal.register(()=>{clearTimeout(m)})}if(e.lifetime!==void 0&&e.lifetime>=0){let m=e.lifetime*1e3-u,g;s===void 0?g=m:e.lifetime<3&&s>=100?(g=Math.min(Math.max(3e3-u,Math.max(m,0)+s),m*6),c.info("MF","Manifest update rythm is too frequent. Postponing next request.",{regularRefreshDelay:m,newRefreshDelay:g})):s>=e.lifetime*1e3/10?(g=Math.min(Math.max(m,0)+s,m*6),c.info("MF","Manifest took too long to parse. Postponing next request",{regularRefreshDelay:m,newRefreshDelay:g})):g=m;let h=setTimeout(()=>{l.cancel("manifest request timeout"),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:d})},Math.max(g,f));l.signal.register(()=>{clearTimeout(h)})}}_triggerNextManifestRefresh(e,{enablePartialRefresh:t,unsafeMode:r}){let i=e.updateUrl,a,o;this._prioritizedContentUrl!==null?(a=!0,o=this._prioritizedContentUrl,this._prioritizedContentUrl=null):(a=!t||i===void 0,o=a?e.getUrls()[0]:i);let s=e.clockOffset;r?(this._consecutiveUnsafeMode+=1,c.info("MF",'Refreshing the Manifest in "unsafeMode" for the '+String(this._consecutiveUnsafeMode)+" consecutive time.")):this._consecutiveUnsafeMode>0&&(c.info("MF",'Not parsing the Manifest in "unsafeMode" anymore after '+String(this._consecutiveUnsafeMode)+" consecutive times."),this._consecutiveUnsafeMode=0),!this._isRefreshPending&&(this._isRefreshPending=!0,this._fetchManifest(o).then(d=>d.parse({externalClockOffset:s,previousManifest:e,unsafeMode:r})).then(d=>{this._isRefreshPending=!1;let{manifest:u,sendingTime:f,parsingTime:l}=d,m=F();if(a)e.replace(u);else try{e.update(u)}catch(h){let b=h instanceof Error?h.message:"unknown error";c.warn("MF",`Attempt to update Manifest failed: ${b}`,"Re-downloading the Manifest fully");let{FAILED_PARTIAL_UPDATE_MANIFEST_REFRESH_DELAY:p}=L.getCurrent(),S=f===void 0?0:F()-f,T=Math.max(this._settings.minimumManifestUpdateInterval-S,0),R=O,E=setTimeout(()=>{R(),this._triggerNextManifestRefresh(e,{enablePartialRefresh:!1,unsafeMode:!1})},Math.max(p-S,T));R=this._canceller.signal.register(()=>{clearTimeout(E)});return}let g=F()-m;this._recursivelyRefreshManifest(e,{sendingTime:f,parsingTime:l,updatingTime:g})}).catch(d=>{this._isRefreshPending=!1,this._onFatalError(d)}))}_onFatalError(e){this._canceller.isUsed()||(this.trigger("error",e),this.dispose("ManifestFetcher fatal err"))}};function _l(n){return n instanceof Promise}var ea=Gn;function ta(n,e){let t=new WeakMap;return{createRequest(r,i,a,o){let s=u=>e(r,a,u),d=n.create(s,i,a,o);return t.set(d,s),d},updatePriority(r,i){let a=t.get(r);if(a===void 0){c.warn("SF","Cannot update the priority of a request: task not found.");return}n.updatePriority(a,i)}}}var na=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}},As=na;var Rl=Me();function ra({bufferType:n,pipeline:e,cdnPrioritizer:t,cmcdDataBuilder:r,eventListeners:i,requestOptions:a}){let o;a.connectionTimeout===void 0||a.connectionTimeout<0?o=void 0:o=a.connectionTimeout;let s={timeout:a.requestTimeout<0?void 0:a.requestTimeout,connectionTimeout:o,cmcdPayload:void 0},d=fe(["audio","video"],n)?new As:void 0,{loadSegment:u,parseSegment:f}=e;return async function(m,g,h){var G,Q,K;let{segment:b,adaptation:p,representation:S,manifest:T,period:R}=m,E=He(m),C=Rl(),P,x=[],A=0,k=!1,N={segment:b,type:p.type,language:p.language,isLive:T.isLive,periodStart:R.start,periodEnd:R.end,mimeType:S.mimeType,baseCodecs:S.baseCodecs,chosenCodec:S.chosenCodec,manifestPublishTime:T.publishTime},w={onProgress(q){var Z;P===void 0&&q.totalSize!==void 0&&q.size<q.totalSize&&((Z=i.onProgress)==null||Z.call(i,{duration:q.duration,size:q.size,totalSize:q.totalSize,timestamp:F(),id:C}))},onNewChunk(q){g.onChunk(M(q,!0))}},W=d!==void 0?d.get(m):null;if(W!==null)return c.debug("SF","Found wanted segment in cache",E),g.onChunk(M(W,!1)),Promise.resolve();c.debug("SF","Beginning request",E),(G=i.onRequestBegin)==null||G.call(i,{requestTimestamp:F(),id:C,content:m}),h.register(B);try{let q=await qn(m.representation.cdnMetadata,t,_,H({onRetry:D},a),h);if(q.resultType==="segment-loaded"){let Z=q.resultData.responseData;d!==void 0&&d.add(m,q.resultData.responseData),g.onChunk(M(Z,!1))}else q.resultType==="segment-created"&&g.onChunk(M(q.resultData,!1));c.debug("SF","Segment request ended with success",E),g.onAllChunksReceived(),q.resultType!=="segment-created"?(P=q.resultData,U()):P=null,h.isCancelled()||(Q=i.onRequestEnd)==null||Q.call(i,{id:C}),h.deregister(B)}catch(q){throw h.deregister(B),P=null,q instanceof ue?(c.debug("SF","Segment request aborted",E),q):(c.debug("SF","Segment request failed",E),(K=i.onRequestEnd)==null||K.call(i,{id:C}),Le(q))}function B(){var q;P===void 0&&(c.debug("SF","Segment request cancelled",E),P=null,(q=i.onRequestEnd)==null||q.call(i,{id:C}))}function _(q){return s.cmcdPayload=r==null?void 0:r.getCmcdDataForSegmentRequest(m),u(q,N,s,h,w)}function M(q,Z){x.push(!1);let X=x.length-1;return function(pe){let Qe={data:q,isChunked:Z};try{let ie=f(Qe,N,pe);return x[X]||(A=A!==void 0&&ie.segmentType==="media"&&ie.chunkInfos!==null&&ie.chunkInfos.duration!==void 0?A+ie.chunkInfos.duration:void 0,x[X]=!0,U()),ie}catch(ie){throw ge(ie,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}}}function D(q){g.onRetry(Le(q))}function U(){var q;k||!v(P)&&P.size!==void 0&&P.requestDuration!==void 0&&x.length>0&&x.every(Z=>Z)&&(k=!0,(q=i.onMetrics)==null||q.call(i,{size:P.size,requestDuration:P.requestDuration,content:m,segmentDuration:A}))}}}function xs({maxRetry:n,lowLatencyMode:e,requestTimeout:t,connectionTimeout:r}){let{DEFAULT_MAX_REQUESTS_RETRY_ON_ERROR:i,DEFAULT_REQUEST_TIMEOUT:a,DEFAULT_CONNECTION_TIMEOUT:o,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?a:t,connectionTimeout:r===void 0?o:r}}var Hn=class extends ce{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,r){var s;(s=this._currentContentInfo)==null||s.currentCanceller.cancel(r!=null?r:"SegmentQueue reset");let i=new $({initSegment:null,segmentQueue:[]}),a=new z("SegmentQueue "+e.adaptation.type);a.signal.register(()=>{i.finish()});let o={content:e,downloadQueue:i,initSegmentInfoRef:t?new $(void 0):new $(null),currentCanceller:a,initSegmentRequest:null,mediaSegmentRequest:null,mediaSegmentAwaitingInitMetadata:null};return this._currentContentInfo=o,this.isMediaSegmentQueueInterrupted.onUpdate(d=>{d||(c.debug("SF","Media segment can be loaded again, restarting queue.",{type:e.adaptation.type}),this._restartMediaSegmentDownloadingQueue(o,"interrupt end"))},{clearSignal:a.signal}),i.onUpdate(d=>{let{segmentQueue:u}=d;if(u.length>0&&u[0].segment.id===o.mediaSegmentAwaitingInitMetadata)return;let f=o.mediaSegmentRequest;if(u.length===0){if(f===null)return;c.debug("SF","no more media segment to request. Cancelling queue.",{type:e.adaptation.type}),this._restartMediaSegmentDownloadingQueue(o,"media segment queue empty");return}else if(f===null){c.debug("SF","Media segments now need to be requested. Starting queue.",{type:e.adaptation.type,queueLength:u.length}),this._restartMediaSegmentDownloadingQueue(o,"media segment queue start");return}else{let l=u[0];if(f.segment.id!==l.segment.id){c.debug("SF","Next media segment changed, cancelling previous",{type:e.adaptation.type}),this._restartMediaSegmentDownloadingQueue(o,"next media segment changed");return}f.priority!==l.priority&&(c.debug("SF","Priority of next media segment changed, updating",{type:e.adaptation.type,prevPriority:f.priority,newPriority:l.priority}),this._segmentFetcher.updatePriority(f.request,l.priority));return}},{emitCurrentValue:!0,clearSignal:a.signal}),i.onUpdate(d=>{var f;let u=o.initSegmentRequest;if(d.initSegment!==null&&u!==null){d.initSegment.priority!==u.priority&&this._segmentFetcher.updatePriority(u.request,d.initSegment.priority);return}else if(((f=d.initSegment)==null?void 0:f.segment.id)===(u==null?void 0:u.segment.id))return;d.initSegment===null&&c.debug("SF","no more init segment to request. Cancelling queue.",{type:e.adaptation.type}),this._restartInitSegmentDownloadingQueue(o,d.initSegment,"init segment queue empty")},{emitCurrentValue:!0,clearSignal:a.signal}),i}stop(e){var t;(t=this._currentContentInfo)==null||t.currentCanceller.cancel(e!=null?e:"SegmentQueue stop"),this._currentContentInfo=null}_restartMediaSegmentDownloadingQueue(e,t){e.mediaSegmentRequest!==null&&e.mediaSegmentRequest.canceller.cancel(t!=null?t:"SegmentQueue media restart");let{downloadQueue:r,content:i,initSegmentInfoRef:a,currentCanceller:o}=e,s=()=>{var E;if(this.isMediaSegmentQueueInterrupted.getValue()){c.debug("SF","Segment fetching postponed because it cannot stream now.");return}let{segmentQueue:d}=r.getValue(),u=d[0];if(o!==null&&o.isUsed()){e.mediaSegmentRequest=null;return}if(u===void 0){e.mediaSegmentRequest=null,this.trigger("emptyQueue",null);return}let f=new z("SegmentQueue media segments queue "+i.adaptation.type),l=o===null?O:f.linkToSignal(o.signal),{segment:m,priority:g}=u,h=H({segment:m,nextSegment:(E=d[1])==null?void 0:E.segment},i),b=!1,p=!1;f.signal.register(()=>{e.mediaSegmentRequest=null,!b&&(e.mediaSegmentAwaitingInitMetadata===m.id&&(e.mediaSegmentAwaitingInitMetadata=null),b=!0,p=!1)});let S=C=>{Se(C.segmentType==="media","Should have loaded a media segment."),this.trigger("parsedMediaSegment",H({},C,{segment:m}))},T=()=>{let C=r.getValue().segmentQueue;if(C.length===0){b=!0,this.trigger("emptyQueue",null);return}else C[0].segment.id===m.id&&C.shift();b=!0,s()},R=this._segmentFetcher.createRequest(h,g,{onRetry:C=>{this.trigger("requestRetry",{segment:m,error:C})},beforeInterrupted(){c.info("SF","segment request interrupted temporarly.",{segmentId:m.id,segmentTime:m.time})},onChunk:C=>{let P=a.getValue();P!==void 0?S(C(P!=null?P:void 0)):(p=!0,a.waitUntilDefined(x=>{S(C(x!=null?x:void 0))},{clearSignal:f.signal}))},onAllChunksReceived:()=>{p?(e.mediaSegmentAwaitingInitMetadata=m.id,a.waitUntilDefined(()=>{e.mediaSegmentAwaitingInitMetadata=null,p=!1,this.trigger("fullyLoadedSegment",m)},{clearSignal:f.signal})):this.trigger("fullyLoadedSegment",m)},beforeEnded:()=>{l(),e.mediaSegmentRequest=null,p?a.waitUntilDefined(T,{clearSignal:f.signal}):T()}},f.signal);R.catch(C=>{l(),b||(b=!0,this.stop("request err"),this.trigger("error",C))}),e.mediaSegmentRequest={segment:m,priority:g,request:R,canceller:f}};s()}_restartInitSegmentDownloadingQueue(e,t,r){let{content:i,initSegmentInfoRef:a}=e;if(e.initSegmentRequest!==null&&e.initSegmentRequest.canceller.cancel(r!=null?r:"SegmentQueue init restart"),t===null)return;let o=new z("SegmentQueue init segment "+i.adaptation.type),s=e.currentCanceller===null?O:o.linkToSignal(e.currentCanceller.signal),{segment:d,priority:u}=t,f=H({segment:d,nextSegment:void 0},i),l=!1,m=this._segmentFetcher.createRequest(f,u,{onRetry:g=>{this.trigger("requestRetry",{segment:d,error:g})},beforeInterrupted:()=>{c.info("SF","init segment request interrupted temporarly.",{segmentId:d.id})},beforeEnded:()=>{s(),e.initSegmentRequest=null,l=!0},onChunk:g=>{var b;let h=g(void 0);Se(h.segmentType==="init","Should have loaded an init segment."),this.trigger("parsedInitSegment",H({},h,{segment:d})),h.segmentType==="init"&&a.setValue((b=h.initTimescale)!=null?b:null)},onAllChunksReceived:()=>{this.trigger("fullyLoadedSegment",d)}},o.signal);m.catch(g=>{s(),l||(l=!0,this.stop("request err"),this.trigger("error",g))}),o.signal.register(()=>{e.initSegmentRequest=null,!l&&(l=!0)}),e.initSegmentRequest={segment:d,priority:u,request:m,canceller:o}}};var jn=class{constructor({prioritySteps:e}){if(this._minPendingPriority=null,this._waitingQueue=[],this._pendingTasks=[],this._prioritySteps=e,this._prioritySteps.high>=this._prioritySteps.low)throw new Error("The max high level priority should be given a lowerpriority number than the min low priority.")}create(e,t,r,i){let a;return Ct(i,(o,s)=>(a={hasEnded:!1,priority:t,trigger:()=>{if(a.hasEnded)return;let u=()=>{g(),this._endTask(a)},f=h=>{r.beforeEnded(),u(),o(h)},l=h=>{u(),s(h)},m=new z(void 0),g=m.linkToSignal(i);a.interrupter=m,m.signal.register(()=>{a.interrupter=null,i.isCancelled()||r.beforeInterrupted()}),this._minPendingPriority=this._minPendingPriority===null?a.priority:Math.min(this._minPendingPriority,a.priority),this._pendingTasks.push(a),a.taskFn(m.signal).then(f).catch(h=>{!i.isCancelled()&&m.isUsed()&&h instanceof ue||l(h)})},taskFn:e,interrupter:null},this._canBeStartedNow(a)?(a.trigger(),this._isRunningHighPriorityTasks()&&this._interruptCancellableTasks()):this._waitingQueue.push(a),()=>this._endTask(a)))}_endTask(e){e.hasEnded=!0;let t=Kn(e.taskFn,this._waitingQueue);if(t>=0)this._waitingQueue.splice(t,1);else{let r=Kn(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=Kn(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=Kn(e,this._pendingTasks);if(i<0){c.warn("SF","request to update the priority of a non-existent task");return}let a=this._pendingTasks[i];if(a.priority===t)return;let o=a.priority;a.priority=t,this._minPendingPriority===null||t<this._minPendingPriority?this._minPendingPriority=t:this._minPendingPriority===o&&(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?(c.warn("SF","Tried to start a non existing task"),!1):(this._waitingQueue.splice(e,1)[0].trigger(),!0)}_interruptPendingTask(e){var r;let t=Kn(e.taskFn,this._pendingTasks);if(t<0){c.warn("SF","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("TaskPrioritizer interrupt")}_canBeStartedNow(e){return this._minPendingPriority===null||e.priority<=this._minPendingPriority}_isRunningHighPriorityTasks(){return this._minPendingPriority!==null&&this._minPendingPriority<=this._prioritySteps.high}};function Kn(n,e){return ae(e,t=>t.taskFn===n)}var Yn=class{constructor(e,t,r,i){let{MIN_CANCELABLE_PRIORITY:a,MAX_HIGH_PRIORITY_LEVEL:o}=L.getCurrent();this._transport=e,this._prioritizer=new jn({prioritySteps:{high:o,low:a}}),this._cdnPrioritizer=t,this._backoffOptions=i,this._cmcdDataBuilder=r}createSegmentQueue(e,t,r){let i=xs(this._backoffOptions),a=this._transport[e],o=ra({bufferType:e,pipeline:a,cdnPrioritizer:this._cdnPrioritizer,cmcdDataBuilder:this._cmcdDataBuilder,eventListeners:t,requestOptions:i}),s=ta(this._prioritizer,o);return new Hn(s,r)}};var ia=Yn;function aa(n,e){let{loadThumbnail:t}=n,r=[];return async function(a,o){o.register(E);let{segment:s,track:d}=a,u,f=j(r,({thumbnailContext:x})=>x.period.id===a.period.id&&x.track.id===a.track.id&&x.segment.id===a.segment.id);if(f!==void 0){c.debug("Thumbnails","Requesting same thumbnail than the pending one",{time:a.segment.time}),u=f,u.referenceCount++;let x;try{x=await u.promise}catch(A){throw o.deregister(E),A}if(o.deregister(E),o.isCancelled())throw o.cancellationError;return R(x)}let l=Pl({}),m;l.connectionTimeout===void 0||l.connectionTimeout<0?m=void 0:m=l.connectionTimeout;let g={timeout:l.requestTimeout<0?void 0:l.requestTimeout,connectionTimeout:m,cmcdPayload:void 0},h=new z("Thumbnail request"),b=T();u={thumbnailContext:a,promise:b,referenceCount:1},r.push(u);let p=()=>{let x=r.indexOf(u);x>=0&&r.splice(x,1)},S;try{S=await b}catch(x){throw p(),o.deregister(E),x}if(p(),o.deregister(E),o.isCancelled())throw o.cancellationError;return R(S);async function T(){c.debug("Thumbnails","Beginning thumbnail request",{time:s.time});try{let x=await qn(d.cdnMetadata,e,C,H({onRetry:P},l),h.signal);return c.debug("Thumbnails","Thumbnail request ended with success",{time:s.time}),x}catch(x){throw x instanceof ue?(c.debug("Thumbnails","Thumbnail request aborted",{time:s.time}),x):(c.debug("Thumbnails","Thumbnail request failed",{time:s.time}),Le(x))}}function R(x){try{return n.parseThumbnail(x.responseData,{thumbnail:s,thumbnailTrack:d})}catch(A){throw ge(A,{defaultCode:"PIPELINE_PARSE_ERROR",defaultReason:"Unknown parsing error"})}}function E(){c.debug("Thumbnails","Thumbnail request cancelled",{time:s.time});let x=r.indexOf(u);x<0||(r[x].referenceCount--,r[x].referenceCount<=0&&(h.cancel("Thumbnail request aborted"),r.splice(x,1)))}function C(x){return t(x,s,g,h.signal)}function P(x){let A=Le(x);c.warn("Thumbnails","Thumbnail request retry ",{time:s.time},A)}}}function Pl({maxRetry:n,requestTimeout:e,connectionTimeout:t}){let{DEFAULT_MAX_THUMBNAIL_REQUESTS_RETRY_ON_ERROR:r,DEFAULT_THUMBNAIL_REQUEST_TIMEOUT:i,DEFAULT_THUMBNAIL_CONNECTION_TIMEOUT:a,INITIAL_BACKOFF_DELAY_BASE:o,MAX_BACKOFF_DELAY_BASE:s}=L.getCurrent();return{maxRetry:n!=null?n:r,baseDelay:o.REGULAR,maxDelay:s.REGULAR,requestTimeout:e===void 0?i:e,connectionTimeout:t===void 0?a:t}}var Qn=class{constructor(e,t){this._contentId=e,this._messageSender=t,this._queues={pushTextData:[],remove:[]}}pushTextData(e){return new Promise((t,r)=>{this._queues.pushTextData.push({resolve:t,reject:r}),this._messageSender({type:"push-text-data",contentId:this._contentId,value:e})})}remove(e,t){return new Promise((r,i)=>{this._queues.remove.push({resolve:r,reject:i}),this._messageSender({type:"remove-text-data",contentId:this._contentId,value:{start:e,end:t}})})}reset(){this._messageSender({type:"reset-text-displayer",contentId:this._contentId,value:null}),this._resetCurrentQueue("WorkerTextDisplayerInterface reset")}stop(e){this._messageSender({type:"stop-text-displayer",contentId:this._contentId,value:null}),this._resetCurrentQueue(e)}_resetCurrentQueue(e){let t=new ue("WorkerTextDisplayerInterface queue",e!=null?e:"reset");this._queues.pushTextData.forEach(r=>{r.reject(t)}),this._queues.pushTextData.length=0,this._queues.remove.forEach(r=>{r.reject(t)}),this._queues.remove.length=0}onPushedTrackSuccess(e){let t=this._queues.pushTextData.shift();if(t===void 0){c.error("text","pushTextData success for inexistant operation");return}t.resolve(e)}onPushedTrackError(e){let t=this._queues.pushTextData.shift();if(t===void 0){c.error("text","pushTextData error for inexistant operation");return}t.reject(e)}onRemoveSuccess(e){let t=this._queues.remove.shift();if(t===void 0){c.error("text","remove success for inexistant operation");return}t.resolve(e)}onRemoveError(e){let t=this._queues.remove.shift();if(t===void 0){c.error("text","remove error for inexistant operation");return}t.reject(e)}};var ks=6,oa=4e3,zr=6e3,vl=6e4,qt=class{constructor(e){this._segmentSinksStore=e,this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=null,this._lastFlushAttempt=null,this._lastSegmentInfo={audio:[],video:[]}}onNewObservation(e){var p,S;let t=F();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:a}=L.getCurrent(),{readyState:o,rebuffering:s,freezing:d,fullyLoaded:u}=e,f=e.position.getPolled(),l=Ms(e.bufferGap);if(!(d!==null||o===1&&(l>=ks||u)))return this._decipherabilityFreezeStartingTimestamp=null,null;let g=(S=(p=d==null?void 0:d.timestamp)!=null?p:s==null?void 0:s.timestamp)!=null?S:null;if(c.info("Freeze","Freeze detected",{freezeStart:g,timeFrozen:t-(g!=null?g:t)}),this._lastFlushAttempt!==null&&t-this._lastFlushAttempt.timestamp<a.MAXIMUM&&t-this._lastFlushAttempt.timestamp>=a.MINIMUM&&Math.abs(f-this._lastFlushAttempt.position)<a.POSITION_DELTA){let T=this._getStrategyIfFlushingFails(f);return this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+zr,T}let b=this._checkForDecipherabilityRelatedFreeze(e,t);return b!==null?b:g!==null&&t-g>r?(this._lastFlushAttempt={timestamp:t,position:f+i},c.debug("Freeze","Trying to flush to un-freeze"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+zr,{type:"flush",value:{relativeSeek:i}}):null}_checkForDecipherabilityRelatedFreeze(e,t){let{readyState:r,rebuffering:i,freezing:a,fullyLoaded:o}=e,s=Ms(e.bufferGap),d=i!==null&&t-i.timestamp>oa,{hasUndecipherableData:u,hasEncryptedData:f}=Cl(this._segmentSinksStore);if(u===!0)return c.warn("Freeze","we have undecipherable segments left in the buffer, reloading"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+zr,{type:"reload",value:null};let l=a!==null&&t-a.timestamp>oa;return(d||l)&&(s>=ks||o)&&r<=1?this._decipherabilityFreezeStartingTimestamp===null&&(c.debug("Freeze","Start of a potential decipherability freeze detected"),this._decipherabilityFreezeStartingTimestamp=t):this._decipherabilityFreezeStartingTimestamp=null,this._decipherabilityFreezeStartingTimestamp!==null&&F()-this._decipherabilityFreezeStartingTimestamp>oa&&f&&u===!1?(c.warn("Freeze","we are frozen despite only having decipherable segments left in the buffer, reloading"),this._decipherabilityFreezeStartingTimestamp=null,this._ignoreFreezeUntil=t+zr,{type:"reload",value:null}):null}_getStrategyIfFlushingFails(e){c.warn("Freeze","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 a=i[i.length-1];if(a.segment===null)continue;let o=a.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!==o.infos.representation.uniqueId&&a.timestamp-u.timestamp<5e3){s=u;break}else u.segment.start===o.start&&e-u.position<3e3&&(a=u)}if(s===void 0||s.segment===null)c.debug("Freeze","Freeze when beginning to play a content, try avoiding this quality"),t.push({adaptation:o.infos.adaptation,period:o.infos.period,representation:o.infos.representation});else{if(o.infos.period.id!==s.segment.infos.period.id)return c.debug("Freeze","Freeze when switching Period, reloading"),{type:"reload",value:null};o.infos.representation.uniqueId!==s.segment.infos.representation.uniqueId&&(c.warn("Freeze","Freeze when switching Representation, avoiding",{bitrate:o.infos.representation.bitrate}),t.push({adaptation:o.infos.adaptation,period:o.infos.period,representation:o.infos.representation}))}}return t.length>0?{type:"avoid-representations",value:t}:(c.debug("Freeze","Reloading because flush doesn't work"),{type:"reload",value:null})}_addPositionToHistory(e,t){var i,a;let r=e.position.getPolled();for(let o of["audio","video"]){let s=this._segmentSinksStore.getStatus(o);if(s.type==="initialized")for(let f of s.value.getLastKnownInventory())((i=f.bufferedStart)!=null?i:f.start)<=r&&((a=f.bufferedEnd)!=null?a:f.end)>r&&this._lastSegmentInfo[o].push({segment:f,position:r,timestamp:t});else this._lastSegmentInfo[o].push({segment:null,position:r,timestamp:t});if(this._lastSegmentInfo[o].length>100){let f=this._lastSegmentInfo[o].length-100;this._lastSegmentInfo[o].splice(0,f)}let d=t-vl,u;for(u=0;u<this._lastSegmentInfo[o].length&&!(this._lastSegmentInfo[o][u].timestamp>d);u++);u>0&&this._lastSegmentInfo[o].splice(0,u)}}};function Cl(n){let e=!0,t=!0;for(let r of["audio","video"]){let i=n.getStatus(r);if(i.type==="initialized")for(let a of i.value.getLastKnownInventory()){let{representation:o}=a.infos;if(o.decipherable===!1)return{hasUndecipherableData:!0,hasEncryptedData:!0};o.contentProtections!==void 0&&(t=!1,o.decipherable!==!0&&(e=!1))}}return{hasEncryptedData:!t,hasUndecipherableData:e?!1:void 0}}function Ms(n){return n!==void 0&&isFinite(n)?n:0}var $n=class{constructor(){this._refs=new Map}reset(){var e,t,r,i,a,o,s,d,u,f,l,m;for(let g of this._refs.keys())(t=(e=this._refs.get(g))==null?void 0:e.audio)==null||t.trackReference.finish(),(i=(r=this._refs.get(g))==null?void 0:r.audio)==null||i.representations.finish(),(o=(a=this._refs.get(g))==null?void 0:a.video)==null||o.trackReference.finish(),(d=(s=this._refs.get(g))==null?void 0:s.video)==null||d.representations.finish(),(f=(u=this._refs.get(g))==null?void 0:u.text)==null||f.trackReference.finish(),(m=(l=this._refs.get(g))==null?void 0:l.text)==null||m.representations.finish();this._refs=new Map}addTrackSetter(e,t,r){var s,d;let i=this._refs.get(e);i===void 0&&(i={},this._refs.set(e,i)),i[t]!==void 0&&(c.warn("Track","Track for periodId already declared",{periodId:e,bufferType:t}),(s=i[t])==null||s.trackReference.finish(),(d=i[t])==null||d.representations.finish());let a=r.getValue(),o;v(a)?o=new $({representationIds:[],switchingMode:"lazy"}):(o=new $(a.representations.getValue()),r.setValue(H({},a,{representations:o}))),i[t]={trackReference:r,representations:o}}setTrack(e,t,r){var a;let i=(a=this._refs.get(e))==null?void 0:a[t];return i===void 0?(c.debug("Track","Setting track for inexistent periodId",{periodId:e,bufferType:t}),!1):(v(r)?(i.representations=new $({representationIds:[],switchingMode:"lazy"}),i.trackReference.setValue(r)):(i.representations=new $(r.initialRepresentations),i.trackReference.setValue({adaptationId:r.adaptationId,switchingMode:r.switchingMode,representations:i.representations,relativeResumingPosition:r.relativeResumingPosition})),!0)}updateRepresentations(e,t,r,i){var s;let a=(s=this._refs.get(e))==null?void 0:s[r];if(a===void 0)return c.debug("Track","Setting track for inexistent periodId",{periodId:e,bufferType:r}),!1;let o=a.trackReference.getValue();return v(o)||o.adaptationId!==t?(c.debug("Track","Desynchronized Adaptation id",{oldId:o==null?void 0:o.adaptationId,newId:t}),!1):(a.representations.setValue(i),!0)}removeTrackSetter(e,t){let r=this._refs.get(e),i=r==null?void 0:r[t];return r===void 0||i===void 0?(c.debug("Track","Removing track setter for inexistent periodId",{periodId:e,bufferType:t}),!1):(i.trackReference.finish(),i.representations.finish(),delete r[t],Object.keys(r).length===0&&this._refs.delete(e),!0)}};function Oe(n){return ge(n,{defaultCode:"NONE",defaultReason:"An unknown error stopped content playback."}).serialize()}function Os(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 ws(n){var t,r;if(v(ln.MediaSource_))return;let e=new Map;for(let i of n.periods){let a=[...(t=i.adaptations.video)!=null?t:[],...(r=i.adaptations.audio)!=null?r:[]];for(let o of a)for(let s of o.representations){let d=s.getMimeTypeString();if(e.has(d))s.isCodecSupportedInWebWorker=e.get(d);else{let u=ln.MediaSource_.isTypeSupported(d);s.isCodecSupportedInWebWorker=u,e.set(d,u)}}}}function Ds(n,e){var a,o,s,d,u,f,l;let t,r,i;return typeof((a=n.representationFilter)==null?void 0:a.fn)=="function"?i=n.representationFilter.fn:typeof((o=n.representationFilter)==null?void 0:o.eval)=="string"?i=Ro(n.representationFilter.eval):typeof((s=n.representationFilter)==null?void 0:s.workerId)=="string"&&(i=e.representationFilters.get(n.representationFilter.workerId)),typeof((d=n.manifestLoader)==null?void 0:d.fn)=="function"?t=n.manifestLoader.fn:typeof((u=n.manifestLoader)==null?void 0:u.workerId)=="string"&&(t=e.manifestLoaders.get(n.manifestLoader.workerId)),typeof((f=n.segmentLoader)==null?void 0:f.fn)=="function"?r=n.segmentLoader.fn:typeof((l=n.segmentLoader)==null?void 0:l.workerId)=="string"&&(r=e.segmentLoaders.get(n.segmentLoader.workerId)),{manifestLoader:t,segmentLoader:r,representationFilter:i}}var Bs=Me(),Gt=class{constructor({hasVideo:e}){this._currentContent=null,this._currentMediaSourceCanceller=new z("ContentPreparer MediaSource"),this._hasVideo=e;let t=new z("ContentPreparer");this._contentCanceller=t}initializeNewContent(e,t,r,i){return new Promise((a,o)=>{var D,U;this.disposeCurrentContent("new init");let s=this._contentCanceller,d=new z("ContentPreparer MediaSource");this._currentMediaSourceCanceller=d,d.linkToSignal(s.signal);let{contentId:u,url:f,hasText:l,transportOptions:m,useMseInWorker:g,enableRepresentationAvoidance:h,transport:b}=t,p=null,S=ke.transports[b];if(typeof S!="function"){o(new Error(`transport "${b}" not supported. Did you add the corresponding feature?`));return}let T=S(J(J({},m),Ds(m,i))),R=t.cmcd===void 0?null:new vs(t.cmcd),E=new ea(f===void 0?void 0:[f],T,J({cmcdDataBuilder:R},t.manifestRetryOptions)),C=Rs({initialBitrates:{audio:(D=t.initialAudioBitrate)!=null?D:0,video:(U=t.initialVideoBitrate)!=null?U:0},lowLatencyMode:m.lowLatencyMode,throttlers:r}),P=d.signal.register(G=>{o(G)}),x=new Vn(s.signal),A=new ia(T,x,R,t.segmentRetryOptions),k=aa(T.thumbnails,x),N=new $n,[w,W,B]=Ns(e,u,{useMseInWorker:g,hasVideo:this._hasVideo,hasText:l},d.signal),_=new qt(W);this._currentContent={cmcdDataBuilder:R,contentId:u,enableRepresentationAvoidance:h,freezeResolver:_,mediaSource:w,manifest:null,manifestFetcher:E,representationEstimator:C,segmentSinksStore:W,segmentQueueCreator:A,fetchThumbnailData:k,coreTextSender:B,trackChoiceSetter:N,useMseInWorker:g},w.addEventListener("mediaSourceOpen",function(){M()},d.signal),s.signal.register(G=>{E.dispose(G.reason)}),E.addEventListener("warning",G=>{e({type:"warning",contentId:u,value:Oe(G)})},s.signal),E.addEventListener("manifestReady",G=>{if(p!==null){c.warn("Core","Multiple `manifestReady` events, ignoring");return}p=G,this._currentContent!==null&&(this._currentContent.manifest=p),M()},d.signal),E.addEventListener("error",G=>{o(G)},s.signal),E.start();function M(){p===null||w.readyState==="closed"||d.isUsed()||(ws(p),p.addEventListener("manifestUpdate",G=>{p!==null&&e({type:"manifest-update",contentId:u,value:{manifest:p,updates:G}})},s.signal),P(),a(p))}})}getCurrentContent(){return this._currentContent}scheduleManifestRefresh(e){var t;(t=this._currentContent)==null||t.manifestFetcher.scheduleManualRefresh(e)}reloadMediaSource(e){var a;if(this._currentMediaSourceCanceller.cancel("ContentPreparer MediaSource reload"),this._currentContent===null)return Promise.reject(new Error("CP: No content anymore"));this._currentContent.trackChoiceSetter.reset(),(a=this._currentContent.coreTextSender)==null||a.stop("ContentPreparer MediaSource reload"),this._currentMediaSourceCanceller=new z("ContentPreparer MediaSource"),this._currentMediaSourceCanceller.linkToSignal(this._contentCanceller.signal);let[t,r,i]=Ns(e,this._currentContent.contentId,{useMseInWorker:this._currentContent.useMseInWorker,hasVideo:this._hasVideo,hasText:this._currentContent.coreTextSender!==null},this._currentMediaSourceCanceller.signal);return this._currentContent.mediaSource=t,this._currentContent.segmentSinksStore=r,this._currentContent.freezeResolver=new qt(r),this._currentContent.coreTextSender=i,new Promise((o,s)=>{t.addEventListener("mediaSourceOpen",function(){o()},this._currentMediaSourceCanceller.signal),t.addEventListener("mediaSourceClose",function(){s(new Error("MediaSource ReadyState changed to close during init."))},this._currentMediaSourceCanceller.signal),this._currentMediaSourceCanceller.signal.register(d=>{s(d)})})}disposeCurrentContent(e){this._contentCanceller.cancel(e),this._contentCanceller=new z("ContentPreparer")}};function Ns(n,e,t,r){let i;if(t.useMseInWorker){let d=new xn(Bs());i=d;let u,f=d.handle;if(f.type==="handle")u={type:"handle",value:f.value};else{let l=URL.createObjectURL(f.value);u={type:"url",value:l},r.register(()=>{URL.revokeObjectURL(l)})}n({type:"attach-media-source",contentId:e,value:u,mediaSourceId:i.id},[f.value])}else i=new kn(Bs(),e,n);let a=t.hasText?new Qn(e,n):null,{hasVideo:o}=t,s=new St(i,o,a);return r.register(d=>{s.disposeAll(d.reason),a==null||a.stop(d.reason),i.dispose(d.reason)}),[i,s,a]}var Us=.001,Xn=class extends ce{constructor(e,t,r){super(),this._canceller=new z("Boundaries Observation"),this._manifest=e,this._activeStreams=new Map,this._allBufferTypes=r,this._lastCurrentPeriodId=null;let i=new sa(e);fe(this._allBufferTypes,"video")||i.updateLastVideoAdaptation(null),fe(this._allBufferTypes,"audio")||i.updateLastAudioAdaptation(null),this._maximumPositionCalculator=i;let a=this._canceller.signal;at(()=>{t.listen(({position:o})=>{let s=o.getWanted(),d=e.getMinimumSafePosition(),u=i.getMaximumAvailablePosition();if(s<d-Us){let f=new ee("MEDIA_TIME_BEFORE_MANIFEST","The current position is behind the earliest time announced in the Manifest.",{timeInfo:{position:s,minPosition:d,maxPosition:u}});this.trigger("warning",f)}else if(s>u+Us){let f=new ee("MEDIA_TIME_AFTER_MANIFEST","The current position is after the latest time announced in the Manifest.",{timeInfo:{position:s,minPosition:d,maxPosition:u}});this.trigger("warning",f)}},{includeLastObservation:!1,clearSignal:a})}),e.addEventListener("manifestUpdate",()=>{this.trigger("endingPositionChange",this._getManifestEndTime()),!a.isCancelled()&&this._checkEndOfStream()},a)}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 a=this._maximumPositionCalculator.getEndingPosition(),o=a!==void 0?{isEnd:!0,endingPosition:a}:{isEnd:!1,endingPosition:this._maximumPositionCalculator.getMaximumAvailablePosition()};this.trigger("endingPositionChange",o)}}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(e){this.removeEventListener(),this._canceller.cancel(e!=null?e:"ContentTimeBoundariesObserver dispose")}_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 a=this._activeStreams.get(i);if(a===void 0)return;if(!a.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 kt((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)}},sa=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=Wr(this._lastVideoAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}}else if(this._lastVideoAdaptation===null){let e=Wr(this._lastAudioAdaptation);return typeof e!="number"?this._manifest.getMaximumSafePosition():e}else{let e=Wr(this._lastAudioAdaptation),t=Wr(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=Vr(this._lastVideoAdaptation))!=null?e:void 0;if(this._lastVideoAdaptation===null)return(t=Vr(this._lastAudioAdaptation))!=null?t:void 0;{let r=Vr(this._lastAudioAdaptation),i=Vr(this._lastVideoAdaptation);return typeof r!="number"||typeof i!="number"?void 0:Math.min(r,i)}}}};function Wr(n){let{representations:e}=n,t=null,r;for(let i of e)if(i.index!==r){r=i.index;let a=i.index.getLastAvailablePosition();if(a===void 0)return;a!==null&&(t=v(t)?a:Math.min(t,a))}return t}function Vr(n){let{representations:e}=n,t=null,r;for(let i of e)if(i.index!==r){r=i.index;let a=i.index.getEnd();if(a===void 0)return;a!==null&&(t=v(t)?a:Math.min(t,a))}return t}function da(n,e,t,r,i,a){a.register(d=>{e.interruptDurationSetting(d.reason)});let o=new Xn(n,t,r.getBufferTypes());a.register(d=>{o.dispose(d.reason)}),o.addEventListener("warning",d=>i.onWarning(d)),o.addEventListener("periodChange",d=>i.onPeriodChanged(d)),o.addEventListener("endingPositionChange",d=>{e.setDuration(d.endingPosition,d.isEnd)}),o.addEventListener("endOfStream",()=>{c.debug("mse","Start applying end-of-stream order."),e.maintainEndOfStream()}),o.addEventListener("resumeStream",()=>{e.stopEndOfStream()});let s=o.getCurrentEndingTime();return e.setDuration(s.endingPosition,s.isEnd),o}function ua(n,e){let t={audio:null,video:null,text:null};if(e!==null&&(t.text=e.getBufferedRanges()),n===null)return t;let r=j(n.sourceBuffers,s=>s.type==="audio"),i=j(n.sourceBuffers,s=>s.type==="video"),a=r==null?void 0:r.getBuffered();a!==void 0&&(t.audio=a);let o=i==null?void 0:i.getBuffered();return o!==void 0&&(t.video=o),t}async function la(n,e,t,r,i){let a=e.getPeriod(t);if(a===void 0)throw new Error("Wanted Period not found.");let o=j(a.thumbnailTracks,d=>d.id===r);if(o===void 0)throw new Error("Wanted Period has no thumbnail track.");let s=o.index.getSegments(i,1)[0];if(s===void 0)throw new Error("No thumbnail for the given timestamp");return n({segment:s,track:o,period:a},new z(void 0).signal)}function fa(n,e,t){let{DEFAULT_WANTED_BUFFER_AHEAD:r,DEFAULT_MAX_VIDEO_BUFFER_SIZE:i,DEFAULT_MAX_BUFFER_AHEAD:a,DEFAULT_MAX_BUFFER_BEHIND:o}=L.getCurrent(),s={wantedBufferAhead:new $(r),maxVideoBufferSize:new $(i),maxBufferAhead:new $(a),maxBufferBehind:new $(o),limitVideoResolution:new $({height:void 0,width:void 0,pixelRatio:1}),throttleVideoBitrate:new $(1/0)},d=!1,u=new Gt({hasVideo:!0}),f=null,l=null;n(m=>{var h,b;c.debug("Core","received message",{name:m.data.type});let g=m.data;switch(g.type){case"init":{if(Se(!d),d=!0,uo(g.value),Ls(g.value.logLevel,g.value.logFormat,g.value.sendBackLogs),!v(g.value.dashWasmUrl)){let p=ke.dashParsers.wasm;p===null?c.error("Core","Could not initialize DASH_WASM parser: DASH_WASM feature not added"):p.isCompatible()?p.initialize({wasmUrl:g.value.dashWasmUrl}).catch(S=>{let T=S instanceof Error?S.toString():"Unknown Error";c.error("Core","Could not initialize DASH_WASM parser",T)}):c.warn("Core","Could not initialize DASH_WASM parser: Browser not compatible")}g.value.hasVideo||(u.disposeCurrentContent("Received Init msg"),u=new Gt({hasVideo:g.value.hasVideo})),e({type:"init-success",value:null})}break;case"log-level-update":Ls(g.value.logLevel,g.value.logFormat,g.value.sendBackLogs);break;case"prepare":Al(e,u,g.value,s,t);break;case"start":{let p=u.getCurrentContent();if(g.contentId!==(p==null?void 0:p.contentId))return;f==null||f.stop(),l==null||l.finish();let S=new $(H(g.value.initialObservation,{position:new xt(...g.value.initialObservation.position)}));l=S,f=kl(e,g.value,u,S,s);break}case"observation":{let p=u.getCurrentContent();if(g.contentId!==(p==null?void 0:p.contentId))return;let S=g.value,{buffered:T}=S,R=ua(p.mediaSource,null);R.audio!==null&&(T.audio=R.audio),R.video!==null&&(T.video=R.video),l==null||l.setValue(H(S,{position:new xt(...g.value.position)}));break}case"ref-update":xl(g,s);break;case"stop":if(g.contentId!==((h=u.getCurrentContent())==null?void 0:h.contentId))return;u.disposeCurrentContent("StopContent message"),f==null||f.stop(),f=null,l==null||l.finish(),l=null;break;case"ms-reload":{let p=u.getCurrentContent();if(g.mediaSourceId!==(p==null?void 0:p.mediaSource.id))return;f==null||f.signalMediaSourceReload()}break;case"sb-success":{let p=u.getCurrentContent();if(g.mediaSourceId!==(p==null?void 0:p.mediaSource.id))return;let{sourceBuffers:S}=p.mediaSource,T=j(S,R=>R.type===g.sourceBufferType);if(T===void 0){c.info("Core","Success for an unknown SourceBuffer",{sourceBufferType:g.sourceBufferType});return}if(T.onOperationSuccess===void 0){c.warn("Core","A SourceBufferInterface with MSE performed a cross-thread operation",{sourceBufferType:g.sourceBufferType});return}T.onOperationSuccess(g.operationId,g.value.buffered);break}case"sb-error":{let p=u.getCurrentContent();if(g.mediaSourceId!==(p==null?void 0:p.mediaSource.id))return;let{sourceBuffers:S}=p.mediaSource,T=j(S,R=>R.type===g.sourceBufferType);if(T===void 0){c.info("Core","Error for an unknown SourceBuffer",{sourceBufferType:g.sourceBufferType});return}if(T.onOperationFailure===void 0){c.warn("Core","A SourceBufferInterface with MSE performed a cross-thread operation",{sourceBufferType:g.sourceBufferType});return}T.onOperationFailure(g.operationId,g.value);break}case"media-source-ready-state-change":{let p=u.getCurrentContent();if(g.mediaSourceId!==(p==null?void 0:p.mediaSource.id))return;if(p.mediaSource.onMediaSourceReadyStateChanged===void 0){c.warn("Core","A MediaSourceInterface with MSE performed a cross-thread operation");return}p.mediaSource.onMediaSourceReadyStateChanged(g.value);break}case"decipherability-update":{if(g.contentId!==((b=u.getCurrentContent())==null?void 0:b.contentId))return;let p=u.getCurrentContent();if(p===null||p.manifest===null)return;let S=g.value;p.manifest.updateRepresentationsDeciperability(T=>{for(let R of S)if(T.representation.uniqueId===R.representationUniqueId)return R.decipherable;return T.representation.decipherable});break}case"codec-support-update":{let p=u.getCurrentContent();if(p===null||p.manifest===null)return;let S=g.value;try{let T=p.manifest.updateCodecSupport(S);T!==null&&e({type:"warning",contentId:p.contentId,value:Oe(T)})}catch(T){e({type:"error",contentId:p.contentId,value:Oe(T)})}break}case"urls-update":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;p.manifestFetcher.updateContentUrls(g.value.urls,g.value.refreshNow);break}case"track-update":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;p.trackChoiceSetter.setTrack(g.value.periodId,g.value.bufferType,g.value.choice);break}case"rep-update":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;p.trackChoiceSetter.updateRepresentations(g.value.periodId,g.value.adaptationId,g.value.bufferType,g.value.choice);break}case"add-text-success":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;if(p.coreTextSender===null){c.error("Core","Added text track but text track aren't enabled");return}p.coreTextSender.onPushedTrackSuccess(g.value.ranges);break}case"push-text-error":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;if(p.coreTextSender===null){c.error("Core","Added text track but text track aren't enabled");return}p.coreTextSender.onPushedTrackError(new Error(g.value.message));break}case"remove-text-success":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;if(p.coreTextSender===null){c.error("Core","Removed text track but text track aren't enabled");return}p.coreTextSender.onRemoveSuccess(g.value.ranges);break}case"remove-text-error":{let p=u.getCurrentContent();if(p===null||p.contentId!==g.contentId)return;if(p.coreTextSender===null){c.error("Core","Removed text track but text track aren't enabled");return}p.coreTextSender.onRemoveError(new Error(g.value.message));break}case"pull-segment-sink-store-infos":{Ml(e,u,g.value.requestId);break}case"thumbnail-request":{wl(e,u,g);break}case"config-update":{L.update(g.value);break}case"app-defined":break;default:Ne(g)}})}function Al(n,e,t,r,i){e.initializeNewContent(n,t,{limitResolution:{video:r.limitVideoResolution},throttleBitrate:{video:r.throttleVideoBitrate}},i).then(a=>{n({type:"manifest-ready",contentId:t.contentId,value:{manifest:a}})},a=>{n({type:"error",contentId:t.contentId,value:Oe(a)})})}function xl(n,e){switch(n.value.name){case"wantedBufferAhead":e.wantedBufferAhead.setValueIfChanged(n.value.newVal);break;case"maxVideoBufferSize":e.maxVideoBufferSize.setValueIfChanged(n.value.newVal);break;case"maxBufferBehind":e.maxBufferBehind.setValueIfChanged(n.value.newVal);break;case"maxBufferAhead":e.maxBufferAhead.setValueIfChanged(n.value.newVal);break;case"limitVideoResolution":e.limitVideoResolution.setValueIfChanged(n.value.newVal);break;case"throttleVideoBitrate":e.throttleVideoBitrate.setValueIfChanged(n.value.newVal);break;default:Ne(n.value)}}function kl(n,e,t,r,i){c.debug("Core","Loading pepared content.");let a=new z("Start Content Worker"),o=null;return s(e.initialTime),{signalMediaSourceReload:()=>u(),stop:()=>{a.cancel("ContentHandle stop")}};function s(f){var B;o==null||o.cancel("Reloading content worker"),o=new z("(Re)Loading Content Worker"),o.linkToSignal(a.signal);let l=new Map,m=t.getCurrentContent();if(m===null||m.manifest===null){let _=new _e("NONE","Loading content when none is prepared");throw n({type:"error",contentId:void 0,value:Oe(_)}),_}let{contentId:g,cmcdDataBuilder:h,enableRepresentationAvoidance:b,manifest:p,mediaSource:S,representationEstimator:T,segmentSinksStore:R,segmentQueueCreator:E}=m,{drmSystemId:C,enableFastSwitching:P,onCodecSwitch:x}=e;r.onUpdate(_=>{Os(_,R);let M=m.freezeResolver.onNewObservation(_);M!==null&&Ol(n,M,{contentId:g,manifest:p,handleMediaSourceReload:d,enableRepresentationAvoidance:b})},{clearSignal:o.signal});let A=(B=p.getPeriodForTime(f))!=null?B:p.getNextPeriod(f);if(A===void 0){let _=new ee("MEDIA_STARTING_TIME_NOT_FOUND","Wanted starting time not found in the Manifest.");throw n({type:"error",contentId:g,value:Oe(_)}),_}let k=new In(r,g,n,o.signal);h==null||h.startMonitoringPlayback(k),o.signal.register(()=>{h==null||h.stopMonitoringPlayback()});let N=da(p,S,k,R,{onWarning:_=>n({type:"warning",contentId:g,value:Oe(_)}),onPeriodChanged:_=>{n({type:"active-period-changed",contentId:g,value:{periodId:_.id}})}},o.signal);ps({initialPeriod:A,manifest:p},k,T,R,E,{wantedBufferAhead:i.wantedBufferAhead,maxVideoBufferSize:i.maxVideoBufferSize,maxBufferAhead:i.maxBufferAhead,maxBufferBehind:i.maxBufferBehind,drmSystemId:C,enableFastSwitching:P,onCodecSwitch:x},w(),o.signal);function w(){return{needsBufferFlush(_){n({type:"needs-buffer-flush",contentId:g,value:_})},streamStatusUpdate(_){W(_),p.isLastPeriodKnown&&_.period.id===p.periods[p.periods.length-1].id&&(_.hasFinishedLoading||_.isEmptyStream?N.onLastSegmentFinishedLoading(_.bufferType):N.onLastSegmentLoadingResume(_.bufferType))},needsManifestRefresh(){t.scheduleManifestRefresh({enablePartialRefresh:!0,canUseUnsafeMode:!0})},manifestMightBeOufOfSync(){let{OUT_OF_SYNC_MANIFEST_REFRESH_DELAY:_}=L.getCurrent();t.scheduleManifestRefresh({enablePartialRefresh:!1,canUseUnsafeMode:!1,delay:_})},lockedStream(_){n({type:"locked-stream",contentId:g,value:{periodId:_.period.id,bufferType:_.bufferType}})},adaptationChange(_){var M,D;n({type:"adaptation-changed",contentId:g,value:{adaptationId:(D=(M=_.adaptation)==null?void 0:M.id)!=null?D:null,periodId:_.period.id,type:_.type}}),N.onAdaptationChange(_.type,_.period,_.adaptation)},representationChange(_){var M,D;N.onRepresentationChange(_.type,_.period),!(o===null||o.signal.isCancelled())&&n({type:"representation-changed",contentId:g,value:{adaptationId:_.adaptation.id,representationId:(D=(M=_.representation)==null?void 0:M.id)!=null?D:null,periodId:_.period.id,type:_.type}})},inbandEvent(_){n({type:"inband-event",contentId:g,value:_})},warning(_){n({type:"warning",contentId:g,value:Oe(_)})},periodStreamReady(_){m!==null&&(m.trackChoiceSetter.addTrackSetter(_.period.id,_.type,_.adaptationRef),n({type:"period-stream-ready",contentId:g,value:{periodId:_.period.id,bufferType:_.type}}))},periodStreamCleared(_){if(m===null)return;let M=l.get(_.period);M!==void 0&&(M.delete(_.type),M.size===0&&l.delete(_.period)),N.onPeriodCleared(_.type,_.period),m.trackChoiceSetter.removeTrackSetter(_.period.id,_.type),n({type:"period-stream-cleared",contentId:g,value:{periodId:_.period.id,bufferType:_.type}})},bitrateEstimateChange(_){var M;m!==null&&((M=m.cmcdDataBuilder)==null||M.updateThroughput(_.type,_.bitrate)),n({type:"bitrate-estimate-change",contentId:g,value:{bitrate:_.bitrate,bufferType:_.type}})},needsMediaSourceReload(_){d(_)},needsDecipherabilityFlush(){n({type:"needs-decipherability-flush",contentId:g,value:null})},encryptionDataEncountered(_){for(let M of _){let D=M.content,U=J({},D);U.manifest instanceof It&&(U.manifest=U.manifest.getMetadataSnapshot()),U.period instanceof ht&&(U.period=U.period.getMetadataSnapshot()),U.adaptation instanceof ct&&(U.adaptation=U.adaptation.getMetadataSnapshot()),U.representation instanceof un&&(U.representation=U.representation.getMetadataSnapshot()),n({type:"encryption-data-encountered",contentId:g,value:{keyIds:M.keyIds,values:M.values,content:U,type:M.type}})}},error(_){n({type:"error",contentId:g,value:Oe(_)})}}}function W(_){let{imminentDiscontinuity:M}=_,D=l.get(_.period),U=D==null?void 0:D.get(_.bufferType);if(U!==void 0){if(U.discontinuity===null){if(M===null)return}else if(M!==null&&U.discontinuity.start===M.start&&U.discontinuity.end===M.end)return}D===void 0&&(D=new Map,l.set(_.period,D));let G={periodId:_.period.id,bufferType:_.bufferType,discontinuity:_.imminentDiscontinuity,position:_.position};D.set(_.bufferType,G),n({type:"discontinuity-update",contentId:g,value:G})}}function d(f){var m;o!==null&&(o.cancel("WorkerMain MediaSource reload"),o=null);let l=(m=t.getCurrentContent())==null?void 0:m.mediaSource.id;if(l===void 0){c.warn("Core","Cannot reload MediaSource: no MediaSource currently.");return}c.debug("Core","Reloading MediaSource",{timeOffset:f.timeOffset,minimumPosition:f.minimumPosition,maximumPosition:f.maximumPosition}),n({type:"reloading-media-source",mediaSourceId:l,value:f},[]),u()}function u(){var g;let l=r.getValue().position.getWanted();o!==null&&(o.cancel("MediaSource reload"),o=null);let m=(g=t.getCurrentContent())==null?void 0:g.contentId;t.reloadMediaSource(n).then(()=>{c.info("Core","MediaSource Reloaded, loading content again",{newInitialTime:l}),s(l)},h=>{if(z.isCancellationError(h)){c.info("Core","A reloading operation was cancelled");return}n({type:"error",contentId:m,value:Oe(h)})})}}function Ls(n,e,t){t?c.setLevel(n,"standard",(r,i,a)=>{let o=a.map(s=>s instanceof Error?Oe(s):s);postMessage({type:"log",value:{namespace:i,logLevel:r,logs:o}})}):c.setLevel(n,e)}function Ml(n,e,t){let r=e.getCurrentContent();if(r===null)return;let i=r.segmentSinksStore.getSegmentSinksMetrics();n({type:"segment-sink-store-update",contentId:r.contentId,value:{segmentSinkMetrics:i,requestId:t}})}function Ol(n,e,{contentId:t,manifest:r,handleMediaSourceReload:i,enableRepresentationAvoidance:a}){switch(e.type){case"reload":{c.info("Core","Planning reload due to freeze"),i({timeOffset:0,minimumPosition:0,maximumPosition:1/0});break}case"flush":{c.info("Core","Flushing buffer due to freeze"),n({type:"needs-buffer-flush",contentId:t,value:{relativeResumingPosition:e.value.relativeSeek,relativePosHasBeenDefaulted:!1}});break}case"avoid-representations":{c.info("Core","Planning Representation avoidance due to freeze");let o=e.value;a&&r.addRepresentationsToAvoid(o),i({timeOffset:0,minimumPosition:0,maximumPosition:1/0});break}default:Ne(e)}}function wl(n,e,t){let r=e.getCurrentContent(),i=a=>{n({type:"thumbnail-response",contentId:t.contentId,value:{status:"error",requestId:t.value.requestId,error:Oe(a)}})};if(r===null||r.manifest===null||r.contentId!==t.contentId)return i(new Error("Content changed"));la(r.fetchThumbnailData,r.manifest,t.value.periodId,t.value.thumbnailTrackId,t.value.time).then(a=>{let o=a.data.slice(0);n({type:"thumbnail-response",contentId:t.contentId,value:{status:"success",requestId:t.value.requestId,data:de(J({},a),{data:o})}},[o])},a=>i(a))}var Fs=fa;var Dl="<",Bl=60,zs=">",qr=62,ma=45,Ws=47,Nl=33,Vs=39,qs=34,ca=91,Ul=93,Ll=`\r
|
|
4
4
|
>/= `;function pa(n,e={}){var m,g;let t=(m=e.pos)!=null?m:0,r=e.keepComments===!0,i=e.keepWhitespace===!0,a;if(e.attrValue!==void 0)for(e.attrName=(g=e.attrName)!=null?g:"id",a=[];(t=l())!==-1;)t=n.lastIndexOf("<",t),t!==-1&&a.push(u()),n=n.substring(t),t=0;else a=o("");return e.filter!==void 0&&(a=Gs(a,e.filter)),a;function o(h){let b=[];for(;n[t]!==void 0;)if(n.charCodeAt(t)===Bl){if(n.charCodeAt(t+1)===Ws){let S=t+2;if(t=n.indexOf(zs,t),n.substring(S,t).indexOf(h)===-1){let R=n.substring(0,t).split(`
|
|
5
5
|
`);throw new Error(`Unexpected close tag
|
|
6
6
|
Line: `+(R.length-1)+`
|