@inappstory/js-sdk 3.5.4 → 3.6.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.
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.IasVideoOnDemandPlugin=t():e.IasVideoOnDemandPlugin=t()}(self,(()=>(()=>{"use strict";var e={d:(t,i)=>{for(var n in i)e.o(i,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:i[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};let i;e.d(t,{default:()=>Dt}),i=function(){};let n=class e{static alwaysError(...e){}static alwaysWarn(...e){}static warnOnce(t,...i){e.oneTimeWarningIssued_.has(t)||(e.oneTimeWarningIssued_.add(t),e.alwaysWarn(...i))}static error(...e){}static warning(...e){}static info(...e){}static debug(...e){}static v1(...e){}static v2(...e){}};n.Level={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4,V1:5,V2:6},n.MAX_LOG_LEVEL=3,n.oneTimeWarningIssued_=new Set,window.console&&(n.logMap_={[n.Level.ERROR]:(...e)=>console.error(...e),[n.Level.WARNING]:(...e)=>console.warn(...e),[n.Level.INFO]:(...e)=>console.info(...e),[n.Level.DEBUG]:(...e)=>console.log(...e),[n.Level.V1]:(...e)=>console.debug(...e),[n.Level.V2]:(...e)=>console.debug(...e)},n.alwaysWarn=(...e)=>console.warn(...e),n.alwaysError=(...e)=>console.error(...e),n.setLevel=e=>{const t=t=>t<=e?(console.assert(n.logMap_[t],"Unexpected log level"),n.logMap_[t]):()=>{};n.currentLevel=e,n.error=t(n.Level.ERROR),n.warning=t(n.Level.WARNING),n.info=t(n.Level.INFO),n.debug=t(n.Level.DEBUG),n.v1=t(n.Level.V1),n.v2=t(n.Level.V2)},n.setLevel(n.MAX_LOG_LEVEL));class s{constructor(){this.map_={}}push(e,t){this.map_.hasOwnProperty(e)?this.map_[e].push(t):this.map_[e]=[t]}get(e){const t=this.map_[e];return t?t.slice():null}getAll(){const e=[];for(const t in this.map_)e.push(...this.map_[t]);return e}remove(e,t){e in this.map_&&(this.map_[e]=this.map_[e].filter((e=>e!=t)),0==this.map_[e].length&&delete this.map_[e])}clear(){this.map_={}}forEach(e){for(const t in this.map_)e(t,this.map_[t])}size(){return Object.keys(this.map_).length}keys(){return Object.keys(this.map_)}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class a{static fromRealEvent(e){const t=new a(e.type);for(const i in e)Object.defineProperty(t,i,{value:e[i],writable:!0,enumerable:!0});return t}static recastDictAsObject_(e){return console.assert(!(e instanceof Map),"dict should not be a map"),e}constructor(e,t){if(t)if(t instanceof Map)for(const e of t.keys())Object.defineProperty(this,e,{value:t.get(e),writable:!0,enumerable:!0});else{const e=a.recastDictAsObject_(t);for(const t in e)Object.defineProperty(this,t,{value:e[t],writable:!0,enumerable:!0})}this.bubbles=!1,this.cancelable=!1,this.defaultPrevented=!1,this.timeStamp=window.performance&&window.performance.now?window.performance.now():Date.now(),this.type=e,this.isTrusted=!1,this.currentTarget=null,this.target=null,this.stopped=!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopImmediatePropagation(){this.stopped=!0}stopPropagation(){}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}a.EventName={AbrStatusChanged:"abrstatuschanged",Adaptation:"adaptation",Buffering:"buffering",Complete:"complete",DownloadFailed:"downloadfailed",DownloadHeadersReceived:"downloadheadersreceived",DrmSessionUpdate:"drmsessionupdate",Emsg:"emsg",Prft:"prft",Error:"error",ExpirationUpdated:"expirationupdated",FirstQuartile:"firstquartile",GapJumped:"gapjumped",KeyStatusChanged:"keystatuschanged",Loaded:"loaded",Loading:"loading",ManifestParsed:"manifestparsed",ManifestUpdated:"manifestupdated",MediaQualityChanged:"mediaqualitychanged",Metadata:"metadata",Midpoint:"midpoint",OnStateChange:"onstatechange",RateChange:"ratechange",SegmentAppended:"segmentappended",SessionDataEvent:"sessiondata",StallDetected:"stalldetected",Started:"started",StateChanged:"statechanged",Streaming:"streaming",TextChanged:"textchanged",TextTrackVisibility:"texttrackvisibility",ThirdQuartile:"thirdquartile",TimelineRegionAdded:"timelineregionadded",TimelineRegionEnter:"timelineregionenter",TimelineRegionExit:"timelineregionexit",TracksChanged:"trackschanged",Unloading:"unloading",VariantChanged:"variantchanged"};class r{constructor(){this.listeners_=new s,this.dispatchTarget=this}addEventListener(e,t,i){this.listeners_&&this.listeners_.push(e,t)}listenToAllEvents(e){this.addEventListener(r.ALL_EVENTS_,e)}removeEventListener(e,t,i){this.listeners_&&this.listeners_.remove(e,t)}dispatchEvent(e){if(console.assert(e instanceof a,"FakeEventTarget can only dispatch FakeEvents!"),!this.listeners_)return!0;let t=this.listeners_.get(e.type)||[];const i=this.listeners_.get(r.ALL_EVENTS_);i&&(t=t.concat(i));for(const i of t){e.target=this.dispatchTarget,e.currentTarget=this.dispatchTarget;try{i.handleEvent?i.handleEvent(e):i.call(this,e)}catch(e){n.error("Uncaught exception in event handler",e,e?e.message:null,e?e.stack:null)}if(e.stopped)break}return e.defaultPrevented}release(){this.listeners_=null}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}r.ALL_EVENTS_="All";class o{constructor(e){this.onTick_=e,this.cancelPending_=null}tickAfter(e){this.stop();let t=!0,i=null;return this.cancelPending_=()=>{window.clearTimeout(i),t=!1},i=window.setTimeout((()=>{t&&this.onTick_()}),1e3*e),this}stop(){this.cancelPending_&&(this.cancelPending_(),this.cancelPending_=null)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class l{constructor(e){this.onTick_=e,this.ticker_=null}tickNow(){return this.stop(),this.onTick_(),this}tickAfter(e){return this.stop(),this.ticker_=new o((()=>{this.onTick_()})).tickAfter(e),this}tickEvery(e){var t;this.stop();{const e=null!==(t=Error("Timer created").stack)&&void 0!==t?t:"";l.activeTimers.set(this,e)}return this.ticker_=new o((()=>{var t;null===(t=this.ticker_)||void 0===t||t.tickAfter(e),this.onTick_()})).tickAfter(e),this}stop(){this.ticker_&&(this.ticker_.stop(),this.ticker_=null),l.activeTimers.delete(this)}static get[Symbol.for("___CTOR_ARGS___")](){return["() => void"]}}l.activeTimers=new Map;class d{static equal(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;if(e.byteLength!=t.byteLength)return!1;if(d.unsafeGetArrayBuffer_(e)==d.unsafeGetArrayBuffer_(t)&&(e.byteOffset||0)==(t.byteOffset||0))return!0;const i=d.toUint8(e),n=d.toUint8(t);for(let t=0;t<e.byteLength;t++)if(i[t]!=n[t])return!1;return!0}static unsafeGetArrayBuffer_(e){return e instanceof ArrayBuffer?e:e.buffer}static toArrayBuffer(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}static toUint8(e,t=0,i=1/0){return d.view_(e,t,i,Uint8Array)}static toUint16(e,t=0,i=1/0){return d.view_(e,t,i,Uint16Array)}static toDataView(e,t=0,i=1/0){return d.view_(e,t,i,DataView)}static view_(e,t,i,n){const s=d.unsafeGetArrayBuffer_(e);let a=1;"BYTES_PER_ELEMENT"in n&&(a=n.BYTES_PER_ELEMENT);const r=((e.byteOffset||0)+e.byteLength)/a,o=((e.byteOffset||0)+t)/a,l=Math.floor(Math.max(0,Math.min(o,r)));return new n(s,l,Math.floor(Math.min(l+Math.max(i,0),r))-l)}}var c,h,u,_,m,g,f,p,T,S,y,E,v;!function(e){e[e.RECOVERABLE=1]="RECOVERABLE",e[e.CRITICAL=2]="CRITICAL"}(c||(c={})),function(e){e[e.NETWORK=1]="NETWORK",e[e.TEXT=2]="TEXT",e[e.MEDIA=3]="MEDIA",e[e.MANIFEST=4]="MANIFEST",e[e.STREAMING=5]="STREAMING",e[e.DRM=6]="DRM",e[e.PLAYER=7]="PLAYER",e[e.CAST=8]="CAST",e[e.STORAGE=9]="STORAGE",e[e.ADS=10]="ADS"}(h||(h={})),function(e){e[e.UNSUPPORTED_SCHEME=1e3]="UNSUPPORTED_SCHEME",e[e.BAD_HTTP_STATUS=1001]="BAD_HTTP_STATUS",e[e.HTTP_ERROR=1002]="HTTP_ERROR",e[e.TIMEOUT=1003]="TIMEOUT",e[e.MALFORMED_DATA_URI=1004]="MALFORMED_DATA_URI",e[e.REQUEST_FILTER_ERROR=1006]="REQUEST_FILTER_ERROR",e[e.RESPONSE_FILTER_ERROR=1007]="RESPONSE_FILTER_ERROR",e[e.MALFORMED_TEST_URI=1008]="MALFORMED_TEST_URI",e[e.UNEXPECTED_TEST_REQUEST=1009]="UNEXPECTED_TEST_REQUEST",e[e.ATTEMPTS_EXHAUSTED=1010]="ATTEMPTS_EXHAUSTED",e[e.SEGMENT_MISSING=1011]="SEGMENT_MISSING",e[e.SEGMENT_DURATION_IS_NULL=1012]="SEGMENT_DURATION_IS_NULL",e[e.INVALID_TEXT_HEADER=2e3]="INVALID_TEXT_HEADER",e[e.INVALID_TEXT_CUE=2001]="INVALID_TEXT_CUE",e[e.UNABLE_TO_DETECT_ENCODING=2003]="UNABLE_TO_DETECT_ENCODING",e[e.BAD_ENCODING=2004]="BAD_ENCODING",e[e.INVALID_XML=2005]="INVALID_XML",e[e.INVALID_MP4_TTML=2007]="INVALID_MP4_TTML",e[e.INVALID_MP4_VTT=2008]="INVALID_MP4_VTT",e[e.UNABLE_TO_EXTRACT_CUE_START_TIME=2009]="UNABLE_TO_EXTRACT_CUE_START_TIME",e[e.INVALID_MP4_CEA=2010]="INVALID_MP4_CEA",e[e.TEXT_COULD_NOT_GUESS_MIME_TYPE=2011]="TEXT_COULD_NOT_GUESS_MIME_TYPE",e[e.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS=2012]="CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS",e[e.TEXT_ONLY_WEBVTT_SRC_EQUALS=2013]="TEXT_ONLY_WEBVTT_SRC_EQUALS",e[e.MISSING_TEXT_PLUGIN=2014]="MISSING_TEXT_PLUGIN",e[e.CHAPTERS_TRACK_FAILED=2015]="CHAPTERS_TRACK_FAILED",e[e.UNSUPPORTED_EXTERNAL_THUMBNAILS_URI=2017]="UNSUPPORTED_EXTERNAL_THUMBNAILS_URI",e[e.BUFFER_READ_OUT_OF_BOUNDS=3e3]="BUFFER_READ_OUT_OF_BOUNDS",e[e.JS_INTEGER_OVERFLOW=3001]="JS_INTEGER_OVERFLOW",e[e.EBML_OVERFLOW=3002]="EBML_OVERFLOW",e[e.EBML_BAD_FLOATING_POINT_SIZE=3003]="EBML_BAD_FLOATING_POINT_SIZE",e[e.MP4_SIDX_WRONG_BOX_TYPE=3004]="MP4_SIDX_WRONG_BOX_TYPE",e[e.MP4_SIDX_INVALID_TIMESCALE=3005]="MP4_SIDX_INVALID_TIMESCALE",e[e.MP4_SIDX_TYPE_NOT_SUPPORTED=3006]="MP4_SIDX_TYPE_NOT_SUPPORTED",e[e.WEBM_CUES_ELEMENT_MISSING=3007]="WEBM_CUES_ELEMENT_MISSING",e[e.WEBM_EBML_HEADER_ELEMENT_MISSING=3008]="WEBM_EBML_HEADER_ELEMENT_MISSING",e[e.WEBM_SEGMENT_ELEMENT_MISSING=3009]="WEBM_SEGMENT_ELEMENT_MISSING",e[e.WEBM_INFO_ELEMENT_MISSING=3010]="WEBM_INFO_ELEMENT_MISSING",e[e.WEBM_DURATION_ELEMENT_MISSING=3011]="WEBM_DURATION_ELEMENT_MISSING",e[e.WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING=3012]="WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING",e[e.WEBM_CUE_TIME_ELEMENT_MISSING=3013]="WEBM_CUE_TIME_ELEMENT_MISSING",e[e.MEDIA_SOURCE_OPERATION_FAILED=3014]="MEDIA_SOURCE_OPERATION_FAILED",e[e.MEDIA_SOURCE_OPERATION_THREW=3015]="MEDIA_SOURCE_OPERATION_THREW",e[e.VIDEO_ERROR=3016]="VIDEO_ERROR",e[e.QUOTA_EXCEEDED_ERROR=3017]="QUOTA_EXCEEDED_ERROR",e[e.TRANSMUXING_FAILED=3018]="TRANSMUXING_FAILED",e[e.CONTENT_TRANSFORMATION_FAILED=3019]="CONTENT_TRANSFORMATION_FAILED",e[e.MSS_MISSING_DATA_FOR_TRANSMUXING=3020]="MSS_MISSING_DATA_FOR_TRANSMUXING",e[e.MSS_TRANSMUXING_CODEC_UNKNOWN=3021]="MSS_TRANSMUXING_CODEC_UNKNOWN",e[e.MSS_TRANSMUXING_FAILED=3022]="MSS_TRANSMUXING_FAILED",e[e.TRANSMUXING_NO_VIDEO_DATA=3023]="TRANSMUXING_NO_VIDEO_DATA",e[e.UNABLE_TO_GUESS_MANIFEST_TYPE=4e3]="UNABLE_TO_GUESS_MANIFEST_TYPE",e[e.DASH_INVALID_XML=4001]="DASH_INVALID_XML",e[e.DASH_NO_SEGMENT_INFO=4002]="DASH_NO_SEGMENT_INFO",e[e.DASH_EMPTY_ADAPTATION_SET=4003]="DASH_EMPTY_ADAPTATION_SET",e[e.DASH_EMPTY_PERIOD=4004]="DASH_EMPTY_PERIOD",e[e.DASH_WEBM_MISSING_INIT=4005]="DASH_WEBM_MISSING_INIT",e[e.DASH_UNSUPPORTED_CONTAINER=4006]="DASH_UNSUPPORTED_CONTAINER",e[e.DASH_PSSH_BAD_ENCODING=4007]="DASH_PSSH_BAD_ENCODING",e[e.DASH_NO_COMMON_KEY_SYSTEM=4008]="DASH_NO_COMMON_KEY_SYSTEM",e[e.DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED=4009]="DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED",e[e.DASH_CONFLICTING_KEY_IDS=4010]="DASH_CONFLICTING_KEY_IDS",e[e.RESTRICTIONS_CANNOT_BE_MET=4012]="RESTRICTIONS_CANNOT_BE_MET",e[e.HLS_PLAYLIST_HEADER_MISSING=4015]="HLS_PLAYLIST_HEADER_MISSING",e[e.INVALID_HLS_TAG=4016]="INVALID_HLS_TAG",e[e.HLS_INVALID_PLAYLIST_HIERARCHY=4017]="HLS_INVALID_PLAYLIST_HIERARCHY",e[e.DASH_DUPLICATE_REPRESENTATION_ID=4018]="DASH_DUPLICATE_REPRESENTATION_ID",e[e.HLS_MULTIPLE_MEDIA_INIT_SECTIONS_FOUND=4020]="HLS_MULTIPLE_MEDIA_INIT_SECTIONS_FOUND",e[e.HLS_REQUIRED_ATTRIBUTE_MISSING=4023]="HLS_REQUIRED_ATTRIBUTE_MISSING",e[e.HLS_REQUIRED_TAG_MISSING=4024]="HLS_REQUIRED_TAG_MISSING",e[e.HLS_COULD_NOT_GUESS_CODECS=4025]="HLS_COULD_NOT_GUESS_CODECS",e[e.HLS_KEYFORMATS_NOT_SUPPORTED=4026]="HLS_KEYFORMATS_NOT_SUPPORTED",e[e.DASH_UNSUPPORTED_XLINK_ACTUATE=4027]="DASH_UNSUPPORTED_XLINK_ACTUATE",e[e.DASH_XLINK_DEPTH_LIMIT=4028]="DASH_XLINK_DEPTH_LIMIT",e[e.CONTENT_UNSUPPORTED_BY_BROWSER=4032]="CONTENT_UNSUPPORTED_BY_BROWSER",e[e.CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM=4033]="CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM",e[e.NO_VARIANTS=4036]="NO_VARIANTS",e[e.PERIOD_FLATTENING_FAILED=4037]="PERIOD_FLATTENING_FAILED",e[e.INCONSISTENT_DRM_ACROSS_PERIODS=4038]="INCONSISTENT_DRM_ACROSS_PERIODS",e[e.HLS_VARIABLE_NOT_FOUND=4039]="HLS_VARIABLE_NOT_FOUND",e[e.HLS_MSE_ENCRYPTED_MP2T_NOT_SUPPORTED=4040]="HLS_MSE_ENCRYPTED_MP2T_NOT_SUPPORTED",e[e.HLS_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED=4041]="HLS_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED",e[e.NO_WEB_CRYPTO_API=4042]="NO_WEB_CRYPTO_API",e[e.CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_LIVE_STREAM=4045]="CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_LIVE_STREAM",e[e.MSS_INVALID_XML=4046]="MSS_INVALID_XML",e[e.MSS_LIVE_CONTENT_NOT_SUPPORTED=4047]="MSS_LIVE_CONTENT_NOT_SUPPORTED",e[e.AES_128_INVALID_IV_LENGTH=4048]="AES_128_INVALID_IV_LENGTH",e[e.AES_128_INVALID_KEY_LENGTH=4049]="AES_128_INVALID_KEY_LENGTH",e[e.DASH_CONFLICTING_AES_128=4050]="DASH_CONFLICTING_AES_128",e[e.DASH_UNSUPPORTED_AES_128=4051]="DASH_UNSUPPORTED_AES_128",e[e.DASH_EMPTY_INDEX_RANGE=4052]="DASH_EMPTY_INDEX_RANGE",e[e.DASH_INVALID_JSON=4053]="DASH_INVALID_JSON",e[e.STREAMING_ENGINE_STARTUP_INVALID_STATE=5006]="STREAMING_ENGINE_STARTUP_INVALID_STATE",e[e.NO_RECOGNIZED_KEY_SYSTEMS=6e3]="NO_RECOGNIZED_KEY_SYSTEMS",e[e.REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE=6001]="REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE",e[e.FAILED_TO_CREATE_CDM=6002]="FAILED_TO_CREATE_CDM",e[e.FAILED_TO_ATTACH_TO_VIDEO=6003]="FAILED_TO_ATTACH_TO_VIDEO",e[e.INVALID_SERVER_CERTIFICATE=6004]="INVALID_SERVER_CERTIFICATE",e[e.FAILED_TO_CREATE_SESSION=6005]="FAILED_TO_CREATE_SESSION",e[e.FAILED_TO_GENERATE_LICENSE_REQUEST=6006]="FAILED_TO_GENERATE_LICENSE_REQUEST",e[e.LICENSE_REQUEST_FAILED=6007]="LICENSE_REQUEST_FAILED",e[e.LICENSE_RESPONSE_REJECTED=6008]="LICENSE_RESPONSE_REJECTED",e[e.ENCRYPTED_CONTENT_WITHOUT_DRM_INFO=6010]="ENCRYPTED_CONTENT_WITHOUT_DRM_INFO",e[e.NO_LICENSE_SERVER_GIVEN=6012]="NO_LICENSE_SERVER_GIVEN",e[e.OFFLINE_SESSION_REMOVED=6013]="OFFLINE_SESSION_REMOVED",e[e.EXPIRED=6014]="EXPIRED",e[e.SERVER_CERTIFICATE_REQUIRED=6015]="SERVER_CERTIFICATE_REQUIRED",e[e.INIT_DATA_TRANSFORM_ERROR=6016]="INIT_DATA_TRANSFORM_ERROR",e[e.SERVER_CERTIFICATE_REQUEST_FAILED=6017]="SERVER_CERTIFICATE_REQUEST_FAILED",e[e.MIN_HDCP_VERSION_NOT_MATCH=6018]="MIN_HDCP_VERSION_NOT_MATCH",e[e.ERROR_CHECKING_HDCP_VERSION=6019]="ERROR_CHECKING_HDCP_VERSION",e[e.LOAD_INTERRUPTED=7e3]="LOAD_INTERRUPTED",e[e.OPERATION_ABORTED=7001]="OPERATION_ABORTED",e[e.NO_VIDEO_ELEMENT=7002]="NO_VIDEO_ELEMENT",e[e.OBJECT_DESTROYED=7003]="OBJECT_DESTROYED",e[e.CONTENT_NOT_LOADED=7004]="CONTENT_NOT_LOADED",e[e.SRC_EQUALS_PRELOAD_NOT_SUPPORTED=7005]="SRC_EQUALS_PRELOAD_NOT_SUPPORTED",e[e.NOT_CONFIGURED=7001]="NOT_CONFIGURED",e[e.CAST_API_UNAVAILABLE=8e3]="CAST_API_UNAVAILABLE",e[e.NO_CAST_RECEIVERS=8001]="NO_CAST_RECEIVERS",e[e.ALREADY_CASTING=8002]="ALREADY_CASTING",e[e.UNEXPECTED_CAST_ERROR=8003]="UNEXPECTED_CAST_ERROR",e[e.CAST_CANCELED_BY_USER=8004]="CAST_CANCELED_BY_USER",e[e.CAST_CONNECTION_TIMED_OUT=8005]="CAST_CONNECTION_TIMED_OUT",e[e.CAST_RECEIVER_APP_UNAVAILABLE=8006]="CAST_RECEIVER_APP_UNAVAILABLE",e[e.STORAGE_NOT_SUPPORTED=9e3]="STORAGE_NOT_SUPPORTED",e[e.INDEXED_DB_ERROR=9001]="INDEXED_DB_ERROR",e[e.DEPRECATED_OPERATION_ABORTED=9002]="DEPRECATED_OPERATION_ABORTED",e[e.REQUESTED_ITEM_NOT_FOUND=9003]="REQUESTED_ITEM_NOT_FOUND",e[e.MALFORMED_OFFLINE_URI=9004]="MALFORMED_OFFLINE_URI",e[e.CANNOT_STORE_LIVE_OFFLINE=9005]="CANNOT_STORE_LIVE_OFFLINE",e[e.NO_INIT_DATA_FOR_OFFLINE=9007]="NO_INIT_DATA_FOR_OFFLINE",e[e.LOCAL_PLAYER_INSTANCE_REQUIRED=9008]="LOCAL_PLAYER_INSTANCE_REQUIRED",e[e.NEW_KEY_OPERATION_NOT_SUPPORTED=9011]="NEW_KEY_OPERATION_NOT_SUPPORTED",e[e.KEY_NOT_FOUND=9012]="KEY_NOT_FOUND",e[e.MISSING_STORAGE_CELL=9013]="MISSING_STORAGE_CELL",e[e.STORAGE_LIMIT_REACHED=9014]="STORAGE_LIMIT_REACHED",e[e.DOWNLOAD_SIZE_CALLBACK_ERROR=9015]="DOWNLOAD_SIZE_CALLBACK_ERROR",e[e.MODIFY_OPERATION_NOT_SUPPORTED=9016]="MODIFY_OPERATION_NOT_SUPPORTED",e[e.INDEXED_DB_INIT_TIMED_OUT=9017]="INDEXED_DB_INIT_TIMED_OUT",e[e.CS_IMA_SDK_MISSING=1e4]="CS_IMA_SDK_MISSING",e[e.CS_AD_MANAGER_NOT_INITIALIZED=10001]="CS_AD_MANAGER_NOT_INITIALIZED",e[e.SS_IMA_SDK_MISSING=10002]="SS_IMA_SDK_MISSING",e[e.SS_AD_MANAGER_NOT_INITIALIZED=10003]="SS_AD_MANAGER_NOT_INITIALIZED",e[e.CURRENT_DAI_REQUEST_NOT_FINISHED=10004]="CURRENT_DAI_REQUEST_NOT_FINISHED",e[e.MT_AD_MANAGER_NOT_INITIALIZED=10005]="MT_AD_MANAGER_NOT_INITIALIZED"}(u||(u={}));class b{constructor(e,t,i,...n){this.severity=e,this.category=t,this.code=i,this.data=n,this.handled=!1;let s="Shaka Error "+this.code;{let e="UNKNOWN",t="UNKNOWN";for(const t in b.Category)b.Category[t]==this.category&&(e=t);for(const e in b.Code)b.Code[e]==this.code&&(t=e);s="Player Error "+e+"."+t+" ("+this.data.toString()+")"}if(this.message=s,b.createStack)try{throw new Error(this.message||"Player Error")}catch(e){this.stack=e.stack}}toString(){return"PlayerError "+JSON.stringify(this,null," ")}static get[Symbol.for("___CTOR_ARGS___")](){return["PlayerErrorSeverity","PlayerErrorCategory","PlayerErrorCode","any[]"]}}b.Severity=c,b.Category=h,b.Code=u,b.createStack=!0;class I{static defaultEquals(e,t){return!("number"!=typeof e||"number"!=typeof t||!isNaN(e)||!isNaN(t))||e===t}static remove(e,t){const i=e.indexOf(t);i>-1&&e.splice(i,1)}static count(e,t){let i=0;for(const n of e)i+=t(n)?1:0;return i}static hasSameElements(e,t,i=I.defaultEquals){if(i||(i=I.defaultEquals),e.length!=t.length)return!1;const n=t.slice();for(const t of e){const e=n.findIndex((e=>i(t,e)));if(-1==e)return!1;n[e]=n[n.length-1],n.pop()}return 0==n.length}static equal(e,t,i=I.defaultEquals){if(i||(i=I.defaultEquals),e.length!=t.length)return!1;for(let n=0;n<e.length;++n)if(!i(e[n],t[n]))return!1;return!0}}class A{constructor(){this.operations_=[]}manage(e){this.operations_.push(e.finally((()=>{I.remove(this.operations_,e)})))}destroy(){const e=[];for(const t of this.operations_)t.promise.catch((()=>{})),e.push(t.abort());return this.operations_=[],Promise.all(e)}}class w{static cloneObject(e){const t=new WeakSet,i=e=>{switch(typeof e){case"undefined":case"boolean":case"number":case"string":case"symbol":case"function":return e;default:{if(!e)return e;if(e.buffer&&e.buffer.constructor==ArrayBuffer)return e;if(t.has(e))return null;const n=e.constructor==Array;if(e.constructor!=Object&&!n)return null;t.add(e);const s=n?[]:{};for(const t in e)s[t]=i(e[t]);return n&&(s.length=e.length),s}}};return i(e)}static shallowCloneObject(e){const t={};for(const i in e)t[i]=e[i];return t}}class C extends Promise{constructor(){let e=null,t=null;super(((e,t)=>{}));const i=new Promise(((i,n)=>{e=i,t=n}));return i.resolve=e,i.reject=t,i}resolve(e){}reject(e){}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class M{constructor(e,t){this.onAbort_=t,this.aborted_=!1,this.promise=e}static failed(e){return new M(Promise.reject(e),(()=>Promise.resolve()))}static aborted(){const e=Promise.reject(M.abortError());return e.catch((()=>{})),new M(e,(()=>Promise.resolve()))}static abortError(){return new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.OPERATION_ABORTED)}static completed(e){return new M(Promise.resolve(e),(()=>Promise.resolve()))}static notAbortable(e){return new M(e,(()=>e.catch((()=>{}))))}abort(){return this.aborted_=!0,this.onAbort_()}static all(e){return new M(Promise.all(e.map((e=>e.promise))),(()=>Promise.all(e.map((e=>e.abort())))))}finally(e){return this.promise.then((t=>e(!0)),(t=>e(!1))),this}chain(e,t){const i=new C,n=M.abortError();let s=()=>(i.reject(n),this.abort());const a=a=>r=>{if(this.aborted_&&a)return void i.reject(n);const o=a?e:t;o?s=M.wrapChainCallback_(o,r,i):(a?i.resolve:i.reject)(r)};return this.promise.then(a(!0),a(!1)),new M(i,(()=>s()))}static wrapChainCallback_(e,t,i){try{const n=e(t);return n&&n.promise&&n.abort?(i.resolve(n.promise),()=>n.abort()):(i.resolve(n),()=>Promise.resolve(n).then((()=>{}),(()=>{})))}catch(e){return i.reject(e),()=>Promise.resolve()}}static get[Symbol.for("___CTOR_ARGS___")](){return["Promise","() => Promise<void>"]}}class R{constructor(e,t=!1){const i=R.defaultRetryParameters();this.maxAttempts_=null==e.maxAttempts?i.maxAttempts:e.maxAttempts,console.assert(this.maxAttempts_>=1,"maxAttempts should be >= 1"),this.baseDelay_=null==e.baseDelay?i.baseDelay:e.baseDelay,console.assert(this.baseDelay_>=0,"baseDelay should be >= 0"),this.fuzzFactor_=null==e.fuzzFactor?i.fuzzFactor:e.fuzzFactor,console.assert(this.fuzzFactor_>=0,"fuzzFactor should be >= 0"),this.backoffFactor_=null==e.backoffFactor?i.backoffFactor:e.backoffFactor,console.assert(this.backoffFactor_>=0,"backoffFactor should be >= 0"),this.numAttempts_=0,this.nextUnfuzzedDelay_=this.baseDelay_,this.autoReset_=t,this.autoReset_&&(console.assert(this.maxAttempts_>=2,"maxAttempts must be >= 2 for autoReset == true"),this.numAttempts_=1)}async attempt(){if(this.numAttempts_>=this.maxAttempts_){if(!this.autoReset_)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.ATTEMPTS_EXHAUSTED);this.reset_()}const e=this.numAttempts_;if(this.numAttempts_++,0==e)return void console.assert(!this.autoReset_,"Failed to delay with auto-reset!");const t=R.fuzz_(this.nextUnfuzzedDelay_,this.fuzzFactor_);await new Promise((e=>{R.defer(t,e)})),this.nextUnfuzzedDelay_*=this.backoffFactor_}static defaultRetryParameters(){return{maxAttempts:2,baseDelay:1e3,backoffFactor:2,fuzzFactor:.5,timeout:3e4,stallTimeout:5e3,connectionTimeout:1e4}}static fuzz_(e,t){return e*(1+(2*Math.random()-1)*t)}reset_(){console.assert(this.autoReset_,"Should only be used for auto-reset!"),this.numAttempts_=1,this.nextUnfuzzedDelay_=this.baseDelay_}static defer(e,t){new l(t).tickAfter(e/1e3)}static get[Symbol.for("___CTOR_ARGS___")](){return["RetryParameters","boolean"]}}!function(e){e[e.MANIFEST=0]="MANIFEST",e[e.SEGMENT=1]="SEGMENT",e[e.LICENSE=2]="LICENSE",e[e.APP=3]="APP",e[e.TIMING=4]="TIMING",e[e.SERVER_CERTIFICATE=5]="SERVER_CERTIFICATE",e[e.KEY=6]="KEY",e[e.ADS=7]="ADS",e[e.CONTENT_STEERING=8]="CONTENT_STEERING"}(_||(_={})),function(e){e[e.INIT_SEGMENT=0]="INIT_SEGMENT",e[e.MEDIA_SEGMENT=1]="MEDIA_SEGMENT",e[e.MEDIA_PLAYLIST=2]="MEDIA_PLAYLIST",e[e.MASTER_PLAYLIST=3]="MASTER_PLAYLIST",e[e.MPD=4]="MPD",e[e.MSS=5]="MSS"}(m||(m={})),function(e){e[e.FALLBACK=1]="FALLBACK",e[e.PREFERRED=2]="PREFERRED",e[e.APPLICATION=3]="APPLICATION"}(g||(g={}));class O extends M{constructor(e,t,i){super(e,t),this.bytesRemaining_=i}getBytesRemaining(){return this.bytesRemaining_.getBytes()}static get[Symbol.for("___CTOR_ARGS___")](){return["Promise","() => Promise<void>","NumBytesRemainingClass"]}}class D extends r{constructor(e,t,i,n,s){super(),this.destroyed_=!1,this.operationManager_=new A,this.requestFilters_=new Set,this.responseFilters_=new Set,this.onProgressUpdated_=e||null,this.onHeadersReceived_=t||null,this.onDownloadFailed_=i||null,this.onRequest_=n||null,this.onRetry_=s||null,this.forceHTTPS_=!1}setForceHTTPS(e){this.forceHTTPS_=e}static registerScheme(e,t,i,n=!1){console.assert(null==i||i>0,"explicit priority must be > 0"),i=i||D.PluginPriority.APPLICATION;const s=D.schemes_[e];(!s||i>=s.priority)&&(D.schemes_[e]={priority:i,plugin:t,progressSupport:n})}static unregisterScheme(e){delete D.schemes_[e]}registerRequestFilter(e){this.requestFilters_.add(e)}unregisterRequestFilter(e){this.requestFilters_.delete(e)}clearAllRequestFilters(){this.requestFilters_.clear()}registerResponseFilter(e){this.responseFilters_.add(e)}unregisterResponseFilter(e){this.responseFilters_.delete(e)}clearAllResponseFilters(){this.responseFilters_.clear()}static defaultRetryParameters(){return R.defaultRetryParameters()}static makeRequest(e,t,i=null){return{contentType:null,packetNumber:null,requestStartTime:null,timeToFirstByte:null,uris:e,method:"GET",body:null,headers:{},allowCrossSiteCredentials:!1,retryParameters:t,licenseRequestType:null,sessionId:null,drmInfo:null,initData:null,initDataType:null,streamDataCallback:i}}destroy(){return this.destroyed_=!0,this.requestFilters_.clear(),this.responseFilters_.clear(),super.release(),this.operationManager_.destroy()}request(e,t,i=null){const n=new D.NumBytesRemainingClass;if(this.destroyed_){const e=Promise.reject(new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.OPERATION_ABORTED));return e.catch((()=>{})),new D.PendingRequest(e,(()=>Promise.resolve()),n)}console.assert(t.uris&&t.uris.length,"Request without URIs!"),t.method=t.method||"GET",t.headers=t.headers||{},t.retryParameters=t.retryParameters?w.cloneObject(t.retryParameters):D.defaultRetryParameters(),t.uris=w.cloneObject(t.uris);const s=this.filterRequest_(e,t,i),a=s.chain((()=>this.makeRequestWithRetry_(e,t,i,n))),r=a.chain((t=>this.filterResponse_(e,t,i))),o=Date.now();let l=0;s.promise.then((()=>{l=Date.now()-o}),(()=>{}));let d=0;a.promise.then((()=>{d=Date.now()}),(()=>{}));const c=r.chain((n=>{var s;const a=Date.now()-d,r=n.response;if(null!=r.timeMs&&(r.timeMs+=l,r.timeMs+=a),!n.gotProgress&&this.onProgressUpdated_&&!r.fromCache&&"HEAD"!=t.method&&e==D.RequestType.SEGMENT){const e=this.allowSwitch_(i);this.onProgressUpdated_(null!==(s=r.timeMs)&&void 0!==s?s:0,r.data.byteLength,e,t)}return r}),(e=>{throw e&&(console.assert(e instanceof b,"Wrong error type"),e.severity=b.Severity.CRITICAL),e})),h=new D.PendingRequest(c.promise,(()=>c.abort()),n);return this.operationManager_.manage(h),h}filterRequest_(e,t,i){let n=M.completed(void 0);const s=s=>{n=n.chain((n=>(t.body&&(t.body=d.toArrayBuffer(t.body)),s(e,t,i))))};this.onRequest_&&s(this.onRequest_);for(const e of this.requestFilters_)s(e);return n.chain(void 0,(e=>{if(e&&e instanceof b&&e.code==b.Code.OPERATION_ABORTED)throw e;throw new b(b.Severity.CRITICAL,b.Category.NETWORK,b.Code.REQUEST_FILTER_ERROR,e)}))}makeRequestWithRetry_(e,t,i,n){const s=new R(t.retryParameters,!1);return this.send_(e,t,i,s,0,null,n)}send_(e,t,i,n,s,r,o){if(this.forceHTTPS_&&(t.uris[s]=t.uris[s].replace("http://","https://")),s>0&&this.onRetry_){const n=t.uris[s],a=t.uris[s-1];this.onRetry_(e,i,n,a)}const d=new URL(t.uris[s]),c=d.protocol;console.assert(":"==c[c.length-1],"uri.protocol expected to end with a colon!");let h=c.slice(0,-1),u=!1;h||(h=D.getLocationProtocol_(),console.assert(":"==h[h.length-1],"location.protocol expected to end with a colon!"),h=h.slice(0,-1),d.protocol=h,t.uris[s]=d.toString()),h=h.toLowerCase();const _=D.schemes_[h],m=_?_.plugin:null;if(!m)return M.failed(new b(b.Severity.CRITICAL,b.Category.NETWORK,b.Code.UNSUPPORTED_SCHEME,d));const g=_.progressSupport,f=M.notAbortable(n.attempt());let p,T=null,S=null,y=!1,E=!1;return f.chain((n=>{if(this.destroyed_)return M.aborted();p=Date.now();const a=D.RequestType.SEGMENT;let r=0;t.requestStartTime=Date.now();const d=m(t.uris[s],t,e,((n,s,l)=>{if(T&&T.stop(),S&&S.tickAfter(h/1e3),this.onProgressUpdated_&&e==a){r++,t.packetNumber=r;const e=this.allowSwitch_(i);this.onProgressUpdated_(n,s,e,t),u=!0,o.setBytes(l)}}),(i=>{this.onHeadersReceived_&&this.onHeadersReceived_(i,t,e),E=!0,t.timeToFirstByte=Date.now()-t.requestStartTime}));if(!g)return d;const c=t.retryParameters.connectionTimeout;c&&(T=new l((()=>{y=!0,d.abort()})),T.tickAfter(c/1e3));const h=t.retryParameters.stallTimeout;return h&&(S=new l((()=>{y=!0,d.abort()}))),d})).chain((i=>{T&&T.stop(),S&&S.stop(),null==i.timeMs&&(i.timeMs=Date.now()-p);const n={response:i,gotProgress:u};return E||this.onHeadersReceived_&&this.onHeadersReceived_(i.headers,t,e),n}),(l=>{if(T&&T.stop(),S&&S.stop(),this.onDownloadFailed_){let e=null,i=0;l instanceof b&&(e=l,l.code==b.Code.BAD_HTTP_STATUS&&(i=l.data[1])),this.onDownloadFailed_(t,e,i,y)}if(this.destroyed_)return M.aborted();if(y&&(l=new b(b.Severity.RECOVERABLE,b.Category.NETWORK,b.Code.TIMEOUT,t.uris[s],e)),l instanceof b){if(l.code==b.Code.OPERATION_ABORTED)throw l;if(l.code==b.Code.ATTEMPTS_EXHAUSTED)throw console.assert(r,"Should have last error"),r;if(l.severity==b.Severity.RECOVERABLE){const r=(new Map).set("error",l),d=new a("retry",r);return this.dispatchEvent(d),s=(s+1)%t.uris.length,this.send_(e,t,i,n,s,l,o)}}throw l}))}filterResponse_(e,t,i){let n=M.completed(void 0);for(const s of this.responseFilters_)n=n.chain((()=>{const n=t.response;return n.data&&(n.data=d.toArrayBuffer(n.data)),s(e,n,i)}));return n.chain((()=>t),(e=>{let t=b.Severity.CRITICAL;if(e instanceof b){if(e.code==b.Code.OPERATION_ABORTED)throw e;t=e.severity}throw new b(t,b.Category.NETWORK,b.Code.RESPONSE_FILTER_ERROR,e)}))}allowSwitch_(e){if(e){const t=e.segment,i=e.stream;if(t&&i&&i.fastSwitching&&t.isPartial())return!1}return!0}static getLocationProtocol_(){return location.protocol}static get[Symbol.for("___CTOR_ARGS___")](){return["NetworkOnProgressUpdated","NetworkOnHeadersReceived","NetworkOnDownloadFailed","NetworkOnRequest","NetworkOnRetry"]}}D.RequestType=_,D.AdvancedRequestType=m,D.PluginPriority=g,D.PendingRequest=O,D.NumBytesRemainingClass=class{constructor(){this.bytesToLoad_=0}setBytes(e){this.bytesToLoad_=e}getBytes(){return this.bytesToLoad_}},D.schemes_={};class P{static async getMimeType(e,t,i){const n=P.getExtension_(e);let s=P.EXTENSIONS_TO_MIME_TYPES_[n];if(s)return s;const a=D.RequestType.MANIFEST,r=D.makeRequest([e],i);try{r.method="HEAD",s=(await t.request(a,r).promise).headers["content-type"]}catch(e){!e||e.code!=b.Code.HTTP_ERROR&&e.code!=b.Code.BAD_HTTP_STATUS||(r.method="GET",s=(await t.request(a,r).promise).headers["content-type"])}return s?s.toLowerCase().split(";").shift():""}static getExtension_(e){const t=new URL(e).pathname.split("/").pop().split(".");return 1==t.length?"":t.pop().toLowerCase()}}P.EXTENSIONS_TO_MIME_TYPES_={mp4:"video/mp4",m4v:"video/mp4",m4a:"audio/mp4",webm:"video/webm",weba:"audio/webm",mkv:"video/webm",ts:"video/mp2t",ogv:"video/ogg",ogg:"audio/ogg",mpg:"video/mpeg",mpeg:"video/mpeg",m3u8:"application/x-mpegurl",mpd:"application/dash+xml",ism:"application/vnd.ms-sstr+xml",mp3:"audio/mpeg",aac:"audio/aac",flac:"audio/flac",wav:"audio/wav",sbv:"text/x-subviewer",srt:"text/srt",vtt:"text/vtt",webvtt:"text/vtt",ttml:"application/ttml+xml",lrc:"application/x-subtitle-lrc",ssa:"text/x-ssa",ass:"text/x-ssa"};class N{static supportsMediaSource(){const e=window.ManagedMediaSource||window.MediaSource;return!!e&&!!e.isTypeSupported}static supportsMediaType(e){return""!=N.anyMediaElement().canPlayType(e)}static isEdge(){return!!navigator.userAgent.match(/Edge?\//)}static isLegacyEdge(){return!!navigator.userAgent.match(/Edge\//)}static isIE(){return N.userAgentContains_("Trident/")}static isXboxOne(){return N.userAgentContains_("Xbox One")}static isTizen(){return N.userAgentContains_("Tizen")}static isTizen4(){return N.userAgentContains_("Tizen 4")}static isTizen3(){return N.userAgentContains_("Tizen 3")}static isTizen2(){return N.userAgentContains_("Tizen 2")}static isWebOS(){return N.userAgentContains_("Web0S")}static isWebOS3(){return N.userAgentContains_("Web0S")&&N.userAgentContains_("Chrome/38.0.2125.122 Safari/537.36")}static isWebOS4(){return!!navigator.userAgent.match(/webOS\/4/i)}static isWebOS5(){return!!navigator.userAgent.match(/webOS\/5/i)}static isChromecast(){return N.userAgentContains_("CrKey")}static chromeVersion(){if(!N.isChrome())return null;const e=navigator.userAgent.match(/Chrome\/(\d+)/);return e?parseInt(e[1],10):null}static isChrome(){return N.userAgentContains_("Chrome")&&!N.isLegacyEdge()}static isFirefox(){return N.userAgentContains_("Firefox")}static isApple(){return!!navigator.vendor&&navigator.vendor.includes("Apple")&&!N.isTizen()&&!N.isEOS()&&!N.isAPL()&&!N.isVirginMedia()&&!N.isOrange()&&!N.isPS4()&&!N.isAmazonFireTV()&&!N.isWPE()}static isPS5(){return N.userAgentContains_("PlayStation 5")}static isPS4(){return N.userAgentContains_("PlayStation 4")}static isHisense(){return N.userAgentContains_("Hisense")||N.userAgentContains_("VIDAA")}static isVirginMedia(){return N.userAgentContains_("VirginMedia")}static isOrange(){return N.userAgentContains_("SOPOpenBrowser")}static isAmazonFireTV(){return N.userAgentContains_("AFT")}static isWPE(){return N.userAgentContains_("WPE")}static safariVersion(){if(!N.isApple())return null;let e=navigator.userAgent.match(/Version\/(\d+)/);return e?parseInt(e[1],10):(e=navigator.userAgent.match(/OS (\d+)(?:_\d+)?/),e?parseInt(e[1],10):null)}static isSafari(){return!!N.safariVersion()}static isEOS(){return N.userAgentContains_("PC=EOS")}static isAPL(){return N.userAgentContains_("PC=APL")}static isMobile(){return!!/(?:iPhone|iPad|iPod|Android)/.test(navigator.userAgent)||N.isApple()&&navigator.maxTouchPoints>1}static isMac(){return navigator.userAgentData&&navigator.userAgentData.platform?"macos"==navigator.userAgentData.platform.toLowerCase():navigator.platform.toLowerCase().includes("mac")}static isWindows(){return navigator.userAgentData&&navigator.userAgentData.platform?"windows"==navigator.userAgentData.platform.toLowerCase():navigator.platform.toLowerCase().includes("windows")}static isAndroid(){return N.userAgentContains_("Android")}static userAgentContains_(e){return(navigator.userAgent||"").includes(e)}static anyMediaElement(){return N.cachedMediaElement_||(N.cacheExpirationTimer_||(N.cacheExpirationTimer_=new l((()=>{N.cachedMediaElement_=null}))),N.cachedMediaElement_=document.getElementsByTagName("video")[0]||document.getElementsByTagName("audio")[0],N.cachedMediaElement_||(N.cachedMediaElement_=document.createElement("video")),N.cacheExpirationTimer_.tickAfter(1)),N.cachedMediaElement_}static requiresEncryptionInfoInAllInitSegments(){return N.isTizen()||N.isXboxOne()||N.isOrange()}static supportsSequenceMode(){return!(N.isTizen3()||N.isTizen2()||N.isWebOS3()||N.isPS4())}static supportsSmoothCodecSwitching(){return!(N.isTizen2()||N.isTizen3()||N.isTizen4()||N.isWebOS3()||N.isWebOS4()||N.isWebOS5()||N.isWindows()&&N.isEdge())}static isMediaKeysPolyfilled(){return!!window.shakaMediaKeysPolyfill}static async detectMaxHardwareResolution(){const e={width:1/0,height:1/0};if(N.isChromecast())window.cast&&cast.__platform__&&cast.__platform__.canDisplayType&&cast.__platform__.canDisplayType('video/mp4; codecs="avc1.640028"; width=3840; height=2160')?(e.width=3840,e.height=2160):(e.width=1920,e.height=1080);else if(N.isTizen()){e.width=1920,e.height=1080;try{if(webapis.systeminfo&&webapis.systeminfo.getMaxVideoResolution){const t=webapis.systeminfo.getMaxVideoResolution();e.width=t.width,e.height=t.height}else webapis.productinfo.is8KPanelSupported&&webapis.productinfo.is8KPanelSupported()?(e.width=7680,e.height=4320):webapis.productinfo.isUdPanelSupported&&webapis.productinfo.isUdPanelSupported()&&(e.width=3840,e.height=2160)}catch(e){n.alwaysWarn("Tizen: Error detecting screen size, default screen size 1920x1080.")}}else if(N.isXboxOne()){const t=new Windows.Media.Protection.ProtectionCapabilities,i=Windows.Media.Protection.ProtectionCapabilityResult;let n=null;try{const e='video/mp4;codecs="hvc1,mp4a";features="decode-res-x=3840,decode-res-y=2160,decode-bitrate=20000,decode-fps=30,decode-bpc=10,display-res-x=3840,display-res-y=2160,display-bpc=8"',s="com.microsoft.playready.recommendation";do{n=t.isTypeSupported(e,s)}while(n===i.maybe)}catch(e){n=i.notSupported}n===i.probably?(e.width=3840,e.height=2160):(e.width=1920,e.height=1080)}else if(N.isWebOS())try{const t=JSON.parse(window.PalmSystem.deviceInfo);e.width=Math.max(1920,t.screenWidth),e.height=Math.max(1080,t.screenHeight)}catch(t){n.alwaysWarn("WebOS: Error detecting screen size, default screen size 1920x1080."),e.width=1920,e.height=1080}else if(N.isHisense())window.Hisense_Get4KSupportState&&window.Hisense_Get4KSupportState()?(e.width=3840,e.height=2160):(e.width=1920,e.height=1080);else if(N.isPS4()||N.isPS5()){let t=!1;try{t="4K"===(await window.msdk.device.getDisplayInfo()).resolution}catch(e){try{t="4K"===(await window.msdk.device.getDisplayInfoImmediate()).resolution}catch(e){n.alwaysWarn("PlayStation: Failed to get the display info:",e)}}t?(e.width=3840,e.height=2160):(e.width=1920,e.height=1080)}return e}}N.cacheExpirationTimer_=null,N.cachedMediaElement_=null;class L{constructor(e){this.gen_=e,this.value_=void 0}value(){return null==this.value_&&(this.value_=this.gen_(),console.assert(null!=this.value_,"Unable to create lazy value")),this.value_}reset(){this.value_=void 0}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class x{static fromUTF8(e){if(!e)return"";let t=d.toUint8(e);if(239==t[0]&&187==t[1]&&191==t[2]&&(t=t.subarray(3)),window.TextDecoder&&!N.isPS4()){const e=(new TextDecoder).decode(t);return e.includes("�")&&n.alwaysError('Decoded string contains an "unknown character" codepoint. That probably means the UTF8 encoding was incorrect!'),e}{let e="";for(let i=0;i<t.length;++i){let n=65533;if(0==(128&t[i])?n=t[i]:t.length>=i+2&&192==(224&t[i])&&128==(192&t[i+1])?(n=(31&t[i])<<6|63&t[i+1],i+=1):t.length>=i+3&&224==(240&t[i])&&128==(192&t[i+1])&&128==(192&t[i+2])?(n=(15&t[i])<<12|(63&t[i+1])<<6|63&t[i+2],i+=2):t.length>=i+4&&240==(241&t[i])&&128==(192&t[i+1])&&128==(192&t[i+2])&&128==(192&t[i+3])&&(n=(7&t[i])<<18|(63&t[i+1])<<12|(63&t[i+2])<<6|63&t[i+3],i+=3),n<=65535)e+=String.fromCharCode(n);else{const t=n-65536,i=t>>10,s=1023&t;e+=String.fromCharCode(55296+i),e+=String.fromCharCode(56320+s)}}return e}}static fromUTF16(e,t,i){if(!e)return"";if(!i&&e.byteLength%2!=0)throw n.error("Data has an incorrect length, must be even."),new b(b.Severity.CRITICAL,b.Category.TEXT,b.Code.BAD_ENCODING);const s=Math.floor(e.byteLength/2),a=new Uint16Array(s),r=d.toDataView(e);for(let e=0;e<s;e++)a[e]=r.getUint16(2*e,t);return x.fromCharCode(a)}static fromBytesAutoDetect(e){if(!e)return"";const t=d.toUint8(e);if(239==t[0]&&187==t[1]&&191==t[2])return x.fromUTF8(t);if(254==t[0]&&255==t[1])return x.fromUTF16(t.subarray(2),!1);if(255==t[0]&&254==t[1])return x.fromUTF16(t.subarray(2),!0);const i=e=>t.byteLength<=e||t[e]>=32&&t[e]<=126;if(n.debug("Unable to find byte-order-mark, making an educated guess."),0==t[0]&&0==t[2])return x.fromUTF16(e,!1);if(0==t[1]&&0==t[3])return x.fromUTF16(e,!0);if(i(0)&&i(1)&&i(2)&&i(3))return x.fromUTF8(e);throw new b(b.Severity.CRITICAL,b.Category.TEXT,b.Code.UNABLE_TO_DETECT_ENCODING)}static toUTF8(e){if(window.TextEncoder&&!N.isPS4()){const t=new TextEncoder;return d.toArrayBuffer(t.encode(e))}{const t=encodeURIComponent(e),i=unescape(t),n=new Uint8Array(i.length);for(let e=0;e<i.length;e++){const t=i[e];n[e]=t.charCodeAt(0)}return d.toArrayBuffer(n)}}static toUTF16(e,t){const i=new ArrayBuffer(2*e.length),n=new DataView(i);for(let i=0;i<e.length;++i){const s=e.charCodeAt(i);n.setUint16(2*i,s,t)}return i}static fromCharCode(e){return x.fromCharCodeImpl_.value()(e)}static resetFromCharCode(){x.fromCharCodeImpl_.reset()}static htmlUnescape(e){const t={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&apos;":"'","&nbsp;":" ","&lrm;":"‎","&rlm;":"‏"},i=/&(?:amp|lt|gt|quot|apos|#(0+)?39|nbsp|lrm|rlm);/g,n=RegExp(i.source);return e&&n.test(e)?e.replace(i,(e=>t[e]||"'")):e||""}}x.fromCharCodeImpl_=new L((()=>{const e=e=>{try{const t=new Uint8Array(e),i=String.fromCharCode.apply(null,t);return console.assert(i,"Should get value"),i.length>0}catch(e){return!1}};for(let t=65536;t>0;t/=2)if(e(t))return e=>{let i="";for(let n=0;n<e.length;n+=t){const s=e.subarray(n,n+t);i+=String.fromCharCode.apply(null,s)}return i};return console.assert(!1,"Unable to create a fromCharCode method"),null}));class k{static toStandardBase64(e){const t=x.fromCharCode(d.toUint8(e));return btoa(t)}static toBase64(e,t){t=null==t||t;const i=k.toStandardBase64(e).replace(/\+/g,"-").replace(/\//g,"_");return t?i:i.replace(/[=]*$/,"")}static fromBase64(e){const t=window.atob(e.replace(/-/g,"+").replace(/_/g,"/")),i=new Uint8Array(t.length);for(let e=0;e<t.length;++e)i[e]=t.charCodeAt(e);return i}static fromHex(e){const t=e.length/2,i=new Uint8Array(t);for(let n=0;n<t;n++)i[n]=window.parseInt(e.substr(2*n,2),16);return i}static toHex(e){const t=d.toUint8(e);let i="";for(let e of t)e=e.toString(16),1==e.length&&(e="0"+e),i+=e;return i}static concat(...e){let t=0;for(let i=0;i<e.length;++i)t+=e[i].byteLength;const i=new Uint8Array(t);let n=0;for(let t=0;t<e.length;++t){const s=e[t];s instanceof Uint8Array?i.set(s,n):i.set(d.toUint8(s),n),n+=s.byteLength}return i}}!function(e){e.HLS="HLS",e.DASH="DASH",e.MSS="MSS",e.UNKNOWN="UNKNOWN"}(f||(f={})),function(e){e.VIDEO="video",e.AUDIO="audio",e.TEXT="text",e.IMAGE="image",e.APPLICATION="application",e.UNKNOWN="UNKNOWN"}(p||(p={})),function(e){e.SUBTITLE="subtitle",e.CLOSED_CAPTION="caption"}(T||(T={})),function(e){e.VISUALLY_IMPAIRED="visually impaired",e.HARD_OF_HEARING="hard of hearing"}(S||(S={})),function(e){e.SDR="SDR",e.PQ="PQ",e.HLG="HLG"}(y||(y={}));class U{static resolveUris(e,t){if(0==t.length)return e;if(1==e.length&&1==t.length){const i=new URL(e[0]);return[new URL(t[0],i).toString()]}const i=[];for(const n of e){const e=new URL(n);for(const n of t)i.push(new URL(n,e).toString())}return i}static createDrmInfo(e,t){return{keySystem:e,licenseServerUri:"",distinctiveIdentifierRequired:!1,persistentStateRequired:!1,audioRobustness:"",videoRobustness:"",serverCertificate:null,serverCertificateUri:"",sessionType:"",initData:t||[],keyIds:new Set}}static createDrmInfoFromClearKeys(e){const t=[],i=[],n=[];e.forEach(((e,s)=>{let a=s;22!=a.length&&(a=k.toBase64(k.fromHex(s),!1));let r=e;22!=r.length&&(r=k.toBase64(k.fromHex(e),!1));const o={kty:"oct",kid:a,k:r};t.push(o),i.push(o.kid),n.push(s)}));const s={keys:t},a=JSON.stringify(s),r=JSON.stringify({kids:i}),o=[{initData:d.toUint8(x.toUTF8(r)),initDataType:"keyids",keyId:null}];return{keySystem:"org.w3.clearkey",licenseServerUri:"data:application/json;base64,"+window.btoa(a),distinctiveIdentifierRequired:!1,persistentStateRequired:!1,audioRobustness:"",videoRobustness:"",serverCertificate:null,serverCertificateUri:"",sessionType:"",initData:o,keyIds:new Set(n)}}static guessCodecs(e,t){if(1==t.length)return t[0];const i=U.guessCodecsSafe(e,t);if(null!=i)return i;throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.HLS_COULD_NOT_GUESS_CODECS,t)}static guessCodecsSafe(e,t){const i=U.CODEC_REGEXPS_BY_CONTENT_TYPE_[e];for(const e of i)for(const i of t)if(e.test(i.trim()))return i.trim();return e==U.ContentType.TEXT?"":null}static guessAllCodecsSafe(e,t){const i=[],n=U.CODEC_REGEXPS_BY_CONTENT_TYPE_[e];for(const e of n)for(const n of t)e.test(n.trim())&&i.push(n.trim());return i}}U.ContentType=p,U.TextStreamKind=T,U.GAP_OVERLAP_TOLERANCE_SECONDS=1/15,U.VIDEO_CODEC_REGEXPS_=[/^avc/,/^hev/,/^hvc/,/^vvc/,/^vvi/,/^vp0?[89]/,/^av01/,/^dvh/,/^dva/,/^dav/],U.AUDIO_CODEC_REGEXPS_=[/^vorbis$/,/^Opus$/,/^opus$/,/^fLaC$/,/^flac$/,/^mp4a/,/^[ae]c-3$/,/^ac-4$/,/^dts[cex]$/,/^iamf/],U.TEXT_CODEC_REGEXPS_=[/^vtt$/,/^wvtt/,/^stpp/],U.CODEC_REGEXPS_BY_CONTENT_TYPE_={[p.AUDIO]:U.AUDIO_CODEC_REGEXPS_,[p.VIDEO]:U.VIDEO_CODEC_REGEXPS_,[p.TEXT]:U.TEXT_CODEC_REGEXPS_};class B{destroy(){}static registerTransmuxer(e,t,i){const n=B.normalizeMimeType_(e)+"-"+i;B.transmuxerMap_[n]={priority:i,plugin:t}}static unregisterTransmuxer(e,t){const i=B.normalizeMimeType_(e)+"-"+t;delete B.transmuxerMap_[i]}static findTransmuxer(e,t){const i=B.normalizeMimeType_(e),n=[B.PluginPriority.APPLICATION,B.PluginPriority.PREFERRED,B.PluginPriority.PREFERRED_SECONDARY,B.PluginPriority.FALLBACK];for(const s of n){const n=i+"-"+s,a=B.transmuxerMap_[n];if(a){const i=a.plugin(),n=i.isSupported(e,t);if(i.destroy(),n)return a.plugin}}return null}static normalizeMimeType_(e){return e.toLowerCase().split(";")[0]}static isSupported(e,t){return!!B.findTransmuxer(e)}static convertCodecs(e,t){const i=B.findTransmuxer(t);if(!i)return t;const n=i(),s=n.convertCodecs(e,t);return n.destroy(),s}}B.transmuxerMap_={},B.PluginPriority={FALLBACK:1,PREFERRED_SECONDARY:2,PREFERRED:3,APPLICATION:4};class F{static getFullType(e,t){let i=e;return t&&!F.RAW_FORMATS.includes(e)&&(i+='; codecs="'+t+'"'),i}static getFullTypeWithAllCodecs(e,t){let i=e;return t&&(i+='; codecs="'+t+'"'),i}static getFullOrConvertedType(e,t,i){const n=F.getFullType(e,t),s=F.getFullTypeWithAllCodecs(e,t),a=U.ContentType;return B.isSupported(s,i)?B.convertCodecs(i,s):"video/mp2t"!=e&&i==a.AUDIO?n.replace("video","audio"):n}static getExtendedType(e){const t=[e.mimeType];return F.EXTENDED_MIME_PARAMETERS_.forEach(((i,n)=>{const s=e[n];"codecs"==n&&F.RAW_FORMATS.includes(e.mimeType)||s&&t.push(i+'="'+s+'"')})),e.hdr===y.PQ&&t.push('eotf="smpte2084"'),t.join(";")}static getContainerType(e){return e.split(";")[0].split("/")[1]}static splitCodecs(e){return e.split(",")}static getNormalizedCodec(e){const t=F.getCodecParts_(e),i=t[0],n=t[1].toLowerCase();switch(!0){case"mp4a"===i&&"69"===n:case"mp4a"===i&&"6b"===n:case"mp4a"===i&&"40.34"===n:return"mp3";case"mp4a"===i&&"66"===n:case"mp4a"===i&&"67"===n:case"mp4a"===i&&"68"===n:case"mp4a"===i&&"40.2"===n:case"mp4a"===i&&"40.02"===n:case"mp4a"===i&&"40.5"===n:case"mp4a"===i&&"40.05"===n:case"mp4a"===i&&"40.29"===n:case"mp4a"===i&&"40.42"===n:return"aac";case"mp4a"===i&&"a5"===n:return"ac-3";case"mp4a"===i&&"a6"===n:return"ec-3";case"mp4a"===i&&"b2"===n:return"dtsx";case"mp4a"===i&&"a9"===n:return"dtsc";case"avc1"===i:case"avc3"===i:return"avc";case"hvc1"===i:case"hev1"===i:return"hevc";case"dvh1"===i:case"dvhe"===i:return"dovi"}return i}static getCodecBase(e){const t=[];for(const i of e.split(",")){const e=F.getCodecParts_(i);t.push(e[0])}return t.sort().join(",")}static getBasicType(e){return e.split(";")[0]}static getCodecs(e){const t=e.split(/ *; */);t.shift();const i=t.find((e=>e.startsWith("codecs=")));return i?i.split("=")[1].replace(/^"|"$/g,""):""}static isHlsType(e){return"application/x-mpegurl"===e||"application/vnd.apple.mpegurl"===e}static getCodecParts_(e){const t=e.split("."),i=t[0];return t.shift(),[i,t.join(".")]}}F.EXTENDED_MIME_PARAMETERS_=(new Map).set("codecs","codecs").set("frameRate","framerate").set("bandwidth","bitrate").set("width","width").set("height","height").set("channelsCount","channels"),F.CEA608_CLOSED_CAPTION_MIMETYPE="application/cea-608",F.CEA708_CLOSED_CAPTION_MIMETYPE="application/cea-708",F.RAW_FORMATS=["audio/aac","audio/ac3","audio/ec3","audio/mpeg"];class V{static createFallbackPromiseChain(e,t){return e.reduce(((e,i)=>e.catch((()=>t(i)))),Promise.reject())}static collapseArrays(e,t){return e.concat(t)}static ignored(...e){}static noop(){}static isNotNull(e){return null!=e}}class G{static isTypeSupported(e){const t=G.MediaSourceTypeSupportMap;if(t.has(e))return t.get(e);if(window.ManagedMediaSource){const i=ManagedMediaSource.isTypeSupported(e);return t.set(e,i),i}if(window.MediaSource){const i=MediaSource.isTypeSupported(e);return t.set(e,i),i}return!1}static isChangeTypeSupported(){return!!window.SourceBuffer&&!!SourceBuffer.prototype&&!!SourceBuffer.prototype.changeType}}G.MediaSourceTypeSupportMap=new Map;class H{static areLocaleCompatible(e,t){const i=i;return(e=i.normalize(e))==i.normalize(t)}static areLanguageCompatible(e,t){const i=i;e=i.normalize(e),t=i.normalize(t);const n=i.disassembleLocale_(e),s=i.disassembleLocale_(t);return n[0]==s[0]}static isParentOf(e,t){e=H.normalize(e),t=H.normalize(t);const i=H.disassembleLocale_(e),n=H.disassembleLocale_(t);return i[0]==n[0]&&1==i.length&&2==n.length}static isSiblingOf(e,t){e=H.normalize(e),t=H.normalize(t);const i=H.disassembleLocale_(e),n=H.disassembleLocale_(t);return 2==i.length&&2==n.length&&i[0]==n[0]}static normalize(e){const[t="",i=""]=e.split("-x-"),[n="",s=""]=t.split("-"),a=i?`x-${i}`:"";let r=n.toLowerCase();r=H.isoMap_.get(r)||r;const o=s.toUpperCase();return`${o?`${r}-${o}`:r}${a?`-${a}`:""}`}static areSiblings(e,t){const i=i,n=i.getBase(e),s=i.getBase(t);return e!=n&&t!=s&&n==s}static relatedness(e,t){const i=i;return e=i.normalize(e),(t=i.normalize(t))==e?4:i.isParentOf(t,e)?3:i.isSiblingOf(t,e)?2:i.isParentOf(e,t)?1:0}static getBase(e){const t=t,i=e.indexOf("-");let n;return n=i>=0?e.substring(0,i):e,n=n.toLowerCase(),n=t.isoMap_.get(n)||n,n}static getLocaleForText(e){const t=t,i=U.ContentType;console.assert(e.type==i.TEXT,"Can only get language from text streams");const n=e.language||"und";return t.normalize(n)}static getLocaleForVariant(e){return e.language?H.normalize(e.language):e.audio&&e.audio.language?H.normalize(e.audio.language):e.video&&e.video.language?H.normalize(e.video.language):"und"}static findClosestLocale(e,t){const i=H.normalize(e),n=new Set;for(const e of t)n.add(H.normalize(e));for(const e of n)if(e==i)return e;for(const e of n)if(H.isParentOf(e,i))return e;for(const e of n)if(H.isSiblingOf(e,i))return e;for(const e of n)if(H.isParentOf(i,e))return e;return null}static disassembleLocale_(e){const t=e.split("-");return console.assert(t.length<=2,["Locales should not have more than 2 components. ",e," has too many components."].join()),t}}H.isoMap_=new Map([["aar","aa"],["abk","ab"],["afr","af"],["aka","ak"],["alb","sq"],["amh","am"],["ara","ar"],["arg","an"],["arm","hy"],["asm","as"],["ava","av"],["ave","ae"],["aym","ay"],["aze","az"],["bak","ba"],["bam","bm"],["baq","eu"],["bel","be"],["ben","bn"],["bih","bh"],["bis","bi"],["bod","bo"],["bos","bs"],["bre","br"],["bul","bg"],["bur","my"],["cat","ca"],["ces","cs"],["cha","ch"],["che","ce"],["chi","zh"],["chu","cu"],["chv","cv"],["cor","kw"],["cos","co"],["cre","cr"],["cym","cy"],["cze","cs"],["dan","da"],["deu","de"],["div","dv"],["dut","nl"],["dzo","dz"],["ell","el"],["eng","en"],["epo","eo"],["est","et"],["eus","eu"],["ewe","ee"],["fao","fo"],["fas","fa"],["fij","fj"],["fin","fi"],["fra","fr"],["fre","fr"],["fry","fy"],["ful","ff"],["geo","ka"],["ger","de"],["gla","gd"],["gle","ga"],["glg","gl"],["glv","gv"],["gre","el"],["grn","gn"],["guj","gu"],["hat","ht"],["hau","ha"],["heb","he"],["her","hz"],["hin","hi"],["hmo","ho"],["hrv","hr"],["hun","hu"],["hye","hy"],["ibo","ig"],["ice","is"],["ido","io"],["iii","ii"],["iku","iu"],["ile","ie"],["ina","ia"],["ind","id"],["ipk","ik"],["isl","is"],["ita","it"],["jav","jv"],["jpn","ja"],["kal","kl"],["kan","kn"],["kas","ks"],["kat","ka"],["kau","kr"],["kaz","kk"],["khm","km"],["kik","ki"],["kin","rw"],["kir","ky"],["kom","kv"],["kon","kg"],["kor","ko"],["kua","kj"],["kur","ku"],["lao","lo"],["lat","la"],["lav","lv"],["lim","li"],["lin","ln"],["lit","lt"],["ltz","lb"],["lub","lu"],["lug","lg"],["mac","mk"],["mah","mh"],["mal","ml"],["mao","mi"],["mar","mr"],["may","ms"],["mkd","mk"],["mlg","mg"],["mlt","mt"],["mon","mn"],["mri","mi"],["msa","ms"],["mya","my"],["nau","na"],["nav","nv"],["nbl","nr"],["nde","nd"],["ndo","ng"],["nep","ne"],["nld","nl"],["nno","nn"],["nob","nb"],["nor","no"],["nya","ny"],["oci","oc"],["oji","oj"],["ori","or"],["orm","om"],["oss","os"],["pan","pa"],["per","fa"],["pli","pi"],["pol","pl"],["por","pt"],["pus","ps"],["que","qu"],["roh","rm"],["ron","ro"],["rum","ro"],["run","rn"],["rus","ru"],["sag","sg"],["san","sa"],["sin","si"],["slk","sk"],["slo","sk"],["slv","sl"],["sme","se"],["smo","sm"],["sna","sn"],["snd","sd"],["som","so"],["sot","st"],["spa","es"],["sqi","sq"],["srd","sc"],["srp","sr"],["ssw","ss"],["sun","su"],["swa","sw"],["swe","sv"],["tah","ty"],["tam","ta"],["tat","tt"],["tel","te"],["tgk","tg"],["tgl","tl"],["tha","th"],["tib","bo"],["tir","ti"],["ton","to"],["tsn","tn"],["tso","ts"],["tuk","tk"],["tur","tr"],["twi","tw"],["uig","ug"],["ukr","uk"],["urd","ur"],["uzb","uz"],["ven","ve"],["vie","vi"],["vol","vo"],["wel","cy"],["wln","wa"],["wol","wo"],["xho","xh"],["yid","yi"],["yor","yo"],["zha","za"],["zho","zh"],["zul","zu"]]);class W{init(e){}parse(e){return[]}}class q{extract(e,t){}decode(){return[]}clear(){}getStreams(){return[]}}class X{constructor(e){this.ceaParser_=new W;const t=X.findParser(e.toLowerCase());t&&(this.ceaParser_=t()),this.ceaDecoder_=new q;const i=X.findDecoder();i&&(this.ceaDecoder_=i())}init(e){this.ceaParser_.init(e)}parseFrom(e){const t=this.ceaParser_.parse(e);for(const e of t){const t=d.toUint8(e.packet);t.length>0&&this.ceaDecoder_.extract(t,e.pts)}return this.ceaDecoder_.decode()}reset(){this.ceaDecoder_.clear()}getStreams(){return this.ceaDecoder_.getStreams()}static registerParser(e,t){X.parserMap_[e]=t}static unregisterParser(e){delete X.parserMap_[e]}static findParser(e){return X.parserMap_[e]}static registerDecoder(e){X.decoderFactory_=e}static unregisterDecoder(){X.decoderFactory_=null}static findDecoder(){return X.decoderFactory_}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}X.parserMap_={},X.decoderFactory_=null;class z{constructor(e){this.parser_=null,this.displayer_=e,this.segmentRelativeVttTiming_=!1,this.timestampOffset_=0,this.appendWindowStart_=0,this.appendWindowEnd_=1/0,this.bufferStart_=null,this.bufferEnd_=null,this.selectedClosedCaptionId_="",this.modifyCueCallback_=(e,t)=>{},this.closedCaptionsMap_=new Map}static registerParser(e,t){z.parserMap_[e]=t}static unregisterParser(e){delete z.parserMap_[e]}static findParser(e){return z.parserMap_[e]}static isTypeSupported(e){return!!z.parserMap_[e]||(e==F.CEA608_CLOSED_CAPTION_MIMETYPE||e==F.CEA708_CLOSED_CAPTION_MIMETYPE)&&Boolean(X.findDecoder())}destroy(){return this.parser_=null,this.displayer_=null,this.closedCaptionsMap_.clear(),Promise.resolve()}setDisplayer(e){this.displayer_=e}initParser(e,t,i,s){if(e==F.CEA608_CLOSED_CAPTION_MIMETYPE||e==F.CEA708_CLOSED_CAPTION_MIMETYPE)return void(this.parser_=null);const a=z.parserMap_[e];console.assert(a,"Text type negotiation should have happened already"),this.parser_=a(),this.parser_.setSequenceMode?this.parser_.setSequenceMode(t):n.alwaysWarn('Text parsers should have a "setSequenceMode" method!'),this.parser_.setManifestType?this.parser_.setManifestType(s):n.alwaysWarn('Text parsers should have a "setManifestType" method!'),this.segmentRelativeVttTiming_=i}setModifyCueCallback(e){this.modifyCueCallback_=e}async appendBuffer(e,t,i,n){if(console.assert(this.parser_,"The parser should already be initialized"),await Promise.resolve(),!this.parser_||!this.displayer_)return;if(null==t||null==i)return void this.parser_.parseInit(d.toUint8(e));const s=this.segmentRelativeVttTiming_?t:this.timestampOffset_,a={periodStart:this.timestampOffset_,segmentStart:t,segmentEnd:i,vttOffset:s},r=this.parser_.parseMedia(d.toUint8(e),a,n);for(const e of r)this.modifyCueCallback_(e,n||null,a);const o=r.filter((e=>e.startTime>=this.appendWindowStart_&&e.startTime<this.appendWindowEnd_));this.displayer_.append(o),null==this.bufferStart_?this.bufferStart_=Math.max(t,this.appendWindowStart_):(console.assert(null!=this.bufferEnd_,"There should already be a buffered range end."),console.assert(t-this.bufferEnd_<=1,"There should not be a gap in text references >1s")),this.bufferEnd_=Math.min(i,this.appendWindowEnd_)}async remove(e,t){await Promise.resolve(),this.displayer_&&this.displayer_.remove(e,t)&&(null==this.bufferStart_?console.assert(null==this.bufferEnd_,"end must be null if startTime is null"):(console.assert(null!=this.bufferEnd_,"end must be non-null if startTime is non-null"),t<=this.bufferStart_||e>=this.bufferEnd_||(e<=this.bufferStart_&&t>=this.bufferEnd_?this.bufferStart_=this.bufferEnd_=null:e<=this.bufferStart_&&t<this.bufferEnd_?this.bufferStart_=t:e>this.bufferStart_&&t>=this.bufferEnd_?this.bufferEnd_=e:console.assert(!1,"removal from the middle is not supported by TextEngine"))))}setTimestampOffset(e){this.timestampOffset_=e}setAppendWindow(e,t){this.appendWindowStart_=e,this.appendWindowEnd_=t}bufferStart(){return this.bufferStart_}bufferEnd(){return this.bufferEnd_}isBuffered(e){return null!=this.bufferStart_&&null!=this.bufferEnd_&&e>=this.bufferStart_&&e<this.bufferEnd_}bufferedAheadOf(e){return null==this.bufferEnd_||this.bufferEnd_<e?0:(console.assert(null!=this.bufferStart_,"start should not be null if end is not null"),this.bufferEnd_-Math.max(e,this.bufferStart_))}setSelectedClosedCaptionId(e,t){this.selectedClosedCaptionId_=e;const i=this.closedCaptionsMap_.get(e);if(i)for(const e of i.keys()){const n=i.get(e).filter((e=>e.endTime<=t));n&&this.displayer_.append(n)}}applyVideoTimestampOffsetRecursive_(e,t){e.startTime+=t,e.endTime+=t;for(const i of e.nestedCues)this.applyVideoTimestampOffsetRecursive_(i,t)}storeAndAppendClosedCaptions(e,t,i,n){const s=t+" "+i,a=new Map;for(const t of e){const e=t.stream,i=t.cue;a.has(e)||a.set(e,new Map),a.get(e).has(s)||a.get(e).set(s,[]),this.applyVideoTimestampOffsetRecursive_(i,n),i.startTime>=this.appendWindowStart_&&i.startTime<this.appendWindowEnd_&&(a.get(e).get(s).push(i),e==this.selectedClosedCaptionId_&&this.displayer_.append([i]))}for(const e of a.keys()){this.closedCaptionsMap_.has(e)||this.closedCaptionsMap_.set(e,new Map);for(const t of a.get(e).keys()){const i=a.get(e).get(t);this.closedCaptionsMap_.get(e).set(t,i)}}null==this.bufferStart_?this.bufferStart_=Math.max(t,this.appendWindowStart_):this.bufferStart_=Math.min(this.bufferStart_,Math.max(t,this.appendWindowStart_)),this.bufferEnd_=Math.max(this.bufferEnd_,Math.min(i,this.appendWindowEnd_))}getNumberOfClosedCaptionChannels(){return this.closedCaptionsMap_.size}getNumberOfClosedCaptionsInChannel(e){const t=this.closedCaptionsMap_.get(e);return t?t.size:0}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}z.parserMap_={};class j{static chooseCodecsAndFilterManifest(e,t,i,a){let r=e.variants;if((t.length||i.length)&&(r=j.choosePreferredCodecs(r,t,i)),a.length){const e=new s;for(const t of r)e.push(String(t.video.width||0),t);const t=[];e.forEach(((e,i)=>{let n=0,s=[];for(const e of i){const t=a.filter((t=>e.decodingInfos[0][t])).length;t>n?(n=t,s=[e]):t==n&&s.push(e)}t.push(...s)})),r=t}const o=new Set,l=new Set;for(const e of r)e.audio&&o.add(e.audio),e.video&&l.add(e.video);const d=Array.from(o).sort(((e,t)=>e.bandwidth-t.bandwidth)),c=[],h=new Map,u=e=>e.language+(e.channelsCount||0)+(e.audioSamplingRate||0)+e.roles.join(",")+e.label+e.groupId+e.fastSwitching;for(const e of d){const t=u(e),i=h.get(t)||[];if(i.length){const t=i[i.length-1];F.getNormalizedCodec(t.codecs)==F.getNormalizedCodec(e.codecs)&&e.bandwidth>t.bandwidth&&(i.push(e),c.push(e.id))}else i.push(e),c.push(e.id);h.set(t,i)}const _=Array.from(l).sort(((e,t)=>e.bandwidth&&t.bandwidth?e.bandwidth-t.bandwidth:e.width-t.width)),m=G.isChangeTypeSupported(),g=[],f=new Map,p=e=>Math.round(e.frameRate||0)+(e.hdr||"")+e.fastSwitching;for(const e of _){const t=p(e),i=f.get(t)||[];if(i.length){const t=i[i.length-1];if(!m&&F.getNormalizedCodec(t.codecs)!==F.getNormalizedCodec(e.codecs))continue;(e.width>t.width||e.height>t.height||e.width==t.width&&e.height==t.height&&F.getNormalizedCodec(t.codecs)==F.getNormalizedCodec(e.codecs)&&e.bandwidth>t.bandwidth)&&(i.push(e),g.push(e.id))}else i.push(e),g.push(e.id);f.set(t,i)}e.variants=e.variants.filter((e=>{const t=e.audio,i=e.video;return t&&!c.includes(t.id)?(n.debug("Dropping Variant (better codec available)",e),!1):!(i&&!g.includes(i.id)&&(n.debug("Dropping Variant (better codec available)",e),1))}))}static choosePreferredCodecs(e,t,i){let n=e;for(const e of t){const t=n.filter((t=>t.video&&t.video.codecs.startsWith(e)));if(t.length){n=t;break}}for(const e of i){const t=n.filter((t=>t.audio&&t.audio.codecs.startsWith(e)));if(t.length){n=t;break}}return n}static filterByRestrictions(e,t,i){e.variants=e.variants.filter((e=>j.meetsRestrictions(e,t,i)))}static meetsRestrictions(e,t,i){const n=(e,t,i)=>e>=t&&e<=i,s=e.video;if(s&&s.width&&s.height){let e=s.width,a=s.height;if(a>e&&([e,a]=[a,e]),!n(e,t.minWidth,Math.min(t.maxWidth,i.width)))return!1;if(!n(a,t.minHeight,Math.min(t.maxHeight,i.height)))return!1;if(!n(s.width*s.height,t.minPixels,t.maxPixels))return!1}return!(e&&e.video&&e.video.frameRate&&!n(e.video.frameRate,t.minFrameRate,t.maxFrameRate)||!n(e.bandwidth,t.minBandwidth,t.maxBandwidth))}static applyRestrictions(e,t,i){let n=!1;for(const s of e){const e=s.allowedByApplication;s.allowedByApplication=j.meetsRestrictions(s,t,i),e!=s.allowedByApplication&&(n=!0)}return n}static async filterManifest(e){await j.filterManifestByMediaCapabilities(e,e.offlineSessionIds.length>0),j.filterTextStreams_(e),await j.filterImageStreams_(e)}static async filterManifestByMediaCapabilities(e,t){console.assert(navigator.mediaCapabilities,"MediaCapabilities should be valid."),await j.getDecodingInfosForVariants(e.variants,t,!1,[]);const i=U.ContentType,s=N.isXboxOne(),a=N.isFirefox()&&N.isAndroid();e.variants=e.variants.filter((e=>{const t=e.video,r=t&&t.width||0,o=t&&t.height||0;if(s&&t&&(r>1920||o>1080)&&(t.codecs.includes("avc1.")||t.codecs.includes("avc3.")))return n.debug("Dropping variant - not compatible with platform",j.getVariantSummaryString_(e)),!1;if(t){let e=j.getCorrectVideoCodecs_(t.codecs);if(t.codecs.includes(",")){const n=t.codecs.split(",");e=U.guessCodecs(i.VIDEO,n),e=j.getCorrectVideoCodecs_(e);let s=U.guessCodecs(i.AUDIO,n);s=j.getCorrectAudioCodecs_(s);const a=F.getFullOrConvertedType(t.mimeType,s,i.AUDIO);if(!Capabilities.isTypeSupported(a))return!1;e=[e,s].join(",")}const n=F.getFullOrConvertedType(t.mimeType,e,i.VIDEO);if(!G.isTypeSupported(n))return!1;t.codecs=e}const l=e.audio;if(a&&l&&l.encrypted&&l.codecs.toLowerCase().includes("opus"))return n.debug("Dropping variant - not compatible with platform",j.getVariantSummaryString_(e)),!1;if(l){const e=j.getCorrectAudioCodecs_(l.codecs),t=F.getFullOrConvertedType(l.mimeType,e,i.AUDIO);if(!G.isTypeSupported(t))return!1;l.codecs=e}const d=e.decodingInfos.some((e=>!!e.supported));return d||n.debug("Dropping variant - not compatible with platform",j.getVariantSummaryString_(e)),d}))}static alphabeticalKeyOrderStringify_(e){const t=[];for(const i in e)t.push(i);t.sort();const i=[];for(const n of t){const t=JSON.stringify(n),s=e[n];if(s instanceof Object){const e=j.alphabeticalKeyOrderStringify_(s);i.push(t+":"+e)}else{const e=JSON.stringify(s);i.push(t+":"+e)}}return"{"+i.join(",")+"}"}static async getDecodingInfosForVariant_(e,t){const i=j.alphabeticalKeyOrderStringify_(t),s=j.decodingConfigCache_;if(s[i])n.v2("Using cached results of mediaCapabilities.decodingInfo","for key",i),e.decodingInfos.push(s[i]);else{const n=await j.checkEachDecodingConfigCombination_(t);if(n&&n.length){let t=null;for(const e of n)t?(t.supported=t.supported&&e.supported,t.powerEfficient=t.powerEfficient&&e.powerEfficient,t.smooth=t.smooth&&e.smooth,e.keySystemAccess||(t.keySystemAccess=null)):t=e;t&&(s[i]=t,e.decodingInfos.push(t))}}}static checkEachDecodingConfigCombination_(e){let t=[""];e.video&&(t=F.getCodecs(e.video.contentType).split(","));let i=[""];e.audio&&(i=F.getCodecs(e.audio.contentType).split(","));const s=[];for(const n of t)for(const t of i){const i=w.cloneObject(e);if(e.video){const e=F.getBasicType(i.video.contentType);i.video.contentType=F.getFullType(e,n)}if(e.audio){const e=F.getBasicType(i.audio.contentType);i.audio.contentType=F.getFullType(e,t)}s.push(new Promise(((e,t)=>{navigator.mediaCapabilities.decodingInfo(i).then((t=>{e(t)})).catch(t)})))}return Promise.all(s).catch((t=>(n.info("MediaCapabilities.decodingInfo() failed.",JSON.stringify(e),t),null)))}static async getDecodingInfosForVariants(e,t,i,s){if(e.some((e=>e.decodingInfos.length)))n.debug("Already got the variants' decodingInfo.");else{for(const n of s){let s=!1;for(const a of e){const e=j.getDecodingConfigs_(a,t,i).filter((e=>(e.keySystemConfiguration&&e.keySystemConfiguration.keySystem)===n));for(const t of e)await j.getDecodingInfosForVariant_(a,t);a.decodingInfos.length&&(s=!0)}if(s)return}for(const n of e){const e=j.getDecodingConfigs_(n,t,i).filter((e=>{const t=e.keySystemConfiguration&&e.keySystemConfiguration.keySystem;return!t||!s.includes(t)}));for(const t of e)await j.getDecodingInfosForVariant_(n,t)}}}static getDecodingConfigs_(e,t,i){const s=e.audio,a=e.video,r=U.ContentType,o={type:i?"file":"media-source"};if(a){let t=a.codecs;if(a.codecs.includes(",")){const i=a.codecs.split(",");t=U.guessCodecs(r.VIDEO,i),t=j.getCorrectVideoCodecs_(t);let n=U.guessCodecs(r.AUDIO,i);n=j.getCorrectAudioCodecs_(n);const s=F.getFullOrConvertedType(a.mimeType,n,r.AUDIO);o.audio={contentType:s,channels:2,bitrate:e.bandwidth||1,samplerate:1,spatialRendering:!1}}t=j.getCorrectVideoCodecs_(t);const i=F.getFullOrConvertedType(a.mimeType,t,r.VIDEO);if(o.video={contentType:i,width:a.width||64,height:a.height||64,bitrate:a.bandwidth||e.bandwidth||1,framerate:a.frameRate||1},a.hdr)switch(a.hdr){case"SDR":o.video.transferFunction="srgb";break;case"PQ":o.video.transferFunction="pq";break;case"HLG":o.video.transferFunction="hlg"}}if(s){const t=j.getCorrectAudioCodecs_(s.codecs),i=F.getFullOrConvertedType(s.mimeType,t,r.AUDIO);o.audio={contentType:i,channels:s.channelsCount||2,bitrate:s.bandwidth||e.bandwidth||1,samplerate:s.audioSamplingRate||1,spatialRendering:s.spatialAudio}}const l=e.video?e.video.drmInfos:[],d=e.audio?e.audio.drmInfos:[],c=l.concat(d);if(!c.length)return[o];const h=[],u=new Map;for(const e of c)u.get(e.keySystem)||u.set(e.keySystem,[]),u.get(e.keySystem).push(e);const _=t?"required":"optional",m=t?["persistent-license"]:["temporary"];for(const e of u.keys()){const t=Object.assign({},o),i=u.get(e),r={keySystem:e,initDataType:"cenc",persistentState:_,distinctiveIdentifier:"optional",sessionTypes:m};for(const e of i){if(e.initData&&e.initData.length){const t=new Set;for(const i of e.initData)t.add(i.initDataType);t.size>1&&n.v2("DrmInfo contains more than one initDataType,","and we use the initDataType of the first initData.",e),r.initDataType=e.initData[0].initDataType}e.distinctiveIdentifierRequired&&(r.distinctiveIdentifier="required"),e.persistentStateRequired&&(r.persistentState="required"),e.sessionType&&(r.sessionTypes=[e.sessionType]),s&&(""!=e.audioRobustness?r.audio?r.audio.robustness=r.audio.robustness||e.audioRobustness:r.audio={robustness:e.audioRobustness}:r.audio||(r.audio={})),a&&(""!=e.videoRobustness?r.video?r.video.robustness=r.video.robustness||e.videoRobustness:r.video={robustness:e.videoRobustness}:r.video||(r.video={}))}t.keySystemConfiguration=r,h.push(t)}return h}static getCorrectAudioCodecs_(e){return"fLaC"!==e||N.isSafari()?"Opus"===e?"opus":e:"flac"}static getCorrectVideoCodecs_(e){if(e.includes("avc1")){const t=e.split(".");if(3==t.length){let e=t.shift()+".";return e+=parseInt(t.shift(),10).toString(16),e+=("000"+parseInt(t.shift(),10).toString(16)).slice(-4),e}}else if("vp9"==e)return"vp09.00.41.08";return e}static filterManifestByCurrentVariant(e,t){const i=i;t.variants=t.variants.filter((t=>{const s=t.audio,a=t.video;return s&&e&&e.audio&&!i.areStreamsCompatible_(s,e.audio)?(n.debug("Dropping variant - not compatible with active audio","active audio",i.getStreamSummaryString_(e.audio),"variant.audio",i.getStreamSummaryString_(s)),!1):!(a&&e&&e.video&&!i.areStreamsCompatible_(a,e.video)&&(n.debug("Dropping variant - not compatible with active video","active video",i.getStreamSummaryString_(e.video),"variant.video",i.getStreamSummaryString_(a)),1))}))}static filterTextStreams_(e){e.textStreams=e.textStreams.filter((e=>{const t=F.getFullType(e.mimeType,e.codecs),i=z.isTypeSupported(t);return i||n.debug("Dropping text stream. Is not supported by the platform.",e),i}))}static async filterImageStreams_(e){const t=[];for(const i of e.imageStreams){let e=i.mimeType;if("application/mp4"==e&&"mjpg"==i.codecs&&(e="image/jpg"),!j.supportedImageMimeTypes_.has(e)){const t=j.minImage_.get(e);if(t){const i=await j.isImageSupported_(t);j.supportedImageMimeTypes_.set(e,i)}else j.supportedImageMimeTypes_.set(e,!1)}j.supportedImageMimeTypes_.get(e)?t.push(i):n.debug("Dropping image stream. Is not supported by the platform.",i)}e.imageStreams=t}static isImageSupported_(e){return new Promise((t=>{const i=new Image;i.src=e,"decode"in i?i.decode().then((()=>{t(!0)})).catch((()=>{t(!1)})):i.onload=i.onerror=()=>{t(2===i.height)}}))}static areStreamsCompatible_(e,t){return e.mimeType==t.mimeType&&e.codecs.split(".")[0]==t.codecs.split(".")[0]}static variantToTrack(e){const t=e.audio,i=e.video,n=t?t.mimeType:null,s=i?i.mimeType:null,a=t?t.codecs:null,r=i?i.codecs:null,o=[];r&&o.push(r),a&&o.push(a);const l=[];i&&l.push(i.mimeType),t&&l.push(t.mimeType);const d=l[0]||null,c=[];t&&c.push(t.kind),i&&c.push(i.kind);const h=c[0]||null,u=new Set;if(t)for(const e of t.roles)u.add(e);if(i)for(const e of i.roles)u.add(e);const _={id:e.id,active:!1,type:"variant",bandwidth:e.bandwidth,language:e.language,label:null,kind:h,width:null,height:null,frameRate:null,pixelAspectRatio:null,hdr:null,videoLayout:null,mimeType:d,audioMimeType:n,videoMimeType:s,codecs:o.join(", "),audioCodec:a,videoCodec:r,primary:e.primary,roles:Array.from(u),audioRoles:null,forced:!1,videoId:null,audioId:null,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,tilesLayout:null,audioBandwidth:null,videoBandwidth:null,originalVideoId:null,originalAudioId:null,originalTextId:null,originalImageId:null,accessibilityPurpose:null,originalLanguage:null};return i&&(_.videoId=i.id,_.originalVideoId=i.originalId,_.width=i.width||null,_.height=i.height||null,_.frameRate=i.frameRate||null,_.pixelAspectRatio=i.pixelAspectRatio||null,_.videoBandwidth=i.bandwidth||null,_.hdr=i.hdr||null,_.videoLayout=i.videoLayout||null),t&&(_.audioId=t.id,_.originalAudioId=t.originalId,_.channelsCount=t.channelsCount,_.audioSamplingRate=t.audioSamplingRate,_.audioBandwidth=t.bandwidth||null,_.spatialAudio=t.spatialAudio,_.label=t.label,_.audioRoles=t.roles,_.accessibilityPurpose=t.accessibilityPurpose,_.originalLanguage=t.originalLanguage),_}static textStreamToTrack(e){const t=U.ContentType;return{id:e.id,active:!1,type:t.TEXT,bandwidth:0,language:e.language,label:e.label,kind:e.kind||null,width:null,height:null,frameRate:null,pixelAspectRatio:null,hdr:null,videoLayout:null,mimeType:e.mimeType,audioMimeType:null,videoMimeType:null,codecs:e.codecs||null,audioCodec:null,videoCodec:null,primary:e.primary,roles:e.roles,audioRoles:null,forced:e.forced,videoId:null,audioId:null,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,tilesLayout:null,audioBandwidth:null,videoBandwidth:null,originalVideoId:null,originalAudioId:null,originalTextId:e.originalId,originalImageId:null,accessibilityPurpose:e.accessibilityPurpose,originalLanguage:e.originalLanguage}}static imageStreamToTrack(e){const t=U.ContentType;let i=e.width||null,n=e.height||null,s=null;e.segmentIndex&&(s=e.segmentIndex.get(0));let a=e.tilesLayout;return s&&(a=s.getTilesLayout()||a),a&&null!=i&&(i/=Number(a.split("x")[0])),a&&null!=n&&(n/=Number(a.split("x")[1])),{id:e.id,active:!1,type:t.IMAGE,bandwidth:e.bandwidth||0,language:"",label:null,kind:null,width:i,height:n,frameRate:null,pixelAspectRatio:null,hdr:null,videoLayout:null,mimeType:e.mimeType,audioMimeType:null,videoMimeType:null,codecs:e.codecs||null,audioCodec:null,videoCodec:null,primary:!1,roles:[],audioRoles:null,forced:!1,videoId:null,audioId:null,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,tilesLayout:a||null,audioBandwidth:null,videoBandwidth:null,originalVideoId:null,originalAudioId:null,originalTextId:null,originalImageId:e.originalId,accessibilityPurpose:null,originalLanguage:null}}static html5TrackId(e){return e.__shaka_id||(e.__shaka_id=j.nextTrackId_++),e.__shaka_id}static html5TextTrackToTrack(e){const t=F.CEA608_CLOSED_CAPTION_MIMETYPE,i=i,n=i.html5TrackToGenericShakaTrack_(e);return n.active="disabled"!=e.mode,n.type="text",n.originalTextId=e.id,"captions"==e.kind&&(n.mimeType=t),"subtitles"==e.kind&&(n.mimeType="text/vtt"),e.kind&&(n.roles=[e.kind]),"forced"==e.kind&&(n.forced=!0),n}static html5AudioTrackToTrack(e){const t=t,i=t.html5TrackToGenericShakaTrack_(e);return i.active=e.enabled,i.type="variant",i.originalAudioId=e.id,"main"==e.kind&&(i.primary=!0),e.kind&&(i.roles=[e.kind],i.audioRoles=[e.kind],i.label=e.label),i}static html5TrackToGenericShakaTrack_(e){const t=e.language;return{id:j.html5TrackId(e),active:!1,type:"",bandwidth:0,language:H.normalize(t||"und"),label:e.label,kind:e.kind,width:null,height:null,frameRate:null,pixelAspectRatio:null,hdr:null,videoLayout:null,mimeType:null,audioMimeType:null,videoMimeType:null,codecs:null,audioCodec:null,videoCodec:null,primary:!1,roles:[],forced:!1,audioRoles:null,videoId:null,audioId:null,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,tilesLayout:null,audioBandwidth:null,videoBandwidth:null,originalVideoId:null,originalAudioId:null,originalTextId:null,originalImageId:null,accessibilityPurpose:null,originalLanguage:t}}static isPlayable(e){return e.allowedByApplication&&e.allowedByKeySystem&&0==e.disabledUntilTime}static getPlayableVariants(e){return e.filter((e=>j.isPlayable(e)))}static filterStreamsByLanguageAndRole(e,t,i,s){let a=e;const r=e.filter((e=>e.primary));r.length&&(a=r);const o=a.length?a[0].language:"";if(a=a.filter((e=>e.language==o)),t){const i=H.findClosestLocale(H.normalize(t),e.map((e=>e.language)));i&&(a=e.filter((e=>H.normalize(e.language)==i)))}if(a=a.filter((e=>e.forced==s)),i){const e=j.filterStreamsByRole_(a,i);if(e.length)return e;n.warning("No exact match for the text role could be found.")}else{const e=a.filter((e=>0==e.roles.length));if(e.length)return e}const l=a.map((e=>e.roles)).reduce(V.collapseArrays,[]);return l.length?j.filterStreamsByRole_(a,l[0]):a}static filterStreamsByRole_(e,t){return e.filter((e=>e.roles.includes(t)))}static isAudio(e){const t=U.ContentType;return e.type==t.AUDIO}static isVideo(e){const t=U.ContentType;return e.type==t.VIDEO}static getVariantStreams(e){const t=[];return e.audio&&t.push(e.audio),e.video&&t.push(e.video),t}static isFastSwitching(e){return!(!e.audio||!e.audio.fastSwitching)||!(!e.video||!e.video.fastSwitching)}static getVariantSummaryString_(e){const t=[];return e.audio&&t.push(j.getStreamSummaryString_(e.audio)),e.video&&t.push(j.getStreamSummaryString_(e.video)),t.join(", ")}static getStreamSummaryString_(e){return j.isAudio(e)?"type=audio codecs="+e.codecs+" bandwidth="+e.bandwidth+" channelsCount="+e.channelsCount+" audioSamplingRate="+e.audioSamplingRate:j.isVideo(e)?"type=video codecs="+e.codecs+" bandwidth="+e.bandwidth+" frameRate="+e.frameRate+" width="+e.width+" height="+e.height:"unexpected stream type"}}j.decodingConfigCache_={},j.nextTrackId_=0,j.DecodingAttributes={SMOOTH:"smooth",POWER:"powerEfficient"},j.supportedImageMimeTypes_=(new Map).set("image/svg+xml",!0).set("image/png",!0).set("image/jpeg",!0).set("image/jpg",!0),j.minWebPImage_="data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA",j.minAvifImage_="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A=",j.minImage_=(new Map).set("image/webp",j.minWebPImage_).set("image/avif",j.minAvifImage_);class Y{static async isFairPlaySupported(){const e={initDataTypes:["cenc","sinf","skd"],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42E01E"'}]};try{return await navigator.requestMediaKeySystemAccess("com.apple.fps",[e]),!0}catch(e){return!1}}static defaultGetContentId(e){const t=x.fromBytesAutoDetect(e);return new URL(t).hostname}static initDataTransform(e,t,i){if(!i||!i.byteLength)throw new b(b.Severity.CRITICAL,b.Category.DRM,b.Code.SERVER_CERTIFICATE_REQUIRED);let n;n="string"==typeof t?x.toUTF16(t,!0):t;const s=x.fromBytesAutoDetect(e),a=x.toUTF16(s,!0),r=new Uint8Array(12+a.byteLength+n.byteLength+i.byteLength);let o=0;const l=e=>{const t=d.toDataView(r),i=e.byteLength;t.setUint32(o,i,!0),o+=4,(e=>{r.set(d.toUint8(e),o),o+=e.byteLength})(e)};return l(a),l(n),l(i),console.assert(o==r.length,"Inconsistent init data length"),r}static basicInitDataTransform_(e,t,i){if("skd"!==t)return e;const n=n,s=s,a=i.serverCertificate,r=n.fromBytesAutoDetect(e).split("skd://").pop();return s.initDataTransform(e,r,a)}static verimatrixInitDataTransform(e,t,i){return Y.basicInitDataTransform_(e,t,i)}static ezdrmInitDataTransform(e,t,i){if("skd"!==t)return e;const n=n,s=s,a=i.serverCertificate,r=n.fromBytesAutoDetect(e).split(";").pop();return s.initDataTransform(e,r,a)}static conaxInitDataTransform(e,t,i){if("skd"!==t)return e;const n=n,s=s,a=i.serverCertificate,r=n.fromBytesAutoDetect(e).split("skd://").pop().split("?").shift(),o=(e=>{const t=new ArrayBuffer(2*e.length),i=d.toUint16(t);for(let t=0,n=e.length;t<n;t++)i[t]=e.charCodeAt(t);return i})(window.atob(r));return s.initDataTransform(e,o,a)}static expressplayInitDataTransform(e,t,i){return Y.basicInitDataTransform_(e,t,i)}static verimatrixFairPlayRequest(e,t,i){if(e!==D.RequestType.LICENSE)return;const n=t.body,s=d.toUint8(n),a=k.toBase64(s);t.headers["Content-Type"]="application/x-www-form-urlencoded",t.body=x.toUTF8("spc="+a)}static octetStreamFairPlayRequest_(e,t,i){e===D.RequestType.LICENSE&&(t.headers["Content-Type"]="application/octet-stream")}static ezdrmFairPlayRequest(e,t,i){Y.octetStreamFairPlayRequest_(e,t)}static conaxFairPlayRequest(e,t,i){Y.octetStreamFairPlayRequest_(e,t)}static expressplayFairPlayRequest(e,t,i){Y.octetStreamFairPlayRequest_(e,t)}static commonFairPlayResponse(e,t,i){if(e!==D.RequestType.LICENSE)return;let n;try{n=x.fromUTF8(t.data)}catch(e){return}let s=!1;n=n.trim(),"<ckc>"===n.substr(0,5)&&"</ckc>"===n.substr(-6)&&(n=n.slice(5,-6),s=!0);try{const e=JSON.parse(n);e.ckc&&(n=e.ckc,s=!0),e.CkcMessage&&(n=e.CkcMessage,s=!0),e.License&&(n=e.License,s=!0)}catch(e){}s&&(t.data=d.toArrayBuffer(k.fromBase64(n)))}}class K{static mergeConfigObjects(e,t,i,s,a){console.assert(e,"Destination config must not be null!");const r=a in s;let o=!0;for(const l in t){const d=a+"."+l,c=r?s[a]:i[l];if(r||l in i)if(void 0===t[l])void 0===c||r?delete e[l]:e[l]=w.cloneObject(c);else if(c.constructor==Object&&t[l]&&t[l].constructor==Object){e[l]||(e[l]=w.cloneObject(c));const i=K.mergeConfigObjects(e[l],t[l],c,s,d);o=o&&i}else typeof t[l]!=typeof c||null==t[l]||"function"!=typeof t[l]&&t[l].constructor!=c.constructor?(n.alwaysError("Invalid config, wrong type for "+d),o=!1):"function"==typeof i[l]&&i[l].length!=t[l].length?(n.alwaysWarn("Unexpected number of arguments for "+d),e[l]=t[l]):e[l]=t[l];else n.alwaysError("Invalid config, unrecognized key "+d),o=!1}return o}static convertToConfigObject(e,t){const i={};let n=i,s=0,a=0;for(;;){const t=e.indexOf(".",s);if(t<0)break;if(0==t||"\\"!=e[t-1]){const i=e.substring(a,t).replace(/\\\./g,".");n[i]={},n=n[i],a=t+1}s=t+1}return n[e.substring(a).replace(/\\\./g,".")]=t,i}static referenceParametersAndReturn(e,t){return e&&t}}class Q{constructor(e){console.assert(e>0,"expected halfLife to be positive"),this.alpha_=Math.exp(Math.log(.5)/e),this.estimate_=0,this.totalWeight_=0}updateAlpha(e){console.assert(e>0,"expected halfLife to be positive"),this.alpha_=Math.exp(Math.log(.5)/e)}sample(e,t){const i=Math.pow(this.alpha_,e),n=t*(1-i)+i*this.estimate_;isNaN(n)||(this.estimate_=n,this.totalWeight_+=e)}getEstimate(){const e=1-Math.pow(this.alpha_,this.totalWeight_);return this.estimate_/e}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class ${constructor(){this.fast_=new Q(2),this.slow_=new Q(5),this.bytesSampled_=0,this.minTotalBytes_=128e3,this.minBytes_=16e3}configure(e){this.minTotalBytes_=e.minTotalBytes,this.minBytes_=e.minBytes,this.fast_.updateAlpha(e.fastHalfLife),this.slow_.updateAlpha(e.slowHalfLife)}sample(e,t){if(t<this.minBytes_)return;const i=8e3*t/e,n=e/1e3;this.bytesSampled_+=t,this.fast_.sample(n,i),this.slow_.sample(n,i)}getBandwidthEstimate(e){return this.bytesSampled_<this.minTotalBytes_?e:Math.min(this.fast_.getEstimate(),this.slow_.getEstimate())}hasGoodEstimate(){return this.bytesSampled_>=this.minTotalBytes_}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class J{constructor(){this.switch_=null,this.enabled_=!1,this.bandwidthEstimator_=new $,this.onNetworkInformationChange_=null,navigator.connection&&navigator.connection.addEventListener&&(this.onNetworkInformationChange_=()=>{if(this.enabled_&&this.config_.useNetworkInformation){this.bandwidthEstimator_=new $,this.config_&&this.bandwidthEstimator_.configure(this.config_.advanced);const e=this.chooseVariant();e&&navigator.onLine&&this.switch_(e,this.config_.clearBufferSwitch,this.config_.safeMarginSwitch)}},navigator.connection.addEventListener("change",this.onNetworkInformationChange_)),this.variants_=[],this.playbackRate_=1,this.startupComplete_=!1,this.lastTimeChosenMs_=null,this.config_=null,this.mediaElement_=null,this.resizeObserver_=null,this.resizeObserverTimer_=new l((()=>{if(this.config_.restrictToElementSize){const e=this.chooseVariant();e&&this.switch_(e,this.config_.clearBufferSwitch,this.config_.safeMarginSwitch)}})),this.cmsdManager_=null}stop(){this.switch_=null,this.enabled_=!1,this.variants_=[],this.playbackRate_=1,this.lastTimeChosenMs_=null,this.mediaElement_=null,this.resizeObserver_&&(this.resizeObserver_.disconnect(),this.resizeObserver_=null),this.resizeObserverTimer_.stop(),this.cmsdManager_=null}release(){navigator.connection&&navigator.connection.removeEventListener&&(navigator.connection.removeEventListener("change",this.onNetworkInformationChange_),this.onNetworkInformationChange_=null),this.resizeObserverTimer_=null}init(e){this.switch_=e}chooseVariant(e=!1){let t=1/0,i=1/0;if(this.config_.restrictToScreenSize){const e=this.config_.ignoreDevicePixelRatio?1:window.devicePixelRatio;t=window.screen.height*e,i=window.screen.width*e}if(this.resizeObserver_&&this.config_.restrictToElementSize){const e=this.config_.ignoreDevicePixelRatio?1:window.devicePixelRatio;t=Math.min(t,this.mediaElement_.clientHeight*e),i=Math.min(i,this.mediaElement_.clientWidth*e)}let s=this.variants_.filter((e=>!j.isFastSwitching(e)));s.length||(s=this.variants_);let a=s;e&&s.length!=this.variants_.length&&(a=this.variants_.filter((e=>j.isFastSwitching(e))));let r=this.filterAndSortVariants_(this.config_.restrictions,a,1/0,1/0);if(t!=1/0||i!=1/0){const e=this.getResolutionList_(r);for(const n of e)if(n.height>=t&&n.width>=i){t=n.height,i=n.width;break}r=this.filterAndSortVariants_(this.config_.restrictions,a,t,i)}const o=this.getBandwidthEstimate();a.length&&!r.length&&(n.warning("No variants met the ABR restrictions. Choosing a variant by lowest bandwidth."),r=this.filterAndSortVariants_(null,a,1/0,1/0),r=[r[0]]);let l=r[0]||null;for(let e=0;e<r.length;e++){const t=r[e],i=isNaN(this.playbackRate_)?1:Math.abs(this.playbackRate_),s=i*t.bandwidth,a=s/this.config_.bandwidthDowngradeTarget;let d={bandwidth:1/0};for(let i=e+1;i<r.length;i++)if(t.bandwidth!=r[i].bandwidth){d=r[i];break}const c=i*d.bandwidth/this.config_.bandwidthUpgradeTarget;n.v2("Bandwidth ranges:",(s/1e6).toFixed(3),(a/1e6).toFixed(3),(c/1e6).toFixed(3)),o>=a&&o<=c&&l.bandwidth!=t.bandwidth&&(l=t)}return this.lastTimeChosenMs_=Date.now(),l}enable(){this.enabled_=!0}disable(){this.enabled_=!1}segmentDownloaded(e,t,i,s){n.v2("Segment downloaded:","contentType="+(s&&s.contentType),"deltaTimeMs="+e,"numBytes="+t,"lastTimeChosenMs="+this.lastTimeChosenMs_,"enabled="+this.enabled_),console.assert(e>=0,"expected a non-negative duration"),this.bandwidthEstimator_.sample(e,t),i&&null!=this.lastTimeChosenMs_&&this.enabled_&&this.suggestStreams_()}trySuggestStreams(){null!=this.lastTimeChosenMs_&&this.enabled_&&this.suggestStreams_()}getBandwidthEstimate(){const e=this.getDefaultBandwidth_(),t=this.bandwidthEstimator_.getBandwidthEstimate(e);return this.cmsdManager_?this.cmsdManager_.getBandwidthEstimate(t):t}setVariants(e){this.variants_=e}playbackRateChanged(e){this.playbackRate_=e}setMediaElement(e){this.mediaElement_=e,this.resizeObserver_&&(this.resizeObserver_.disconnect(),this.resizeObserver_=null),this.mediaElement_&&"ResizeObserver"in window&&(this.resizeObserver_=new ResizeObserver((()=>{this.resizeObserverTimer_.tickAfter(J.RESIZE_OBSERVER_BATCH_TIME)})),this.resizeObserver_.observe(this.mediaElement_))}setCmsdManager(e){this.cmsdManager_=e}configure(e){this.config_=e,this.bandwidthEstimator_&&this.config_&&this.bandwidthEstimator_.configure(this.config_.advanced)}suggestStreams_(){if(n.v2("Suggesting Streams..."),console.assert(null!=this.lastTimeChosenMs_,"lastTimeChosenMs_ should not be null"),this.startupComplete_){if(Date.now()-this.lastTimeChosenMs_<1e3*this.config_.switchInterval)return void n.v2("Still within switch interval...")}else{if(!this.bandwidthEstimator_.hasGoodEstimate())return void n.v2("Still waiting for a good estimate...");this.startupComplete_=!0}const e=this.chooseVariant(),t=this.getBandwidthEstimate(),i=Math.round(t/1e3);e&&(n.debug("Calling switch_(), bandwidth="+i+" kbps"),this.switch_(e,this.config_.clearBufferSwitch,this.config_.safeMarginSwitch))}getDefaultBandwidth_(){let e=this.config_.defaultBandwidthEstimate;return navigator.connection&&navigator.connection.downlink&&this.config_.useNetworkInformation&&(e=1e6*navigator.connection.downlink),e}filterAndSortVariants_(e,t,i,n){if(this.cmsdManager_){const e=this.cmsdManager_.getMaxBitrate();e&&(t=t.filter((t=>!t.bandwidth||!e||t.bandwidth<=e)))}return e&&(t=t.filter((t=>(console.assert(e,"Restrictions should exist!"),j.meetsRestrictions(t,e,{width:n,height:i}))))),t.sort(((e,t)=>e.bandwidth-t.bandwidth))}getResolutionList_(e){const t=[];for(const i of e){const e=i.video;e&&e.height&&e.width&&t.push({height:e.height,width:e.width})}return t.sort(((e,t)=>e.width-t.width))}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}J.RESIZE_OBSERVER_BATCH_TIME=1;class Z{static createDefault(){let e=1/0;navigator.connection&&navigator.connection.saveData&&(e=360);const t={retryParameters:D.defaultRetryParameters(),servers:{},clearKeys:{},advanced:{},delayLicenseRequestUntilPlayed:!1,persistentSessionOnlinePlayback:!1,persistentSessionsMetadata:[],initDataTransform:(e,t,i)=>{if(N.isMediaKeysPolyfilled()&&"skd"==t){const t=i.serverCertificate,n=Y.defaultGetContentId(e);e=Y.initDataTransform(e,n,t)}return e},logLicenseExchange:!1,updateExpirationTime:1,preferredKeySystems:[],keySystemsMapping:{},parseInbandPsshEnabled:N.isXboxOne(),minHdcpVersion:"",ignoreDuplicateInitData:!N.isTizen2()};let i="reload",s=!1;N.supportsSmoothCodecSwitching()&&(i="smooth",s=!0);const a={retryParameters:D.defaultRetryParameters(),availabilityWindowOverride:NaN,disableAudio:!1,disableVideo:!1,disableText:!1,disableThumbnails:!1,defaultPresentationDelay:0,segmentRelativeVttTiming:!1,raiseFatalErrorOnManifestUpdateRequestFailure:!1,dash:{clockSyncUri:"",ignoreDrmInfo:!1,disableXlinkProcessing:!1,xlinkFailGracefully:!1,ignoreMinBufferTime:!1,autoCorrectDrift:!0,initialSegmentLimit:1e3,ignoreSuggestedPresentationDelay:!1,ignoreEmptyAdaptationSet:!1,ignoreMaxSegmentDuration:!1,keySystemsByURI:{"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":"org.w3.clearkey","urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e":"org.w3.clearkey","urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":"com.widevine.alpha","urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:79f0049a-4098-8642-ab92-e65be0885f95":"com.microsoft.playready"},manifestPreprocessor:e=>K.referenceParametersAndReturn([e],e),sequenceMode:!1,enableAudioGroups:!1,multiTypeVariantsAllowed:s,useStreamOnceInPeriodFlattening:!1},hls:{ignoreTextStreamFailures:!1,ignoreImageStreamFailures:!1,defaultAudioCodec:"mp4a.40.2",defaultVideoCodec:"avc1.42E01E",ignoreManifestProgramDateTime:!1,ignoreManifestProgramDateTimeForTypes:[],mediaPlaylistFullMimeType:'video/mp2t; codecs="avc1.42E01E, mp4a.40.2"',useSafariBehaviorForLive:!0,liveSegmentsDelay:3,sequenceMode:N.supportsSequenceMode(),ignoreManifestTimestampsInSegmentsMode:!1,disableCodecGuessing:!1,allowLowLatencyByteRangeOptimization:!0},mss:{manifestPreprocessor:e=>K.referenceParametersAndReturn([e],e),sequenceMode:!1,keySystemsBySystemId:{"9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","79f0049a-4098-8642-ab92-e65be0885f95":"com.microsoft.playready"}}},r={retryParameters:D.defaultRetryParameters(),failureCallback:e=>(n.error("Unhandled streaming error",e),K.referenceParametersAndReturn([e],void 0)),rebufferingGoal:2,bufferingGoal:10,bufferBehind:30,evictionGoal:1,ignoreTextStreamFailures:!1,alwaysStreamText:!1,startAtSegmentBoundary:!1,gapDetectionThreshold:.5,gapJumpTimerTime:.25,durationBackoff:1,safeSeekOffset:5,stallEnabled:!0,stallThreshold:1,stallSkip:.1,useNativeHlsForFairPlay:!0,inaccurateManifestTolerance:2,lowLatencyMode:!1,autoLowLatencyMode:!1,forceHTTPS:!1,preferNativeHls:!1,updateIntervalSeconds:1,dispatchAllEmsgBoxes:!1,observeQualityChanges:!1,maxDisabledTime:30,parsePrftBox:!1,segmentPrefetchLimit:0,prefetchAudioLanguages:[],disableAudioPrefetch:!1,disableTextPrefetch:!1,disableVideoPrefetch:!1,liveSync:!1,liveSyncMaxLatency:1,liveSyncPlaybackRate:1.1,liveSyncMinLatency:0,liveSyncMinPlaybackRate:1,liveSyncPanicMode:!1,liveSyncPanicThreshold:60,allowMediaSourceRecoveries:!0,minTimeBetweenRecoveries:5,vodDynamicPlaybackRate:!1,vodDynamicPlaybackRateLowBufferRate:.95,vodDynamicPlaybackRateBufferRatio:.5,infiniteLiveStreamDuration:!1};(N.isWebOS()||N.isTizen()||N.isChromecast()||N.isHisense())&&(r.stallSkip=0);const o={trackSelectionCallback:async e=>e,downloadSizeCallback:async e=>{if(navigator.storage&&navigator.storage.estimate){const t=await navigator.storage.estimate();return t.usage+e<.95*t.quota}return!0},progressCallback:(e,t)=>K.referenceParametersAndReturn([e,t],void 0),usePersistentLicense:!0,numberOfParallelDownloads:5},l={drm:t,manifest:a,streaming:r,mediaSource:{codecSwitchingStrategy:i,addExtraFeaturesToSourceBuffer:e=>K.referenceParametersAndReturn([e],""),forceTransmux:!1,insertFakeEncryptionInInit:!0,modifyCueCallback:(e,t)=>K.referenceParametersAndReturn([e,t],void 0)},offline:o,abrFactory:()=>new J,abr:{enabled:!0,useNetworkInformation:!0,defaultBandwidthEstimate:1e6,switchInterval:8,bandwidthUpgradeTarget:.85,bandwidthDowngradeTarget:.95,restrictions:{minWidth:0,maxWidth:1/0,minHeight:0,maxHeight:e,minPixels:0,maxPixels:1/0,minFrameRate:0,maxFrameRate:1/0,minBandwidth:0,maxBandwidth:1/0},advanced:{minTotalBytes:128e3,minBytes:16e3,fastHalfLife:2,slowHalfLife:5},restrictToElementSize:!1,restrictToScreenSize:!1,ignoreDevicePixelRatio:!1,clearBufferSwitch:!1,safeMarginSwitch:0},autoShowText:3,preferredAudioLanguage:"",preferredAudioLabel:"",preferredTextLanguage:"",preferredVariantRole:"",preferredTextRole:"",preferredAudioChannelCount:2,preferredVideoHdrLevel:"AUTO",preferredVideoLayout:"",preferredVideoLabel:"",preferredVideoCodecs:[],preferredAudioCodecs:[],preferForcedSubs:!1,preferSpatialAudio:!1,preferredDecodingAttributes:[],restrictions:{minWidth:0,maxWidth:1/0,minHeight:0,maxHeight:1/0,minPixels:0,maxPixels:1/0,minFrameRate:0,maxFrameRate:1/0,minBandwidth:0,maxBandwidth:1/0},playRangeStart:0,playRangeEnd:1/0,textDisplayFactory:()=>null,cmcd:{enabled:!1,sessionId:"",contentId:"",rtpSafetyFactor:5,useHeaders:!1,includeKeys:[]},cmsd:{enabled:!0,applyMaximumSuggestedBitrate:!0,estimatedThroughputWeightRatio:.5},lcevc:{enabled:!1,dynamicPerformanceScaling:!0,logLevel:0,drawLogo:!1},ads:{customPlayheadTracker:!1}};return o.trackSelectionCallback=async e=>Z.defaultTrackSelect(e,l.preferredAudioLanguage,l.preferredVideoHdrLevel),l}static mergeConfigObjects(e,t,i){const n={".drm.keySystemsMapping":"",".drm.servers":"",".drm.clearKeys":"",".drm.advanced":{distinctiveIdentifierRequired:!1,persistentStateRequired:!1,videoRobustness:"",audioRobustness:"",sessionType:"",serverCertificate:new Uint8Array(0),serverCertificateUri:"",individualizationServer:""}};return K.mergeConfigObjects(e,t,i||Z.createDefault(),n,"")}static defaultTrackSelect(e,t,i){const s=U.ContentType;let a=i;"AUTO"==a&&(a=window.matchMedia("(color-gamut: p3)").matches?"PQ":"SDR");const r=e.filter((e=>"variant"==e.type&&(!e.hdr||e.hdr==a)));let o=[];const l=H.findClosestLocale(t,r.map((e=>e.language)));l&&(o=r.filter((e=>H.normalize(e.language)==l))),0==o.length&&(o=r.filter((e=>e.primary))),0==o.length&&(new Set(r.map((e=>e.language))).size>1&&n.warning("Could not choose a good audio track based on language preferences or primary tracks. An arbitrary language will be stored!"),o=r);const d=o.filter((e=>e.height&&e.height<=480));d.length&&(d.sort(((e,t)=>(console.assert(null!=e.height,"Null height"),console.assert(null!=t.height,"Null height"),t.height-e.height))),o=d.filter((e=>e.height==d[0].height)));const c=[];if(o.length){const e=Math.floor(o.length/2);o.sort(((e,t)=>e.bandwidth-t.bandwidth)),c.push(o[e])}for(const t of e)t.type!=s.TEXT&&t.type!=s.IMAGE||c.push(t);return c}}class ee{constructor(){this.bindingMap_=new s}release(){this.removeAll(),this.bindingMap_=null}listen(e,t,i,n){if(!this.bindingMap_)return;const s=new ee.Binding_(e,t,i,n);this.bindingMap_.push(t,s)}listenOnce(e,t,i,n){const s=n=>{this.unlisten(e,t,s),i(n)};this.listen(e,t,s,n)}unlisten(e,t,i){if(!this.bindingMap_)return;const n=this.bindingMap_.get(t)||[];for(const s of n)s.target==e&&(i!=s.listener&&i||(s.unlisten(),this.bindingMap_.remove(t,s)))}removeAll(){if(!this.bindingMap_)return;const e=this.bindingMap_.getAll();for(const t of e)t.unlisten();this.bindingMap_.clear()}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}ee.Binding_=class{constructor(e,t,i,n){this.target=e,this.type=t,this.listener=i,this.options=ee.Binding_.convertOptions_(e,n),this.target.addEventListener(t,i,this.options)}unlisten(){console.assert(this.target,"Missing target"),this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static convertOptions_(e,t){if(null==t)return!1;if("boolean"==typeof t)return t;{const i=new Set(["passive","capture"]),n=Object.keys(t).filter((e=>!i.has(e)));return console.assert(0==n.length,"Unsupported flag(s) to addEventListener: "+n.join(",")),ee.Binding_.doesSupportObject_(e)?t:t.capture||!1}}static doesSupportObject_(e){let t=ee.Binding_.supportsObject_;if(null==t){t=!1;try{const i={},n={get:()=>(t=!0,!1)};Object.defineProperty(i,"passive",n),Object.defineProperty(i,"capture",n);const s=()=>{};e.addEventListener("test",s,i),e.removeEventListener("test",s,i)}catch(e){t=!1}ee.Binding_.supportsObject_=t}return t||!1}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0]}},ee.Binding_.supportsObject_=void 0;class te{constructor(){this.open_=null,this.closed_=[]}update(e){return null==this.open_?(this.start_(e),!0):this.update_(e)}getTimeSpentIn(e){let t=0;this.open_&&this.open_.state==e&&(t+=this.open_.duration);for(const i of this.closed_)t+=i.state==e?i.duration:0;return t}getCopy(){const e=e=>({timestamp:e.timestamp,state:e.state,duration:e.duration}),t=[];for(const i of this.closed_)t.push(e(i));return this.open_&&t.push(e(this.open_)),t}start_(e){console.assert(null==this.open_,"There must be no open entry in order when we start"),n.v1("Changing Player state to",e),this.open_={timestamp:this.getNowInSeconds_(),state:e,duration:0}}update_(e){console.assert(this.open_,"There must be an open entry in order to update it");const t=this.getNowInSeconds_();return this.open_.duration=t-this.open_.timestamp,this.open_.state!=e&&(n.v1("Changing Player state to",e),this.closed_.push(this.open_),this.open_={timestamp:t,state:e,duration:0},!0)}getNowInSeconds_(){return Date.now()/1e3}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class ie{constructor(){this.currentVariant_=null,this.currentText_=null,this.history_=[]}updateCurrentVariant(e,t){this.currentVariant_!=e&&(this.currentVariant_=e,this.history_.push({timestamp:this.getNowInSeconds_(),id:e.id,type:"variant",fromAdaptation:t,bandwidth:e.bandwidth}))}updateCurrentText(e,t){this.currentText_!=e&&(this.currentText_=e,this.history_.push({timestamp:this.getNowInSeconds_(),id:e.id,type:"text",fromAdaptation:t,bandwidth:null}))}getCopy(){const e=[];for(const t of this.history_)e.push(this.clone_(t));return e}getNowInSeconds_(){return Date.now()/1e3}clone_(e){return{timestamp:e.timestamp,id:e.id,type:e.type,fromAdaptation:e.fromAdaptation,bandwidth:e.bandwidth}}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class ne{constructor(){this.width_=NaN,this.height_=NaN,this.totalDroppedFrames_=NaN,this.totalDecodedFrames_=NaN,this.totalCorruptedFrames_=NaN,this.totalStallsDetected_=NaN,this.totalGapsJumped_=NaN,this.completionPercent_=NaN,this.loadLatencySeconds_=NaN,this.manifestTimeSeconds_=NaN,this.drmTimeSeconds_=NaN,this.licenseTimeSeconds_=NaN,this.liveLatencySeconds_=NaN,this.maxSegmentDurationSeconds_=NaN,this.currentStreamBandwidth_=NaN,this.bandwidthEstimate_=NaN,this.stateHistory_=new te,this.switchHistory_=new ie}setDroppedFrames(e,t){this.totalDroppedFrames_=e,this.totalDecodedFrames_=t}setCorruptedFrames(e){this.totalCorruptedFrames_=e}setStallsDetected(e){this.totalStallsDetected_=e}setGapsJumped(e){this.totalGapsJumped_=e}setResolution(e,t){this.width_=e,this.height_=t}setLoadLatency(e){this.loadLatencySeconds_=e}setManifestTime(e){this.manifestTimeSeconds_=e}setCompletionPercent(e){isNaN(this.completionPercent_)?this.completionPercent_=e:this.completionPercent_=Math.max(this.completionPercent_,e)}setDrmTime(e){this.drmTimeSeconds_=e}setLicenseTime(e){this.licenseTimeSeconds_=e}setLiveLatency(e){this.liveLatencySeconds_=e}setMaxSegmentDuration(e){this.maxSegmentDurationSeconds_=e}setCurrentStreamBandwidth(e){this.currentStreamBandwidth_=e}setBandwidthEstimate(e){this.bandwidthEstimate_=e}getStateHistory(){return this.stateHistory_}getSwitchHistory(){return this.switchHistory_}getBlob(){return{width:this.width_,height:this.height_,streamBandwidth:this.currentStreamBandwidth_,decodedFrames:this.totalDecodedFrames_,droppedFrames:this.totalDroppedFrames_,corruptedFrames:this.totalCorruptedFrames_,stallsDetected:this.totalStallsDetected_,gapsJumped:this.totalGapsJumped_,estimatedBandwidth:this.bandwidthEstimate_,completionPercent:this.completionPercent_,loadLatency:this.loadLatencySeconds_,manifestTimeSeconds:this.manifestTimeSeconds_,drmTimeSeconds:this.drmTimeSeconds_,playTime:this.stateHistory_.getTimeSpentIn("playing"),pauseTime:this.stateHistory_.getTimeSpentIn("paused"),bufferingTime:this.stateHistory_.getTimeSpentIn("buffering"),licenseTime:this.licenseTimeSeconds_,liveLatency:this.liveLatencySeconds_,maxSegmentDuration:this.maxSegmentDurationSeconds_,stateHistory:this.stateHistory_.getCopy(),switchHistory:this.switchHistory_.getCopy()}}static getEmptyBlob(){return{width:NaN,height:NaN,streamBandwidth:NaN,decodedFrames:NaN,droppedFrames:NaN,corruptedFrames:NaN,stallsDetected:NaN,gapsJumped:NaN,estimatedBandwidth:NaN,completionPercent:NaN,loadLatency:NaN,manifestTimeSeconds:NaN,drmTimeSeconds:NaN,playTime:NaN,pauseTime:NaN,bufferingTime:NaN,licenseTime:NaN,liveLatency:NaN,maxSegmentDuration:NaN,switchHistory:[],stateHistory:[]}}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class se{constructor(e,t){this.playerInterface_=e,this.config_=t,this.sf_=void 0,this.playbackStarted_=!1,this.buffering_=!0,this.starved_=!1}configure(e){this.config_=e}setBuffering(e){e||this.playbackStarted_||(this.playbackStarted_=!0),this.playbackStarted_&&e&&(this.starved_=!0),this.buffering_=e}applyData(e,t,i={}){if(!this.config_.enabled)return;if("HEAD"===t.method)return void this.apply_(t);const n=D.RequestType,s=se.ObjectType;switch(e){case n.MANIFEST:this.applyManifestData(t,i);break;case n.SEGMENT:this.applySegmentData(t,i);break;case n.LICENSE:case n.SERVER_CERTIFICATE:case n.KEY:this.apply_(t,{ot:s.KEY});break;case n.TIMING:this.apply_(t,{ot:s.OTHER})}}applyManifestData(e,t){try{if(!this.config_.enabled)return;t.type&&(this.sf_=this.getStreamFormat_(t.type)),this.apply_(e,{ot:se.ObjectType.MANIFEST,su:!this.playbackStarted_})}catch(e){n.warnOnce("CMCD_MANIFEST_ERROR","Could not generate manifest CMCD data.",e)}}applySegmentData(e,t){try{if(!this.config_.enabled)return;const i=t.segment;let n=0;i&&(n=i.endTime-i.startTime);const s={d:1e3*n,st:this.getStreamType_()};s.ot=this.getObjectType_(t);const a=se.ObjectType,r=s.ot===a.VIDEO||s.ot===a.AUDIO||s.ot===a.MUXED||s.ot===a.TIMED_TEXT,o=t.stream;if(o){if(r&&(s.bl=this.getBufferLength_(o.type),s.ot!==a.TIMED_TEXT)){const e=this.getRemainingBufferLength_(o.type),t=this.playerInterface_.getPlaybackRate();s.dl=t?e/Math.abs(t):e}if(o.bandwidth&&(s.br=o.bandwidth/1e3),o.segmentIndex&&i){const t=o.segmentIndex.getIteratorForTime(i.endTime,!0);if(t){const n=t.next().value;if(n&&n!=i&&(I.equal(i.getUris(),n.getUris())||(s.nor=this.urlToRelativePath_(n.getUris()[0],e.uris[0])),(n.startByte||n.endByte)&&(i.startByte!=n.startByte||i.endByte!=n.endByte))){let e=n.startByte+"-";n.endByte&&(e+=n.endByte),s.nrr=e}}const n=this.calculateRtp_(o,i);isNaN(n)||(s.rtp=n)}}r&&s.ot!==a.TIMED_TEXT&&(s.tb=this.getTopBandwidth_(s.ot)/1e3),this.apply_(e,s)}catch(e){n.warnOnce("CMCD_SEGMENT_ERROR","Could not generate segment CMCD data.",e)}}applyTextData(e){try{if(!this.config_.enabled)return;this.apply_(e,{ot:se.ObjectType.CAPTION,su:!0})}catch(e){n.warnOnce("CMCD_TEXT_ERROR","Could not generate text CMCD data.",e)}}appendSrcData(e,t){try{if(!this.config_.enabled)return e;const i=this.createData_();i.ot=this.getObjectTypeFromMimeType_(t),i.su=!0;const n=se.toQuery(i);return se.appendQueryToUri(e,n)}catch(t){return n.warnOnce("CMCD_SRC_ERROR","Could not generate src CMCD data.",t),e}}appendTextTrackData(e){try{if(!this.config_.enabled)return e;const t=this.createData_();t.ot=se.ObjectType.CAPTION,t.su=!0;const i=se.toQuery(t);return se.appendQueryToUri(e,i)}catch(t){return n.warnOnce("CMCD_TEXT_TRACK_ERROR","Could not generate text track CMCD data.",t),e}}createData_(){return this.config_.sessionId||(this.config_.sessionId=window.crypto.randomUUID()),{v:se.Version,sf:this.sf_,sid:this.config_.sessionId,cid:this.config_.contentId,mtp:this.playerInterface_.getBandwidthEstimate()/1e3}}apply_(e,t={},i=this.config_.useHeaders){if(!this.config_.enabled)return;Object.assign(t,this.createData_()),t.pr=this.playerInterface_.getPlaybackRate();const n=t.ot===se.ObjectType.VIDEO||t.ot===se.ObjectType.MUXED;this.starved_&&n&&(t.bs=!0,t.su=!0,this.starved_=!1),null==t.su&&(t.su=this.buffering_);const s=this.filterKeys_(t);if(i){const t=se.toHeaders(s);if(!Object.keys(t).length)return;Object.assign(e.headers,t)}else{const t=se.toQuery(s);if(!t)return;e.uris=e.uris.map((e=>se.appendQueryToUri(e,t)))}}filterKeys_(e){const t=this.config_.includeKeys;return t.length?Object.keys(e).reduce(((i,n)=>(t.includes(n)&&(i[n]=e[n]),i)),{}):e}getObjectType_(e){if(e.type===D.AdvancedRequestType.INIT_SEGMENT)return se.ObjectType.INIT;const t=e.stream;if(!t)return;const i=t.type;return"video"==i?t.codecs&&t.codecs.includes(",")?se.ObjectType.MUXED:se.ObjectType.VIDEO:"audio"==i?se.ObjectType.AUDIO:"text"==i?"application/mp4"===t.mimeType?se.ObjectType.TIMED_TEXT:se.ObjectType.CAPTION:void 0}getObjectTypeFromMimeType_(e){switch(e.toLowerCase()){case"audio/mp4":case"audio/webm":case"audio/ogg":case"audio/mpeg":case"audio/aac":case"audio/flac":case"audio/wav":return se.ObjectType.AUDIO;case"video/webm":case"video/mp4":case"video/mpeg":case"video/mp2t":return se.ObjectType.MUXED;case"application/x-mpegurl":case"application/vnd.apple.mpegurl":case"application/dash+xml":case"video/vnd.mpeg.dash.mpd":case"application/vnd.ms-sstr+xml":return se.ObjectType.MANIFEST;default:return}}getBufferLength_(e){const t=this.playerInterface_.getBufferedInfo()[e];if(!t.length)return NaN;const i=this.playerInterface_.getCurrentTime(),n=t.find((e=>e.start<=i&&e.end>=i));return n?1e3*(n.end-i):NaN}getRemainingBufferLength_(e){const t=this.playerInterface_.getBufferedInfo()[e];if(!t.length)return 0;const i=this.playerInterface_.getCurrentTime(),n=t.find((e=>e.start<=i&&e.end>=i));return n?1e3*(n.end-i):0}urlToRelativePath_(e,t){const i=new URL(e),n=new URL(t);if(i.origin!==n.origin)return e;const s=i.pathname.split("/").slice(1),a=n.pathname.split("/").slice(1,-1);for(;s[0]===a[0];)s.shift(),a.shift();for(;a.length;)a.shift(),s.unshift("..");return s.join("/")}calculateRtp_(e,t){const i=this.playerInterface_.getPlaybackRate()||1,n=this.getRemainingBufferLength_(e.type)||500,s=e.bandwidth;return s?s*(t.endTime-t.startTime)/1e3/(n/i/1e3)*this.config_.rtpSafetyFactor:NaN}getStreamFormat_(e){const t=D.AdvancedRequestType;switch(e){case t.MPD:return se.StreamingFormat.DASH;case t.MASTER_PLAYLIST:case t.MEDIA_PLAYLIST:return se.StreamingFormat.HLS;case t.MSS:return se.StreamingFormat.SMOOTH}}getStreamType_(){return this.playerInterface_.isLive()?se.StreamType.LIVE:se.StreamType.VOD}getTopBandwidth_(e){const t=this.playerInterface_.getVariantTracks();if(!t.length)return NaN;let i=t[0];for(const e of t)"variant"===e.type&&e.bandwidth>i.bandwidth&&(i=e);const n=se.ObjectType;switch(e){case n.VIDEO:return i.videoBandwidth||NaN;case n.AUDIO:return i.audioBandwidth||NaN;default:return i.bandwidth}}static serialize(e){const t=[],i=e=>!Number.isNaN(e)&&null!=e&&""!==e&&!1!==e,n=e=>Math.round(e),s=e=>100*n(e/100),a={br:n,d:n,bl:s,dl:s,mtp:s,nor:e=>encodeURIComponent(e),rtp:s,tb:n},r=Object.keys(e||{}).sort();for(const n of r){let s=e[n];if(!i(s))continue;if("v"===n&&1===s)continue;if("pr"==n&&1===s)continue;const r=a[n];r&&(s=r(s));const o=typeof s;let l;l="string"===o&&"ot"!==n&&"sf"!==n&&"st"!==n?`${n}=${JSON.stringify(s)}`:"boolean"===o?n:"symbol"===o?`${n}=${s.description}`:`${n}=${s}`,t.push(l)}return t.join(",")}static toHeaders(e){const t=Object.keys(e),i={},n=["Object","Request","Session","Status"],s=[{},{},{},{}],a={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const i of t)s[null!=a[i]?a[i]:1][i]=e[i];for(let e=0;e<s.length;e++){const t=se.serialize(s[e]);t&&(i[`CMCD-${n[e]}`]=t)}return i}static toQuery(e){return se.serialize(e)}static appendQueryToUri(e,t){if(!t)return e;if(e.includes("offline:"))return e;const i=new URL(e);return i.searchParams.set("CMCD",t),i.toString()}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}se.PlayerInterface,se.ObjectType={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},se.StreamType={VOD:"v",LIVE:"l"},se.StreamingFormat={DASH:"d",HLS:"h",SMOOTH:"s",OTHER:"o"},se.Version=1;class ae{constructor(e){this.config_=e,this.staticParams_=null,this.dynamicParams_=null}configure(e){this.config_=e}reset(){this.staticParams_=null,this.dynamicParams_=null}processHeaders(e){if(!this.config_.enabled)return;const t=e[ae.CMSD_STATIC_HEADER_NAME_];if(t){const e=this.parseCMSDStatic_(t);e&&(this.staticParams_=e)}const i=e[ae.CMSD_DYNAMIC_HEADER_NAME_];if(i){const e=this.parseCMSDDynamic_(i);e&&(this.dynamicParams_=e)}}getMaxBitrate(){const e=ae.KEYS_.MAX_SUGGESTED_BITRATE;return this.config_.enabled&&this.config_.applyMaximumSuggestedBitrate&&this.dynamicParams_&&this.dynamicParams_.has(e)?1e3*this.dynamicParams_.get(e):null}getEstimatedThroughput(){const e=ae.KEYS_.ESTIMATED_THROUGHPUT;return this.config_.enabled&&this.dynamicParams_&&this.dynamicParams_.has(e)?1e3*this.dynamicParams_.get(e):null}getResponseDelay(){const e=ae.KEYS_.RESPONSE_DELAY;return this.config_.enabled&&this.dynamicParams_&&this.dynamicParams_.has(e)?this.dynamicParams_.get(e):null}getRoundTripTime(){const e=ae.KEYS_.ROUND_TRIP_TIME;return this.config_.enabled&&this.dynamicParams_&&this.dynamicParams_.has(e)?this.dynamicParams_.get(e):null}getBandwidthEstimate(e){const t=this.getEstimatedThroughput();if(!t)return e;const i=this.config_.estimatedThroughputWeightRatio;return i>0&&i<=1?e*(1-i)+t*i:e}parseCMSDStatic_(e){try{const t=new Map,i=e.split(",");for(let e=0;e<i.length;e++){const n=i[e].split("="),s=n[0],a=this.parseParameterValue_(n[1]);t.set(s,a)}return t}catch(e){return n.warning("Failed to parse CMSD-Static response header value:",e),null}}parseCMSDDynamic_(e){try{const t=new Map,i=e.split(";");for(let e=1;e<i.length;e++){const n=i[e].split("="),s=n[0],a=this.parseParameterValue_(n[1]);t.set(s,a)}return t}catch(e){return n.warning("Failed to parse CMSD-Dynamic response header value:",e),null}}parseParameterValue_(e){return!e||"false"!==e.toLowerCase()&&(/^[-0-9]/.test(e)?parseInt(e,10):e.replace(/["]+/g,""))}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}ae.CMSD_STATIC_HEADER_NAME_="cmsd-static",ae.CMSD_DYNAMIC_HEADER_NAME_="cmsd-dynamic",ae.KEYS_={AVAILABILITY_TIME:"at",DURESS:"du",ENCODED_BITRATE:"br",ESTIMATED_THROUGHPUT:"etp",HELD_TIME:"ht",INTERMEDIARY_IDENTIFIER:"n",MAX_SUGGESTED_BITRATE:"mb",NEXT_OBJECT_RESPONSE:"nor",NEXT_RANGE_RESPONSE:"nrr",OBJECT_DURATION:"d",OBJECT_TYPE:"ot",RESPONSE_DELAY:"rd",ROUND_TRIP_TIME:"rtt",STARTUP:"su",STREAM_TYPE:"st",STREAMING_FORMAT:"sf",VERSION:"v"};class re{static init(e){console.assert(null==re.enforcer_,"Deprecate.init should only be called once."),re.enforcer_=new re.Enforcer(re.Version.parse(e),re.onPending_,re.onExpired_)}static deprecateFeature(e,t,i){const n=re.enforcer_;console.assert(n,"Missing deprecation enforcer. Was |init| called?");const s=new re.Version(e,0);n.enforce(s,t,i)}static onPending_(e,t,i,s){n.alwaysWarn([i,"has been deprecated and will be removed in",t,". We are currently at version",e,". Additional information:",s].join(" "))}static onExpired_(e,t,i,s){const a=[i,"has been deprecated and has been removed in",t,". We are now at version",e,". Additional information:",s].join(" ");n.alwaysError(a),console.assert(!1,a)}}re.enforcer_=null,re.Version=class{constructor(e,t){this.major_=e,this.minor_=t}major(){return this.major_}minor(){return this.minor_}compareTo(e){const t=this.major_-e.major_,i=this.minor_-e.minor_;return t||i}toString(){return"v"+this.major_+"."+this.minor_}static parse(e){const t=e.substring(1).split(".",2);return new re.Version(Number(t[0]),Number(t[1]))}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}},re.Enforcer=class{constructor(e,t,i){this.libraryVersion_=e,this.onPending_=t,this.onExpired_=i}enforce(e,t,i){(e.compareTo(this.libraryVersion_)>0?this.onPending_:this.onExpired_)(this.libraryVersion_,e,t,i)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0]}};class oe{constructor(e,t){this.dataView_=d.toDataView(e),this.littleEndian_=t==oe.Endianness.LITTLE_ENDIAN,this.position_=0}getDataView(){return this.dataView_}hasMoreData(){return this.position_<this.dataView_.byteLength}getPosition(){return this.position_}getLength(){return this.dataView_.byteLength}readUint8(){try{const e=this.dataView_.getUint8(this.position_);return this.position_+=1,e}catch(e){throw this.outOfBounds_()}}readUint16(){try{const e=this.dataView_.getUint16(this.position_,this.littleEndian_);return this.position_+=2,e}catch(e){throw this.outOfBounds_()}}readUint32(){try{const e=this.dataView_.getUint32(this.position_,this.littleEndian_);return this.position_+=4,e}catch(e){throw this.outOfBounds_()}}readInt32(){try{const e=this.dataView_.getInt32(this.position_,this.littleEndian_);return this.position_+=4,e}catch(e){throw this.outOfBounds_()}}readUint64(){let e,t;try{this.littleEndian_?(e=this.dataView_.getUint32(this.position_,!0),t=this.dataView_.getUint32(this.position_+4,!0)):(t=this.dataView_.getUint32(this.position_,!1),e=this.dataView_.getUint32(this.position_+4,!1))}catch(e){throw this.outOfBounds_()}if(t>2097151)throw new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.JS_INTEGER_OVERFLOW);return this.position_+=8,t*Math.pow(2,32)+e}readBytes(e){if(console.assert(e>=0,"Bad call to DataViewReader.readBytes"),this.position_+e>this.dataView_.byteLength)throw this.outOfBounds_();const t=d.toUint8(this.dataView_,this.position_,e);return this.position_+=e,t}skip(e){if(console.assert(e>=0,"Bad call to DataViewReader.skip"),this.position_+e>this.dataView_.byteLength)throw this.outOfBounds_();this.position_+=e}rewind(e){if(console.assert(e>=0,"Bad call to DataViewReader.rewind"),this.position_<e)throw this.outOfBounds_();this.position_-=e}seek(e){if(console.assert(e>=0,"Bad call to DataViewReader.seek"),e<0||e>this.dataView_.byteLength)throw this.outOfBounds_();this.position_=e}readTerminatedString(){const e=this.position_;for(;this.hasMoreData()&&0!=this.dataView_.getUint8(this.position_);)this.position_+=1;const t=d.toUint8(this.dataView_,e,this.position_-e);return this.position_+=1,x.fromUTF8(t)}outOfBounds_(){return new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.BUFFER_READ_OUT_OF_BOUNDS)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}oe.Endianness={BIG_ENDIAN:0,LITTLE_ENDIAN:1};class le{constructor(){this.headers_=[],this.boxDefinitions_=[],this.done_=!1}box(e,t){const i=le.typeFromString_(e);return this.headers_[i]=le.BoxType_.BASIC_BOX,this.boxDefinitions_[i]=t,this}fullBox(e,t){const i=le.typeFromString_(e);return this.headers_[i]=le.BoxType_.FULL_BOX,this.boxDefinitions_[i]=t,this}stop(){this.done_=!0}parse(e,t,i){const n=new oe(e,oe.Endianness.BIG_ENDIAN);for(this.done_=!1;n.hasMoreData()&&!this.done_;)this.parseNext(0,n,t,i)}parseNext(e,t,i,s){const a=t.getPosition();if(s&&a+8>t.getLength())return void(this.done_=!0);let r=t.readUint32();const o=t.readUint32(),l=le.typeToString(o);let d=!1;switch(n.v2("Parsing MP4 box",l),r){case 0:r=t.getLength()-a;break;case 1:if(s&&t.getPosition()+8>t.getLength())return void(this.done_=!0);r=t.readUint64(),d=!0}const c=this.boxDefinitions_[o];if(c){let n=null,h=null;if(this.headers_[o]==le.BoxType_.FULL_BOX){if(s&&t.getPosition()+4>t.getLength())return void(this.done_=!0);const e=t.readUint32();n=e>>>24,h=16777215&e}let u=a+r;if(i&&u>t.getLength()&&(u=t.getLength()),s&&u>t.getLength())return void(this.done_=!0);const _=u-t.getPosition(),m=_>0?t.readBytes(_):new Uint8Array(0);c({name:l,parser:this,partialOkay:i||!1,version:n,flags:h,reader:new oe(m,oe.Endianness.BIG_ENDIAN),size:r,start:a+e,has64BitSize:d})}else{const e=Math.min(a+r-t.getPosition(),t.getLength()-t.getPosition());t.skip(e)}}static children(e){const t=le.headerSize(e);for(;e.reader.hasMoreData()&&!e.parser.done_;)e.parser.parseNext(e.start+t,e.reader,e.partialOkay)}static sampleDescription(e){const t=le.headerSize(e),i=e.reader.readUint32();for(let n=0;n<i&&(e.parser.parseNext(e.start+t,e.reader,e.partialOkay),!e.parser.done_);n++);}static visualSampleEntry(e){const t=le.headerSize(e);for(e.reader.skip(78);e.reader.hasMoreData()&&!e.parser.done_;)e.parser.parseNext(e.start+t,e.reader,e.partialOkay)}static audioSampleEntry(e){const t=le.headerSize(e);e.reader.skip(8);const i=e.reader.readUint16();for(e.reader.skip(6),2==i?e.reader.skip(48):e.reader.skip(12),1==i&&e.reader.skip(16);e.reader.hasMoreData()&&!e.parser.done_;)e.parser.parseNext(e.start+t,e.reader,e.partialOkay)}static allData(e){return t=>{const i=t.reader.getLength()-t.reader.getPosition();e(t.reader.readBytes(i))}}static typeFromString_(e){console.assert(4==e.length,"Mp4 box names must be 4 characters long");let t=0;for(const i of e)t=t<<8|i.charCodeAt(0);return t}static typeToString(e){return String.fromCharCode(e>>24&255,e>>16&255,e>>8&255,255&e)}static headerSize(e){return 8+(e.has64BitSize?8:0)+(null!=e.flags?4:0)}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}le.CallbackType,le.BoxType_={BASIC_BOX:0,FULL_BOX:1};class de{static parseTFHD(e,t){let i=null,n=null,s=null;const a=e.readUint32();return 1&t&&(s=e.readUint64()),2&t&&e.skip(4),8&t&&(i=e.readUint32()),16&t&&(n=e.readUint32()),{trackId:a,defaultSampleDuration:i,defaultSampleSize:n,baseDataOffset:s}}static parseTFDT(e,t){return{baseMediaDecodeTime:1==t?e.readUint64():e.readUint32()}}static parseTFDTInaccurate(e,t){if(1==t){const t=e.readUint32(),i=e.readUint32();return{baseMediaDecodeTime:t*Math.pow(2,32)+i}}return{baseMediaDecodeTime:e.readUint32()}}static parsePRFTInaccurate(e,t){e.readUint32();const i=1e3*e.readUint32()+e.readUint32()/2**32*1e3;let n;if(0===t)n=e.readUint32();else{const t=e.readUint32(),i=e.readUint32();n=t*Math.pow(2,32)+i}return{mediaTime:n,ntpTimestamp:i}}static parseMDHD(e,t){1==t?(e.skip(8),e.skip(8)):(e.skip(4),e.skip(4));const i=e.readUint32();e.skip(4);const n=e.readUint16();return{timescale:i,language:String.fromCharCode(96+(n>>10))+String.fromCharCode(96+((960&n)>>5))+String.fromCharCode(96+(31&n))}}static parseTREX(e){return e.skip(4),e.skip(4),{defaultSampleDuration:e.readUint32(),defaultSampleSize:e.readUint32()}}static parseTRUN(e,t,i){const n=e.readUint32(),s=[];let a=null;1&i&&(a=e.readUint32()),4&i&&e.skip(4);for(let a=0;a<n;a++){const n={sampleDuration:null,sampleSize:null,sampleCompositionTimeOffset:null};256&i&&(n.sampleDuration=e.readUint32()),512&i&&(n.sampleSize=e.readUint32()),1024&i&&e.skip(4),2048&i&&(n.sampleCompositionTimeOffset=0==t?e.readUint32():e.readInt32()),s.push(n)}return{sampleCount:n,sampleData:s,dataOffset:a}}static parseTKHD(e,t){1==t?(e.skip(8),e.skip(8)):(e.skip(4),e.skip(4));const i=e.readUint32();return 1==t?e.skip(8):e.skip(4),e.skip(4),e.skip(8),e.skip(2),e.skip(2),e.skip(2),e.skip(2),e.skip(36),{trackId:i,width:e.readUint16()+e.readUint16()/16,height:e.readUint16()+e.readUint16()/16}}static parseMP4A(e){e.skip(6),e.skip(2),e.skip(8);const t=e.readUint16();return e.skip(2),e.skip(2),e.skip(2),{channelCount:t,sampleRate:e.readUint16()+e.readUint16()/65536}}static parseESDS(e){let t,i,n="mp4a";for(;e.hasMoreData();){t=e.readUint8();let n=e.readUint8();for(;128&n;)n=e.readUint8();if(3==t){e.readUint16();const t=e.readUint8();128&t&&e.readUint16(),64&t&&e.skip(e.readUint8()),32&t&&e.readUint16()}else if(4==t)i=e.readUint8(),e.skip(12);else if(5==t)break}if(i&&(n+="."+de.toHex_(i),5==t&&e.hasMoreData())){const t=e.readUint8();let i=(248&t)>>3;31===i&&e.hasMoreData()&&(i=32+((7&t)<<3)+((224&e.readUint8())>>5)),n+="."+i}return{codec:n}}static parseAVCC(e,t,i){const n=n;return t.skip(1),{codec:e+"."+n.toHex_(t.readUint8())+n.toHex_(t.readUint8())+n.toHex_(t.readUint8())}}static parseHVCC(e,t,i){const n=n;t.skip(1);const s=t.readUint8(),a=["","A","B","C"][s>>6],r=31&s,o=t.readUint32(),l=(32&s)>>5?"H":"L",d=[t.readUint8(),t.readUint8(),t.readUint8(),t.readUint8(),t.readUint8(),t.readUint8()],c=t.readUint8();let h=e;h+="."+a+r,h+="."+n.toHex_(n.reverseBits_(o),!0),h+="."+l+c;let u="";for(let e=d.length;e--;){const t=d[e];(t||u)&&(u="."+t.toString(16).toUpperCase()+u)}return h+=u,{codec:h}}static parseDVCC(e,t,i){const n=n;t.skip(2);const s=t.readUint8(),a=s>>1&127,r=s<<5&32|t.readUint8()>>3&31;return{codec:e+"."+n.addLeadingZero_(a)+"."+n.addLeadingZero_(r)}}static parseVPCC(e,t,i){const n=n,s=t.readUint8(),a=t.readUint8(),r=t.readUint8()>>4&15;return{codec:e+"."+n.addLeadingZero_(s)+"."+n.addLeadingZero_(a)+"."+n.addLeadingZero_(r)}}static parseAV1C(e,t,i){const n=n;t.skip(1);const s=t.readUint8(),a=t.readUint8(),r=s>>>5,o=31&s,l=a>>>7?"H":"M",d=(64&a)>>6,c=2===r&&d?(32&a)>>5?12:10:d?10:8,h=(16&a)>>4,u=(8&a)>>3,_=(4&a)>>2,m=3&a;return{codec:e+"."+r+"."+n.addLeadingZero_(o)+l+"."+n.addLeadingZero_(c)+"."+h+"."+u+_+m+"."+n.addLeadingZero_(1)+"."+n.addLeadingZero_(1)+"."+n.addLeadingZero_(1)+".0"}}static parseFRMA(e){const t=e.readUint32();return{codec:le.typeToString(t)}}static parseTENC(e){return e.readUint8(),e.readUint8(),e.readUint8(),e.readUint8(),{defaultKID:k.toHex(e.readBytes(16))}}static parseHDLR(e){e.skip(8);const t=e.readBytes(4);let i="";return i+=String.fromCharCode(t[0]),i+=String.fromCharCode(t[1]),i+=String.fromCharCode(t[2]),i+=String.fromCharCode(t[3]),{handlerType:i}}static toHex_(e,t=!1){const i=e.toString(16).toUpperCase();return t?i:("0"+i).slice(-2)}static reverseBits_(e){let t=e,i=0;for(let e=0;e<32&&(i|=1&t,31!=e);e++)i<<=1,t>>=1;return i}static addLeadingZero_(e){return(e<10?"0":"")+e}}class ce{static isHeader_(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}static isFooter_(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}static readSize_(e,t){let i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3],i}static getFrameData_(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=ce.readSize_(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}static decodeFrame_(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if("APIC"===e.type){if(e.size<2)return null;if(e.data[0]!==ce.UTF8_encoding)return n.warning("Ignore frame with unrecognized character encoding"),null;const i=e.data.subarray(1).indexOf(0);if(-1===i)return null;const s=x.fromUTF8(d.toUint8(e.data,1,i)),a=e.data[2+i],r=e.data.subarray(3+i).indexOf(0);if(-1===r)return null;const o=x.fromUTF8(d.toUint8(e.data,3+i,r));let l;return l="--\x3e"===s?x.fromUTF8(d.toUint8(e.data,4+i+r)):d.toArrayBuffer(e.data.subarray(4+i+r)),t.mimeType=s,t.pictureType=a,t.description=o,t.data=l,t}if("TXXX"===e.type){if(e.size<2)return null;if(e.data[0]!==ce.UTF8_encoding)return n.warning("Ignore frame with unrecognized character encoding"),null;const i=e.data.subarray(1).indexOf(0);if(-1===i)return null;const s=x.fromUTF8(d.toUint8(e.data,1,i)),a=x.fromUTF8(d.toUint8(e.data,2+i)).replace(/\0*$/,"");return t.description=s,t.data=a,t}if("WXXX"===e.type){if(e.size<2)return null;if(e.data[0]!==ce.UTF8_encoding)return n.warning("Ignore frame with unrecognized character encoding"),null;const i=e.data.subarray(1).indexOf(0);if(-1===i)return null;const s=x.fromUTF8(d.toUint8(e.data,1,i)),a=x.fromUTF8(d.toUint8(e.data,2+i)).replace(/\0*$/,"");return t.description=s,t.data=a,t}if("PRIV"===e.type){if(e.size<2)return null;const i=e.data.indexOf(0);if(-1===i)return null;const n=x.fromUTF8(d.toUint8(e.data,0,i));if(t.description=n,"com.apple.streaming.transportStreamTimestamp"==n){const i=e.data.subarray(n.length+1),s=1&i[3];let a=(i[4]<<23)+(i[5]<<15)+(i[6]<<7)+i[7];a/=45,s&&(a+=47721858.84),t.data=a}else{const i=d.toArrayBuffer(e.data.subarray(n.length+1));t.data=i}return t}if("T"===e.type[0]){if(e.size<2)return null;if(e.data[0]!==ce.UTF8_encoding)return n.warning("Ignore frame with unrecognized character encoding"),null;const i=x.fromUTF8(e.data.subarray(1)).replace(/\0*$/,"");return t.data=i,t}if("W"===e.type[0]){const i=x.fromUTF8(e.data).replace(/\0*$/,"");return t.data=i,t}return e.data?(n.warning("Unrecognized ID3 frame type:",e.type),t.data=d.toArrayBuffer(e.data),t):null}static getID3Frames(e){const t=t;let i=0;const n=[];for(;t.isHeader_(e,i);){const s=t.readSize_(e,i+6);e[i+5]>>6&1&&(i+=10),i+=10;const a=i+s;for(;i+10<a;){const s=t.getFrameData_(e.subarray(i)),a=t.decodeFrame_(s);a&&n.push(a),i+=s.size+10}t.isFooter_(e,i)&&(i+=10)}return n}static getID3Data(e,t=0){const i=i,n=t;let s=0;for(;i.isHeader_(e,t);)e[t+5]>>6&1&&(s+=10),s+=10,s+=i.readSize_(e,t+6),i.isFooter_(e,t+10)&&(s+=10),t+=s;return s>0?e.subarray(n,n+s):new Uint8Array([])}}ce.UTF8_encoding=3;class he{constructor(e,t=!1){this.data_=e,t&&(this.data_=this.ebsp2rbsp_(e)),this.workingBytesAvailable_=this.data_.byteLength,this.workingWord_=0,this.workingBitsAvailable_=0}ebsp2rbsp_(e){const t=new Uint8Array(e.byteLength);let i=0;for(let n=0;n<e.byteLength;n++)n>=2&&3==e[n]&&0==e[n-1]&&0==e[n-2]||(t[i]=e[n],i++);return d.toUint8(t,0,i)}loadWord_(){const e=this.data_.byteLength-this.workingBytesAvailable_,t=new Uint8Array(4),i=Math.min(4,this.workingBytesAvailable_);if(0===i)return;t.set(this.data_.subarray(e,e+i));const n=new oe(t,oe.Endianness.BIG_ENDIAN);this.workingWord_=n.readUint32(),this.workingBitsAvailable_=8*i,this.workingBytesAvailable_-=i}skipBits(e){if(this.workingBitsAvailable_<=e){e-=this.workingBitsAvailable_;const t=Math.floor(e/8);e-=8*t,this.workingBitsAvailable_-=t,this.loadWord_()}this.workingWord_<<=e,this.workingBitsAvailable_-=e}readBits(e){let t=Math.min(this.workingBitsAvailable_,e);const i=this.workingWord_>>>32-t;return this.workingBitsAvailable_-=t,this.workingBitsAvailable_>0?this.workingWord_<<=t:this.workingBytesAvailable_>0&&this.loadWord_(),t=e-t,t>0?i<<t|this.readBits(t):i}skipLeadingZeros_(){let e;for(e=0;e<this.workingBitsAvailable_;++e)if(0!=(this.workingWord_&2147483648>>>e))return this.workingWord_<<=e,this.workingBitsAvailable_-=e,e;return this.loadWord_(),e+this.skipLeadingZeros_()}skipExpGolomb(){this.skipBits(1+this.skipLeadingZeros_())}readUnsignedExpGolomb(){const e=this.skipLeadingZeros_();return this.readBits(e+1)-1}readExpGolomb(){const e=this.readUnsignedExpGolomb();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUnsignedByte(){return this.readBits(8)}skipScalingList(e){let t=8,i=8;for(let n=0;n<e;n++)0!==i&&(i=(t+this.readExpGolomb()+256)%256),t=0===i?t:i}readSliceType(){return this.readUnsignedByte(),this.readUnsignedExpGolomb(),this.readUnsignedExpGolomb()}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}class ue{constructor(){this.pmtId_=null,this.pmtParsed_=!1,this.videoPid_=null,this.videoCodec_=null,this.videoData_=[],this.videoPes_=[],this.audioPid_=null,this.audioCodec_=null,this.audioData_=[],this.audioPes_=[],this.id3Pid_=null,this.id3Data_=[],this.referencePts_=null,this.referenceDts_=null}clearData(){this.videoData_=[],this.videoPes_=[],this.audioData_=[],this.audioPes_=[],this.id3Data_=[]}parse(e){const t=ue.PacketLength_;if(e.length<3*t)return this;const i=Math.max(0,ue.syncOffset(e)),s=e.length-(e.length+i)%t;let a=!1;for(let r=i;r<s;r+=t)if(71==e[r]){const s=!!(64&e[r+1]),o=((31&e[r+1])<<8)+e[r+2];let l;if((48&e[r+3])>>4>1){if(l=r+5+e[r+4],l==r+t)continue}else l=r+4;switch(o){case 0:s&&(l+=e[l]+1),this.pmtId_=this.getPmtId_(e,l);break;case 17:case 8191:break;case this.pmtId_:{s&&(l+=e[l]+1);const o=this.parsePMT_(e,l);-1!=o.video&&(this.videoPid_=o.video,this.videoCodec_=o.videoCodec),-1!=o.audio&&(this.audioPid_=o.audio,this.audioCodec_=o.audioCodec),-1!=o.id3&&(this.id3Pid_=o.id3),a&&!this.pmtParsed_&&(n.debug("reparse from beginning"),a=!1,r=i-t),this.pmtParsed_=!0;break}case this.videoPid_:{const i=e.subarray(l,r+t);s?this.videoData_.push([i]):this.videoData_.length&&this.videoData_[this.videoData_.length-1]&&this.videoData_[this.videoData_.length-1].push(i);break}case this.audioPid_:{const i=e.subarray(l,r+t);s?this.audioData_.push([i]):this.audioData_.length&&this.audioData_[this.audioData_.length-1]&&this.audioData_[this.audioData_.length-1].push(i);break}case this.id3Pid_:{const i=e.subarray(l,r+t);s?this.id3Data_.push([i]):this.id3Data_.length&&this.id3Data_[this.id3Data_.length-1]&&this.id3Data_[this.id3Data_.length-1].push(i);break}default:a=!0}}else n.warning("Found TS packet that do not start with 0x47");return this}getPmtId_(e,t){return(31&e[t+10])<<8|e[t+11]}parsePMT_(e,t){const i={audio:-1,video:-1,id3:-1,audioCodec:"",videoCodec:""},n=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<n;){const n=(31&e[t+1])<<8|e[t+2],s=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 6:if(s>0){let a=t+5,r=s;for(;r>2;){const t=e[a],s=e[a+1]+2;switch(t){case 5:{const t=e.subarray(a+2,a+s),r=x.fromCharCode(t);-1==i.audio&&"Opus"===r?(i.audio=n,i.audioCodec="opus"):-1==i.video&&"AV01"===r&&(i.video=n,i.videoCodec="av1");break}case 106:-1==i.audio&&(i.audio=n,i.audioCodec="ac3");break;case 122:-1==i.audio&&(i.audio=n,i.audioCodec="ec3");break;case 124:-1==i.audio&&(i.audio=n,i.audioCodec="aac")}a+=s,r-=s}}break;case 207:case 219:break;case 15:-1==i.audio&&(i.audio=n,i.audioCodec="aac");break;case 17:-1==i.audio&&(i.audio=n,i.audioCodec="aac-loas");break;case 21:-1==i.id3&&(i.id3=n);break;case 27:-1==i.video&&(i.video=n,i.videoCodec="avc");break;case 3:case 4:-1==i.audio&&(i.audio=n,i.audioCodec="mp3");break;case 36:-1==i.video&&(i.video=n,i.videoCodec="hvc");break;case 129:-1==i.audio&&(i.audio=n,i.audioCodec="ac3");break;case 132:case 135:-1==i.audio&&(i.audio=n,i.audioCodec="ec3")}t+=s+5}return i}parsePES_(e){if(1!=(e[0]<<16|e[1]<<8|e[2]))return null;const t={data:new Uint8Array(0),packetLength:e[4]<<8|e[5],pts:null,dts:null,nalus:[]};if(t.packetLength&&t.packetLength>e.byteLength-6)return null;const i=e[7];if(192&i){const n=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2;if(null==this.referencePts_&&(this.referencePts_=n),t.pts=this.handleRollover_(n,this.referencePts_),this.referencePts_=t.pts,t.dts=t.pts,64&i){const i=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2;null==this.referenceDts_&&(this.referenceDts_=i),t.dts=this.handleRollover_(i,this.referenceDts_)}this.referenceDts_=t.dts}const n=e[8]+9;return e.byteLength<=n?null:(t.data=e.subarray(n),t)}parseAvcNalus(e,t){return re.deprecateFeature(5,"TsParser.parseAvcNalus","Please use parseNalus function instead."),this.parseNalus(e)}parseNalus(e,t,i){const s=ue.Timescale,a=e.pts?e.pts/s:null,r=e.data,o=r.byteLength;let l=1;"hvc"==this.videoCodec_&&(l=2);let d=i||0;const c=[];let h,u=-1,_=0;for(let e=0;e<o;++e){const s=r[e];if(s)if(d>=2&&1==s){if(t&&!c.length&&-1==u){const n=e-(d>3?3:d);if(i&&0!=n){const e=r.subarray(0,n);t.data=k.concat(t.data,e),t.fullData=k.concat(t.fullData,e)}}if(u>=0){const t=u+l,i=e-((d>3?3:d)+1),n={data:r.subarray(t,i+1),fullData:r.subarray(u,i+1),type:_,time:a};c.push(n)}else if(t&&!c.length){const i=e-d;if(i>0){const e=r.subarray(0,i);t.data=k.concat(t.data,e),t.fullData=k.concat(t.fullData,e)}}if(e>=o-l)return n.warning("Malformed TS, incomplete NALU, ignoring."),c;e++,u=e,_="hvc"==this.videoCodec_?r[e]>>1&63:31&r[e],d=0}else d=0;else d++;if(e>=o-1&&u>=0&&d>=0){const e=u+l;h={data:r.subarray(e,o),fullData:r.subarray(u,o),type:_,time:a}}}return h&&c.push(h),!c.length&&t&&(t.data=k.concat(t.data,r),t.fullData=k.concat(t.fullData,r)),i=Math.min(3,d),c}getMetadata(){const e=ue.Timescale,t=[];for(const i of this.id3Data_){const n=k.concat(...i),s=this.parsePES_(n);s&&t.push({cueTime:s.pts?s.pts/e:null,data:s.data,frames:ce.getID3Frames(s.data),dts:s.dts,pts:s.pts})}return t}getAudioData(){if(this.audioData_.length&&!this.audioPes_.length){let e=!1;for(const t of this.audioData_){const i=k.concat(...t),n=this.parsePES_(i);let s=this.audioPes_.length?this.audioPes_[this.audioPes_.length-1]:null;if(n&&null!=n.pts&&null!=n.dts&&(!s||s.pts!=n.pts&&s.dts!=n.dts))this.audioPes_.length&&n.dts<(s.dts||0)&&(e=!0),this.audioPes_.push(n);else if(this.audioPes_.length){const e=n?n.data:i;if(!e)continue;s=this.audioPes_.pop(),s.data=k.concat(s.data,e),this.audioPes_.push(s)}}e&&(this.audioPes_=this.audioPes_.sort(((e,t)=>{const i=(e.dts||0)-(t.dts||0),n=(e.pts||0)-(t.pts||0);return i||n})))}return this.audioPes_}getVideoData(e=!0){if(this.videoData_.length&&!this.videoPes_.length){let t=!1;for(const e of this.videoData_){const i=k.concat(...e),n=this.parsePES_(i);let s=this.videoPes_.length?this.videoPes_[this.videoPes_.length-1]:null;if(n&&null!=n.pts&&null!=n.dts&&(!s||s.pts!=n.pts&&s.dts!=n.dts))this.videoPes_.length&&n.dts<(s.dts||0)&&(t=!0),this.videoPes_.push(n);else if(this.videoPes_.length){const e=n?n.data:i;if(!e)continue;s=this.videoPes_.pop(),s.data=k.concat(s.data,e),this.videoPes_.push(s)}}if(e){let e,t;for(const i of this.videoPes_)i.nalus=this.parseNalus(i,e,t),i.nalus.length&&(e=i.nalus[i.nalus.length-1]);this.videoPes_=this.videoPes_.filter((e=>e.nalus.length))}t&&(this.videoPes_=this.videoPes_.sort(((e,t)=>{const i=(e.dts||0)-(t.dts||0),n=(e.pts||0)-(t.pts||0);return i||n})))}if(!e){const e=this.videoPes_;return this.videoPes_=[],e}return this.videoPes_}getStartTime(e){const t=ue.Timescale;if("audio"==e){let e=null;const i=this.getAudioData();if(i.length){const n=i[0];e=Math.min(n.dts,n.pts)/t}return e}if("video"==e){let e=null;const i=this.getVideoData(!1);if(i.length){const n=i[0];e=Math.min(n.dts,n.pts)/t}return e}return null}getCodecs(){return{audio:this.audioCodec_,video:this.videoCodec_}}getVideoNalus(){const e=[];for(const t of this.getVideoData())e.push(...t.nalus);return e}getVideoResolution(){re.deprecateFeature(5,"TsParser.getVideoResolution","Please use getVideoInfo function instead.");const e=this.getVideoInfo();return{height:e.height,width:e.width}}getVideoInfo(){return"hvc"==this.videoCodec_?this.getHvcInfo_():this.getAvcInfo_()}getAvcInfo_(){const e=e,t={height:null,width:null,codec:null},i=this.getVideoNalus();if(!i.length)return t;const n=i.find((t=>t.type==e.H264_NALU_TYPE_SPS_));if(!n)return t;const s=new he(n.data),a=s.readUnsignedByte(),r=s.readUnsignedByte(),o=s.readUnsignedByte();if(s.skipExpGolomb(),e.PROFILES_WITH_OPTIONAL_SPS_DATA_.includes(a)){const e=s.readUnsignedExpGolomb();if(3===e&&s.skipBits(1),s.skipExpGolomb(),s.skipExpGolomb(),s.skipBits(1),s.readBoolean()){const t=3!==e?8:12;for(let e=0;e<t;e++)s.readBoolean()&&(e<6?s.skipScalingList(16):s.skipScalingList(64))}}s.skipExpGolomb();const l=s.readUnsignedExpGolomb();if(0===l)s.readUnsignedExpGolomb();else if(1===l){s.skipBits(1),s.skipExpGolomb(),s.skipExpGolomb();const e=s.readUnsignedExpGolomb();for(let t=0;t<e;t++)s.skipExpGolomb()}s.skipExpGolomb(),s.skipBits(1);const d=s.readUnsignedExpGolomb(),c=s.readUnsignedExpGolomb(),h=s.readBits(1);0===h&&s.skipBits(1),s.skipBits(1);let u=0,_=0,m=0,g=0;return s.readBoolean()&&(u=s.readUnsignedExpGolomb(),_=s.readUnsignedExpGolomb(),m=s.readUnsignedExpGolomb(),g=s.readUnsignedExpGolomb()),t.height=String((2-h)*(c+1)*16-2*m-2*g),t.width=String(16*(d+1)-2*u-2*_),t.codec="avc1."+this.byteToHex_(a)+this.byteToHex_(r)+this.byteToHex_(o),t}getHvcInfo_(){const e=e,t={height:null,width:null,codec:null},i=this.getVideoNalus();if(!i.length)return t;const n=i.find((t=>t.type==e.H265_NALU_TYPE_SPS_));if(!n)return t;const s=new he(n.fullData,!0);s.readUnsignedByte(),s.readUnsignedByte(),s.readBits(4);const a=s.readBits(3);s.readBoolean();const r=s.readBits(2),o=s.readBits(1),l=s.readBits(5),d=s.readBits(32),c=s.readUnsignedByte(),h=s.readUnsignedByte(),u=s.readUnsignedByte(),_=s.readUnsignedByte(),m=s.readUnsignedByte(),g=s.readUnsignedByte(),f=s.readUnsignedByte(),p=[],T=[];for(let e=0;e<a;e++)p.push(s.readBoolean()),T.push(s.readBoolean());if(a>0)for(let e=a;e<8;e++)s.readBits(2);for(let e=0;e<a;e++)p[e]&&s.readBits(88),T[e]&&s.readUnsignedByte();s.readUnsignedExpGolomb();const S=s.readUnsignedExpGolomb();3==S&&s.readBits(1);const y=s.readUnsignedExpGolomb(),E=s.readUnsignedExpGolomb();let v=0,b=0,I=0,A=0;s.readBoolean()&&(v+=s.readUnsignedExpGolomb(),b+=s.readUnsignedExpGolomb(),I+=s.readUnsignedExpGolomb(),A+=s.readUnsignedExpGolomb());const w=1===S||2===S?2:1,C=1===S?2:1;t.width=String(y-(v+b)*w),t.height=String(E-(I+A)*C);const M=1==o?"H":"L";let R="hvc1";return R+="."+["","A","B","C"][r]+l,R+="."+(e=>{let t=0;for(let i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0})(d).toString(16).toUpperCase(),R+="."+M+f,g&&(R+="."+g.toString(16).toUpperCase()),m&&(R+="."+m.toString(16).toUpperCase()),_&&(R+="."+_.toString(16).toUpperCase()),u&&(R+="."+u.toString(16).toUpperCase()),h&&(R+="."+h.toString(16).toUpperCase()),c&&(R+="."+c.toString(16).toUpperCase()),t.codec=R,t}byteToHex_(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}handleRollover_(e,t){let i=1;for(e>t&&(i=-1);Math.abs(t-e)>4294967296;)e+=8589934592*i;return e}static probe(e){const t=ue.syncOffset(e);return!(t<0||(t>0&&n.warning("MPEG2-TS detected but first sync word found @ offset "+t+", junk ahead ?"),0))}static syncOffset(e){const t=ue.PacketLength_,i=Math.min(1e3,e.length-3*t);let n=0;for(;n<i;){if(71==e[n]&&71==e[n+t]&&71==e[n+2*t])return n;n++}return-1}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}ue.Timescale=9e4,ue.PacketLength_=188,ue.H264_NALU_TYPE_SPS_=7,ue.H265_NALU_TYPE_SPS_=33,ue.PROFILES_WITH_OPTIONAL_SPS_DATA_=[100,110,122,244,44,83,86,118,128,138,139,134];class _e{static registerParserByMime(e,t){E.parsersByMime[e]=t}static unregisterParserByMime(e){delete E.parsersByMime[e]}static probeSupport(){const e={};if(N.supportsMediaSource())for(const t in E.parsersByMime)e[t]=!0;const t=["application/dash+xml","application/x-mpegurl","application/vnd.apple.mpegurl","application/vnd.ms-sstr+xml"];for(const i of t)N.supportsMediaSource()?e[i]=!!E.parsersByMime[i]:e[i]=N.supportsMediaType(i);return e}static getFactory(e,t){if(t){const e=E.parsersByMime[t.toLowerCase()];if(e)return e;n.warning("Could not determine manifest type using MIME type ",t)}throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.UNABLE_TO_GUESS_MANIFEST_TYPE,e,t)}static isSupported(e){return!!N.supportsMediaSource()&&e in E.parsersByMime}}E=_e,_e.ManifestType=f,_e.HLS=E.ManifestType.HLS,_e.DASH=E.ManifestType.HLS,_e.MSS=E.ManifestType.MSS,_e.UNKNOWN=E.ManifestType.UNKNOWN,_e.AccessibilityPurpose=S,_e.parsersByMime={};class me{constructor(e){this.destroyed_=!1,this.waitOnDestroy_=new C,this.onDestroy_=e}destroyed(){return this.destroyed_}destroy(){return this.destroyed_?this.waitOnDestroy_:(this.destroyed_=!0,this.onDestroy_().then((()=>{this.waitOnDestroy_.resolve()}),(()=>{this.waitOnDestroy_.resolve()})))}ensureNotDestroyed(e){if(this.destroyed_){if(e instanceof b&&e.code==b.Code.OBJECT_DESTROYED)throw e;throw me.destroyedError(e)}}static destroyedError(e){return new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.OBJECT_DESTROYED,e)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class ge{static bufferStart(e){return e?1==e.length&&e.end(0)-e.start(0)<1e-6?null:1==e.length&&e.start(0)<0?0:e.length?e.start(0):null:null}static bufferEnd(e){return e?1==e.length&&e.end(0)-e.start(0)<1e-6?null:e.length?e.end(e.length-1):null:null}static isBuffered(e,t){return!(!e||!e.length||1==e.length&&e.end(0)-e.start(0)<1e-6||t>e.end(e.length-1)||!(t>=e.start(0)))}static bufferedAheadOf(e,t){if(!e||!e.length)return 0;if(1==e.length&&e.end(0)-e.start(0)<1e-6)return 0;let i=0;for(const{start:n,end:s}of ge.getBufferedInfo(e))s>t&&(i+=s-Math.max(n,t));return i}static getGapIndex(e,t,i){if(!e||!e.length)return null;if(1==e.length&&e.end(0)-e.start(0)<1e-6)return null;const n=ge.getBufferedInfo(e).findIndex(((e,n,s)=>e.start>t&&(0==n||s[n-1].end-t<=i)));return n>=0?n:null}static getBufferedInfo(e){if(!e)return[];const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static computeAddedRange(e,t){var i;if(!e||!e.length)return null;if(!t||!t.length)return null!==(i=ge.getBufferedInfo(t).pop())&&void 0!==i?i:null;const n=ge.getBufferedInfo(t).reverse(),s=ge.getBufferedInfo(e).reverse();for(const e of n){let t=!1;for(const i of s)if(i.end>=e.start&&i.end<=e.end&&(t=!0,e.end>i.end))return{start:i.end,end:e.end};if(!t)return e}return null}}class fe{static fakeEncryption(e){let t,i=d.toUint8(e),s=!1;const a=[],r=e=>{a.push(e),le.children(e)},o=e=>{s=!0},l=[];if((new le).box("moov",r).box("trak",r).box("mdia",r).box("minf",r).box("stbl",r).fullBox("stsd",(e=>{t=e,a.push(e),le.sampleDescription(e)})).fullBox("encv",o).fullBox("enca",o).fullBox("dvav",(e=>{l.push({box:e,newType:fe.BOX_TYPE_ENCV_})})).fullBox("dva1",(e=>{l.push({box:e,newType:fe.BOX_TYPE_ENCV_})})).fullBox("dvh1",(e=>{l.push({box:e,newType:fe.BOX_TYPE_ENCV_})})).fullBox("dvhe",(e=>{l.push({box:e,newType:fe.BOX_TYPE_ENCV_})})).fullBox("hev1",(e=>{l.push({box:e,newType:fe.BOX_TYPE_ENCV_})})).fullBox("hvc1",(e=>{l.push({box:e,newType:fe.BOX_TYPE_ENCV_})})).fullBox("avc1",(e=>{l.push({box:e,newType:fe.BOX_TYPE_ENCV_})})).fullBox("avc3",(e=>{l.push({box:e,newType:fe.BOX_TYPE_ENCV_})})).fullBox("ac-3",(e=>{l.push({box:e,newType:fe.BOX_TYPE_ENCA_})})).fullBox("ec-3",(e=>{l.push({box:e,newType:fe.BOX_TYPE_ENCA_})})).fullBox("ac-4",(e=>{l.push({box:e,newType:fe.BOX_TYPE_ENCA_})})).fullBox("mp4a",(e=>{l.push({box:e,newType:fe.BOX_TYPE_ENCA_})})).parse(i),s)return n.debug("Init segment already indicates encryption."),i;if(0==l.length||!t)throw n.error("Failed to find boxes needed to fake encryption!"),n.v2("Failed init segment (hex):",k.toHex(i)),new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.CONTENT_TRANSFORMATION_FAILED);l.reverse();for(const e of l){const s=le.typeToString(e.newType);n.debug(`Inserting "${s}" box into init segment.`),i=fe.insertEncryptionMetadata_(i,t,e.box,a,e.newType)}return i}static insertEncryptionMetadata_(e,t,i,n,s){const a=fe.createEncryptionMetadata_(e,i,s),r=new Uint8Array(e.byteLength+a.byteLength),o=N.isXboxOne()?i.start:i.start+i.size,l=e.subarray(0,o),c=e.subarray(o);r.set(l),r.set(a,o),r.set(c,o+a.byteLength);for(const e of n)console.assert(e.start<o,"Ancestor MP4 box found in the wrong location! Modified init segment will not make sense!"),fe.updateBoxSize_(r,e.start,e.size+a.byteLength);const h=d.toDataView(r,t.start),u=le.headerSize(t),_=h.getUint32(u);return h.setUint32(u,_+1),r}static createEncryptionMetadata_(e,t,i){const n=fe.CANNED_SINF_BOX_.value(),s=e.subarray(t.start,t.start+t.size),a=d.toDataView(s),r=new Uint8Array(t.size+n.byteLength);r.set(s,0);const o=d.toDataView(r);o.setUint32(fe.BOX_TYPE_OFFSET_,i),r.set(n,t.size);const l=a.getUint32(fe.BOX_TYPE_OFFSET_);return o.setUint32(t.size+fe.CANNED_SINF_BOX_FORMAT_OFFSET_,l),fe.updateBoxSize_(r,0,r.byteLength),r}static updateBoxSize_(e,t,i){const n=d.toDataView(e,t),s=n.getUint32(fe.BOX_SIZE_OFFSET_);0==s||(1==s?(n.setUint32(fe.BOX_SIZE_64_OFFSET_,i>>32),n.setUint32(fe.BOX_SIZE_64_OFFSET_+4,4294967295&i)):n.setUint32(fe.BOX_SIZE_OFFSET_,i))}}fe.CANNED_SINF_BOX_=new L((()=>new Uint8Array([0,0,0,80,115,105,110,102,0,0,0,12,102,114,109,97,0,0,0,0,0,0,0,20,115,99,104,109,0,0,0,0,99,101,110,99,0,1,0,0,0,0,0,40,115,99,104,105,0,0,0,32,116,101,110,99,0,0,0,0,0,0,1,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]))),fe.CANNED_SINF_BOX_FORMAT_OFFSET_=16,fe.BOX_SIZE_OFFSET_=0,fe.BOX_TYPE_OFFSET_=4,fe.BOX_SIZE_64_OFFSET_=8,fe.BOX_TYPE_ENCV_=1701733238,fe.BOX_TYPE_ENCA_=1701733217;class pe{constructor(e,t,i,n){this.video_=e,this.config_=null,this.textDisplayer_=t,this.sourceBuffers_={},this.sourceBufferTypes_={},this.expectedEncryption_={},this.textEngine_=null,this.segmentRelativeVttTiming_=!1,this.onMetadata_=i||((e,t,i)=>{}),this.lcevcDec_=n||null,this.queues_={},this.eventManager_=new ee,this.transmuxers_={},this.captionParser_=null,this.mediaSourceOpen_=new C,this.url_="",this.playbackHasBegun_=!1,this.mediaSource_=this.createMediaSource(this.mediaSourceOpen_),this.reloadingMediaSource_=!1,this.destroyer_=new me((()=>this.doDestroy_())),this.sequenceMode_=!1,this.manifestType_=_e.UNKNOWN,this.ignoreManifestTimestampsInSegmentsMode_=!1,this.attemptTimestampOffsetCalculation_=!1,this.textSequenceModeOffset_=new C,this.needSplitMuxedContent_=!1,this.streamingAllowed_=!0,this.lastDuration_=null,this.tsParser_=null}createMediaSource(e){if(window.ManagedMediaSource){this.video_.disableRemotePlayback=!0;const t=new ManagedMediaSource;return this.eventManager_.listen(t,"startstreaming",(()=>{this.streamingAllowed_=!0})),this.eventManager_.listen(t,"endstreaming",(()=>{this.streamingAllowed_=!1})),this.eventManager_.listenOnce(t,"sourceopen",(()=>this.onSourceOpen_(e))),this.eventManager_.listenOnce(this.video_,"playing",(()=>{this.playbackHasBegun_=!0})),this.url_=pe.createObjectURL(t),this.video_.src=this.url_,t}{const t=new MediaSource;return this.eventManager_.listenOnce(t,"sourceopen",(()=>this.onSourceOpen_(e))),this.eventManager_.listenOnce(this.video_,"playing",(()=>{this.playbackHasBegun_=!0})),this.url_=pe.createObjectURL(t),this.video_.src=this.url_,t}}onSourceOpen_(e){console.assert(this.url_,"Must have object URL"),URL.revokeObjectURL(this.url_),e.resolve()}static isStreamSupported(e){const t=F.getFullType(e.mimeType,e.codecs),i=F.getExtendedType(e),n=F.getFullTypeWithAllCodecs(e.mimeType,e.codecs);return z.isTypeSupported(t)||G.isTypeSupported(i)||B.isSupported(n,e.type)}static probeSupport(){const e=['video/mp4; codecs="avc1.42E01E"','video/mp4; codecs="avc3.42E01E"','video/mp4; codecs="hev1.1.6.L93.90"','video/mp4; codecs="hvc1.1.6.L93.90"','video/mp4; codecs="hev1.2.4.L153.B0"; eotf="smpte2084"','video/mp4; codecs="hvc1.2.4.L153.B0"; eotf="smpte2084"','video/mp4; codecs="vp9"','video/mp4; codecs="vp09.00.10.08"','video/mp4; codecs="av01.0.01M.08"','video/mp4; codecs="dvh1.20.01"','audio/mp4; codecs="mp4a.40.2"','audio/mp4; codecs="ac-3"','audio/mp4; codecs="ec-3"','audio/mp4; codecs="ac-4"','audio/mp4; codecs="opus"','audio/mp4; codecs="flac"','audio/mp4; codecs="dtsc"','audio/mp4; codecs="dtse"','audio/mp4; codecs="dtsx"','video/webm; codecs="vp8"','video/webm; codecs="vp9"','video/webm; codecs="vp09.00.10.08"','audio/webm; codecs="vorbis"','audio/webm; codecs="opus"','video/mp2t; codecs="avc1.42E01E"','video/mp2t; codecs="avc3.42E01E"','video/mp2t; codecs="hvc1.1.6.L93.90"','video/mp2t; codecs="mp4a.40.2"','video/mp2t; codecs="ac-3"','video/mp2t; codecs="ec-3"',"text/vtt",'application/mp4; codecs="wvtt"',"application/ttml+xml",'application/mp4; codecs="stpp"',...F.RAW_FORMATS],t={};for(const i of e){N.supportsMediaSource()?z.isTypeSupported(i)?t[i]=!0:t[i]=G.isTypeSupported(i)||B.isSupported(i):t[i]=N.supportsMediaType(i);const e=i.split(";")[0];t[e]=t[e]||t[i]}return t}destroy(){return this.destroyer_.destroy()}async doDestroy_(){const e=[];for(const t in this.queues_){const i=this.queues_[t],n=i[0];this.queues_[t]=i.slice(0,1),n&&e.push(n.p.catch(V.noop));for(const e of i.slice(1))e.p.reject(me.destroyedError())}this.textEngine_&&e.push(this.textEngine_.destroy()),this.textDisplayer_&&e.push(this.textDisplayer_.destroy());for(const t in this.transmuxers_)e.push(this.transmuxers_[t].destroy());await Promise.all(e),this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null),this.video_&&(this.video_.removeAttribute("src"),this.video_.load(),this.video_=null),this.config_=null,this.mediaSource_=null,this.textEngine_=null,this.textDisplayer_=null,this.sourceBuffers_={},this.transmuxers_={},this.captionParser_=null;for(const e in this.queues_)console.assert(0==this.queues_[e].length,e+" queue should be empty after destroy!");this.queues_={},this.lcevcDec_=null,this.tsParser_=null}open(){return this.mediaSourceOpen_}async init(e,t=!1,i=_e.UNKNOWN,n=!1){const s=U.ContentType;await this.mediaSourceOpen_,this.sequenceMode_=t,this.manifestType_=i,this.ignoreManifestTimestampsInSegmentsMode_=n,this.attemptTimestampOffsetCalculation_=!this.sequenceMode_&&this.manifestType_==_e.HLS&&!this.ignoreManifestTimestampsInSegmentsMode_,this.tsParser_=null;for(const t of e.keys()){const i=e.get(t);this.initSourceBuffer_(t,i,i.codecs),this.needSplitMuxedContent_?(this.queues_[s.AUDIO]=[],this.queues_[s.VIDEO]=[]):this.queues_[t]=[]}}initSourceBuffer_(e,t,i){const n=U.ContentType;console.assert(pe.isStreamSupported(t),"Type negotiation should happen before MediaSourceEngine.init!");let s=F.getFullType(t.mimeType,i);if(e==n.TEXT)this.reinitText(s,this.sequenceMode_,t.external);else{let a=this.config_.forceTransmux;(!G.isTypeSupported(s)||!this.sequenceMode_&&F.RAW_FORMATS.includes(s))&&(a=!0);const r=F.getFullTypeWithAllCodecs(t.mimeType,i);if(a){const a=U.guessCodecsSafe(n.AUDIO,(i||"").split(",")),o=U.guessCodecsSafe(n.VIDEO,(i||"").split(","));if(a&&o)return this.needSplitMuxedContent_=!0,this.initSourceBuffer_(n.AUDIO,t,a),void this.initSourceBuffer_(n.VIDEO,t,o);const l=B.findTransmuxer(r);if(l){const t=l();this.transmuxers_[e]=t,s=t.convertCodecs(e,r)}}const o=this.addExtraFeaturesToMimeType_(s);let l;this.destroyer_.ensureNotDestroyed();try{l=this.mediaSource_.addSourceBuffer(o)}catch(e){throw new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.MEDIA_SOURCE_OPERATION_THREW,e,"The mediaSource_ status was "+this.mediaSource_.readyState+" expected 'open'")}this.sequenceMode_&&(l.mode=pe.SourceBufferMode_.SEQUENCE),this.eventManager_.listen(l,"error",(()=>this.onError_(e))),this.eventManager_.listen(l,"updateend",(()=>this.onUpdateEnd_(e))),this.sourceBuffers_[e]=l,this.sourceBufferTypes_[e]=s,this.expectedEncryption_[e]=!1}}configure(e){this.config_=e,this.textEngine_&&this.textEngine_.setModifyCueCallback(e.modifyCueCallback)}isStreamingAllowed(){return this.streamingAllowed_}reinitText(e,t,i){this.textEngine_||(this.textEngine_=new z(this.textDisplayer_),this.textEngine_&&this.textEngine_.setModifyCueCallback(this.config_.modifyCueCallback)),this.textEngine_.initParser(e,t,i||this.segmentRelativeVttTiming_,this.manifestType_)}ended(){return!(this.reloadingMediaSource_||this.mediaSource_&&"ended"!=this.mediaSource_.readyState)}bufferStart(e){return this.reloadingMediaSource_||!Object.keys(this.sourceBuffers_).length?null:e==U.ContentType.TEXT?this.textEngine_.bufferStart():ge.bufferStart(this.getBuffered_(e))}bufferEnd(e){return this.reloadingMediaSource_?null:e==U.ContentType.TEXT?this.textEngine_.bufferEnd():ge.bufferEnd(this.getBuffered_(e))}isBuffered(e,t){if(this.reloadingMediaSource_)return!1;if(e==U.ContentType.TEXT)return this.textEngine_.isBuffered(t);{const i=this.getBuffered_(e);return ge.isBuffered(i,t)}}bufferedAheadOf(e,t){if(this.reloadingMediaSource_)return 0;if(e==U.ContentType.TEXT)return this.textEngine_.bufferedAheadOf(t);{const i=this.getBuffered_(e);return ge.bufferedAheadOf(i,t)}}getBufferedInfo(){const e=U.ContentType,t={total:this.reloadingMediaSource_?[]:ge.getBufferedInfo(this.video_.buffered),audio:this.reloadingMediaSource_?[]:ge.getBufferedInfo(this.getBuffered_(e.AUDIO)),video:this.reloadingMediaSource_?[]:ge.getBufferedInfo(this.getBuffered_(e.VIDEO)),text:[]};if(this.textEngine_){const e=this.textEngine_.bufferStart(),i=this.textEngine_.bufferEnd();null!=e&&null!=i&&t.text.push({start:e,end:i})}return t}getBuffered_(e){try{return this.sourceBuffers_[e].buffered}catch(t){return e in this.sourceBuffers_&&n.error("failed to get buffered range for "+e,t),null}}getCaptionParser(e){return new X(e)}getTimestampAndDispatchMetadata_(e,t,i,n,s){let a=null;const r=d.toUint8(t);if(F.RAW_FORMATS.includes(n)){const e=ce.getID3Frames(r);if(e.length&&i){const t=e.find((e=>"com.apple.streaming.transportStreamTimestamp"===e.description));t&&t.data&&(a=Math.round(t.data)/1e3);const n={cueTime:i.startTime,data:r,frames:e,dts:i.startTime,pts:i.startTime};this.onMetadata_([n],0,i.endTime)}}else if(n.includes("/mp4")&&i&&0==i.timestampOffset&&i.initSegmentReference&&i.initSegmentReference.timescale){const e=i.initSegmentReference.timescale;if(!isNaN(e)){let i=0,n=!1;(new le).box("moof",le.children).box("traf",le.children).fullBox("tfdt",(t=>{console.assert(0==t.version||1==t.version,"TFDT version can only be 0 or 1");const s=de.parseTFDTInaccurate(t.reader,t.version);i=s.baseMediaDecodeTime/e,n=!0,t.parser.stop()})).parse(t,!0),n&&(a=i)}}else if(!n.includes("/mp4")&&!n.includes("/webm")&&ue.probe(r)){this.tsParser_?this.tsParser_.clearData():this.tsParser_=new ue;const t=this.tsParser_.parse(r),n=t.getStartTime(e);null!=n&&(a=n);const o=t.getMetadata();o.length&&this.onMetadata_(o,s,i?i.endTime:null)}return a}async appendBuffer(e,t,i,s,a,r=!1,o=!1,l=!1,d=!1){const c=U.ContentType;if(e==c.TEXT){if(this.sequenceMode_){const e=await this.textSequenceModeOffset_;this.textEngine_.setTimestampOffset(e)}return void await this.textEngine_.appendBuffer(t,i?i.startTime:null,i?i.endTime:null,i?i.getUris()[0]:null)}if(!d&&this.needSplitMuxedContent_)return await this.appendBuffer(c.AUDIO,t,i,s,a,r,o,l,!0),void await this.appendBuffer(c.VIDEO,t,i,s,a,r,o,l,!0);if(!this.sourceBuffers_[e])return void n.warning("Attempted to restore a non-existent source buffer");let h=this.sourceBuffers_[e].timestampOffset,u=this.sourceBufferTypes_[e];if(this.transmuxers_[e]&&(u=this.transmuxers_[e].getOriginalMimeType()),i){const n=this.getTimestampAndDispatchMetadata_(e,t,i,u,h);if(null!=n){const t=i.startTime-n;(Math.abs(h-t)>=.001||r||o)&&(!l||t>0||!h)&&(h=t,this.attemptTimestampOffsetCalculation_&&(this.enqueueOperation_(e,(()=>this.abort_(e))),this.enqueueOperation_(e,(()=>this.setTimestampOffset_(e,h)))));const s=e==c.VIDEO||!(c.VIDEO in this.sourceBuffers_);this.sequenceMode_&&s&&this.textSequenceModeOffset_.resolve(h)}}if(a&&e==c.VIDEO){if(this.textEngine_||this.reinitText(F.CEA608_CLOSED_CAPTION_MIMETYPE,this.sequenceMode_,!1),!this.captionParser_){const e=u.split(";",1)[0];this.captionParser_=this.getCaptionParser(e)}if(i){const e=this.captionParser_.parseFrom(t);e.length&&this.textEngine_.storeAndAppendClosedCaptions(e,i.startTime,i.endTime,h)}else this.captionParser_.init(t)}if(this.transmuxers_[e]&&(t=await this.transmuxers_[e].transmux(t,s,i,this.mediaSource_.duration,e)),t=this.workAroundBrokenPlatforms_(t,i?i.startTime:null,e),i&&this.sequenceMode_&&e!=c.TEXT&&(r||o)){const t=i.startTime;this.enqueueOperation_(e,(()=>this.abort_(e))),this.enqueueOperation_(e,(()=>this.setTimestampOffset_(e,t)))}let _=null;if(await this.enqueueOperation_(e,(()=>{!i||i.isPreload()||l||(_=this.getBuffered_(e)),this.append_(e,t,h)})),i&&!i.isPreload()&&!l){const t=this.getBuffered_(e),s=ge.computeAddedRange(_,t);if(s){const e=i.endTime-i.startTime,t=Math.abs(s.end-i.endTime);e>.1&&t>e/2&&n.error("Possible encoding problem detected!","Unexpected buffered range for reference",i,"from URIs",i.getUris(),"should be",{start:i.startTime,end:i.endTime},"but got",s)}}}setSelectedClosedCaptionId(e){const t=U.ContentType.VIDEO,i=this.bufferEnd(t)||0;this.textEngine_.setSelectedClosedCaptionId(e,i)}clearSelectedClosedCaptionId(){this.textEngine_&&this.textEngine_.setSelectedClosedCaptionId("",0)}async remove(e,t,i){const n=U.ContentType;e==n.TEXT?await this.textEngine_.remove(t,i):(await this.enqueueOperation_(e,(()=>this.remove_(e,t,i))),this.needSplitMuxedContent_&&await this.enqueueOperation_(n.AUDIO,(()=>this.remove_(n.AUDIO,t,i))))}async clear(e){const t=U.ContentType;if(e==t.TEXT){if(!this.textEngine_)return;await this.textEngine_.remove(0,1/0)}else await this.enqueueOperation_(e,(()=>this.remove_(e,0,this.mediaSource_.duration))),this.needSplitMuxedContent_&&await this.enqueueOperation_(t.AUDIO,(()=>this.remove_(t.AUDIO,0,this.mediaSource_.duration)))}resetCaptionParser(){this.captionParser_&&this.captionParser_.reset()}async flush(e){const t=U.ContentType;e!=t.TEXT&&(await this.enqueueOperation_(e,(()=>this.flush_(e))),this.needSplitMuxedContent_&&await this.enqueueOperation_(t.AUDIO,(()=>this.flush_(t.AUDIO))))}async setStreamProperties(e,t,i,n,s,a,r,o){const l=U.ContentType;if(e==l.TEXT)return s||this.textEngine_.setTimestampOffset(t),void this.textEngine_.setAppendWindow(i,n);const d=[];await this.codecSwitchIfNecessary_(e,a,r,o)||(d.push(this.enqueueOperation_(e,(()=>this.abort_(e)))),this.needSplitMuxedContent_&&d.push(this.enqueueOperation_(l.AUDIO,(()=>this.abort_(l.AUDIO))))),s||(d.push(this.enqueueOperation_(e,(()=>this.setTimestampOffset_(e,t)))),this.needSplitMuxedContent_&&d.push(this.enqueueOperation_(l.AUDIO,(()=>this.setTimestampOffset_(l.AUDIO,t))))),d.push(this.enqueueOperation_(e,(()=>this.setAppendWindow_(e,i,n)))),this.needSplitMuxedContent_&&d.push(this.enqueueOperation_(l.AUDIO,(()=>this.setAppendWindow_(l.AUDIO,i,n)))),await Promise.all(d)}async resync(e,t){const i=U.ContentType;e!=i.TEXT&&(this.enqueueOperation_(e,(()=>this.abort_(e))),this.needSplitMuxedContent_&&this.enqueueOperation_(i.AUDIO,(()=>this.abort_(i.AUDIO))),await this.enqueueOperation_(e,(()=>this.setTimestampOffset_(e,t))),this.needSplitMuxedContent_&&await this.enqueueOperation_(i.AUDIO,(()=>this.setTimestampOffset_(i.AUDIO,t))))}async endOfStream(e){await this.enqueueBlockingOperation_((()=>{this.ended()||"closed"===this.mediaSource_.readyState||(e?this.mediaSource_.endOfStream(e):this.mediaSource_.endOfStream())}))}async setDuration(e){await this.enqueueBlockingOperation_((()=>{if(e<this.mediaSource_.duration)for(const e in this.sourceBuffers_){const t={start:()=>{},p:new C};this.queues_[e].unshift(t)}this.mediaSource_.duration=e,this.lastDuration_=e}))}getDuration(){return this.mediaSource_.duration}append_(e,t,i){e==U.ContentType.VIDEO&&this.lcevcDec_&&this.lcevcDec_.appendBuffer(t,i),this.sourceBuffers_[e].appendBuffer(t)}remove_(e,t,i){i<=t?this.onUpdateEnd_(e):this.sourceBuffers_[e].remove(t,i)}abort_(e){const t=this.sourceBuffers_[e].appendWindowStart,i=this.sourceBuffers_[e].appendWindowEnd;this.sourceBuffers_[e].abort(),this.sourceBuffers_[e].appendWindowStart=t,this.sourceBuffers_[e].appendWindowEnd=i,this.onUpdateEnd_(e)}flush_(e){console.assert(0==this.video_.buffered.length,"MediaSourceEngine.flush_ should only be used after clearing all data!"),this.video_.currentTime-=.001,this.onUpdateEnd_(e)}setTimestampOffset_(e,t){t<0&&(t+=.001),this.sourceBuffers_[e].timestampOffset=t,this.onUpdateEnd_(e)}setAppendWindow_(e,t,i){this.sourceBuffers_[e].appendWindowStart=0,this.sourceBuffers_[e].appendWindowEnd=i,this.sourceBuffers_[e].appendWindowStart=t,this.onUpdateEnd_(e)}onError_(e){const t=this.queues_[e][0];console.assert(t,"Spurious error event!"),console.assert(!this.sourceBuffers_[e].updating,"SourceBuffer should not be updating on error!");const i=this.video_.error?this.video_.error.code:0;t.p.reject(new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.MEDIA_SOURCE_OPERATION_FAILED,i))}onUpdateEnd_(e){if(this.reloadingMediaSource_)return;const t=this.queues_[e][0];console.assert(t,"Spurious updateend event!"),t&&(console.assert(!this.sourceBuffers_[e].updating,"SourceBuffer should not be updating on updateend!"),t.p.resolve(),this.popFromQueue_(e))}enqueueOperation_(e,t){this.destroyer_.ensureNotDestroyed();const i={start:t,p:new C};return this.queues_[e].push(i),1==this.queues_[e].length&&this.startOperation_(e),i.p}async enqueueBlockingOperation_(e){this.destroyer_.ensureNotDestroyed();const t=[];for(const e in this.sourceBuffers_){const i=new C,n={start:()=>i.resolve(),p:i};this.queues_[e].push(n),t.push(i),1==this.queues_[e].length&&n.start()}try{await Promise.all(t)}catch(e){console.assert(this.destroyer_.destroyed(),"Should be destroyed by now");for(const e in this.sourceBuffers_)this.queues_[e].length&&(console.assert(1==this.queues_[e].length,"Should be at most one item in queue!"),console.assert(t.includes(this.queues_[e][0].p),"The item in queue should be one of our waiters!"),this.queues_[e].shift());throw e}for(const e in this.sourceBuffers_)console.assert(0==this.sourceBuffers_[e].updating,"SourceBuffers should not be updating after a blocking op!");try{await e()}catch(e){throw new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.MEDIA_SOURCE_OPERATION_THREW,e,this.video_.error||"No error in the media element")}finally{for(const e in this.sourceBuffers_)this.popFromQueue_(e)}}popFromQueue_(e){this.queues_[e].shift(),this.startOperation_(e)}startOperation_(e){const t=this.queues_[e][0];if(t)try{t.start()}catch(i){"QuotaExceededError"==i.name?t.p.reject(new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.QUOTA_EXCEEDED_ERROR,e)):t.p.reject(new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.MEDIA_SOURCE_OPERATION_THREW,i,this.video_.error||"No error in the media element")),this.popFromQueue_(e)}}getTextDisplayer(){return console.assert(this.textDisplayer_,"TextDisplayer should only be null when this is destroyed"),this.textDisplayer_}setTextDisplayer(e){const t=this.textDisplayer_;this.textDisplayer_=e,t&&(e.setTextVisibility(t.isTextVisible()),t.destroy()),this.textEngine_&&this.textEngine_.setDisplayer(e)}setSegmentRelativeVttTiming(e){this.segmentRelativeVttTiming_=e}workAroundBrokenPlatforms_(e,t,i){const s=null==t,a=this.expectedEncryption_[i];return this.config_.insertFakeEncryptionInInit&&s&&a&&N.requiresEncryptionInfoInAllInitSegments()&&"mp4"==F.getContainerType(this.sourceBufferTypes_[i])&&(n.debug("Forcing fake encryption information in init segment."),e=fe.fakeEncryption(e)),e}change_(e,t,i){if(e!==U.ContentType.TEXT){if(n.debug(`Change Type: ${this.sourceBufferTypes_[e]} -> ${t}`),G.isChangeTypeSupported()){this.transmuxers_[e]&&(this.transmuxers_[e].destroy(),delete this.transmuxers_[e]),i&&(this.transmuxers_[e]=i);const n=this.addExtraFeaturesToMimeType_(t);this.sourceBuffers_[e].changeType(n),this.sourceBufferTypes_[e]=t}else n.debug("Change Type not supported");this.onUpdateEnd_(e)}else n.debug(`Change not supported for ${e}`)}changeType(e,t,i){return this.enqueueOperation_(e,(()=>this.change_(e,t,i)))}async reset_(e){const t=t,i=U.ContentType;this.reloadingMediaSource_=!0,this.needSplitMuxedContent_=!1;const n=this.video_.currentTime,s=this.video_.autoplay,a=this.video_.paused;this.playbackHasBegun_&&(this.video_.autoplay=!1);try{this.eventManager_.removeAll();const s=[];for(const e in this.transmuxers_)s.push(this.transmuxers_[e].destroy());for(const e in this.queues_){const i=this.queues_[e],n=i[0];this.queues_[e]=i.slice(0,1),n&&s.push(n.p.catch(t.noop));for(const e of i.slice(1))e.p.reject(me.destroyedError())}for(const t in this.sourceBuffers_){const i=this.sourceBuffers_[t];try{this.mediaSource_.removeSourceBuffer(i)}catch(e){}}await Promise.all(s),this.transmuxers_={},this.sourceBuffers_={};const a=this.mediaSource_.duration;this.mediaSourceOpen_=new C,this.mediaSource_=this.createMediaSource(this.mediaSourceOpen_),await this.mediaSourceOpen_,!isNaN(a)&&a?this.mediaSource_.duration=a:!isNaN(this.lastDuration_)&&this.lastDuration_&&(this.mediaSource_.duration=this.lastDuration_);const r=new C,o=this.mediaSource_.sourceBuffers,l=e.size;let d=0;this.eventManager_.listen(o,"addsourcebuffer",(e=>{d++,d===l&&r.resolve()}));for(const t of e.keys()){const n=e.get(t);this.initSourceBuffer_(t,n,n.codecs),this.needSplitMuxedContent_?(this.queues_[i.AUDIO]=[],this.queues_[i.VIDEO]=[]):this.queues_[t]=[]}this.video_.currentTime=n,await r}finally{this.reloadingMediaSource_=!1,this.destroyer_.ensureNotDestroyed(),this.eventManager_.listenOnce(this.video_,"canplaythrough",(()=>{this.destroyer_.ensureNotDestroyed(),this.video_.autoplay=s,a||this.video_.play()}))}}reset(e){return this.enqueueBlockingOperation_((()=>this.reset_(e)))}async codecSwitchIfNecessary_(e,t,i,n){const s=U.ContentType;if(e==s.TEXT)return!1;const a=F.getCodecBase(F.getCodecs(this.sourceBufferTypes_[e])),r=F.getBasicType(this.sourceBufferTypes_[e]);let o,l=!1,d=F.getFullType(t,i),c=this.config_.forceTransmux;if((!G.isTypeSupported(d)||!this.sequenceMode_&&F.RAW_FORMATS.includes(d))&&(c=!0),c){const n=F.getFullTypeWithAllCodecs(t,i),a=B.findTransmuxer(n);if(a){o=a();const r=U.guessCodecsSafe(s.AUDIO,(i||"").split(",")),c=U.guessCodecsSafe(s.VIDEO,(i||"").split(","));if(r&&c){l=!0;let i=c;e==s.AUDIO&&(i=r),d=o.convertCodecs(e,F.getFullTypeWithAllCodecs(t,i))}else d=o.convertCodecs(e,n)}}const h=F.getCodecBase(F.getCodecs(d)),u=F.getBasicType(d);if(a===h&&r===u)return!1;let _=!0;return(this.needSplitMuxedContent_||l&&o&&!this.transmuxers_[e])&&(_=!1),_&&"smooth"===this.config_.codecSwitchingStrategy&&G.isChangeTypeSupported()?await this.changeType(e,d,o):(o&&o.destroy(),await this.reset(n)),!0}isCodecSwitchNecessary_(e,t){if(e==U.ContentType.TEXT)return!1;const i=F.getCodecBase(F.getCodecs(this.sourceBufferTypes_[e])),n=F.getBasicType(this.sourceBufferTypes_[e]);let s=F.getFullType(t.mimeType,t.codecs),a=this.config_.forceTransmux;(!G.isTypeSupported(s)||!this.sequenceMode_&&F.RAW_FORMATS.includes(s))&&(a=!0);const r=F.getFullTypeWithAllCodecs(t.mimeType,t.codecs);if(a){const t=B.findTransmuxer(r);if(t){const i=t();s=i.convertCodecs(e,r),i.destroy()}}const o=F.getCodecBase(F.getCodecs(s)),l=F.getBasicType(s);return i!==o||n!==l}isResetMediaSourceNecessary(e,t){return!!this.isCodecSwitchNecessary_(e,t)&&("smooth"!==this.config_.codecSwitchingStrategy||!G.isChangeTypeSupported()||this.needSplitMuxedContent_)}updateLcevcDec(e){this.lcevcDec_=e}addExtraFeaturesToMimeType_(e){const t=e+this.config_.addExtraFeaturesToSourceBuffer(e);return n.debug("Using full mime type",t),t}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,"LCEVCDecoder"]}}pe.createObjectURL=window.URL.createObjectURL,pe.Operation,pe.SourceBufferMode_={SEQUENCE:"sequence",SEGMENTS:"segments"};class Te{constructor(e,t,i){this.lcevcLib_,this.dec_=null,this.variantId_=-1,this.media_=e,this.canvas_=t,this.decConfig_=i,this.toBeDeprecated_=!1,this.create_()}appendBuffer(e,t){this.dec_&&this.dec_.appendBuffer(e,"video",this.variantId_,-t)}hideCanvas(){this.dec_&&this.canvas_.classList.add("shaka-hidden")}create_(){this.isSupported_()&&!this.dec_&&this.lcevcLib_.SupportObject.webGLSupport(this.canvas_)&&(this.canvas_.classList.remove("shaka-hidden"),this.toBeDeprecated_?this.dec_=new this.lcevcLib_.LcevcDil(this.media_,this.canvas_,this.decConfig_):this.dec_=new this.lcevcLib_.LCEVCdec(this.media_,this.canvas_,this.decConfig_))}release(){this.dec_&&(this.dec_.close(),this.dec_=null)}isSupported_(){if("undefined"==typeof libDPIModule&&n.alwaysWarn("Could not find LCEVC Library dependencies on this page"),"undefined"!=typeof LCEVCdec)this.lcevcLib_=LCEVCdec;else{if("undefined"==typeof LcevcDil)return n.alwaysWarn("Could not find LCEVC Library on this page"),!1;this.lcevcLib_=LcevcDil,this.toBeDeprecated_=!0,re.deprecateFeature(5,"LcevcDil","lcevc_dil.js is deprecated, please use lcevc_dec.js instead")}return void 0===this.lcevcLib_.SupportObject?(n.alwaysWarn("Could not find LCEVC Library on this page"),!1):(this.lcevcLib_.SupportObject.SupportStatus||n.alwaysWarn(this.lcevcLib_.SupportObject.SupportError),void 0!==this.lcevcLib_&&"undefined"!=typeof libDPIModule&&this.canvas_ instanceof HTMLCanvasElement&&this.lcevcLib_.SupportObject.SupportStatus)}updateVariant(e,t){let i=Te.ContainerFormat.MPEG2_TS,n=Te.StreamingFormat.OTHER;switch(e.mimeType){case"video/webm":i=Te.ContainerFormat.WEBM;break;case"video/mp4":i=Te.ContainerFormat.MP4}switch(t){case"DASH":n=Te.StreamingFormat.DASH;break;case"HLS":n=Te.StreamingFormat.HLS}this.dec_&&(this.variantId_=e.id,this.dec_.setLevelSwitching(e.id,!0),this.dec_.setContainerFormat(i),this.toBeDeprecated_||this.dec_.setStreamingFormat(n))}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0]}}Te.ContainerFormat={MPEG2_TS:0,WEBM:1,MP4:2},Te.StreamingFormat={HLS:0,DASH:1,OTHER:-1};class Se{constructor(e,t){console.assert(e,"Must have config"),this.config_=e,this.maxHwRes_=t}async filterManifest(e){return await this.filterManifestWithStreamUtils_(e),this.filterManifestWithRestrictions(e)}async filterManifestWithStreamUtils_(e){console.assert(e,"Manifest should exist!"),await j.filterManifest(e),this.checkPlayableVariants_(e)}applyRestrictions(e){return j.applyRestrictions(e.variants,this.config_.restrictions,this.maxHwRes_)}filterManifestWithRestrictions(e){const t=this.applyRestrictions(e);if(e){const t=this.drmEngine_?this.drmEngine_.getDrmInfo():null;if(t&&this.drmEngine_.getMediaKeys())for(const i of e.variants)this.processDrmInfos(t.keySystem,i.video),this.processDrmInfos(t.keySystem,i.audio);this.checkRestrictedVariants(e)}return t}checkPlayableVariants_(e){if(!e.variants.some(j.isPlayable))throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.CONTENT_UNSUPPORTED_BY_BROWSER)}processDrmInfos(e,t){if(t)for(const i of t.drmInfos)if(i.keySystem==e)for(const e of i.initData||[])this.drmEngine_.newInitData(e.initDataType,e.initData)}checkRestrictedVariants(e){const t=this.drmEngine_?this.drmEngine_.getKeyStatuses():{},i=Object.keys(t);i.length&&i[0];let n=!1,s=!1;const a=new Set,r=new Set;for(const t of e.variants){const e=[];t.audio&&e.push(t.audio),t.video&&e.push(t.video),t.allowedByApplication?t.allowedByKeySystem&&(n=!0):s=!0}if(!n){const e={hasAppRestrictions:s,missingKeys:Array.from(a),restrictedKeyStatuses:Array.from(r)};throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.RESTRICTIONS_CANNOT_BE_MET,e)}}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}Se.restrictedStatuses=["output-restricted","internal-error"];class ye{constructor(e,t,i,n=null,s=null,a=null){this.getUris=e,this.startByte=t,this.endByte=i,this.mediaQuality=n,this.timescale=s,this.segmentData=a,this.codecs=null,this.mimeType=null}getStartByte(){return this.startByte}getEndByte(){return this.endByte}getSize(){return this.endByte?this.endByte-this.startByte:null}getMediaQuality(){return this.mediaQuality}getSegmentData(){return this.segmentData}static equal(e,t){return e===t||(e&&t?e.getStartByte()==t.getStartByte()&&e.getEndByte()==t.getEndByte()&&I.equal(e.getUris().sort(),t.getUris().sort())&&d.equal(e.getSegmentData(),t.getSegmentData()):e==t)}static get[Symbol.for("___CTOR_ARGS___")](){return["() => Array<string>","number","number | null","MediaQualityInfo | null","number | null","BufferSource | null"]}}!function(e){e[e.AVAILABLE=0]="AVAILABLE",e[e.UNAVAILABLE=1]="UNAVAILABLE",e[e.MISSING=2]="MISSING"}(v||(v={}));class Ee{constructor(e,t,i,n,s,a,r,o,l,d=[],c="",h=null,u=null,_=Ee.Status.AVAILABLE,m=!1){this.endByte=null,this.initSegmentReference=null,this.tilesLayout=null,this.tileDuration=null,this.syncTime=null,this.thumbnailSprite=null,this.codecs=null,this.mimeType=null,this.segmentData=null,console.assert(e<=t,"startTime must be less than or equal to endTime"),console.assert(null==s||n<s,"startByte must be < endByte"),this.startTime=e,this.endTime=t,this.trueEndTime=t,this.getUrisInner=i,this.startByte=n,this.endByte=s,this.initSegmentReference=a,this.timestampOffset=r,this.appendWindowStart=o,this.appendWindowEnd=l,this.partialReferences=d,this.tilesLayout=c,this.tileDuration=h,this.syncTime=u,this.status=_,this.preload=!1,this.independent=!0,this.byterangeOptimization=!1,this.thumbnailSprite=null,this.discontinuitySequence=0,this.allPartialSegments=m,this.partial=!1,this.lastPartial=!1;for(const e of this.partialReferences)e.markAsPartial();this.allPartialSegments&&this.partialReferences.length&&this.partialReferences[this.partialReferences.length-1].markAsLastPartial(),this.codecs=null,this.mimeType=null,this.segmentData=null}getUris(){return this.getUrisInner()}getStartTime(){return this.startTime}getEndTime(){return this.endTime}getStartByte(){return this.startByte}getEndByte(){return this.endByte}getSize(){return this.endByte?this.endByte-this.startByte:null}hasPartialSegments(){return this.partialReferences.length>0}hasAllPartialSegments(){return this.allPartialSegments}getTilesLayout(){return this.tilesLayout}getTileDuration(){return this.tileDuration}getStatus(){return this.status}markAsUnavailable(){this.status=Ee.Status.UNAVAILABLE}markAsPreload(){this.preload=!0}isPreload(){return this.preload}markAsNonIndependent(){this.independent=!1}isIndependent(){return this.independent}markAsPartial(){this.partial=!0}isPartial(){return this.partial}markAsLastPartial(){this.lastPartial=!0}isLastPartial(){return this.lastPartial}markAsByterangeOptimization(){this.byterangeOptimization=!0}hasByterangeOptimization(){return this.byterangeOptimization}setThumbnailSprite(e){this.thumbnailSprite=e}getThumbnailSprite(){return this.thumbnailSprite}offset(e){this.startTime+=e,this.endTime+=e,this.trueEndTime+=e;for(const t of this.partialReferences)t.startTime+=e,t.endTime+=e,t.trueEndTime+=e}syncAgainst(e){if(null==this.syncTime)return void n.alwaysError("Sync attempted without sync time!");const t=this.syncTime-e-this.startTime;Math.abs(t)>=.001&&this.offset(t)}setSegmentData(e){this.segmentData=e}getSegmentData(){return this.segmentData}static get[Symbol.for("___CTOR_ARGS___")](){return["number","number","() => Array<string>","number","number | null","InitSegmentReference | null","number","number","number","Array","string | null","number | null","number | null","SegmentReferenceStatus","boolean"]}}Ee.Status=v;class ve{constructor(e){this.timer_=null,this.numEvicted_=0,this.immutable_=!1,ve.assertCorrectReferences_(e),this.references=e}getIsImmutable(){return this.immutable_}getNumReferences(){return this.references.length}getNumEvicted(){return this.numEvicted_}release(){this.immutable_||(this.references=[],this.timer_&&this.timer_.stop(),this.timer_=null)}markImmutable(){this.immutable_=!0}forEachTopLevelReference(e){for(const t of this.references)e(t)}earliestReference(){var e;return null!==(e=this.references[0])&&void 0!==e?e:null}dropFirstReferences(e){this.references.splice(0,e)}find(e){const t=this.references.length-1;for(let i=t;i>=0;--i){const n=this.references[i],s=n.startTime,a=i<t?this.references[i+1].startTime:n.endTime;if(e>=s&&e<a)return i+this.numEvicted_}return this.references.length&&e<this.references[0].startTime?this.numEvicted_:null}get(e){if(0==this.references.length)return null;const t=e-this.numEvicted_;return t<0||t>=this.references.length?null:this.references[t]}offset(e){if(!this.immutable_)for(const t of this.references)t.offset(e)}merge(e){if(ve.assertCorrectReferences_(e),this.immutable_)return;if(!e.length)return;const t=Math.round(1e3*e[0].startTime)/1e3;this.references=this.references.filter((e=>Math.round(1e3*e.startTime)/1e3<t)),this.references.push(...e),ve.assertCorrectReferences_(this.references)}mergeAndEvict(e,t){e=e.filter((e=>e.endTime>t&&(0==this.references.length||e.endTime>this.references[0].startTime)));const i=this.references[0];this.merge(e);const n=this.references[0];i&&console.assert(i.startTime==n.startTime,"SegmentIndex.merge should not change the first reference time!"),this.evict(t)}evict(e){if(this.immutable_)return;const t=this.references.length;this.references=this.references.filter((t=>t.endTime>e));const i=t-this.references.length;this.numEvicted_+=i}fit(e,t,i=!1){if(console.assert(null!=t,"Content duration must be known for static content!"),console.assert(t!=1/0,"Content duration must be finite for static content!"),this.immutable_||null==t)return;for(;this.references.length&&this.references[this.references.length-1].startTime>=t;)this.references.pop();for(;this.references.length&&this.references[0].endTime<=e;)this.references.shift(),i||this.numEvicted_++;if(0==this.references.length)return;const n=this.references[this.references.length-1];this.references[this.references.length-1]=new Ee(n.startTime,t,n.getUrisInner,n.startByte,n.endByte,n.initSegmentReference,n.timestampOffset,n.appendWindowStart,n.appendWindowEnd,n.partialReferences,n.tilesLayout,n.tileDuration,n.syncTime,n.status),this.references[this.references.length-1].discontinuitySequence=n.discontinuitySequence}updateEvery(e,t){console.assert(!this.timer_,"SegmentIndex timer already started!"),this.immutable_||(this.timer_&&this.timer_.stop(),this.timer_=new l((()=>{var e;const i=t();i?this.references.push(...i):(null===(e=this.timer_)||void 0===e||e.stop(),this.timer_=null)})),this.timer_.tickEvery(e))}[Symbol.iterator](){const e=this.getIteratorForTime(0);return console.assert(null!=e,"Iterator for 0 should never be null!"),e}getIteratorForTime(e,t=!1){let i=this.find(e);if(null==i)return null;--i;const s=this.get(i+1);let a=-1;if(s&&s.hasPartialSegments())for(let r=s.partialReferences.length-1;r>=0;--r){let o=s.partialReferences[r];if(e>=o.startTime&&e<o.endTime){if(!t){for(;r&&!o.isIndependent();)--r,o=s.partialReferences[r];if(!o.isIndependent())return n.alwaysError("No independent partial segment found!"),null}++i,a=r-1;break}}return new be(this,i,a)}isEmpty(){return 0==this.getNumReferences()}static forSingleSegment(e,t,i){const n=new Ee(e,e+t,(()=>i),0,null,null,e,e,e+t);return new ve([n])}static get[Symbol.for("___CTOR_ARGS___")](){return["Array"]}}ve.assertCorrectReferences_=e=>{console.assert(e.every(((t,i)=>{if(0==i)return!0;const n=e[i-1];return n.startTime<t.startTime||!(n.startTime>t.startTime)&&n.endTime<=t.endTime})),"SegmentReferences are incorrect")};class be{constructor(e,t,i){this.segmentIndex_=e,this.currentPosition_=t,this.currentPartialPosition_=i}currentPosition(){return this.currentPosition_}current(){let e=this.segmentIndex_.get(this.currentPosition_);return e&&e.hasPartialSegments()&&e.hasAllPartialSegments()&&this.currentPartialPosition_>=e.partialReferences.length&&(this.currentPosition_++,this.currentPartialPosition_=0,e=this.segmentIndex_.get(this.currentPosition_)),e&&e.hasPartialSegments()?e.partialReferences[this.currentPartialPosition_]:e}next(){const e=this.segmentIndex_.get(this.currentPosition_);e&&e.hasPartialSegments()?(this.currentPartialPosition_++,e.hasAllPartialSegments()&&this.currentPartialPosition_==e.partialReferences.length&&(this.currentPosition_++,this.currentPartialPosition_=0)):(this.currentPosition_++,this.currentPartialPosition_=0);const t=this.current();return{value:t,done:!t}}static get[Symbol.for("___CTOR_ARGS___")](){return["SegmentIndex","number","number"]}}class Ie extends ve{constructor(){super([]),this.indexes_=[]}appendSegmentIndex(e){console.assert(0==this.indexes_.length||0==e.getNumEvicted(),"Should not append a new segment index with already-evicted segments"),this.indexes_.push(e)}clone(){const e=new Ie;return e.indexes_=this.indexes_.slice(),e}release(){for(const e of this.indexes_)e.release();this.indexes_=[]}find(e){let t=0;for(const i of this.indexes_){const n=i.find(e);if(null!=n)return n+t;t+=i.getNumEvicted()+i.getNumReferences()}return null}get(e){let t=0,i=!1;for(const n of this.indexes_){console.assert(!i||0==n.getNumEvicted(),"Should not see evicted segments after available segments");const s=n.get(e-t);if(s)return s;const a=n.getNumReferences();t+=n.getNumEvicted()+a,i=i||0!=a}return null}offset(e){console.assert(!1,"offset() should not be used in MetaSegmentIndex!")}merge(e){console.assert(!1,"merge() should not be used in MetaSegmentIndex!")}evict(e){console.assert(!1,"evict() should not be used in MetaSegmentIndex!")}mergeAndEvict(e,t){console.assert(!1,"mergeAndEvict() should not be used in MetaSegmentIndex!")}fit(e,t,i=!1){console.assert(!1,"fit() should not be used in MetaSegmentIndex!")}updateEvery(e,t){console.assert(!1,"updateEvery() should not be used in MetaSegmentIndex!")}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class Ae extends r{constructor(e){super(),this.regions_=new Set,this.getSeekRange_=e,this.filterTimer_=new l((()=>{this.filterBySeekRange_()})).tickEvery(Ae.REGION_FILTER_INTERVAL)}release(){this.regions_.clear(),this.filterTimer_.stop(),super.release()}addRegion(e){if(null==this.findSimilarRegion_(e)){this.regions_.add(e);const t=new a("regionadd",new Map([["region",e]]));this.dispatchEvent(t)}}filterBySeekRange_(){const e=this.getSeekRange_();for(const t of this.regions_)if(t.endTime<e.start){this.regions_.delete(t);const e=new a("regionremove",new Map([["region",t]]));this.dispatchEvent(e)}}findSimilarRegion_(e){for(const t of this.regions_)if(t.schemeIdUri==e.schemeIdUri&&t.id==e.id&&t.startTime==e.startTime&&t.endTime==e.endTime)return t;return null}regions(){return this.regions_}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}Ae.REGION_FILTER_INTERVAL=2;class we{constructor(e){this.mediaElement_=e,this.observers_=new Set,this.pollingLoop_=new l((()=>{this.pollAllObservers_(!1)})).tickEvery(.25)}release(){this.pollingLoop_.stop();for(const e of this.observers_)e.release();this.observers_.clear()}manage(e){this.observers_.add(e)}notifyOfSeek(){this.pollAllObservers_(!0)}pollAllObservers_(e){for(const t of this.observers_)t.poll(this.mediaElement_.currentTime,e)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class Ce extends r{constructor(e,t){super(),this.timeline_=e,this.startsPastZero_=t,this.oldPosition_=new Map;const i=Ce.RelativePosition_,n=i.BEFORE_THE_REGION,s=i.IN_THE_REGION,a=i.AFTER_THE_REGION;this.rules_=[{weWere:null,weAre:s,invoke:(e,t)=>this.onEvent_("enter",e,t)},{weWere:n,weAre:s,invoke:(e,t)=>this.onEvent_("enter",e,t)},{weWere:a,weAre:s,invoke:(e,t)=>this.onEvent_("enter",e,t)},{weWere:s,weAre:n,invoke:(e,t)=>this.onEvent_("exit",e,t)},{weWere:s,weAre:a,invoke:(e,t)=>this.onEvent_("exit",e,t)},{weWere:n,weAre:a,invoke:(e,t)=>this.onEvent_("skip",e,t)},{weWere:a,weAre:n,invoke:(e,t)=>this.onEvent_("skip",e,t)}],this.eventManager_=new ee,this.eventManager_.listen(this.timeline_,"regionremove",(e=>{const t=e.region;this.oldPosition_.delete(t)}))}release(){this.timeline_=null,this.oldPosition_.clear(),this.eventManager_.release(),this.eventManager_=null,super.release()}poll(e,t){if(!this.startsPastZero_||0!=e){this.startsPastZero_=!1;for(const i of this.timeline_.regions()){const n=this.oldPosition_.get(i),s=Ce.determinePositionRelativeTo_(i,e);this.oldPosition_.set(i,s);for(const e of this.rules_)e.weWere==n&&e.weAre==s&&e.invoke(i,t)}}}onEvent_(e,t,i){const n=new a(e,new Map([["region",t],["seeking",i]]));this.dispatchEvent(n)}static determinePositionRelativeTo_(e,t){const i=Ce.RelativePosition_;return t<e.startTime?i.BEFORE_THE_REGION:t>e.endTime?i.AFTER_THE_REGION:i.IN_THE_REGION}static get[Symbol.for("___CTOR_ARGS___")](){return["RegionTimeline","boolean"]}}Ce.RelativePosition_={BEFORE_THE_REGION:1,IN_THE_REGION:2,AFTER_THE_REGION:3};class Me extends r{constructor(e){super(),this.contentTypeStates_=new Map,this.getBufferedInfo_=e}release(){this.contentTypeStates_.clear(),super.release()}getContentTypeState_(e){let t=this.contentTypeStates_.get(e);return t||(t={qualityChangePositions:[],currentQuality:null,contentType:e},this.contentTypeStates_.set(e,t)),t}addMediaQualityChange(e,t){const i=this.getContentTypeState_(e.contentType);this.purgeQualityChangePositions_(i);const n={mediaQuality:e,position:t},s=i.qualityChangePositions,a=s.findIndex((e=>e.position>=t));if(a>=0){const e=s[a].position==t?1:0;s.splice(a,e,n)}else s.push(n)}static getMediaQualityAtPosition_(e,t){const i=t.qualityChangePositions;for(let t=i.length-1;t>=0;t--){const n=i[t];if(n.position<=e)return n.mediaQuality}return null}static mediaQualitiesAreTheSame_(e,t){return e===t||!(!e||!t)&&e.bandwidth==t.bandwidth&&e.audioSamplingRate==t.audioSamplingRate&&e.codecs==t.codecs&&e.contentType==t.contentType&&e.frameRate==t.frameRate&&e.height==t.height&&e.mimeType==t.mimeType&&e.channelsCount==t.channelsCount&&e.pixelAspectRatio==t.pixelAspectRatio&&e.width==t.width}poll(e,t){for(const t of this.contentTypeStates_.values()){const i=Me.getMediaQualityAtPosition_(e,t);if(i&&!Me.mediaQualitiesAreTheSame_(t.currentQuality,i)&&this.positionIsBuffered_(e,i.contentType)){t.currentQuality=i,n.debug("Media quality changed at position "+e+" "+JSON.stringify(i));const s=new a("qualitychange",new Map([["quality",i],["position",e]]));this.dispatchEvent(s)}}}positionIsBuffered_(e,t){const i=this.getBufferedInfo_()[t];if(i&&i.length>0){const t=i[0].start,n=i[i.length-1].end;if(e>=t&&e<n)return!0}return!1}purgeQualityChangePositions_(e){const t=this.getBufferedInfo_()[e.contentType];if(t&&t.length>0){const i=t[0].start,n=t[t.length-1].end,s=e.qualityChangePositions;e.qualityChangePositions=s.filter(((e,t)=>!(e.position<=i&&t+1<s.length&&s[t+1].position<=i||e.position>=n)))}else e.qualityChangePositions=[]}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}Me.QualityChangePosition,Me.ContentTypeState;class Re{constructor(e,t,i,n=!0){this.prefetchLimit_=e,this.stream_=t,this.prefetchPosTime_=0,this.fetchDispatcher_=i,this.deleteOnGet_=n,this.segmentPrefetchMap_=new Map,this.initSegmentPrefetchMap_=new Map}replaceFetchDispatcher(e){this.fetchDispatcher_=e;for(const t of this.segmentPrefetchMap_.values())t.replaceFetchDispatcher(e)}getLastKnownPosition(){return this.prefetchPosTime_}prefetchSegmentsByTime(e,t=!1){console.assert(this.prefetchLimit_>0,"SegmentPrefetch can not be used when prefetchLimit <= 0.");const i=Re.logPrefix_(this.stream_);if(!this.stream_.segmentIndex)return void n.debug(i,"missing segmentIndex");const s=Math.max(e,this.prefetchPosTime_),a=this.stream_.segmentIndex.getIteratorForTime(s,!0);if(!a)return;let r=a.next().value;if(t&&(r=a.next().value),r){for(;this.segmentPrefetchMap_.size<this.prefetchLimit_&&null!=r;){let e=!0;if(r.isPreload()&&null!=r.endByte&&(e=!1),r.getStatus()==Ee.Status.MISSING&&(e=!1),e&&r.initSegmentReference&&this.prefetchInitSegment(r.initSegmentReference),e&&!this.segmentPrefetchMap_.has(r)){const e=new Oe(this.fetchDispatcher_);e.dispatchFetch(r,this.stream_),this.segmentPrefetchMap_.set(r,e)}if(this.prefetchPosTime_=r.startTime,this.stream_.fastSwitching&&r.isPartial()&&r.isLastPartial())break;r=a.next().value}this.clearInitSegments_()}}prefetchInitSegment(e){console.assert(this.prefetchLimit_>0,"SegmentPrefetch can not be used when prefetchLimit <= 0.");const t=Re.logPrefix_(this.stream_);if(this.stream_.segmentIndex){if(!this.initSegmentPrefetchMap_.has(e)){const t=new Oe(this.fetchDispatcher_);t.dispatchFetch(e,this.stream_),this.initSegmentPrefetchMap_.set(e,t)}}else n.debug(t,"missing segmentIndex")}getPrefetchedSegment(e,t){console.assert(this.prefetchLimit_>0,"SegmentPrefetch can not be used when prefetchLimit <= 0.");const i=Re.logPrefix_(this.stream_);let s=this.segmentPrefetchMap_;if(e instanceof ye&&(s=this.initSegmentPrefetchMap_),s.has(e)){const a=s.get(e);return t&&a.setStreamDataCallback(t),this.deleteOnGet_&&s.delete(e),e instanceof Ee?n.debug(i,"reused prefetched segment at time:",e.startTime,"mapSize",s.size):n.debug(i,"reused prefetched init segment at time, mapSize",s.size),a.getOperation()}return e instanceof Ee?n.debug(i,"missed segment at time:",e.startTime,"mapSize",s.size):n.debug(i,"missed init segment at time, mapSize",s.size),null}clearMap_(e){for(const t of e.keys())t&&this.abortPrefetchedSegment_(t)}clearAll(){this.clearMap_(this.segmentPrefetchMap_),this.clearMap_(this.initSegmentPrefetchMap_);const e=Re.logPrefix_(this.stream_);n.debug(e,"cleared all"),this.prefetchPosTime_=0}evict(e){for(const t of this.segmentPrefetchMap_.keys())e>t.endTime&&this.abortPrefetchedSegment_(t);this.clearInitSegments_()}clearInitSegments_(){const e=Array.from(this.segmentPrefetchMap_.keys());for(const t of this.initSegmentPrefetchMap_.keys())e.some((e=>e.initSegmentReference===t))||this.abortPrefetchedSegment_(t)}resetLimit(e){console.assert(e>=0,"The new prefetch limit must be >= 0.");const t=Re.logPrefix_(this.stream_);n.debug(t,"resetting prefetch limit to",e),this.prefetchLimit_=e;const i=Array.from(this.segmentPrefetchMap_.keys());for(;i.length>e;){const e=i.pop();e&&this.abortPrefetchedSegment_(e)}this.clearInitSegments_()}deleteOnGet(e){this.deleteOnGet_=e}switchStream(e){console.assert(this.deleteOnGet_,"switchStream should only be used if deleteOnGet is true"),e&&e!==this.stream_&&(this.clearAll(),this.stream_=e)}getStream(){return this.stream_}abortPrefetchedSegment_(e){const t=Re.logPrefix_(this.stream_);let i=this.segmentPrefetchMap_;e instanceof ye&&(i=this.initSegmentPrefetchMap_);const s=i.get(e);i.delete(e),s&&(s.abort(),e instanceof Ee?n.debug(t,"pop and abort prefetched segment at time:",e.startTime):n.debug(t,"pop and abort prefetched init segment"))}static logPrefix_(e){return"SegmentPrefetch("+e.type+":"+e.id+")"}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0]}}class Oe{constructor(e){this.fetchDispatcher_=e,this.streamDataCallback_=null,this.operation_=null}replaceFetchDispatcher(e){this.fetchDispatcher_=e}dispatchFetch(e,t){let i=new Uint8Array(0);this.operation_=this.fetchDispatcher_(e,t,(async e=>{i=i.byteLength>0?k.concat(i,e):e,this.streamDataCallback_&&(await this.streamDataCallback_(i),i=new Uint8Array(0))}))}getOperation(){return this.operation_}setStreamDataCallback(e){this.streamDataCallback_=e}abort(){this.operation_&&this.operation_.abort()}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}Re.FetchDispatcher;class De{constructor(e,t,i=!0,n=!1){this.root_=e,this.variants_=new Set([e]),t=t||[];for(const e of t)this.add(e,i,n)}add(e,t,i){return this.canInclude(e,t,i)?(this.variants_.add(e),!0):(n.warning("Rejecting variant - not compatible with root."),!1)}canInclude(e,t=!0,i=!1){return De.areAdaptable(this.root_,e,t,i)}static areAdaptable(e,t,i,n){return!!e.audio==!!t.audio&&!!e.video==!!t.video&&e.language==t.language&&(console.assert(!!e.audio==!!t.audio,"Both should either have audio or not have audio."),!(e.audio&&t.audio&&!De.areAudiosCompatible_(e.audio,t.audio,i,n)||(console.assert(!!e.video==!!t.video,"Both should either have video or not have video."),e.video&&t.video&&!De.areVideosCompatible_(e.video,t.video,i))))}values(){return this.variants_.values()}static areAudiosCompatible_(e,t,i,n){return!((!e.channelsCount||!t.channelsCount||e.channelsCount>2||t.channelsCount>2)&&e.channelsCount!=t.channelsCount||i&&!De.canTransitionBetween_(e,t)||!De.areRolesEqual_(e.roles,t.roles)||n&&e.groupId!==t.groupId)}static areVideosCompatible_(e,t,i){return!(i&&!De.canTransitionBetween_(e,t)||!De.areRolesEqual_(e.roles,t.roles))}static canTransitionBetween_(e,t){if(e.mimeType!=t.mimeType)return!1;const i=F.splitCodecs(e.codecs).map((e=>F.getCodecBase(e))),n=F.splitCodecs(t.codecs).map((e=>F.getCodecBase(e)));if(i.length!=n.length)return!1;i.sort(),n.sort();for(let e=0;e<i.length;e++)if(i[e]!=n[e])return!1;return!0}static areRolesEqual_(e,t){const i=new Set(e),n=new Set(t),s="main";if(i.delete(s),n.delete(s),i.size!=n.size)return!1;for(const e of i)if(!n.has(e))return!1;return!0}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0]}}class Pe{constructor(e,t="reload",i=!1){this.example_=e,this.codecSwitchingStrategy_=t,this.enableAudioGroups_=i;const n=e.audio&&e.audio.channelsCount?e.audio.channelsCount:0;this.fallback_=new Ne(e.language,"",n,"",!1,"","","",t,i)}create(e){const t="smooth"==this.codecSwitchingStrategy_&&G.isChangeTypeSupported(),i=e.filter((e=>De.areAdaptable(this.example_,e,!t,this.enableAudioGroups_)));return i.length?new De(i[0],i,!t,this.enableAudioGroups_):this.fallback_.create(e)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0]}}class Ne{constructor(e,t,i,n,s,a,r="",o="",l="reload",d=!1){this.language_=e,this.role_=t,this.channelCount_=i,this.hdrLevel_=n,this.spatialAudio_=s,this.videoLayout_=a,this.audioLabel_=r,this.videoLabel_=o,this.codecSwitchingStrategy_=l,this.enableAudioGroups_=d}create(e){const t=Ne;let i=[];const s=t.filterByLanguage_(e,this.language_),a=e.filter((e=>e.primary));i=s.length?s:a.length?a:e;const r=t.filterVariantsByRole_(i,this.role_);if(r.length?i=r:n.warning("No exact match for variant role could be found."),this.videoLayout_){const e=t.filterVariantsByVideoLayout_(i,this.videoLayout_);e.length?i=e:n.warning("No exact match for the video layout could be found.")}if(this.hdrLevel_){const e=t.filterVariantsByHDRLevel_(i,this.hdrLevel_);e.length?i=e:n.warning("No exact match for the hdr level could be found.")}if(this.channelCount_){const e=t.filterVariantsByAudioChannelCount_(i,this.channelCount_);e.length?i=e:n.warning("No exact match for the channel count could be found.")}if(this.audioLabel_){const e=t.filterVariantsByAudioLabel_(i,this.audioLabel_);e.length?i=e:n.warning("No exact match for audio label could be found.")}if(this.videoLabel_){const e=t.filterVariantsByVideoLabel_(i,this.videoLabel_);e.length?i=e:n.warning("No exact match for video label could be found.")}const o=t.filterVariantsBySpatialAudio_(i,this.spatialAudio_);o.length?i=o:n.warning("No exact match for spatial audio could be found.");const l="smooth"==this.codecSwitchingStrategy_&&G.isChangeTypeSupported();return new De(i[0],i,!l,this.enableAudioGroups_)}static filterByLanguage_(e,t){const i=H.normalize(t),n=H.findClosestLocale(i,e.map((e=>H.getLocaleForVariant(e))));return n?e.filter((e=>n==H.getLocaleForVariant(e))):[]}static filterVariantsByRole_(e,t){return e.filter((e=>!!e.audio&&(t?e.audio.roles.includes(t):0==e.audio.roles.length)))}static filterVariantsByAudioLabel_(e,t){return e.filter((e=>!(!e.audio||!e.audio.label)&&e.audio.label.toLowerCase()==t.toLowerCase()))}static filterVariantsByVideoLabel_(e,t){return e.filter((e=>!(!e.video||!e.video.label)&&e.video.label.toLowerCase()==t.toLowerCase()))}static filterVariantsByAudioChannelCount_(e,t){return e.filter((e=>!e.audio||!e.audio.channelsCount||e.audio.channelsCount==t))}static filterVariantsByHDRLevel_(e,t){return"AUTO"==t&&(t=window.matchMedia("(color-gamut: p3)").matches?"PQ":"SDR"),e.filter((e=>!e.video||!e.video.hdr||e.video.hdr==t))}static filterVariantsByVideoLayout_(e,t){return e.filter((e=>!e.video||!e.video.videoLayout||e.video.videoLayout==t))}static filterVariantsBySpatialAudio_(e,t){return e.filter((e=>!e.audio||e.audio.spatialAudio==t))}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0]}}class Le{static createSegmentRequest(e,t,i,n,s=null){const a=D.makeRequest(e,n,s);return 0==t&&null==i||(a.headers.Range=i?"bytes="+t+"-"+i:"bytes="+t+"-"),a}}class xe{constructor(e,t){this.playerInterface_=t,this.manifest_=e,this.config_=null,this.bufferingGoalScale_=1,this.currentVariant_=null,this.currentTextStream_=null,this.textStreamSequenceId_=0,this.parsedPrftEventRaised_=!1,this.mediaStates_=new Map,this.startupComplete_=!1,this.failureCallbackBackoff_=null,this.fatalError_=!1,this.destroyer_=new me((()=>this.doDestroy_())),this.lastMediaSourceReset_=Date.now()/1e3,this.audioPrefetchMap_=new Map}destroy(){return this.destroyer_.destroy()}async doDestroy_(){const e=[];for(const t of this.mediaStates_.values())this.cancelUpdate_(t),e.push(this.abortOperations_(t));for(const e of this.audioPrefetchMap_.values())e.clearAll();await Promise.all(e),this.mediaStates_.clear(),this.audioPrefetchMap_.clear(),this.playerInterface_=null,this.manifest_=null,this.config_=null}configure(e){this.config_=e;const t={maxAttempts:Math.max(e.retryParameters.maxAttempts,2),baseDelay:e.retryParameters.baseDelay,backoffFactor:e.retryParameters.backoffFactor,fuzzFactor:e.retryParameters.fuzzFactor,timeout:0,stallTimeout:0,connectionTimeout:0};this.failureCallbackBackoff_=new R(t,!0);const i=U.ContentType;if(e.disableAudioPrefetch){const e=this.mediaStates_.get(i.AUDIO);e&&e.segmentPrefetch&&(e.segmentPrefetch.clearAll(),e.segmentPrefetch=null);for(const e of this.audioPrefetchMap_.keys())this.audioPrefetchMap_.get(e).clearAll(),this.audioPrefetchMap_.delete(e)}if(e.disableTextPrefetch){const e=this.mediaStates_.get(i.TEXT);e&&e.segmentPrefetch&&(e.segmentPrefetch.clearAll(),e.segmentPrefetch=null)}if(e.disableVideoPrefetch){const e=this.mediaStates_.get(i.VIDEO);e&&e.segmentPrefetch&&(e.segmentPrefetch.clearAll(),e.segmentPrefetch=null)}for(const t of this.mediaStates_.keys()){const i=this.mediaStates_.get(t);i.segmentPrefetch?(i.segmentPrefetch.resetLimit(e.segmentPrefetchLimit),e.segmentPrefetchLimit>0||(i.segmentPrefetch=null)):e.segmentPrefetchLimit>0&&(i.segmentPrefetch=this.createSegmentPrefetch_(i.stream))}e.disableAudioPrefetch||this.updatePrefetchMapForAudio_()}async start(e){console.assert(this.config_,"StreamingEngine configure() must be called before init()!"),await this.initStreams_(e||new Map),this.destroyer_.ensureNotDestroyed(),n.debug("init: completed initial Stream setup"),this.startupComplete_=!0}getCurrentVariant(){return this.currentVariant_}getCurrentTextStream(){return this.currentTextStream_}async loadNewTextStream_(e){const t=U.ContentType;console.assert(!this.mediaStates_.has(t.TEXT),"Should not call loadNewTextStream_ while streaming text!"),this.textStreamSequenceId_++;const i=this.textStreamSequenceId_;try{await this.playerInterface_.mediaSourceEngine.clear(t.TEXT)}catch(e){this.playerInterface_&&this.playerInterface_.onError(e)}const n=F.getFullType(e.mimeType,e.codecs);if(this.playerInterface_.mediaSourceEngine.reinitText(n,this.manifest_.sequenceMode,e.external),(this.playerInterface_.mediaSourceEngine.getTextDisplayer().isTextVisible()||this.config_.alwaysStreamText)&&this.textStreamSequenceId_==i){const i=this.createMediaState_(e);this.mediaStates_.set(t.TEXT,i),this.scheduleUpdate_(i,0)}}unloadTextStream(){const e=U.ContentType,t=this.mediaStates_.get(e.TEXT);t&&(this.cancelUpdate_(t),this.abortOperations_(t).catch((()=>{})),this.mediaStates_.delete(e.TEXT)),this.currentTextStream_=null}setTrickPlay(e){const t=U.ContentType,i=this.mediaStates_.get(t.VIDEO);if(!i)return;const s=i.stream;if(s)if(n.debug("setTrickPlay",e),e){const e=s.trickModeVideo;if(!e)return;if(i.restoreStreamAfterTrickPlay)return;n.debug("Engaging trick mode stream",e),this.switchInternal_(e,!1,0,!1),i.restoreStreamAfterTrickPlay=s}else{const e=i.restoreStreamAfterTrickPlay;if(!e)return;n.debug("Restoring non-trick-mode stream",e),i.restoreStreamAfterTrickPlay=null,this.switchInternal_(e,!0,0,!1)}}switchVariant(e,t=!1,i=0,n=!1,s=!1){this.currentVariant_=e,this.startupComplete_&&(e.video&&this.switchInternal_(e.video,t,i,n,s),e.audio&&this.switchInternal_(e.audio,t,i,n,s))}async switchTextStream(e){if(this.currentTextStream_=e,!this.startupComplete_)return;const t=U.ContentType;console.assert(e&&e.type==t.TEXT,"Wrong stream type passed to switchTextStream!"),e.segmentIndex||await e.createSegmentIndex(),this.switchInternal_(e,!0,0,!1)}reloadTextStream(){const e=U.ContentType,t=this.mediaStates_.get(e.TEXT);t&&this.switchInternal_(t.stream,!0,0,!0)}switchInternal_(e,t,i,s,a){const r=U.ContentType,o=e.type,l=this.mediaStates_.get(o);if(!l&&e.type==r.TEXT)return void this.loadNewTextStream_(e);if(console.assert(l,"switch: expected mediaState to exist"),!l)return;if(l.restoreStreamAfterTrickPlay&&(n.debug("switch during trick play mode",e),e.trickModeVideo?(l.restoreStreamAfterTrickPlay=e,e=e.trickModeVideo,n.debug("switch found trick play stream",e)):(l.restoreStreamAfterTrickPlay=null,n.debug("switch found no special trick play stream"))),l.stream==e&&!s){const e=xe.logPrefix_(l);return void n.debug("switch: Stream "+e+" already active")}if(this.audioPrefetchMap_.has(e)?l.segmentPrefetch=this.audioPrefetchMap_.get(e):l.segmentPrefetch&&l.segmentPrefetch.switchStream(e),e.type==r.TEXT){const t=F.getFullType(e.mimeType,e.codecs);this.playerInterface_.mediaSourceEngine.reinitText(t,this.manifest_.sequenceMode,e.external)}this.audioPrefetchMap_.has(l.stream)||l.stream.closeSegmentIndex&&l.stream.closeSegmentIndex(),l.stream=e,l.segmentIterator=null,l.adaptation=!!a;const d=xe.logPrefix_(l);n.debug("switch: switching to Stream "+d),t&&(l.clearingBuffer?l.waitingToFlushBuffer=!0:l.performingUpdate?(l.waitingToClearBuffer=!0,l.clearBufferSafeMargin=i,l.waitingToFlushBuffer=!0):(this.cancelUpdate_(l),this.clearBuffer_(l,!0,i).catch((e=>{this.playerInterface_&&(console.assert(e instanceof b,"Wrong error type!"),this.playerInterface_.onError(e))})))),this.makeAbortDecision_(l).catch((e=>{this.playerInterface_&&(console.assert(e instanceof b,"Wrong error type!"),this.playerInterface_.onError(e))}))}async makeAbortDecision_(e){if(!e.operation)return;const t=e.stream,i=e.operation;t.segmentIndex||await t.createSegmentIndex(),e.operation==i&&e.stream==t&&(console.assert(e.stream.segmentIndex,"Segment index should exist by now!"),this.shouldAbortCurrentRequest_(e)&&(n.info("Aborting current segment request."),e.operation.abort()))}shouldAbortCurrentRequest_(e){console.assert(e.operation,"Abort logic requires an ongoing operation!"),console.assert(e.stream&&e.stream.segmentIndex,"Abort logic requires a segment index");const t=this.playerInterface_.getPresentationTime(),i=this.playerInterface_.mediaSourceEngine.bufferEnd(e.type),n=this.getTimeNeeded_(e,t),s=e.stream.segmentIndex.find(n),a=null==s?null:e.stream.segmentIndex.get(s);let r=a?a.getSize():null;if(a&&!r&&(r=(a.getEndTime()-a.getStartTime())*(e.stream.bandwidth||0)/8),!r)return!1;const o=a.initSegmentReference;return o&&(r+=o.getSize()||0),8*r/this.playerInterface_.getBandwidthEstimate()<(i||0)-t-Math.max(this.manifest_.minBufferTime||0,this.config_.rebufferingGoal)||e.operation.getBytesRemaining()>r}seeked(){if(!this.playerInterface_)return;const e=this.playerInterface_.getPresentationTime(),t=U.ContentType,i=t=>this.playerInterface_.mediaSourceEngine.isBuffered(t,e);let s=!1;for(const a of this.mediaStates_.keys()){const r=this.mediaStates_.get(a),o=xe.logPrefix_(r);let l=null;r.segmentIterator&&(l=r.segmentIterator.current()),(!l||l.startTime>e||l.endTime<e)&&(r.segmentIterator=null),i(a)||((null!=this.playerInterface_.mediaSourceEngine.bufferEnd(a)||r.performingUpdate)&&(this.forceClearBuffer_(r),s=!0),r.operation&&(r.operation.abort(),n.debug(o,"Aborting operation due to seek"),r.operation=null),a===t.TEXT&&this.playerInterface_.mediaSourceEngine.resetCaptionParser(),r.seeked=!0)}s||n.debug("(all): seeked: buffered seek: presentationTime="+e)}forceClearBuffer_(e){const t=xe.logPrefix_(e);if(e.clearingBuffer)return void n.debug(t,"clear: already clearing the buffer");if(e.waitingToClearBuffer)return void n.debug(t,"clear: already waiting");if(e.performingUpdate)return n.debug(t,"clear: currently updating"),e.waitingToClearBuffer=!0,void(e.clearBufferSafeMargin=0);const i=e.type;if(null==this.playerInterface_.mediaSourceEngine.bufferStart(i))return n.debug(t,"clear: nothing buffered"),void(null==e.updateTimer&&this.scheduleUpdate_(e,0));n.debug(t,"clear: handling right now"),this.cancelUpdate_(e),this.clearBuffer_(e,!1,0).catch((e=>{this.playerInterface_&&(console.assert(e instanceof b,"Wrong error type!"),this.playerInterface_.onError(e))}))}async initStreams_(e){const t=U.ContentType;if(console.assert(this.config_,"StreamingEngine configure() must be called before init()!"),!this.currentVariant_)throw n.error("init: no Streams chosen"),new b(b.Severity.CRITICAL,b.Category.STREAMING,b.Code.STREAMING_ENGINE_STARTUP_INVALID_STATE);const i=new Map,s=new Set;this.currentVariant_.audio&&(i.set(t.AUDIO,this.currentVariant_.audio),s.add(this.currentVariant_.audio)),this.currentVariant_.video&&(i.set(t.VIDEO,this.currentVariant_.video),s.add(this.currentVariant_.video)),this.currentTextStream_&&(i.set(t.TEXT,this.currentTextStream_),s.add(this.currentTextStream_));const a=this.playerInterface_.mediaSourceEngine;await a.init(i,this.manifest_.sequenceMode,this.manifest_.type,this.manifest_.ignoreManifestTimestampsInSegmentsMode),this.destroyer_.ensureNotDestroyed(),this.updateDuration();for(const t of i.keys()){const n=i.get(t);if(!this.mediaStates_.has(t)){const i=this.createMediaState_(n);if(e.has(n.id)){const t=e.get(n.id);t.replaceFetchDispatcher(((e,t,i)=>this.dispatchFetch_(e,t,i))),i.segmentPrefetch=t}this.mediaStates_.set(t,i),this.scheduleUpdate_(i,0)}}}createMediaState_(e){return{stream:e,type:e.type,segmentIterator:null,segmentPrefetch:this.createSegmentPrefetch_(e),lastSegmentReference:null,lastInitSegmentReference:null,lastTimestampOffset:null,lastAppendWindowStart:null,lastAppendWindowEnd:null,restoreStreamAfterTrickPlay:null,endOfStream:!1,performingUpdate:!1,updateTimer:null,waitingToClearBuffer:!1,clearBufferSafeMargin:0,waitingToFlushBuffer:!1,clearingBuffer:!1,seeked:!0,needsResync:!1,recovering:!1,hasError:!1,operation:null}}createSegmentPrefetch_(e){const t=U.ContentType;if(e.type===t.VIDEO&&this.config_.disableVideoPrefetch)return null;if(e.type===t.AUDIO&&this.config_.disableAudioPrefetch)return null;const i=F.CEA608_CLOSED_CAPTION_MIMETYPE,n=F.CEA708_CLOSED_CAPTION_MIMETYPE;if(e.type===t.TEXT&&(e.mimeType==i||e.mimeType==n))return null;if(e.type===t.TEXT&&this.config_.disableTextPrefetch)return null;if(this.audioPrefetchMap_.has(e))return this.audioPrefetchMap_.get(e);const s=e.type,a=this.mediaStates_.get(s),r=a&&a.segmentPrefetch;return r&&e===r.getStream()?r:this.config_.segmentPrefetchLimit>0?new Re(this.config_.segmentPrefetchLimit,e,((e,t,i)=>this.dispatchFetch_(e,t,i))):null}updatePrefetchMapForAudio_(){const e=this.config_.segmentPrefetchLimit,t=this.config_.prefetchAudioLanguages;for(const i of this.manifest_.variants){if(!i.audio)continue;if(this.audioPrefetchMap_.has(i.audio)){const n=this.audioPrefetchMap_.get(i.audio);if(n.resetLimit(e),!(e>0&&t.some((e=>H.areLanguageCompatible(i.audio.language,e))))){n.deleteOnGet(!0);const e=i.audio.type,t=this.mediaStates_.get(e);n!==(t&&t.segmentPrefetch)&&n.clearAll(),this.audioPrefetchMap_.delete(i.audio)}continue}if(e<=0)continue;if(!t.some((e=>H.areLanguageCompatible(i.audio.language,e))))continue;const n=this.createSegmentPrefetch_(i.audio);n.deleteOnGet(!1),n&&(i.audio.segmentIndex||i.audio.createSegmentIndex(),this.audioPrefetchMap_.set(i.audio,n))}}updateDuration(){const e=this.manifest_.presentationTimeline.getDuration();if(e<1/0)this.playerInterface_.mediaSourceEngine.setDuration(e);else{const e=this.config_.infiniteLiveStreamDuration?1/0:Math.pow(2,32);this.playerInterface_.mediaSourceEngine.setDuration(e)}}async onUpdate_(e){this.destroyer_.ensureNotDestroyed();const t=xe.logPrefix_(e);if(console.assert(!e.performingUpdate&&null!=e.updateTimer,t+" unexpected call to onUpdate_()"),e.performingUpdate||null==e.updateTimer)return;if(console.assert(!e.clearingBuffer,t+" onUpdate_() should not be called when clearing the buffer"),e.clearingBuffer)return;if(e.updateTimer=null,e.waitingToClearBuffer)return n.debug(t,"skipping update and clearing the buffer"),void await this.clearBuffer_(e,e.waitingToFlushBuffer,e.clearBufferSafeMargin);if(!e.stream.segmentIndex){const t=e.stream;if(await e.stream.createSegmentIndex(),t!=e.stream)return t.closeSegmentIndex&&(console.assert(!e.stream.segmentIndex,"mediastate.stream should not have segmentIndex yet."),t.closeSegmentIndex()),void(e.performingUpdate||e.updateTimer||this.scheduleUpdate_(e,0))}try{const t=this.update_(e);null!=t&&(this.scheduleUpdate_(e,t),e.hasError=!1)}catch(t){return void await this.handleStreamingError_(e,t)}const i=Array.from(this.mediaStates_.values());if(this.startupComplete_&&i.every((e=>e.endOfStream))){n.v1(t,"calling endOfStream()..."),await this.playerInterface_.mediaSourceEngine.endOfStream(),this.destroyer_.ensureNotDestroyed();const e=this.playerInterface_.mediaSourceEngine.getDuration();0!=e&&e<this.manifest_.presentationTimeline.getDuration()&&this.manifest_.presentationTimeline.setDuration(e)}}update_(e){console.assert(this.manifest_,"manifest_ should not be null"),console.assert(this.config_,"config_ should not be null");const t=U.ContentType;if(xe.isEmbeddedText_(e))return this.playerInterface_.mediaSourceEngine.setSelectedClosedCaptionId(e.stream.originalId||""),null;if(e.type==t.TEXT&&this.playerInterface_.mediaSourceEngine.clearSelectedClosedCaptionId(),!this.playerInterface_.mediaSourceEngine.isStreamingAllowed()&&e.type!=t.TEXT)return this.config_.updateIntervalSeconds/2;const i=xe.logPrefix_(e),s=this.playerInterface_.getPresentationTime();if(e.type===t.AUDIO)for(const e of this.audioPrefetchMap_.keys()){const t=this.audioPrefetchMap_.get(e);t.evict(s),t.prefetchSegmentsByTime(s)}const a=this.getTimeNeeded_(e,s);n.v2(i,"timeNeeded="+a);const r=this.playerInterface_.mediaSourceEngine.bufferedAheadOf(e.type,s);n.v2(i,"update_:","presentationTime="+s,"bufferedAhead="+r);const o=Math.max(this.manifest_.minBufferTime||0,this.config_.rebufferingGoal,this.config_.bufferingGoal),l=Math.max(1,o*this.bufferingGoalScale_),d=this.manifest_.presentationTimeline.getDuration()-a,c=this.playerInterface_.mediaSourceEngine.bufferEnd(e.type);if(d<1e-6&&c){if(n.debug(i,"buffered to end of presentation"),e.endOfStream=!0,e.type==t.VIDEO){const e=this.mediaStates_.get(t.TEXT);e&&xe.isEmbeddedText_(e)&&(e.endOfStream=!0)}return null}if(e.endOfStream=!1,r>=l)return n.v2(i,"buffering goal met"),this.config_.updateIntervalSeconds/2;const h=this.getSegmentReferenceNeeded_(e,s,c);if(!h)return this.config_.updateIntervalSeconds;let u=1/0;const _=Array.from(this.mediaStates_.values());for(const e of _){if(xe.isEmbeddedText_(e))continue;if(e.segmentIterator&&!e.segmentIterator.current())continue;const t=this.getTimeNeeded_(e,s);u=Math.min(u,t)}return a>=u+this.manifest_.presentationTimeline.getMaxSegmentDuration()*xe.MAX_RUN_AHEAD_SEGMENTS_?(n.v2(i,"waiting for other streams to buffer"),this.config_.updateIntervalSeconds):(e.segmentPrefetch&&e.segmentIterator&&!this.audioPrefetchMap_.has(e.stream)&&e.segmentPrefetch.prefetchSegmentsByTime(h.startTime),this.fetchAndAppend_(e,s,h).catch((()=>{})),null)}getTimeNeeded_(e,t){return e.lastSegmentReference?e.lastSegmentReference.endTime:t}getSegmentReferenceNeeded_(e,t,i){const s=xe.logPrefix_(e);if(console.assert(e.stream.segmentIndex,"segment index should have been generated already"),e.segmentIterator)return e.segmentIterator.current();if(e.lastSegmentReference||i){const t=e.lastSegmentReference?e.lastSegmentReference.endTime:i;console.assert(null!=t,"Should have a time to search"),n.v1(s,"looking up segment from new stream endTime:",t),e.needsResync=!0,e.segmentIterator=e.stream.segmentIndex.getIteratorForTime(t);const a=e.segmentIterator&&e.segmentIterator.next().value;return null==a&&n.warning(s,"cannot find segment","endTime:",t),a}{const i=this.config_.inaccurateManifestTolerance,a=Math.max(t-i,0);n.v1(s,"looking up segment","lookupTime:",a,"presentationTime:",t);let r=null;return i&&(e.segmentIterator=e.stream.segmentIndex.getIteratorForTime(a),r=e.segmentIterator&&e.segmentIterator.next().value),r||(e.segmentIterator=e.stream.segmentIndex.getIteratorForTime(t),r=e.segmentIterator&&e.segmentIterator.next().value),null==r&&n.warning(s,"cannot find segment","lookupTime:",a,"presentationTime:",t),r}}async fetchAndAppend_(e,t,i){const s=U.ContentType,a=xe.logPrefix_(e);n.v1(a,"fetchAndAppend_:","presentationTime="+t,"reference.startTime="+i.startTime,"reference.endTime="+i.endTime);const r=e.stream,o=e.segmentIterator;e.performingUpdate=!0;try{if(i.getStatus()==Ee.Status.MISSING)throw new b(b.Severity.RECOVERABLE,b.Category.NETWORK,b.Code.SEGMENT_MISSING);if(await this.initSourceBuffer_(e,i),this.destroyer_.ensureNotDestroyed(),this.fatalError_)return;n.v2(a,"fetching segment");const s="video/mp4"==r.mimeType||"audio/mp4"==r.mimeType,l=window.ReadableStream;if(this.config_.lowLatencyMode&&l&&s&&(this.manifest_.type!=_e.HLS||i.hasByterangeOptimization())){let s,o=new Uint8Array(0),l=!1,d=!1;const c=async n=>{if(!l&&(d=!0,this.destroyer_.ensureNotDestroyed(),!this.fatalError_))try{o=this.concatArray_(o,n);let s=!1,a=0;if((new le).box("mdat",(e=>{a=e.size+e.start,s=!0})).parse(o,!1,!0),s){const n=o.subarray(0,a);o=o.subarray(a),await this.append_(e,t,r,i,n,!0),e.segmentPrefetch&&e.segmentIterator&&e.segmentPrefetch.prefetchSegmentsByTime(i.startTime,!0)}}catch(e){s=e}},h=await this.fetch_(e,i,c);if(s)throw s;if(!d){if(l=!0,this.destroyer_.ensureNotDestroyed(),this.fatalError_)return;if(e.waitingToClearBuffer)return n.info(a,"waitingToClearBuffer, skip append"),e.performingUpdate=!1,void this.scheduleUpdate_(e,0);await this.append_(e,t,r,i,h)}e.segmentPrefetch&&e.segmentIterator&&e.segmentPrefetch.prefetchSegmentsByTime(i.startTime,!0)}else{this.config_.lowLatencyMode&&!l&&n.warning("Low latency streaming mode is enabled, but ReadableStream is not supported by the browser.");const s=this.fetch_(e,i),o=await s;if(this.destroyer_.ensureNotDestroyed(),this.fatalError_)return;if(this.destroyer_.ensureNotDestroyed(),e.waitingToClearBuffer)return n.info(a,"waitingToClearBuffer, skip append"),e.performingUpdate=!1,void this.scheduleUpdate_(e,0);await this.append_(e,t,r,i,o)}if(this.destroyer_.ensureNotDestroyed(),this.fatalError_)return;e.lastSegmentReference=i;const d=o.next().value;n.v2(a,"advancing to next segment",d),e.performingUpdate=!1,e.recovering=!1;const c=this.playerInterface_.mediaSourceEngine.getBufferedInfo()[e.type];n.v1(a,"finished fetch and append",JSON.stringify(c)),e.waitingToClearBuffer||this.playerInterface_.onSegmentAppended(i,e.stream),this.scheduleUpdate_(e,0)}catch(t){if(this.destroyer_.ensureNotDestroyed(t),this.fatalError_)return;console.assert(t instanceof b,"Should only receive a Shaka error"),e.performingUpdate=!1,t.code==b.Code.OPERATION_ABORTED?(e.performingUpdate=!1,this.cancelUpdate_(e),this.scheduleUpdate_(e,0)):e.type==s.TEXT&&this.config_.ignoreTextStreamFailures?(t.code==b.Code.BAD_HTTP_STATUS?n.warning(a,"Text stream failed to download. Proceeding without it."):n.warning(a,"Text stream failed to parse. Proceeding without it."),this.mediaStates_.delete(s.TEXT)):t.code==b.Code.QUOTA_EXCEEDED_ERROR?this.handleQuotaExceeded_(e,t):(n.error(a,"failed fetch and append: code="+t.code),e.hasError=!0,t.severity=b.Severity.CRITICAL,await this.handleStreamingError_(e,t))}}async aesDecrypt_(e,t,i){const n=t;n.cryptoKey||(console.assert(n.fetchKey,"If AES cryptoKey was not preloaded, fetchKey function should be provided"),await n.fetchKey(),console.assert(n.cryptoKey,"AES cryptoKey should now be set"));let s,a=n.iv;if(!a){a=d.toUint8(new ArrayBuffer(16));let e=n.firstMediaSequenceNumber+i;for(let t=a.byteLength-1;t>=0;t--)a[t]=255&e,e>>=8}return s="CBC"==t.blockCipherMode?{name:"AES-CBC",iv:a}:{name:"AES-CTR",counter:a,length:64},window.crypto.subtle.decrypt(s,n.cryptoKey,e)}retry(e){if(this.destroyer_.destroyed())return n.error("Unable to retry after StreamingEngine is destroyed!"),!1;if(this.fatalError_)return n.error("Unable to retry after StreamingEngine encountered a fatal error!"),!1;for(const t of this.mediaStates_.values()){const i=xe.logPrefix_(t);!t.hasError||t.performingUpdate||t.updateTimer||(n.info(i,"Retrying after failure..."),t.hasError=!1,this.scheduleUpdate_(t,e))}return!0}concatArray_(e,t){const i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}handleQuotaExceeded_(e,t){const i=xe.logPrefix_(e);if(Array.from(this.mediaStates_.values()).some((t=>t!=e&&t.recovering)))n.debug(i,"MediaSource threw QuotaExceededError:","waiting for another stream to recover...");else{if(this.config_.maxDisabledTime>0&&this.playerInterface_.disableStream(e.stream,this.config_.maxDisabledTime))return;const s=Math.round(100*this.bufferingGoalScale_);if(s>20)this.bufferingGoalScale_-=.2;else{if(!(s>4))return n.error(i,"MediaSource threw QuotaExceededError too many times"),e.hasError=!0,this.fatalError_=!0,void this.playerInterface_.onError(t);this.bufferingGoalScale_-=.04}const a=Math.round(100*this.bufferingGoalScale_);n.warning(i,"MediaSource threw QuotaExceededError:","reducing buffering goals by "+(100-a)+"%"),e.recovering=!0}this.scheduleUpdate_(e,4)}async initSourceBuffer_(e,t){const i=U.ContentType,s=xe.logPrefix_(e),a=[],r=Math.max(0,t.appendWindowStart-xe.APPEND_WINDOW_START_FUDGE_),o=t.appendWindowEnd+xe.APPEND_WINDOW_END_FUDGE_;console.assert(t.startTime<=o,s+" segment should start before append window end");const l=F.getCodecBase(e.stream.codecs),d=F.getBasicType(e.stream.mimeType),c=t.timestampOffset;if(c!=e.lastTimestampOffset||r!=e.lastAppendWindowStart||o!=e.lastAppendWindowEnd||l!=e.lastCodecs||d!=e.lastMimeType){n.v1(s,"setting timestamp offset to "+c),n.v1(s,"setting append window start to "+r),n.v1(s,"setting append window end to "+o);const a=e.lastCodecs&&e.lastMimeType&&this.playerInterface_.mediaSourceEngine.isResetMediaSourceNecessary(e.type,e.stream);if(a){let t=null;e.type===i.VIDEO?t=this.mediaStates_.get(i.AUDIO):e.type===i.AUDIO&&(t=this.mediaStates_.get(i.VIDEO)),t&&(t.lastInitSegmentReference=null,this.forceClearBuffer_(t),this.abortOperations_(t).catch((()=>{})))}const h=async()=>{const n=new Map;this.currentVariant_.audio&&n.set(i.AUDIO,this.currentVariant_.audio),this.currentVariant_.video&&n.set(i.VIDEO,this.currentVariant_.video);try{e.lastAppendWindowStart=r,e.lastAppendWindowEnd=o,e.lastCodecs=l,e.lastMimeType=d,e.lastTimestampOffset=c;const s=this.manifest_.sequenceMode||this.manifest_.type==_e.HLS;if(await this.playerInterface_.mediaSourceEngine.setStreamProperties(e.type,c,r,o,s,t.mimeType||e.stream.mimeType,t.codecs||e.stream.codecs,n),a){let t=null;e.type===i.VIDEO?t=this.mediaStates_.get(i.AUDIO):e.type===i.AUDIO&&(t=this.mediaStates_.get(i.VIDEO)),t&&(t.waitingToClearBuffer=!1,t.performingUpdate=!1,this.forceClearBuffer_(t))}}catch(t){throw e.lastAppendWindowStart=null,e.lastAppendWindowEnd=null,e.lastCodecs=null,e.lastTimestampOffset=null,t}};await h()}if(!ye.equal(t.initSegmentReference,e.lastInitSegmentReference)&&(e.lastInitSegmentReference=t.initSegmentReference,t.isIndependent()&&t.initSegmentReference)){n.v1(s,"fetching init segment");const r=this.fetch_(e,t.initSegmentReference),o=async()=>{try{const a=await r;this.destroyer_.ensureNotDestroyed();let o=null;const l=new Map;(new le).box("moov",le.children).box("trak",le.children).box("mdia",le.children).fullBox("mdhd",(e=>{console.assert(null!=e.version,"MDHD is a full box and should have a valid version.");const t=de.parseMDHD(e.reader,e.version);o=t.timescale})).box("hdlr",(e=>{switch(de.parseHDLR(e.reader).handlerType){case"soun":l.set(i.AUDIO,o);break;case"vide":l.set(i.VIDEO,o)}o=null})).parse(a),l.has(e.type)?t.initSegmentReference.timescale=l.get(e.type):null!=o&&(t.initSegmentReference.timescale=o),n.v1(s,"appending init segment");const d=e.stream.closedCaptions&&e.stream.closedCaptions.size>0;await this.playerInterface_.beforeAppendSegment(e.type,a),await this.playerInterface_.mediaSourceEngine.appendBuffer(e.type,a,null,e.stream,d)}catch(t){throw e.lastInitSegmentReference=null,t}};this.playerInterface_.onInitSegmentAppended(t.startTime,t.initSegmentReference),a.push(o())}if(this.manifest_.sequenceMode){const i=e.lastSegmentReference?e.lastSegmentReference.discontinuitySequence:null;(t.discontinuitySequence!=i||e.needsResync)&&(e.needsResync=!1,a.push(this.playerInterface_.mediaSourceEngine.resync(e.type,t.startTime)))}await Promise.all(a)}async append_(e,t,i,s,a,r=!1){const o=xe.logPrefix_(e),l=i.closedCaptions&&i.closedCaptions.size>0;let d;const c=null!=i.emsgSchemeIdUris&&i.emsgSchemeIdUris.length>0||this.config_.dispatchAllEmsgBoxes,h=this.config_.parsePrftBox&&!this.parsedPrftEventRaised_;(c||h)&&(d=new le),c&&d.fullBox("emsg",(e=>this.parseEMSG_(s,i.emsgSchemeIdUris,e))),h&&d.fullBox("prft",(e=>this.parsePrft_(s,e))),(c||h)&&d.parse(a),await this.evict_(e,t),this.destroyer_.ensureNotDestroyed();const u=e.seeked;e.seeked=!1;const _=e.adaptation;e.adaptation=!1,await this.playerInterface_.beforeAppendSegment(e.type,a),await this.playerInterface_.mediaSourceEngine.appendBuffer(e.type,a,s,i,l,u,_,r),this.destroyer_.ensureNotDestroyed(),n.v2(o,"appended media segment")}parseEMSG_(e,t,i){let n,s,r,o,l,d,c;0===i.version?(o=i.reader.readTerminatedString(),c=i.reader.readTerminatedString(),n=i.reader.readUint32(),d=i.reader.readUint32(),r=i.reader.readUint32(),s=i.reader.readUint32(),l=e.startTime+d/n):(n=i.reader.readUint32(),l=i.reader.readUint64()/n+e.timestampOffset,d=l-e.startTime,r=i.reader.readUint32(),s=i.reader.readUint32(),o=i.reader.readTerminatedString(),c=i.reader.readTerminatedString());const h=i.reader.readBytes(i.reader.getLength()-i.reader.getPosition());if(t&&t.includes(o)||this.config_.dispatchAllEmsgBoxes)if("urn:mpeg:dash:event:2012"==o)this.playerInterface_.onManifestUpdate();else{const t={startTime:l,endTime:l+r/n,schemeIdUri:o,value:c,timescale:n,presentationTimeDelta:d,eventDuration:r,id:s,messageData:h},i=a.EventName.Emsg,u=(new Map).set("detail",t),_=new a(i,u);if(_.cancelable=!0,this.playerInterface_.onEvent(_),_.defaultPrevented)return;if("https://aomedia.org/emsg/ID3"==o||"https://developer.apple.com/streaming/emsg-id3"==o){const t=ce.getID3Frames(h);if(t.length&&e){const i={cueTime:e.startTime,data:h,frames:t,dts:e.startTime,pts:e.startTime};this.playerInterface_.onMetadata([i],0,e.endTime)}}}}parsePrft_(e,t){if(this.parsedPrftEventRaised_||!e.initSegmentReference.timescale)return;console.assert(0==t.version||1==t.version,"PRFT version can only be 0 or 1");const i=de.parsePRFTInaccurate(t.reader,t.version),n=e.initSegmentReference.timescale,s=this.convertNtp(i.ntpTimestamp),r={wallClockTime:s,programStartDate:new Date(s-i.mediaTime/n*1e3)},o=a.EventName.Prft,l=(new Map).set("detail",r),d=new a(o,l);this.playerInterface_.onEvent(d),this.parsedPrftEventRaised_=!0}convertNtp(e){const t=new Date(Date.UTC(1900,0,1,0,0,0));return new Date(t.getTime()+e).getTime()}async evict_(e,t){const i=xe.logPrefix_(e);n.v2(i,"checking buffer length");const s=Math.max(this.config_.bufferBehind,this.manifest_.presentationTimeline.getMaxSegmentDuration()),a=this.playerInterface_.mediaSourceEngine.bufferStart(e.type);if(null==a)return void n.v2(i,"buffer behind okay because nothing buffered:","presentationTime="+t,"bufferBehind="+s);const r=t-a,o=r-s;o<=this.config_.evictionGoal?n.v2(i,"buffer behind okay:","presentationTime="+t,"bufferedBehind="+r,"bufferBehind="+s,"evictionGoal="+this.config_.evictionGoal,"underflow="+Math.abs(o)):(n.v1(i,"buffer behind too large:","presentationTime="+t,"bufferedBehind="+r,"bufferBehind="+s,"evictionGoal="+this.config_.evictionGoal,"overflow="+o),await this.playerInterface_.mediaSourceEngine.remove(e.type,a,a+o),this.destroyer_.ensureNotDestroyed(),n.v1(i,"evicted "+o+" seconds"))}static isEmbeddedText_(e){const t=F.CEA608_CLOSED_CAPTION_MIMETYPE,i=F.CEA708_CLOSED_CAPTION_MIMETYPE;return e&&e.type==U.ContentType.TEXT&&(e.stream.mimeType==t||e.stream.mimeType==i)}async fetch_(e,t,i){const n=t.getSegmentData();if(n)return n;let s=null;e.segmentPrefetch&&(s=e.segmentPrefetch.getPrefetchedSegment(t,i)),s||(s=this.dispatchFetch_(t,e.stream,i));let a=0;e.segmentIterator&&(a=e.segmentIterator.currentPosition()),e.operation=s;const r=await s.promise;e.operation=null;let o=r.data;return t.aesKey&&(o=await this.aesDecrypt_(o,t.aesKey,a)),o}dispatchFetch_(e,t,i){return console.assert(this.playerInterface_.netEngine,"Must have net engine"),xe.dispatchFetch(e,t,i||null,this.config_.retryParameters,this.playerInterface_.netEngine)}static dispatchFetch(e,t,i,s,a){const r=D.RequestType.SEGMENT,o=e instanceof Ee?e:void 0,l=o?D.AdvancedRequestType.MEDIA_SEGMENT:D.AdvancedRequestType.INIT_SEGMENT,d=Le.createSegmentRequest(e.getUris(),e.startByte,e.endByte,s,i);return d.contentType=t.type,n.v2("fetching: reference=",e),a.request(r,d,{type:l,stream:t,segment:o})}async clearBuffer_(e,t,i){const s=xe.logPrefix_(e);if(console.assert(!e.performingUpdate&&null==e.updateTimer,s+" unexpected call to clearBuffer_()"),e.waitingToClearBuffer=!1,e.waitingToFlushBuffer=!1,e.clearBufferSafeMargin=0,e.clearingBuffer=!0,e.lastSegmentReference=null,e.lastInitSegmentReference=null,e.segmentIterator=null,n.debug(s,"clearing buffer"),e.segmentPrefetch&&!this.audioPrefetchMap_.has(e.stream)&&e.segmentPrefetch.clearAll(),i){const t=this.playerInterface_.getPresentationTime(),n=this.playerInterface_.mediaSourceEngine.getDuration();await this.playerInterface_.mediaSourceEngine.remove(e.type,t+i,n)}else await this.playerInterface_.mediaSourceEngine.clear(e.type),this.destroyer_.ensureNotDestroyed(),t&&await this.playerInterface_.mediaSourceEngine.flush(e.type);this.destroyer_.ensureNotDestroyed(),n.debug(s,"cleared buffer"),e.clearingBuffer=!1,e.endOfStream=!1,e.performingUpdate||e.updateTimer||this.scheduleUpdate_(e,0)}scheduleUpdate_(e,t){const i=xe.logPrefix_(e),s=e.type;s!=U.ContentType.TEXT||this.mediaStates_.has(s)?(n.v2(i,"updating in "+t+" seconds"),console.assert(null==e.updateTimer,i+" did not expect update to be scheduled"),e.updateTimer=new o((async()=>{try{await this.onUpdate_(e)}catch(e){this.playerInterface_&&this.playerInterface_.onError(e)}})).tickAfter(t)):n.v1(i,"Text stream is unloaded. No update is needed.")}cancelUpdate_(e){null!=e.updateTimer&&(e.updateTimer.stop(),e.updateTimer=null)}async abortOperations_(e){e.operation&&await e.operation.abort()}async handleStreamingError_(e,t){await this.failureCallbackBackoff_.attempt(),this.destroyer_.ensureNotDestroyed();const i=this.getDisabledTime_(t);t.category===b.Category.NETWORK&&i>0&&(t.handled=this.playerInterface_.disableStream(e.stream,i),t.handled&&(t.severity=b.Severity.RECOVERABLE)),this.playerInterface_.onError(t),t.handled||this.config_.failureCallback(t)}getDisabledTime_(e){return 0===this.config_.maxDisabledTime&&e.code==b.Code.SEGMENT_MISSING?1:this.config_.maxDisabledTime}async resetMediaSource(){const e=Date.now()/1e3,t=this.config_.minTimeBetweenRecoveries;if(!this.config_.allowMediaSourceRecoveries||e-this.lastMediaSourceReset_<t)return!1;this.lastMediaSourceReset_=e;const i=U.ContentType,n=this.mediaStates_.get(i.AUDIO);n&&(n.lastInitSegmentReference=null,this.forceClearBuffer_(n),this.abortOperations_(n).catch((()=>{})));const s=this.mediaStates_.get(i.VIDEO);s&&(s.lastInitSegmentReference=null,this.forceClearBuffer_(s),this.abortOperations_(s).catch((()=>{})));const a=new Map;return this.currentVariant_.audio&&a.set(i.AUDIO,this.currentVariant_.audio),this.currentVariant_.video&&a.set(i.VIDEO,this.currentVariant_.video),await this.playerInterface_.mediaSourceEngine.reset(a),!0}static logPrefix_(e){return"("+e.type+":"+e.stream.id+")"}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}xe.PlayerInterface,xe.MediaState_,xe.APPEND_WINDOW_START_FUDGE_=.1,xe.APPEND_WINDOW_END_FUDGE_=.01,xe.MAX_RUN_AHEAD_SEGMENTS_=1;class ke extends r{constructor(e,t,i,n,s){super();const a=s;this.assetUri_=e,this.mimeType_=t,this.networkingEngine_=a.networkingEngine,this.startTime_=n,this.currentAdaptationSetCriteria_=null,this.startTimeOfLoad_=i,this.manifestFilterer_=a.manifestFilterer,this.manifestPlayerInterface_=a.manifestPlayerInterface,this.config_=a.config,this.manifest_=null,this.parserFactory_=null,this.parser_=null,this.parserEntrusted_=!1,this.regionTimeline_=a.regionTimeline,this.regionTimelineEntrusted_=!1,this.abrManagerFactory_=null,this.abrManager_=null,this.abrManagerEntrusted_=!1,this.segmentPrefetchById_=new Map,this.segmentPrefetchEntrusted_=!1,this.qualityObserver_=a.qualityObserver,this.stats_=new ne,this.manifestPromise_=new C,this.chooseInitialVariantPromise_=new C,this.destroyPromise_=new C,this.destroyPromise_.catch((e=>{})),this.eventHandoffTarget_=null,this.destroyed_=!1,this.allowPrefetch_=a.allowPrefetch,this.prefetchedVariant_=null,this.allowMakeAbrManager_=a.allowMakeAbrManager,this.hasBeenAttached_=!1,this.queuedOperations_=[],this.latePhaseQueuedOperations_=[]}addQueuedOperation(e,t){const i=e?this.latePhaseQueuedOperations_:this.queuedOperations_;i?i.push(t):t()}stopQueuingLatePhaseQueuedOperations(){if(this.latePhaseQueuedOperations_)for(const e of this.latePhaseQueuedOperations_)e();this.latePhaseQueuedOperations_=null}setEventHandoffTarget(e){if(this.eventHandoffTarget_=e,this.hasBeenAttached_=!0,this.queuedOperations_)for(const e of this.queuedOperations_)e();this.queuedOperations_=null}getStartTime(){return this.startTime_}getStartTimeOfLoad(){return this.startTimeOfLoad_}getMimeType(){return this.mimeType_}getAssetUri(){return this.assetUri_}getManifest(){return this.manifest_}getParserFactory(){return this.parserFactory_}getCurrentAdaptationSetCriteria(){return this.currentAdaptationSetCriteria_}getAbrManagerFactory(){return this.abrManagerFactory_}receiveAbrManager(){return this.abrManagerEntrusted_=!0,this.abrManager_}getAbrManager(){return this.abrManager_}receiveParser(){return this.parserEntrusted_=!0,this.parser_}getParser(){return this.parser_}receiveRegionTimeline(){return this.regionTimelineEntrusted_=!0,this.regionTimeline_}getRegionTimeline(){return this.regionTimeline_}getQualityObserver(){return this.qualityObserver_}getStats(){return this.stats_}getManifestFilterer(){return this.manifestFilterer_}getPrefetchedVariant(){return this.prefetchedVariant_}receiveSegmentPrefetchesById(){return this.segmentPrefetchEntrusted_=!0,this.segmentPrefetchById_}waitForManifest(){return this.manifestPromise_}waitForChooseInitialVariant(){return this.chooseInitialVariantPromise_}attachAbrManager(e,t){this.abrManager_=e,this.abrManagerFactory_=t}attachAdaptationSetCriteria(e){this.currentAdaptationSetCriteria_=e}attachManifest(e,t,i){this.manifest_=e,this.parser_=t,this.parserFactory_=i}async start(){await Promise.resolve();try{if(await this.parseManifestInner_(),this.isDestroyed())return;if(this.manifestPromise_.resolve(),this.isDestroyed())return;if(await this.chooseInitialVariantInner_(),this.isDestroyed())return;this.chooseInitialVariantPromise_.resolve()}catch(e){throw this.destroyPromise_.reject(e),e}}dispatchEvent(e){return this.eventHandoffTarget_?this.eventHandoffTarget_.dispatchEvent(e):super.dispatchEvent(e)}onError(e){e.severity===b.Severity.CRITICAL&&(this.destroyPromise_.reject(e),this.destroy());const t=a.EventName.Error,i=this.makeEvent_(t,(new Map).set("detail",e));this.dispatchEvent(i),i.defaultPrevented&&(e.handled=!0)}makeStateChangeEvent_(e){this.dispatchEvent(new a(a.EventName.OnStateChange,(new Map).set("state",e)))}makeEvent_(e,t){return new a(e,t)}async parseManifestInner_(){this.makeStateChangeEvent_("manifest-parser"),this.parser_||(this.parserFactory_=_e.getFactory(this.assetUri_,this.mimeType_),console.assert(this.parserFactory_,"Must have manifest parser"),this.parser_=this.parserFactory_(),this.parser_.configure(this.config_.manifest));const e=Date.now()/1e3;this.makeStateChangeEvent_("manifest"),this.manifest_||(this.manifest_=await this.parser_.start(this.assetUri_,this.manifestPlayerInterface_));const t=this.makeEvent_(a.EventName.ManifestParsed);if(this.dispatchEvent(t),0==this.manifest_.variants.length)throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.NO_VARIANTS);ke.filterForAVVariants_(this.manifest_);const i=Date.now()/1e3-e;this.stats_.setManifestTime(i)}reconfigure(e){this.config_=e}configure(e,t){const i=K.convertToConfigObject(e,t);Z.mergeConfigObjects(this.config_,i)}getConfiguration(){return w.cloneObject(this.config_)}chooseInitialVariantInner_(){if(console.assert(this.manifest_,"The manifest should already be parsed."),this.currentAdaptationSetCriteria_||(this.currentAdaptationSetCriteria_=new Ne(this.config_.preferredAudioLanguage,this.config_.preferredVariantRole,this.config_.preferredAudioChannelCount,this.config_.preferredVideoHdrLevel,this.config_.preferSpatialAudio,this.config_.preferredVideoLayout,this.config_.preferredAudioLabel,this.config_.preferredVideoLabel,this.config_.mediaSource.codecSwitchingStrategy,this.config_.manifest.dash.enableAudioGroups),j.chooseCodecsAndFilterManifest(this.manifest_,this.config_.preferredVideoCodecs,this.config_.preferredAudioCodecs,this.config_.preferredDecodingAttributes)),this.allowMakeAbrManager_){const e=this.config_.abrFactory;this.abrManagerFactory_=e,this.abrManager_=e(),this.abrManager_.configure(this.config_.abr)}if(this.allowPrefetch_){const e=this.manifest_.presentationTimeline.isLive(),t=j.getPlayableVariants(this.manifest_.variants),i=this.currentAdaptationSetCriteria_.create(t);this.abrManager_.configure(this.config_.abr),this.abrManager_.setVariants(Array.from(i.values()));const n=this.abrManager_.chooseVariant(!0);n&&(this.prefetchedVariant_=n,n.video&&this.makePrefetchForStream_(n.video,e),n.audio&&this.makePrefetchForStream_(n.audio,e))}}async makePrefetchForStream_(e,t){const i=this.config_.streaming.segmentPrefetchLimit||2,n=new Re(i,e,((e,t,i)=>xe.dispatchFetch(e,t,i||null,this.config_.streaming.retryParameters,this.networkingEngine_)));this.segmentPrefetchById_.set(e.id,n),await e.createSegmentIndex();const s=this.startTime_||0,a=e.segmentIndex.getIteratorForTime(s);let r=a?a.current():null;r||(r=e.segmentIndex.get(0)),r&&(t?r.initSegmentReference&&n.prefetchInitSegment(r.initSegmentReference):n.prefetchSegmentsByTime(r.startTime))}waitForFinish(){return Promise.race([this.chooseInitialVariantPromise_,this.destroyPromise_])}async destroy(){if(this.destroyed_=!0,this.parser_&&!this.parserEntrusted_&&await this.parser_.stop(),this.abrManager_&&!this.abrManagerEntrusted_&&await this.abrManager_.stop(),this.regionTimeline_&&!this.regionTimelineEntrusted_&&this.regionTimeline_.release(),this.segmentPrefetchById_.size>0&&!this.segmentPrefetchEntrusted_)for(const e of this.segmentPrefetchById_.values())e.clearAll()}isDestroyed(){return this.destroyed_}hasBeenAttached(){return this.hasBeenAttached_}static filterForAVVariants_(e){const t=e=>e.video&&e.audio||e.video&&e.video.codecs.includes(",");e.variants.some(t)&&(n.debug("Found variant with audio and video content, so filtering out audio-only content."),e.variants=e.variants.filter(t))}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0,void 0]}}class Ue{static waitForReadyState(e,t,i,n){if(t==HTMLMediaElement.HAVE_NOTHING||e.readyState>=t)n();else{const s=Ue.READY_STATES_TO_EVENT_NAMES_.value().get(t);i.listenOnce(e,s,n)}}}Ue.READY_STATES_TO_EVENT_NAMES_=new L((()=>new Map([[HTMLMediaElement.HAVE_METADATA,"loadedmetadata"],[HTMLMediaElement.HAVE_CURRENT_DATA,"loadeddata"],[HTMLMediaElement.HAVE_FUTURE_DATA,"canplay"],[HTMLMediaElement.HAVE_ENOUGH_DATA,"canplaythrough"]])));class Be{constructor(e,t,i,n){this.video_=e,this.onSeek_=t,this.onStarted_=i,this.startTime_=null,this.getStartTime_=()=>(null==this.startTime_&&(this.startTime_=n()),this.startTime_),this.started_=!1,this.eventManager_=new ee,this.mover_=new Be.PlayheadMover(e,10),Ue.waitForReadyState(this.video_,HTMLMediaElement.HAVE_METADATA,this.eventManager_,(()=>{this.setStartTime_(this.getStartTime_())}))}release(){this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null),null!=this.mover_&&(this.mover_.release(),this.mover_=null),this.onSeek_=()=>{},this.video_=null}getTime(){return this.started_?this.video_.currentTime:this.getStartTime_()}setTime(e){this.video_.readyState>0?this.mover_.moveTo(e):Ue.waitForReadyState(this.video_,HTMLMediaElement.HAVE_METADATA,this.eventManager_,(()=>{this.setStartTime_(this.getStartTime_())}))}setStartTime_(e){Math.abs(this.video_.currentTime-e)<.001?this.startListeningToSeeks_():(this.eventManager_.listenOnce(this.video_,"seeking",(()=>{this.startListeningToSeeks_()})),this.mover_.moveTo(this.video_.currentTime&&0!=this.video_.currentTime?this.video_.currentTime:e))}startListeningToSeeks_(){console.assert(this.video_.readyState>0,"The media element should be ready before we listen for seeking."),this.started_=!0,this.eventManager_.listen(this.video_,"seeking",(()=>this.onSeek_())),this.onStarted_(this.video_.currentTime)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0]}}class Fe{constructor(e,t){this.mediaElement_=e,this.maxAttempts_=t,this.remainingAttempts_=0,this.originTime_=0,this.targetTime_=0,this.timer_=new l((()=>this.onTick_()))}release(){this.timer_&&(this.timer_.stop(),this.timer_=null),this.mediaElement_=null}moveTo(e){this.originTime_=this.mediaElement_.currentTime,this.targetTime_=e,this.remainingAttempts_=this.maxAttempts_,this.mediaElement_.currentTime=e,this.timer_.tickEvery(.1)}onTick_(){if(this.remainingAttempts_<=0)return n.warning(["Failed to move playhead from",this.originTime_,"to",this.targetTime_].join(" ")),void this.timer_.stop();this.mediaElement_.currentTime==this.originTime_?(this.mediaElement_.currentTime=this.targetTime_,this.remainingAttempts_--):this.timer_.stop()}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}Be.PlayheadMover=Fe;class Ve{constructor(e,t,i,n,s){this.onEvent_=s,this.video_=e,this.timeline_=t,this.config_=i,this.eventManager_=new ee,this.seekingEventReceived_=!1,this.prevReadyState_=e.readyState,this.startTime_=0,this.gapsJumped_=0,this.stallDetector_=n,this.hadSegmentAppended_=!1,this.eventManager_.listen(e,"waiting",(()=>this.onPollGapJump_())),this.gapJumpTimer_=new l((()=>{this.onPollGapJump_()})).tickEvery(this.config_.gapJumpTimerTime)}release(){this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null),null!=this.gapJumpTimer_&&(this.gapJumpTimer_.stop(),this.gapJumpTimer_=null),this.stallDetector_&&(this.stallDetector_.release(),this.stallDetector_=null),this.onEvent_=null,this.timeline_=null,this.video_=null}onSegmentAppended(){this.hadSegmentAppended_=!0,this.onPollGapJump_()}onStarted(e){this.video_.seeking&&!this.seekingEventReceived_&&(this.seekingEventReceived_=!0,this.startTime_=e)}onSeeking(){this.seekingEventReceived_=!0,this.hadSegmentAppended_=!1}getGapsJumped(){return this.gapsJumped_}onPollGapJump_(){if(0==this.video_.readyState)return;if(this.video_.seeking){if(!this.seekingEventReceived_)return}else this.seekingEventReceived_=!1;if(this.video_.paused&&(this.video_.currentTime!=this.startTime_||!this.video_.autoplay&&this.video_.currentTime==this.startTime_))return;if(this.video_.readyState!=this.prevReadyState_&&(this.prevReadyState_=this.video_.readyState),this.stallDetector_&&this.stallDetector_.poll())return;const e=this.video_.currentTime,t=this.video_.buffered,i=this.config_.gapDetectionThreshold,s=ge.getGapIndex(t,e,i);if(null==s)return;if(0==s&&!this.hadSegmentAppended_)return;const r=t.start(s);if(r>=this.timeline_.getSeekRangeEnd())return;const o=r-e;o<Ve.BROWSER_GAP_TOLERANCE||(0==s?n.info("Jumping forward",o,"seconds because of gap before start time of",r):n.info("Jumping forward",o,"seconds because of gap starting at",t.end(s-1),"and ending at",r),this.video_.currentTime=r,e==this.startTime_&&(this.startTime_=r),this.gapsJumped_++,this.onEvent_(new a(a.EventName.GapJumped)))}static get[Symbol.for("___CTOR_ARGS___")](){return["HTMLMediaElement","PresentationTimeline",void 0,"StallDetector",void 0]}}Ve.BROWSER_GAP_TOLERANCE=.001;class Ge{constructor(e,t,i){this.onEvent_=i,this.implementation_=e,this.wasMakingProgress_=e.shouldBeMakingProgress(),this.value_=e.getPresentationSeconds(),this.lastUpdateSeconds_=e.getWallSeconds(),this.didJump_=!1,this.stallsDetected_=0,this.stallThresholdSeconds_=t,this.onStall_=()=>{}}release(){this.implementation_=null,this.onEvent_=null,this.onStall_=()=>{}}onStall(e){this.onStall_=e}getStallsDetected(){return this.stallsDetected_}poll(){const e=this.implementation_,t=e.shouldBeMakingProgress(),i=e.getPresentationSeconds(),n=e.getWallSeconds();(this.value_!=i||this.wasMakingProgress_!=t)&&(this.lastUpdateSeconds_=n,this.value_=i,this.wasMakingProgress_=t,this.didJump_=!1);const s=n-this.lastUpdateSeconds_,r=s>=this.stallThresholdSeconds_&&t&&!this.didJump_;return r&&(this.onStall_(this.value_,s),this.didJump_=!0,this.value_=e.getPresentationSeconds(),this.stallsDetected_++,this.onEvent_(new a(a.EventName.StallDetected))),r}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0]}}class He{constructor(e){this.mediaElement_=e}shouldBeMakingProgress(){return!this.mediaElement_.paused&&0!=this.mediaElement_.buffered.length&&He.hasContentFor_(this.mediaElement_.buffered,this.mediaElement_.currentTime)}getPresentationSeconds(){return this.mediaElement_.currentTime}getWallSeconds(){return Date.now()/1e3}static hasContentFor_(e,t){for(const{start:i,end:n}of ge.getBufferedInfo(e))if(!(t<i-.1||t>n-.5))return!0;return!1}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class We{constructor(e){this.mediaElement_=e,this.started_=!1,this.startTime_=null,this.eventManager_=new ee}ready(){console.assert(null!=this.mediaElement_,"Playhead should not be released before calling ready()");const e=()=>{if(null==this.startTime_||0==this.startTime_)this.started_=!0;else{this.eventManager_.listenOnce(this.mediaElement_,"seeking",(()=>{this.started_=!0}));const e=this.mediaElement_.currentTime,t=Math.max(0,e+this.startTime_);this.mediaElement_.currentTime=t}};Ue.waitForReadyState(this.mediaElement_,HTMLMediaElement.HAVE_CURRENT_DATA,this.eventManager_,(()=>{e()}))}release(){this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null),this.mediaElement_=null}setStartTime(e){this.startTime_=this.started_?this.startTime_:e}getTime(){return(this.started_?this.mediaElement_.currentTime:this.startTime_)||0}getStallsDetected(){return 0}getGapsJumped(){return 0}notifyOfBufferingChange(){}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class qe{constructor(e,t,i,n,s,a){this.minSeekRange_=3,this.mediaElement_=e,this.timeline_=t.presentationTimeline,this.minBufferTime_=t.minBufferTime||0,this.config_=i,this.onSeek_=s,this.lastCorrectiveSeek_=null,this.stallDetector_=this.createStallDetector_(e,i,a),this.gapController_=new Ve(e,t.presentationTimeline,i,this.stallDetector_,a),this.videoWrapper_=new Be(e,(()=>this.onSeeking_()),(e=>this.onStarted_(e)),(()=>this.getStartTime_(n))),this.checkWindowTimer_=new l((()=>{this.onPollWindow_()}))}ready(){this.checkWindowTimer_.tickEvery(.25)}release(){this.videoWrapper_&&(this.videoWrapper_.release(),this.videoWrapper_=null),this.gapController_&&(this.gapController_.release(),this.gapController_=null),this.checkWindowTimer_&&(this.checkWindowTimer_.stop(),this.checkWindowTimer_=null),this.config_=null,this.timeline_=null,this.videoWrapper_=null,this.mediaElement_=null,this.onSeek_=()=>{}}setStartTime(e){this.videoWrapper_.setTime(e)}getTime(){const e=this.videoWrapper_.getTime();return this.mediaElement_.readyState>0&&!this.mediaElement_.paused?this.clampTime_(e):e}getStallsDetected(){return this.stallDetector_?this.stallDetector_.getStallsDetected():0}getGapsJumped(){return this.gapController_.getGapsJumped()}getStartTime_(e){return null==e?e=this.timeline_.getDuration()<1/0?this.timeline_.getSeekRangeStart():this.timeline_.getSeekRangeEnd():e<0&&(e=this.timeline_.getSeekRangeEnd()+e),this.clampSeekToDuration_(this.clampTime_(e))}notifyOfBufferingChange(){this.gapController_.onSegmentAppended()}onPollWindow_(){if(0==this.mediaElement_.readyState||this.mediaElement_.paused)return;const e=this.videoWrapper_.getTime();let t=this.timeline_.getSeekRangeStart();const i=this.timeline_.getSeekRangeEnd();if(i-t<this.minSeekRange_&&(t=i-this.minSeekRange_),e<t){const t=this.reposition_(e);n.info("Jumping forward "+(t-e)+" seconds to catch up with the seek range."),this.mediaElement_.currentTime=t}}onStarted_(e){this.gapController_.onStarted(e)}onSeeking_(){this.gapController_.onSeeking();const e=this.videoWrapper_.getTime(),t=this.reposition_(e),i=Ve.BROWSER_GAP_TOLERANCE;if(Math.abs(t-e)>i){const e=Date.now()/1e3;if(!this.lastCorrectiveSeek_||this.lastCorrectiveSeek_<e-1)return this.lastCorrectiveSeek_=e,void this.videoWrapper_.setTime(t)}n.v1("Seek to "+e),this.onSeek_()}clampSeekToDuration_(e){const t=this.timeline_.getDuration();return e>=t?(console.assert(this.config_.durationBackoff>=0,"Duration backoff must be non-negative!"),t-this.config_.durationBackoff):e}reposition_(e){console.assert(this.config_,"Cannot reposition playhead when it has beeen destroyed");const t=e=>ge.isBuffered(this.mediaElement_.buffered,e),i=Math.max(this.minBufferTime_,this.config_.rebufferingGoal),s=this.config_.safeSeekOffset;let a=this.timeline_.getSeekRangeStart();const r=this.timeline_.getSeekRangeEnd(),o=this.timeline_.getDuration();r-a<this.minSeekRange_&&(a=r-this.minSeekRange_);const l=this.timeline_.getSafeSeekRangeStart(i),d=this.timeline_.getSafeSeekRangeStart(s),c=this.timeline_.getSafeSeekRangeStart(i+s);return e>=o?(n.v1("Playhead past duration."),this.clampSeekToDuration_(e)):e>r?(n.v1("Playhead past end."),r):e<a?t(d)?(n.v1("Playhead before start & start is buffered"),d):(n.v1("Playhead before start & start is unbuffered"),c):e>=l||t(e)?(n.v1("Playhead in safe region or in buffered region."),e):(n.v1("Playhead outside safe region & in unbuffered region."),c)}clampTime_(e){const t=this.timeline_.getSeekRangeStart();if(e<t)return t;const i=this.timeline_.getSeekRangeEnd();return e>i?i:e}createStallDetector_(e,t,i){if(!t.stallEnabled)return null;const s=t.stallThreshold,a=t.stallSkip,r=new Ge(new He(e),s,i);return r.onStall(((t,i)=>{n.debug(`Stall detected at ${t} for ${i} seconds.`),a?(n.debug(`Seeking forward ${a} seconds to break stall.`),e.currentTime+=a):(n.debug("Pausing and unpausing to break stall."),e.pause(),e.play())})),r}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0,void 0,void 0]}}class Xe{constructor(e,t){const i=Xe.State;this.previousState_=i.SATISFIED,this.thresholds_=(new Map).set(i.SATISFIED,t).set(i.STARVING,e),this.lastRebufferTime_=0}setThresholds(e,t){const i=Xe.State;this.thresholds_.set(i.SATISFIED,t).set(i.STARVING,e)}update(e,t){const i=Xe.State,n=this.thresholds_.get(this.previousState_),s=this.previousState_,a=t||e>=n?i.SATISFIED:i.STARVING;this.previousState_=a;const r=s!=a;return r&&a===i.SATISFIED&&(this.lastRebufferTime_=Date.now()),r}setState(e){this.previousState_=e}getState(){return this.previousState_}getLastRebufferTime(){return this.lastRebufferTime_}resetLastRebufferTime(){this.lastRebufferTime_=0}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}Xe.State={STARVING:0,SATISFIED:1};class ze{constructor(e){this.harness_=e,this.rate_=this.harness_.getRate(),this.pollRate_=.25,this.timer_=new l((()=>{this.harness_.movePlayhead(this.rate_*this.pollRate_)}))}release(){this.set(this.getDefaultRate()),this.timer_&&(this.timer_.stop(),this.timer_=null),this.harness_=null}set(e){this.rate_!=e&&(this.rate_=e,this.apply_())}getRealRate(){return this.rate_}getDefaultRate(){return this.harness_.getDefaultRate()}apply_(){if(this.timer_.stop(),n.v1("Changing effective playback rate to",this.rate_),this.rate_>=0)try{return void this.applyRate_(this.rate_)}catch(e){}this.timer_.tickEvery(this.pollRate_),this.applyRate_(0)}applyRate_(e){const t=this.harness_.getRate();return t!=e&&this.harness_.setRate(e),t!=e}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class je{static createHTMLElement(e){return document.createElement(e)}static createButton(){const e=document.createElement("button");return e.setAttribute("type","button"),e}static asHTMLElement(e){return e}static asHTMLMediaElement(e){return e}static getElementByClassName(e,t){const i=t.getElementsByClassName(e);return console.assert(1==i.length,"Should only be one element with class name "+e),je.asHTMLElement(i[0])}static removeAllChildren(e){for(;e.firstChild;)e.removeChild(e.firstChild)}}class Ye{constructor(e,t,i){const n=n;this.startTime=e,this.endTime=t,this.payload=i,this.region=new Ke,this.position=null,this.positionAlign=n.positionAlign.AUTO,this.size=0,this.textAlign=n.textAlign.CENTER,this.direction=n.direction.HORIZONTAL_LEFT_TO_RIGHT,this.writingMode=n.writingMode.HORIZONTAL_TOP_TO_BOTTOM,this.lineInterpretation=n.lineInterpretation.LINE_NUMBER,this.line=null,this.lineHeight="",this.lineAlign=n.lineAlign.START,this.displayAlign=n.displayAlign.AFTER,this.color="",this.backgroundColor="",this.backgroundImage="",this.border="",this.fontSize="",this.fontWeight=n.fontWeight.NORMAL,this.fontStyle=n.fontStyle.NORMAL,this.fontFamily="",this.letterSpacing="",this.linePadding="",this.opacity=1,this.textCombineUpright="",this.textDecoration=[],this.textShadow="",this.textStrokeColor="",this.textStrokeWidth="",this.wrapLine=!0,this.id="",this.nestedCues=[],this.isContainer=!1,this.lineBreak=!1,this.rubyTag=null,this.cellResolution={columns:32,rows:15}}static lineBreak(e,t){const i=new Ye(e,t,"");return i.lineBreak=!0,i}clone(){const e=new Ye(0,0,"");for(const t in this)e[t]=this[t],e[t]&&e[t].constructor==Array&&(e[t]=e[t].slice());return e}static equal(e,t){if(e.startTime!=t.startTime||e.endTime!=t.endTime||e.payload!=t.payload)return!1;for(const i in e)if("startTime"==i||"endTime"==i||"payload"==i);else if("nestedCues"==i){if(!I.equal(e.nestedCues,t.nestedCues,Ye.equal))return!1}else if("region"==i||"cellResolution"==i){for(const n in e[i])if(e[i][n]!=t[i][n])return!1}else if(Array.isArray(e[i])){if(!I.equal(e[i],t[i]))return!1}else if(e[i]!=t[i])return!1;return!0}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0]}}Ye.positionAlign={LEFT:"line-left",RIGHT:"line-right",CENTER:"center",AUTO:"auto"},Ye.textAlign={LEFT:"left",RIGHT:"right",CENTER:"center",START:"start",END:"end"},Ye.displayAlign={BEFORE:"before",CENTER:"center",AFTER:"after"},Ye.direction={HORIZONTAL_LEFT_TO_RIGHT:"ltr",HORIZONTAL_RIGHT_TO_LEFT:"rtl"},Ye.writingMode={HORIZONTAL_TOP_TO_BOTTOM:"horizontal-tb",VERTICAL_LEFT_TO_RIGHT:"vertical-lr",VERTICAL_RIGHT_TO_LEFT:"vertical-rl"},Ye.lineInterpretation={LINE_NUMBER:0,PERCENTAGE:1},Ye.lineAlign={CENTER:"center",START:"start",END:"end"},Ye.defaultTextColor={white:"white",lime:"lime",cyan:"cyan",red:"red",yellow:"yellow",magenta:"magenta",blue:"blue",black:"black"},Ye.defaultTextBackgroundColor={bg_white:"white",bg_lime:"lime",bg_cyan:"cyan",bg_red:"red",bg_yellow:"yellow",bg_magenta:"magenta",bg_blue:"blue",bg_black:"black"},Ye.fontWeight={NORMAL:400,BOLD:700},Ye.fontStyle={NORMAL:"normal",ITALIC:"italic",OBLIQUE:"oblique"},Ye.textDecoration={UNDERLINE:"underline",LINE_THROUGH:"lineThrough",OVERLINE:"overline"};class Ke{constructor(){this.id="",this.viewportAnchorX=0,this.viewportAnchorY=0,this.regionAnchorX=0,this.regionAnchorY=0,this.width=100,this.height=100,this.heightUnits=Ke.units.PERCENTAGE,this.widthUnits=Ke.units.PERCENTAGE,this.viewportAnchorUnits=Ke.units.PERCENTAGE,this.scroll=Ke.scrollMode.NONE}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}Ke.units={PX:0,PERCENTAGE:1,LINES:2},Ke.scrollMode={NONE:"",UP:"up"};class Qe{static flattenPayload_(e,t){if(e.lineBreak)return"\n";if(e.nestedCues.length)return e.nestedCues.map((t=>Qe.flattenPayload_(t,e))).join("");const i=[],n=e.fontWeight>=Ye.fontWeight.BOLD,s=e.fontStyle==Ye.fontStyle.ITALIC,a=e.textDecoration.includes(Ye.textDecoration.UNDERLINE);n&&i.push(["b"]),s&&i.push(["i"]),a&&i.push(["u"]);let r=e.color;""==r&&t&&(r=t.color);let o="";const l=Qe.getColorName_(r);l&&(o+=`.${l}`);let d=e.backgroundColor;""==d&&t&&(d=t.backgroundColor);const c=Qe.getColorName_(d);return c&&(o+=`.bg_${c}`),o&&i.push(["c",o]),i.reduceRight(((e,[t,i=""])=>`<${t}${i}>${e}</${t}>`),e.payload)}static getColorName_(e){let t=e.toLowerCase();const i=t.replace(/\s/g,"").match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i);switch(i?t="#"+(256|parseInt(i[1],10)).toString(16).slice(1)+(256|parseInt(i[2],10)).toString(16).slice(1)+(256|parseInt(i[3],10)).toString(16).slice(1):t.startsWith("#")&&t.length>7&&(t=t.slice(0,7)),t){case"white":case"#fff":case"#ffffff":return"white";case"lime":case"#0f0":case"#00ff00":return"lime";case"cyan":case"#0ff":case"#00ffff":return"cyan";case"red":case"#f00":case"#ff0000":return"red";case"yellow":case"#ff0":case"#ffff00":return"yellow";case"magenta":case"#f0f":case"#ff00ff":return"magenta";case"blue":case"#00f":case"#0000ff":return"blue";case"black":case"#000":case"#000000":return"black"}return null}static getCuesToFlatten(e,t){const i=[];for(const n of e)if(n.isContainer)i.push(...Qe.getCuesToFlatten(n.nestedCues,n));else{const e=n.clone();e.nestedCues=[],e.payload=Qe.flattenPayload_(n,t),i.push(e)}return i}}class $e{constructor(e,t){this.textTrack_=null;for(const i of Array.from(e.textTracks))i.mode="disabled",i.label==t&&(this.textTrack_=i);this.textTrack_||(this.textTrack_=e.addTextTrack("subtitles",t)),this.textTrack_.mode="hidden"}remove(e,t){return!!this.textTrack_&&($e.removeWhere_(this.textTrack_,(i=>i.startTime<t&&i.endTime>e)),!0)}append(e){const t=Qe.getCuesToFlatten(e),i=[],n=this.textTrack_.cues?Array.from(this.textTrack_.cues):[];for(const e of t)if(!n.some((t=>t.startTime==e.startTime&&t.endTime==e.endTime&&t.text==e.payload))){const t=$e.convertToTextTrackCue_(e);t&&i.push(t)}const s=i.slice().sort(((e,t)=>e.startTime!=t.startTime?e.startTime-t.startTime:e.endTime!=t.endTime?e.endTime-t.startTime:"line"in VTTCue.prototype?i.indexOf(t)-i.indexOf(e):i.indexOf(e)-i.indexOf(t)));for(const e of s)this.textTrack_.addCue(e)}destroy(){if(this.textTrack_){const e=e=>!0;$e.removeWhere_(this.textTrack_,e),this.textTrack_.mode="disabled"}return this.textTrack_=null,Promise.resolve()}isTextVisible(){return"showing"==this.textTrack_.mode}setTextVisibility(e){this.textTrack_.mode=e?"showing":"hidden"}static convertToTextTrackCue_(e){if(e.startTime>=e.endTime)return Logger.warning("Invalid cue times: "+e.startTime+" - "+e.endTime),null;const t=t,i=new VTTCue(e.startTime,e.endTime,e.payload);i.lineAlign=e.lineAlign,i.positionAlign=e.positionAlign,e.size&&(i.size=e.size);try{i.align=e.textAlign}catch(e){}return"center"==e.textAlign&&"center"!=i.align&&(i.align="middle"),e.writingMode==t.writingMode.VERTICAL_LEFT_TO_RIGHT?i.vertical="lr":e.writingMode==t.writingMode.VERTICAL_RIGHT_TO_LEFT&&(i.vertical="rl"),e.lineInterpretation==t.lineInterpretation.PERCENTAGE&&(i.snapToLines=!1),null!=e.line&&(i.line=e.line),null!=e.position&&(i.position=e.position),i}static removeWhere_(e,t){const i=e.mode,n="showing"==i?"showing":"hidden";e.mode=n,console.assert(e.cues,'Cues should be accessible when mode is set to "'+n+'".');for(const i of Array.from(e.cues))i&&t(i)&&e.removeCue(i);e.mode=i}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}class Je{remove(e,t){}append(e){}destroy(){}isTextVisible(){return!1}setTextVisibility(e){}}class Ze{constructor(e,t){console.assert(t,"videoContainer should be valid."),this.isTextVisible_=!1,this.cues_=[],this.video_=e,this.videoContainer_=t,this.aspectRatio_=null,this.textContainer_=je.createHTMLElement("div"),this.textContainer_.classList.add("shaka-text-container"),this.textContainer_.style.textAlign="center",this.textContainer_.style.display="flex",this.textContainer_.style.flexDirection="column",this.textContainer_.style.alignItems="center",this.textContainer_.style.justifyContent="flex-end",this.videoContainer_.appendChild(this.textContainer_),this.captionsTimer_=new l((()=>{this.updateCaptions_()})).tickEvery(.25),this.currentCuesMap_=new Map,this.eventManager_=new ee,this.eventManager_.listen(document,"fullscreenchange",(()=>{this.updateCaptions_(!0)})),this.eventManager_.listen(this.video_,"resize",(()=>{const e=this.video_,t=e.videoWidth,i=e.videoHeight;this.aspectRatio_=t&&i?t/i:null})),this.resizeObserver_=null,"ResizeObserver"in window&&(this.resizeObserver_=new ResizeObserver((()=>{this.updateCaptions_(!0)})),this.resizeObserver_.observe(this.textContainer_)),this.regionElements_=new Map}append(e){const t=[...this.cues_];for(const i of e)t.some((e=>Ye.equal(e,i)))||this.cues_.push(i);this.updateCaptions_()}destroy(){return this.textContainer_?(this.videoContainer_.removeChild(this.textContainer_),this.textContainer_=null,this.isTextVisible_=!1,this.cues_=[],this.captionsTimer_&&this.captionsTimer_.stop(),this.currentCuesMap_.clear(),this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null),this.resizeObserver_&&(this.resizeObserver_.disconnect(),this.resizeObserver_=null),Promise.resolve()):Promise.resolve()}remove(e,t){if(!this.textContainer_)return!1;const i=this.cues_.length;this.cues_=this.cues_.filter((i=>i.startTime<e||i.endTime>=t));const n=i>this.cues_.length;return this.updateCaptions_(n),!0}isTextVisible(){return this.isTextVisible_}setTextVisibility(e){this.isTextVisible_=e}isElementUnderTextContainer_(e){for(;null!=e;){if(e==this.textContainer_)return!0;e=e.parentElement}return!1}updateCuesRecursive_(e,t,i,n){let s=!1;const a=[],r=[];for(const t of e){n.push(t);let e=this.currentCuesMap_.get(t);const o=t.startTime<=i&&t.endTime>i;let l=e?e.wrapper:null;e&&(a.push(e.cueElement),e.regionElement&&a.push(e.regionElement),o||(s=!0,this.currentCuesMap_.delete(t),e=null)),o&&(r.push(t),e?this.isElementUnderTextContainer_(l)||(s=!0):(this.createCue_(t,n),e=this.currentCuesMap_.get(t),l=e.wrapper,s=!0)),t.nestedCues.length>0&&l&&this.updateCuesRecursive_(t.nestedCues,l,i,n);const d=n.pop();console.assert(d==t,"Parent cues should be kept in order")}if(s){for(const e of a)e.parentElement&&e.parentElement.removeChild(e);r.sort(((e,t)=>e.startTime!=t.startTime?e.startTime-t.startTime:e.endTime-t.endTime));for(const e of r){const i=this.currentCuesMap_.get(e);console.assert(i,"cueRegistry should exist."),i.regionElement?(t.appendChild(i.regionElement),i.regionElement.appendChild(i.cueElement)):t.appendChild(i.cueElement)}}}updateCaptions_(e=!1){if(!this.textContainer_)return;const t=this.video_.currentTime;if(!this.isTextVisible_||e){for(const e of this.regionElements_.values())je.removeAllChildren(e);je.removeAllChildren(this.textContainer_),this.currentCuesMap_.clear(),this.regionElements_.clear()}if(this.isTextVisible_){const e=new Map;for(const t of this.currentCuesMap_.keys())e.set(t,this.currentCuesMap_.get(t));this.updateCuesRecursive_(this.cues_,this.textContainer_,t,[]);for(const t of e.keys())if(!this.currentCuesMap_.has(t)){const i=e.get(t).cueElement;console.assert(!i.parentNode,"Cue was not properly removed!")}}}generateRegionId_(e){const t=Ke.units.PERCENTAGE,i=e.heightUnits==t?"%":"px",n=e.viewportAnchorUnits==t?"%":"px";return`${e.id}_${e.width}x${e.height}${i}-${e.viewportAnchorX}x${e.viewportAnchorY}${n}`}getRegionElement_(e){const t=e.region,i=this.aspectRatio_===4/3?2.5:1.9,n=this.generateRegionId_(t);if(this.regionElements_.has(n))return this.regionElements_.get(n);const s=je.createHTMLElement("span"),a=Ke.units.PERCENTAGE,r=t.heightUnits==a?"%":"px",o=t.widthUnits==a?"%":"px",l=t.viewportAnchorUnits==a?"%":"px";s.id="shaka-text-region---"+n,s.classList.add("shaka-text-region"),s.style.position="absolute";const d=Ke.units.LINES;if(t.heightUnits===d&&t.widthUnits===d?(s.style.height=5.33*t.height+"%",s.style.width=t.width*i+"%"):(s.style.height=t.height+r,s.style.width=t.width+o),t.viewportAnchorUnits===d){let e=t.viewportAnchorY/75*100;const n=this.aspectRatio_===4/3?160:210;let a=t.viewportAnchorX/n*100;e-=t.regionAnchorY*t.height*5.33/100,a-=t.regionAnchorX*t.width*i/100,s.style.top=e+"%",s.style.left=a+"%"}else s.style.top=t.viewportAnchorY-t.regionAnchorY*t.height/100+l,s.style.left=t.viewportAnchorX-t.regionAnchorX*t.width/100+l;return s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",e.displayAlign==Ye.displayAlign.BEFORE?s.style.justifyContent="flex-start":e.displayAlign==Ye.displayAlign.CENTER?s.style.justifyContent="center":s.style.justifyContent="flex-end",this.regionElements_.set(n,s),s}createCue_(e,t){const i=t.length>1;let n=i?"span":"div";e.lineBreak&&(n="br"),e.rubyTag&&(n=e.rubyTag);const s=!i&&e.nestedCues.length>0,a=je.createHTMLElement(n);"br"!=n&&this.setCaptionStyles_(a,e,t,s);let r=null;e.region&&e.region.id&&(r=this.getRegionElement_(e));let o=a;s&&(o=je.createHTMLElement("span"),o.classList.add("shaka-text-wrapper"),o.style.backgroundColor=e.backgroundColor,o.style.lineHeight="normal",a.appendChild(o)),this.currentCuesMap_.set(e,{cueElement:a,wrapper:o,regionElement:r})}computeCuePositionAlignment_(e){const t=t,{direction:i,positionAlign:n,textAlign:s}=e;return n!==t.positionAlign.AUTO?n:s===t.textAlign.LEFT||s===t.textAlign.START&&i===t.direction.HORIZONTAL_LEFT_TO_RIGHT||s===t.textAlign.END&&i===t.direction.HORIZONTAL_RIGHT_TO_LEFT?t.positionAlign.LEFT:s===t.textAlign.RIGHT||s===t.textAlign.START&&i===t.direction.HORIZONTAL_RIGHT_TO_LEFT||s===t.textAlign.END&&i===t.direction.HORIZONTAL_LEFT_TO_RIGHT?t.positionAlign.RIGHT:t.positionAlign.CENTER}setCaptionStyles_(e,t,i,n){const s=s,a=e=>Ze.inheritProperty_(i,e),r=e.style,o=0==t.nestedCues.length,l=i.length>1;r.whiteSpace="pre-wrap";const d=t.payload.replace(/\s+$/g,(e=>" ".repeat(e.length)));if(r.webkitTextStrokeColor=t.textStrokeColor,r.webkitTextStrokeWidth=t.textStrokeWidth,r.color=t.color,r.direction=t.direction,r.opacity=t.opacity,r.paddingLeft=Ze.convertLengthValue_(t.linePadding,t,this.videoContainer_),r.paddingRight=Ze.convertLengthValue_(t.linePadding,t,this.videoContainer_),r.textCombineUpright=t.textCombineUpright,r.textShadow=t.textShadow,t.backgroundImage)r.backgroundImage="url('"+t.backgroundImage+"')",r.backgroundRepeat="no-repeat",r.backgroundSize="contain",r.backgroundPosition="center",r.width="100%",r.height="100%";else{let i;if(t.nestedCues.length?i=e:(i=je.createHTMLElement("span"),e.appendChild(i)),t.border&&(i.style.border=t.border),!n){const e=a((e=>e.backgroundColor));e?i.style.backgroundColor=e:d&&(i.style.backgroundColor="rgba(0, 0, 0, 0.8)");const t=a((e=>e.fontFamily));t&&(i.style.fontFamily=t)}d&&(i.textContent=d)}l&&!i[i.length-1].isContainer?r.display="inline":(r.display="flex",r.flexDirection="column",r.alignItems="center",t.displayAlign==s.displayAlign.BEFORE?r.justifyContent="flex-start":t.displayAlign==s.displayAlign.CENTER?r.justifyContent="center":r.justifyContent="flex-end"),o||(r.margin="0"),r.fontFamily=t.fontFamily,r.fontWeight=t.fontWeight.toString(),r.fontStyle=t.fontStyle,r.letterSpacing=t.letterSpacing,r.fontSize=Ze.convertLengthValue_(t.fontSize,t,this.videoContainer_);let c=t.line;if(null!=c){let e=t.lineInterpretation;if(e==s.lineInterpretation.LINE_NUMBER){e=s.lineInterpretation.PERCENTAGE;let t=16;this.aspectRatio_&&this.aspectRatio_<1&&(t=32),c=c<0?100+c/t*100:c/t*100}e==s.lineInterpretation.PERCENTAGE&&(r.position="absolute",t.writingMode==s.writingMode.HORIZONTAL_TOP_TO_BOTTOM?(r.width="100%",t.lineAlign==s.lineAlign.START?r.top=c+"%":t.lineAlign==s.lineAlign.END&&(r.bottom=100-c+"%")):t.writingMode==s.writingMode.VERTICAL_LEFT_TO_RIGHT?(r.height="100%",t.lineAlign==s.lineAlign.START?r.left=c+"%":t.lineAlign==s.lineAlign.END&&(r.right=100-c+"%")):(r.height="100%",t.lineAlign==s.lineAlign.START?r.right=c+"%":t.lineAlign==s.lineAlign.END&&(r.left=100-c+"%")))}r.lineHeight=t.lineHeight,null!=t.position&&(t.writingMode==s.writingMode.HORIZONTAL_TOP_TO_BOTTOM?r.paddingLeft=t.position:r.paddingTop=t.position);const h=this.computeCuePositionAlignment_(t);h==s.positionAlign.LEFT?r.cssFloat="left":h==s.positionAlign.RIGHT&&(r.cssFloat="right"),r.textAlign=t.textAlign,r.textDecoration=t.textDecoration.join(" "),r.writingMode=t.writingMode,"writingMode"in document.documentElement.style&&r.writingMode==t.writingMode||(r.webkitWritingMode=t.writingMode),t.size&&(t.writingMode==s.writingMode.HORIZONTAL_TOP_TO_BOTTOM?r.width=t.size+"%":r.height=t.size+"%")}static getLengthValueInfo_(e){const t=new RegExp(/(\d*\.?\d+)([a-z]+|%+)/).exec(e);return t?{value:Number(t[1]),unit:t[2]}:null}static convertLengthValue_(e,t,i){const n=Ze.getLengthValueInfo_(e);if(!n)return e;const{unit:s,value:a}=n;switch(s){case"%":return Ze.getAbsoluteLengthInPixels_(a/100,t,i);case"c":return Ze.getAbsoluteLengthInPixels_(a,t,i);default:return e}}static getAbsoluteLengthInPixels_(e,t,i){return i.clientHeight*e/t.cellResolution.rows+"px"}static inheritProperty_(e,t){for(let i=e.length-1;i>=0;i--){const n=t(e[i]);if(n||0===n)return n}return null}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}class et{static convert(e,t){const i=e=>{let i=e;for(const n of t)n.end&&n.start<e&&(i+=n.end-n.start);const n=Math.floor(i/3600),s=Math.floor(i/60%60),a=Math.floor(i%60),r=Math.floor(1e3*i%1e3);return(n<10?"0":"")+n+":"+(s<10?"0":"")+s+":"+(a<10?"0":"")+a+"."+(r<100?r<10?"00":"0":"")+r},n=Qe.getCuesToFlatten(e);let s="WEBVTT\n\n";for(const e of n){const t=e=>{const t=[],i=i;switch(e.textAlign){case i.textAlign.LEFT:t.push("align:left");break;case i.textAlign.RIGHT:t.push("align:right");break;case i.textAlign.CENTER:t.push("align:middle");break;case i.textAlign.START:t.push("align:start");break;case i.textAlign.END:t.push("align:end")}switch(e.writingMode){case i.writingMode.VERTICAL_LEFT_TO_RIGHT:t.push("vertical:lr");break;case i.writingMode.VERTICAL_RIGHT_TO_LEFT:t.push("vertical:rl")}return t.length?" "+t.join(" "):""};s+=i(e.startTime)+" --\x3e "+i(e.endTime)+t(e)+"\n",s+=e.payload+"\n\n"}return s}}class tt{constructor(){this.acquiredIdentifier=null,this.unlockQueue=[]}async acquire(e){n.v2(e+" has requested mutex"),this.acquiredIdentifier&&await new Promise((e=>this.unlockQueue.push(e))),this.acquiredIdentifier=e,n.v2(e+" has acquired mutex")}release(){n.v2(this.acquiredIdentifier+" has released mutex"),this.unlockQueue.length>0?this.unlockQueue.shift()():this.acquiredIdentifier=null}releaseAll(){for(;this.acquiredIdentifier;)this.release()}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class it{static parseXml(e,t){const i=x.fromBytesAutoDetect(e);return it.parseXmlString(i,t)}static parseXmlString(e,t){const i=it.parse(e);if(!t&&i.length)return i[0];const s=i.find((e=>this.isNode(e)&&e.tagName===t));return s||(n.error("parseXml root element not found!"),null)}static getKnownNameSpace(e){var t;return it.knownNameSpaces_.has(e)&&null!==(t=it.knownNameSpaces_.get(e))&&void 0!==t?t:""}static setKnownNameSpace(e,t){it.knownNameSpaces_.set(e,t)}static parse(e){let t=0;const i="<".charCodeAt(0),n=">".charCodeAt(0),s="-".charCodeAt(0),a="/".charCodeAt(0),r="!".charCodeAt(0),o="'".charCodeAt(0),l='"'.charCodeAt(0),d="[".charCodeAt(0);function c(o,l=!1){const c=[];for(;e[t];)if(e.charCodeAt(t)==i){if(e.charCodeAt(t+1)===a){const i=t+2;t=e.indexOf(">",t);const n=e.substring(i,t);let s=n.indexOf(o);if(-1==s){const e=o.indexOf(".");if(e>0){const t=o.substring(0,e);s=n.indexOf(t)}}if(-1==s){const i=e.substring(0,t).split("\n");throw new Error("Unexpected close tag\nLine: "+(i.length-1)+"\nColumn: "+(i[i.length-1].length+1)+"\nChar: "+e[t])}return t+1&&(t+=1),c}if(e.charCodeAt(t+1)===r){if(e.charCodeAt(t+2)==s){for(;-1!==t&&(e.charCodeAt(t)!==n||e.charCodeAt(t-1)!=s||e.charCodeAt(t-2)!=s||-1==t);)t=e.indexOf(">",t+1);-1===t&&(t=e.length)}else if(e.charCodeAt(t+2)===d&&e.charCodeAt(t+8)===d&&"cdata"===e.substr(t+3,5).toLowerCase()){const i=e.indexOf("]]>",t);-1==i?(c.push(e.substr(t+9)),t=e.length):(c.push(e.substring(t+9,i)),t=i+3);continue}++t;continue}const i=_(l);if(c.push(i),"string"==typeof i)return c;"?"===i.tagName[0]&&i.children&&(c.push(...i.children),i.children=[])}else{const e=h();l?e.length>0&&c.push(e):(c.length&&1==e.length&&"\n"==e[0]||e.trim().length>0)&&c.push(e),++t}return c}function h(){const i=t;return t=e.indexOf("<",t)-1,-2===t&&(t=e.length),e.slice(i,t+1)}function u(){const i=t;for(;-1==="\r\n\t>/= ".indexOf(e[t])&&e[t];)++t;return e.slice(i,t)}function _(i){t++;const s=u(),r={};let d=[];for(;e.charCodeAt(t)!==n&&e[t];){const a=e.charCodeAt(t);if(a>64&&a<91||a>96&&a<123){const a=u();let c=e.charCodeAt(t);for(;c&&c!==o&&c!==l&&!(c>64&&c<91||c>96&&c<123)&&c!==n;)t++,c=e.charCodeAt(t);let h=m();if(c===o||c===l){if(-1===t){const e={tagName:s,attributes:r,children:d,parent:null};for(let t=0;t<d.length;++t){const i=d[t];"string"!=typeof i&&(i.parent=e)}return e}}else h=null,--t;if(a.startsWith("xmlns:")){const e=a.split(":");it.setKnownNameSpace(null!=h?h:"",e[1])}"tt"===s&&"xml:space"===a&&"preserve"===h&&(i=!0),r[a]=null!=h?h:""}++t}e.charCodeAt(t-1)!==a?(++t,d=c(s,i)):++t;const h={tagName:s,attributes:r,children:d,parent:null},_=d.length;for(let e=0;e<_;e++){const t=d[e];"string"!=typeof t?t.parent=h:e==_-1&&"\n"==t&&d.pop()}return h}function m(){const i=e[t],n=t+1;return t=e.indexOf(i,n),e.slice(n,t)}return c("")}static isNode(e){return Boolean(e&&e.tagName&&e.tagName)}static isText(e){return"string"==typeof e}static getChildNodes(e){const t=[];if(!e.children)return[];for(const i of e.children)"string"!=typeof i&&t.push(i);return t}static findChildren(e,t){const i=[];if(!e.children)return[];for(const n of e.children)this.isNode(n)&&n.tagName===t&&i.push(n);return i}static getTextContents(e){if("string"==typeof e)return x.htmlUnescape(e);const t=e.children.reduce(((e,t)=>"string"==typeof t?e+t:e),"");return""===t?null:x.htmlUnescape(t)}static getContents(e){if(!Array.from(e.children).every((e=>"string"==typeof e)))return null;let t=it.getTextContents(e);return t&&(t=t.trim()),t}static getElementsByTagName(e,t,i=[]){if(e.tagName===t&&i.push(e),e.children)for(const n of e.children)this.isNode(n)&&it.getElementsByTagName(n,t,i);return i}static findChild(e,t){const i=it.findChildren(e,t);return 1!=i.length?null:i[0]}static findChildNS(e,t,i){const n=it.findChildrenNS(e,t,i);return 1!=n.length?null:n[0]}static parseAttr(e,t,i,n=null){let s=null;const a=e.attributes[t];return null!=a&&(s=i(a)),null==s?n:s}static parseAttrWithDefaultValue(e,t,i,n){let s=this.parseAttr(e,t,i);return null!=s?s:n}static getAttributeNS(e,t,i){const n=it.getKnownNameSpace(t);return e.attributes[`${n}:${i}`]||null}static findChildrenNS(e,t,i){const n=it.getKnownNameSpace(t),s=[];if(e.children)for(const t of e.children)t&&this.isNode(t)&&t.tagName===`${n}:${i}`&&s.push(t);return s}static getAttributeNSList(e,t,i){for(const n of t){const t=it.getAttributeNS(e,n,i);if(t)return t}return null}static parseDate(e){if(!e)return null;/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(e)&&(e+="Z");const t=Date.parse(e);return isNaN(t)?null:t/1e3}static parseDuration(e){if(!e)return null;const t=new RegExp("^P(?:([0-9]*)Y)?(?:([0-9]*)M)?(?:([0-9]*)D)?(?:T(?:([0-9]*)H)?(?:([0-9]*)M)?(?:([0-9.]*)S)?)?$").exec(e);if(!t)return n.warning("Invalid duration string:",e),null;const i=31536e3*Number(t[1]||null)+2592e3*Number(t[2]||null)+86400*Number(t[3]||null)+3600*Number(t[4]||null)+60*Number(t[5]||null)+Number(t[6]||null);return isFinite(i)?i:null}static parseRange(e){const t=/([0-9]+)-([0-9]+)/.exec(e);if(!t)return null;const i=Number(t[1]);if(!isFinite(i))return null;const n=Number(t[2]);return isFinite(n)?{start:i,end:n}:null}static parseInt(e){const t=Number(e);return t%1==0?t:null}static parsePositiveInt(e){const t=Number(e);return t%1==0&&t>0?t:null}static parseNonNegativeInt(e){const t=Number(e);return t%1==0&&t>=0?t:null}static parseFloat(e){const t=Number(e);return isNaN(t)?null:t}static parseBoolean(e){return!!e&&"true"===e.toLowerCase()}static evalDivision(e){let t,i;return i=(t=e.match(/^(\d+)\/(\d+)$/))?Number(t[1])/Number(t[2]):Number(e),isNaN(i)?null:i}}it.knownNameSpaces_=new Map([]);class nt{static fillUriTemplate(e,t,i,s,a,r){const o={RepresentationID:t,Number:i,SubNumber:s,Bandwidth:a,Time:r};return e.replace(/\$(RepresentationID|Number|SubNumber|Bandwidth|Time)?(?:%0([0-9]+)([diouxX]))?\$/g,((t,i,s,a)=>{if("$$"==t)return"$";let r,l=o[i];if(console.assert(void 0!==l,"Unrecognized identifier"),null==l)return n.warning("URL template does not have an available substitution for ",'identifier "'+i+'":',e),t;switch("RepresentationID"==i&&s&&(n.warning("URL template should not contain a width specifier for identifier",'"RepresentationID":',e),s=void 0),"Time"==i&&"bigint"!=typeof l&&(console.assert("number"==typeof l,"Time value should be a number or bigint!"),"number"==typeof l&&(Math.abs(l-Math.round(l))>=.2&&n.alwaysWarn("Calculated $Time$ values must be close to integers"),l=Math.round(l))),a){case void 0:case"d":case"i":case"u":r=l.toString();break;case"o":r=l.toString(8);break;case"x":r=l.toString(16);break;case"X":r=l.toString(16).toUpperCase();break;default:console.assert(!1,"Unhandled format specifier"),r=l.toString()}const d=window.parseInt(s,10)||1,c=Math.max(0,d-r.length);return new Array(c+1).join("0")+r}))}static createTimeline(e,t,i,s,a){console.assert(t>0&&t<1/0,"timescale must be a positive, finite integer"),console.assert(s>0,"period duration must be a positive integer");const r=it.findChildren(e,"S"),o=[];let l=-i;for(let e=0;e<r.length;++e){const d=r[e],c=r[e+1];let h=it.parseAttr(d,"t",it.parseNonNegativeInt);const u=it.parseAttr(d,"d",it.parseNonNegativeInt),_=it.parseAttr(d,"r",it.parseInt),m=it.parseAttr(d,"k",it.parseInt)||0;if(null!=h&&(h-=i),!u)return n.warning('"S" element must have a duration:','ignoring the remaining "S" elements.',d),o;let g=null!=h?h:l,f=_||0;if(f<0)if(c){const e=it.parseAttr(c,"t",it.parseNonNegativeInt);if(null==e)return n.warning('An "S" element cannot have a negative repeat','if the next "S" element does not have a valid start time:','ignoring the remaining "S" elements.',d),o;if(g>=e)return n.warning('An "S" element cannot have a negative repeatif its start ','time exceeds the next "S" element\'s start time:','ignoring the remaining "S" elements.',d),o;f=Math.ceil((e-g)/u)-1}else{if(s==1/0)return n.warning('The last "S" element cannot have a negative repeat',"if the Period has an infinite duration:",'ignoring the last "S" element.',d),o;if(g/t>=s)return n.warning('The last "S" element cannot have a negative repeat',"if its start time exceeds the Period's duration:",'igoring the last "S" element.',d),o;f=Math.ceil((s*t-g)/u)-1}if(o.length>0&&g!=l){const e=g-l;Math.abs(e/t)>=U.GAP_OVERLAP_TOLERANCE_SECONDS&&n.warning("SegmentTimeline contains a large gap/overlap:","the content may have errors in it.",d),o[o.length-1].end=g/t}for(let e=0;e<=f;++e){const e=g+u,i={start:g/t,end:e/t,unscaledStart:g,partialSegments:m,segmentPosition:o.length+a};o.push(i),g=e,l=e}}return o}static parseSegmentInfo(e,t){console.assert(t(e.representation),"There must be at least one element of the given type.");const i=nt.inheritAttribute(e,t,"timescale");let n=1;i&&(n=it.parsePositiveInt(i)||1);const s=nt.inheritAttribute(e,t,"duration");let a=it.parsePositiveInt(s||"");const r=U.ContentType;e.representation.contentType==r.IMAGE&&(a=it.parseFloat(s||"")),a&&(a/=n);const o=nt.inheritAttribute(e,t,"startNumber"),l=Number(nt.inheritAttribute(e,t,"presentationTimeOffset"))||0;let d=it.parseNonNegativeInt(o||"");null!=o&&null!=d||(d=1);const c=nt.inheritChild(e,t,"SegmentTimeline");let h=[];return c&&(h=nt.createTimeline(c,n,l,e.periodInfo.duration||1/0,d)),{timescale:n,segmentDuration:a,startNumber:d,scaledPresentationTimeOffset:l/n||0,unscaledPresentationTimeOffset:l,timeline:h}}static getNodes(e,t){return console.assert(t(e.representation),"There must be at least one element of the given type"),[t(e.representation),t(e.adaptationSet),t(e.period)].filter(V.isNotNull)}static inheritAttribute(e,t,i){const n=nt.getNodes(e,t);let s=null;for(const e of n)if(s=e.attributes[i],s)break;return s}static inheritChild(e,t,i){const n=nt.getNodes(e,t);let s=null;for(const e of n)if(s=it.findChild(e,i),s)break;return s}static handleXlinkInElement_(e,t,i,n,s,a){const r=nt.XlinkNamespaceUri_,o=it.getAttributeNS(e,r,"href"),l=it.getAttributeNS(e,r,"actuate")||"onRequest";for(const t of Object.keys(e.attributes)){const i=t.split(":"),n=it.getKnownNameSpace(r);i[0]==n&&delete e.attributes[t]}if(a>=5)return M.failed(new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_XLINK_DEPTH_LIMIT));if("onLoad"!=l)return M.failed(new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_UNSUPPORTED_XLINK_ACTUATE));const d=U.resolveUris([n],[null!=o?o:""]),c=D.RequestType.MANIFEST,h=D.makeRequest(d,t),u=s.request(c,h);return console.assert(u instanceof M,"Unexpected implementation of IAbortableOperation!"),u.chain((n=>{const r=it.parseXml(n.data,e.tagName);if(!r||!it.isNode(r))return M.failed(new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_INVALID_XML,o));for(e.children=[];r.children.length;){const t=r.children.shift();t&&(it.isNode(t)&&(t.parent=e),e.children.push(t))}for(const t of Object.keys(r.attributes))e.attributes[t]=r.attributes[t];return nt.processXlinks(e,t,i,d[0],s,a+1)}))}static processXlinks(e,t,i,n,s,a=0){const r=nt.XlinkNamespaceUri_;if(it.getAttributeNS(e,r,"href")){let r=nt.handleXlinkInElement_(e,t,i,n,s,a);return i&&(r=r.chain(void 0,(r=>nt.processXlinks(e,t,i,n,s,a)))),r}const o=[];for(const l of it.getChildNodes(e)){const d="urn:mpeg:dash:resolve-to-zero:2013";it.getAttributeNS(l,r,"href")==d?e.children=e.children.filter((e=>e!==l)):"SegmentTimeline"!=l.tagName&&o.push(nt.processXlinks(l,t,i,n,s,a))}return M.all(o).chain((()=>e))}}nt.XlinkNamespaceUri_="http://www.w3.org/1999/xlink";let st=class e{static parse(t,i,s,a,r,o,l){let d;const c=(new le).fullBox("sidx",(t=>{d=e.parseSIDX_(i,a,r,o,l,s,t)}));if(t&&c.parse(t),d)return d;throw n.error('Invalid box type, expected "sidx".'),new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.MP4_SIDX_WRONG_BOX_TYPE)}static parseSIDX_(e,t,i,s,a,r,o){console.assert(null!=o.version,"SIDX is a full box and should have a valid version.");const l=[];o.reader.skip(4);const d=o.reader.readUint32();if(0==d)throw n.error("Invalid timescale."),new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.MP4_SIDX_INVALID_TIMESCALE);let c,h;0==o.version?(c=o.reader.readUint32(),h=o.reader.readUint32()):(c=o.reader.readUint64(),h=o.reader.readUint64()),o.reader.skip(2);const u=o.reader.readUint16();let _=c,m=e+o.size+h;for(let e=0;e<u;e++){const e=o.reader.readUint32(),c=(2147483648&e)>>>31,h=2147483647&e,u=o.reader.readUint32();if(o.reader.skip(4),1==c)throw n.error("Heirarchical SIDXs are not supported."),new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.MP4_SIDX_TYPE_NOT_SUPPORTED);const g=_/d,f=(_+u)/d;l.push(new Ee(g+i,f+i,(()=>r),m,m+h-1,t,i,s,a)),_+=u,m+=h}return o.parser.stop(),l}};class at{constructor(e){this.dataView_=d.toDataView(e),this.reader_=new oe(this.dataView_,oe.Endianness.BIG_ENDIAN)}hasMoreData(){return this.reader_.hasMoreData()}parseElement(){const e=this.parseId_(),t=this.parseVint_();let i;i=at.isDynamicSizeValue_(t)?this.dataView_.byteLength-this.reader_.getPosition():at.getVintValue_(t);const n=this.reader_.getPosition()+i<=this.dataView_.byteLength?i:this.dataView_.byteLength-this.reader_.getPosition(),s=d.toDataView(this.dataView_,this.reader_.getPosition(),n);return this.reader_.skip(n),new rt(e,s)}parseId_(){const e=this.parseVint_();if(e.length>7)throw new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.EBML_OVERFLOW);let t=0;for(const i of e)t=256*t+i;return t}parseVint_(){const e=this.reader_.getPosition(),t=this.reader_.readUint8();if(0==t)throw new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.EBML_OVERFLOW);const i=8-Math.floor(Math.log2(t));return console.assert(i<=8&&i>=1,"Incorrect log2 value"),this.reader_.skip(i-1),d.toUint8(this.dataView_,e,i)}static getVintValue_(e){if(8==e.length&&224&e[1])throw new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.JS_INTEGER_OVERFLOW);let t=0;for(let i=0;i<e.length;i++){const n=e[i];t=0==i?n&(1<<8-e.length)-1:256*t+n}return t}static isDynamicSizeValue_(e){for(const t of at.DYNAMIC_SIZES)if(d.equal(e,new Uint8Array(t)))return!0;return!1}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}at.DYNAMIC_SIZES=[[255],[127,255],[63,255,255],[31,255,255,255],[15,255,255,255,255],[7,255,255,255,255,255],[3,255,255,255,255,255,255],[1,255,255,255,255,255,255,255]];class rt{constructor(e,t){this.id=e,this.dataView_=t}getOffset(){return this.dataView_.byteOffset}createParser(){return new at(this.dataView_)}getUint(){if(this.dataView_.byteLength>8)throw new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.EBML_OVERFLOW);if(8==this.dataView_.byteLength&&224&this.dataView_.getUint8(0))throw new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.JS_INTEGER_OVERFLOW);let e=0;for(let t=0;t<this.dataView_.byteLength;t++)e=256*e+this.dataView_.getUint8(t);return e}getFloat(){if(4==this.dataView_.byteLength)return this.dataView_.getFloat32(0);if(8==this.dataView_.byteLength)return this.dataView_.getFloat64(0);throw new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.EBML_BAD_FLOATING_POINT_SIZE)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}let ot=class e{static parse(t,i,s,a,r,o,l){const d=e.parseWebmContainer_(i),c=new at(t).parseElement();if(c.id!=e.CUES_ID)throw n.error("Not a Cues element."),new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.WEBM_CUES_ELEMENT_MISSING);return e.parseCues_(c,d.segmentOffset,d.timecodeScale,d.duration,s,a,r,o,l)}static parseWebmContainer_(t){const i=new at(t);if(i.parseElement().id!=e.EBML_ID)throw n.error("Not an EBML element."),new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.WEBM_EBML_HEADER_ELEMENT_MISSING);const s=i.parseElement();if(s.id!=e.SEGMENT_ID)throw n.error("Not a Segment element."),new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.WEBM_SEGMENT_ELEMENT_MISSING);const a=s.getOffset(),r=e.parseSegment_(s);return{segmentOffset:a,timecodeScale:r.timecodeScale,duration:r.duration}}static parseSegment_(t){const i=t.createParser();let s=null;for(;i.hasMoreData();){const t=i.parseElement();if(t.id==e.INFO_ID){s=t;break}}if(!s)throw n.error("Not an Info element."),new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.WEBM_INFO_ELEMENT_MISSING);return e.parseInfo_(s)}static parseInfo_(t){const i=t.createParser();let n=1e6,s=null;for(;i.hasMoreData();){const t=i.parseElement();t.id==e.TIMECODE_SCALE_ID?n=t.getUint():t.id==e.DURATION_ID&&(s=t.getFloat())}if(null==s)throw new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.WEBM_DURATION_ELEMENT_MISSING);const a=n/1e9;return{timecodeScale:a,duration:s*a}}static parseCues_(t,i,n,s,a,r,o,l,d){const c=[],h=()=>a,u=t.createParser();let _=null,m=null;for(;u.hasMoreData();){const t=u.parseElement();if(t.id!=e.CUE_POINT_ID)continue;const s=e.parseCuePoint_(t);if(!s)continue;const a=n*s.unscaledTime,g=i+s.relativeOffset;null!=_&&(console.assert(null!=m,"last offset cannot be null"),c.push(new Ee(_+o,a+o,h,m,g-1,r,o,l,d))),_=a,m=g}return null!=_&&(console.assert(null!=m,"last offset cannot be null"),c.push(new Ee(_+o,s+o,h,m,null,r,o,l,d))),c}static parseCuePoint_(t){const i=t.createParser(),s=i.parseElement();if(s.id!=e.CUE_TIME_ID)throw n.warning("Not a CueTime element."),new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.WEBM_CUE_TIME_ELEMENT_MISSING);const a=s.getUint(),r=i.parseElement();if(r.id!=e.CUE_TRACK_POSITIONS_ID)throw n.warning("Not a CueTrackPositions element."),new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING);const o=r.createParser();let l=0;for(;o.hasMoreData();){const t=o.parseElement();if(t.id==e.CUE_CLUSTER_POSITION){l=t.getUint();break}}return{unscaledTime:a,relativeOffset:l}}};ot.EBML_ID=440786851,ot.SEGMENT_ID=408125543,ot.INFO_ID=357149030,ot.TIMECODE_SCALE_ID=2807729,ot.DURATION_ID=17545,ot.CUES_ID=475249515,ot.CUE_POINT_ID=187,ot.CUE_TIME_ID=179,ot.CUE_TRACK_POSITIONS_ID=183,ot.CUE_CLUSTER_POSITION=241;class lt{static createInitSegment(e,t){if(null==e.representation)return null;const i=nt.inheritChild(e,t,"Initialization");if(!i)return null;let n=e.representation.getBaseUris();const s=i.attributes.sourceURL;s&&(n=U.resolveUris(n,[x.htmlUnescape(s)]));let a=0,r=null;const o=it.parseAttr(i,"range",it.parseRange);o&&(a=o.start,r=o.end);const l=lt.createQualityInfo(e);return new ye((()=>n),a,r,l,null,null)}static createStreamInfo(e,t){if(null==e.representation)return null;console.assert(e.representation.segmentBase,"Should only be called with SegmentBase");const i=Number(nt.inheritAttribute(e,lt.fromInheritance_,"presentationTimeOffset"))||0,n=nt.inheritAttribute(e,lt.fromInheritance_,"timescale");let s=1;n&&(s=it.parsePositiveInt(n)||1);const a=i/s||0,r=lt.createInitSegment(e,lt.fromInheritance_);lt.checkSegmentIndexRangeSupport_(e,r);const o=w.shallowCloneObject(e);return{generateSegmentIndex:()=>lt.generateSegmentIndex_(o,t,r,a)}}static async generateSegmentIndexFromUris(e,t,i,n,s,a,r){var o,l,d,c,h,u,_;const m=e.presentationTimeline,g=!e.dynamic||!(null===(o=e.periodInfo)||void 0===o?void 0:o.isLastPeriod),f=null!==(d=null===(l=e.periodInfo)||void 0===l?void 0:l.start)&&void 0!==d?d:0,p=null!==(h=null===(c=e.periodInfo)||void 0===c?void 0:c.duration)&&void 0!==h?h:0,T=null!==(_=null===(u=e.representation)||void 0===u?void 0:u.mimeType.split("/")[1])&&void 0!==_?_:"";let S=t,y=null;const E=[S(n,s,a,!1),"webm"==T&&i?S(i.getUris(),i.startByte,i.endByte,!0):null];S=null;const v=await Promise.all(E),b=v[0],I=v[1]||null;let A;const w=f-r,C=f,M=p?f+p:1/0;return"mp4"==T?A=st.parse(b,s,n,i,w,C,M):(console.assert(I,"WebM requires init data"),A=ot.parse(b,I,n,i,w,C,M)),m.notifySegments(A),console.assert(!y,"Should not call generateSegmentIndex twice"),y=new ve(A),g&&y.fit(C,M,!0),y}static fromInheritance_(e){var t;return null!==(t=null==e?void 0:e.segmentBase)&&void 0!==t?t:null}static computeIndexRange_(e){const t=nt.inheritChild(e,lt.fromInheritance_,"RepresentationIndex"),i=nt.inheritAttribute(e,lt.fromInheritance_,"indexRange");let n=it.parseRange(i||"");return t&&(n=it.parseAttr(t,"range",it.parseRange,n)),n}static computeIndexUris_(e){var t,i;const n=nt.inheritChild(e,lt.fromInheritance_,"RepresentationIndex");let s=null!==(i=null===(t=e.representation)||void 0===t?void 0:t.getBaseUris())&&void 0!==i?i:[];if(n){const e=x.htmlUnescape(n.attributes.sourceURL);e&&(s=U.resolveUris(s,[e]))}return s}static checkSegmentIndexRangeSupport_(e,t){if(lt.checkSegmentIndexSupport(e,t),!lt.computeIndexRange_(e))throw n.error("SegmentBase does not contain sufficient segment information:","the SegmentBase does not contain @indexRange","or a RepresentationIndex element.",e.representation),new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_NO_SEGMENT_INFO)}static checkSegmentIndexSupport(e,t){var i,s,a,r;const o=null!==(s=null===(i=e.representation)||void 0===i?void 0:i.contentType)&&void 0!==s?s:p.UNKNOWN,l=null!==(r=null===(a=e.representation)||void 0===a?void 0:a.mimeType.split("/")[1])&&void 0!==r?r:"";if(o!=U.ContentType.TEXT&&"mp4"!=l&&"webm"!=l)throw n.error("SegmentBase specifies an unsupported container type.",e.representation),new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_UNSUPPORTED_CONTAINER);if("webm"==l&&!t)throw n.error("SegmentBase does not contain sufficient segment information:","the SegmentBase uses a WebM container,","but does not contain an Initialization element.",e.representation),new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_WEBM_MISSING_INIT)}static generateSegmentIndex_(e,t,i,n){const s=lt.computeIndexUris_(e),a=lt.computeIndexRange_(e);if(console.assert(a,"Index range should not be null!"),null==a)throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_EMPTY_INDEX_RANGE);return lt.generateSegmentIndexFromUris(e,t,i,s,a.start,a.end,n)}static createQualityInfo(e){var t,i,n,s,a,r,o,l,d;const c=e.representation;return{bandwidth:e.bandwidth,audioSamplingRate:null!==(t=null==c?void 0:c.audioSamplingRate)&&void 0!==t?t:null,codecs:null!==(i=null==c?void 0:c.codecs)&&void 0!==i?i:"",contentType:null!==(n=null==c?void 0:c.contentType)&&void 0!==n?n:p.UNKNOWN,frameRate:null!==(s=null==c?void 0:c.frameRate)&&void 0!==s?s:null,height:null!==(a=null==c?void 0:c.height)&&void 0!==a?a:null,mimeType:null!==(r=null==c?void 0:c.mimeType)&&void 0!==r?r:null,channelsCount:null!==(o=null==c?void 0:c.numChannels)&&void 0!==o?o:null,pixelAspectRatio:null!==(l=null==c?void 0:c.pixelAspectRatio)&&void 0!==l?l:null,width:null!==(d=null==c?void 0:c.width)&&void 0!==d?d:null}}}class dt{static createStreamInfo(e,t){if(null==e.representation||null==e.periodInfo)return null;console.assert(e.representation.segmentList,"Should only be called with SegmentList");const i=lt.createInitSegment(e,dt.fromInheritance_),n=dt.parseSegmentListInfo_(e);dt.checkSegmentListInfo_(e,n);let s=null,a=null;e.period&&e.period.id&&e.representation.id&&(a=t[e.period.id+","+e.representation.id],a&&(s=a.segmentIndex));const r=dt.createSegmentReferences_(e.periodInfo.start,e.periodInfo.duration,n.startNumber,e.representation.getBaseUris,n,i),o=!s;if(s){const t=e.presentationTimeline.getSegmentAvailabilityStart();s.mergeAndEvict(r,t)}else s=new ve(r);if(e.presentationTimeline.notifySegments(r),!e.dynamic||!e.periodInfo.isLastPeriod){const t=e.periodInfo.start,i=e.periodInfo.duration?e.periodInfo.start+e.periodInfo.duration:1/0;s.fit(t,i,o)}return a&&(a.segmentIndex=s),{generateSegmentIndex:()=>(s&&!s.isEmpty()||s.merge(r),Promise.resolve(s))}}static fromInheritance_(e){var t;return null!==(t=null==e?void 0:e.segmentList)&&void 0!==t?t:null}static parseSegmentListInfo_(e){const t=dt.parseMediaSegments_(e),i=nt.parseSegmentInfo(e,dt.fromInheritance_);let s=i.startNumber;0==s&&(n.warning("SegmentList@startNumber must be > 0"),s=1);let a=0;return i.segmentDuration?a=i.segmentDuration*(s-1):i.timeline&&i.timeline.length>0&&(a=i.timeline[0].start),{segmentDuration:i.segmentDuration,startTime:a,startNumber:s,scaledPresentationTimeOffset:i.scaledPresentationTimeOffset,timeline:i.timeline,mediaSegments:t}}static checkSegmentListInfo_(e,t){if(!t.segmentDuration&&!t.timeline&&t.mediaSegments.length>1)throw n.warning("SegmentList does not contain sufficient segment information:","the SegmentList specifies multiple segments,","but does not specify a segment duration or timeline.",e.representation),new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_NO_SEGMENT_INFO);const i=e.periodInfo,s=null==i?void 0:i.duration;if(!t.segmentDuration&&!s&&!t.timeline&&1==t.mediaSegments.length)throw n.warning("SegmentList does not contain sufficient segment information:","the SegmentList specifies one segment,","but does not specify a segment duration, period duration,","or timeline.",e.representation),new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_NO_SEGMENT_INFO);if(t.timeline&&0==t.timeline.length)throw n.warning("SegmentList does not contain sufficient segment information:","the SegmentList has an empty timeline.",e.representation),new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_NO_SEGMENT_INFO)}static createSegmentReferences_(e,t,i,s,a,r){let o=a.mediaSegments.length;a.timeline&&a.timeline.length!=a.mediaSegments.length&&(o=Math.min(a.timeline.length,a.mediaSegments.length),n.warning("The number of items in the segment timeline and the number of ","segment URLs do not match, truncating",a.mediaSegments.length,"to",o));const l=e-a.scaledPresentationTimeOffset,d=e,c=t?e+t:1/0,h=[];let u=a.startTime;for(let i=0;i<o;i++){const n=a.mediaSegments[i],o=u;let _;null!=a.segmentDuration?_=o+a.segmentDuration:a.timeline?_=a.timeline[i].end:(console.assert(1==a.mediaSegments.length&&t,"There should be exactly one segment with a Period duration."),_=o+(null!=t?t:0));let m=null;const g=()=>(null==m&&(m=U.resolveUris(s(),[n.mediaUri])),m);h.push(new Ee(e+o,e+_,g,n.start,n.end,r,l,d,c,[],"",null,null,Ee.Status.AVAILABLE)),u=_}return h}static parseMediaSegments_(e){var t,i,s;return[null===(t=e.representation)||void 0===t?void 0:t.segmentList,null===(i=e.adaptationSet)||void 0===i?void 0:i.segmentList,null===(s=e.period)||void 0===s?void 0:s.segmentList].filter(V.isNotNull).map((e=>it.findChildren(e,"SegmentURL"))).reduce(((e,t)=>e.length>0?e:t)).map((t=>{t.attributes.indexRange&&!e.indexRangeWarningGiven&&(e.indexRangeWarningGiven=!0,n.warning("We do not support the SegmentURL@indexRange attribute on SegmentList. We only use the SegmentList@duration attribute or SegmentTimeline, which must be accurate."));const i=x.htmlUnescape(t.attributes.media),s=it.parseAttrWithDefaultValue(t,"mediaRange",it.parseRange,{start:0,end:null});return{mediaUri:i,start:s.start,end:s.end}}))}}class ct{static createStreamInfo(e,t,i,s,a,r){var o,l,d;if(!e.representation||!e.periodInfo)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.NOT_CONFIGURED);console.assert(e.representation.segmentTemplate,"Should only be called with SegmentTemplate");const c=ct.createInitSegment_(e),h=ct.parseSegmentTemplateInfo_(e);ct.checkSegmentTemplateInfo_(e,h);const u=w.shallowCloneObject(e);if(h.indexTemplate)return lt.checkSegmentIndexSupport(e,c),{generateSegmentIndex:()=>ct.generateSegmentIndexFromIndexTemplate_(u,t,c,h)};if(h.segmentDuration)return s||"image"===(null===(o=e.adaptationSet)||void 0===o?void 0:o.contentType)||(e.presentationTimeline.notifyMaxSegmentDuration(h.segmentDuration),e.presentationTimeline.notifyMinSegmentStartTime(e.periodInfo.start)),{generateSegmentIndex:()=>ct.generateSegmentIndexFromDuration_(u,h,a,c,r)};{let t=null,s=null,a=null;(null===(l=e.period)||void 0===l?void 0:l.id)&&e.representation.id&&(s=e.period.id+","+e.representation.id,a=i[s],a&&(t=a.segmentIndex));const r=e.periodInfo.start,o=e.periodInfo.duration?r+e.periodInfo.duration:1/0;n.debug(`New manifest ${r} - ${o}`);const u=!(e.dynamic&&e.periodInfo.isLastPeriod);if(t){const i=t;i.appendTemplateInfo(h,r,o,u,c);const n=e.presentationTimeline.getSegmentAvailabilityStart();i.evict(n)}else n.debug(`Creating TSI with end ${o}`),t=new ht(h,e.representation.id,e.bandwidth,e.representation.getBaseUris,r,o,c,u,e.representation.segmentSequenceCadence);if(h.timeline&&"image"!==(null===(d=e.adaptationSet)||void 0===d?void 0:d.contentType)){const t=h.timeline;e.presentationTimeline.notifyTimeRange(t,r)}return a&&e.dynamic&&(a.segmentIndex=t),{generateSegmentIndex:()=>(t instanceof ht&&t.isEmpty()&&t.appendTemplateInfo(h,r,o,u,c),Promise.resolve(t))}}}static fromInheritance_(e){var t;return null!==(t=null==e?void 0:e.segmentTemplate)&&void 0!==t?t:null}static parseSegmentTemplateInfo_(e){const t=nt.parseSegmentInfo(e,ct.fromInheritance_),i=nt.inheritAttribute(e,ct.fromInheritance_,"media"),n=nt.inheritAttribute(e,ct.fromInheritance_,"index");return{segmentDuration:t.segmentDuration,timescale:t.timescale,startNumber:t.startNumber,scaledPresentationTimeOffset:t.scaledPresentationTimeOffset,unscaledPresentationTimeOffset:t.unscaledPresentationTimeOffset,timeline:t.timeline,mediaTemplate:i&&x.htmlUnescape(i),indexTemplate:n}}static checkSegmentTemplateInfo_(e,t){let i=0;if(i+=t.indexTemplate?1:0,i+=t.timeline?1:0,i+=t.segmentDuration?1:0,0==i)throw n.error("SegmentTemplate does not contain any segment information:","the SegmentTemplate must contain either an index URL template","a SegmentTimeline, or a segment duration.",e.representation),new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_NO_SEGMENT_INFO);if(1!=i&&(n.warning("SegmentTemplate containes multiple segment information sources:","the SegmentTemplate should only contain an index URL template,","a SegmentTimeline or a segment duration.",e.representation),t.indexTemplate?(n.info("Using the index URL template by default."),t.timeline=null,t.segmentDuration=null):(console.assert(t.timeline,"There should be a timeline"),n.info("Using the SegmentTimeline by default."),t.segmentDuration=null)),!t.indexTemplate&&!t.mediaTemplate)throw n.error("SegmentTemplate does not contain sufficient segment information:","the SegmentTemplate's media URL template is missing.",e.representation),new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_NO_SEGMENT_INFO)}static generateSegmentIndexFromIndexTemplate_(e,t,i,n){var s;if(console.assert(n.indexTemplate,"must be using index template"),!e.representation)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.NOT_CONFIGURED);const a=nt.fillUriTemplate(null!==(s=n.indexTemplate)&&void 0!==s?s:"",e.representation.id,null,null,e.bandwidth||null,null),r=U.resolveUris(e.representation.getBaseUris(),[a]);return lt.generateSegmentIndexFromUris(e,t,i,r,0,null,n.scaledPresentationTimeOffset)}static generateSegmentIndexFromDuration_(e,t,i,n,s){var a,r;if(console.assert(t.mediaTemplate,"There should be a media template with duration"),!e.representation||!e.periodInfo)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.NOT_CONFIGURED);const o=e.presentationTimeline,l=e.periodInfo.start,d=null!==(r=null===(a=e.period)||void 0===a?void 0:a.id)&&void 0!==r?r:null,_=e.periodInfo.duration,m=()=>{const e=null!=d&&s[d]||_;return e?l+e:1/0},g=t.segmentDuration;if(console.assert(null!=g,"Segment duration must not be null!"),null==g)throw new b(c.CRITICAL,h.MANIFEST,u.SEGMENT_DURATION_IS_NULL);const f=t.startNumber,p=t.timescale,T=t.mediaTemplate,S=e.bandwidth||null,y=e.representation.id,E=e.representation.getBaseUris,v=l-t.scaledPresentationTimeOffset,I=()=>{const e=[Math.max(o.getSegmentAvailabilityStart(),l),Math.min(o.getSegmentAvailabilityEnd(),m())];console.assert(e.every(isFinite),"Available presentation times must be finite!"),console.assert(e.every((e=>e>=0)),"Available presentation times must be positive!"),console.assert(null!=g,"Segment duration must not be null!");const t=e.map((e=>e-l));return[Math.ceil(t[0]/g),Math.ceil(t[1]/g)-1].map((e=>e+f))},A=I(),w=e.dynamic?Math.max(A[0],A[1]-i+1):A[0],C=A[1],M=[],R=e=>{console.assert(null!=g,"Segment duration must not be null!");const i=(e-f)*g,s=i+t.scaledPresentationTimeOffset,a=i+l,r=a+g,o=Math.min(r,m());console.assert(a<o,"Generated a segment outside of the period!");const d=new Ee(a,o,(()=>{let t=s*p;"BigInt"in window&&t>Number.MAX_SAFE_INTEGER&&(t=BigInt(s)*BigInt(p));const i=nt.fillUriTemplate(null!=T?T:"",y,e,null,S,t);return U.resolveUris(E(),[i])}),0,null,n,v,l,m(),[],"",null,null,Ee.Status.AVAILABLE);return d.trueEndTime=r,d};for(let e=w;e<=C;++e){const t=R(e);M.push(t)}const O=new ve(M),D=o.getSegmentAvailabilityEnd()<m(),P=o.isLive();if(D||P){let e=Math.max(w,C+1);O.updateEvery(g,(()=>{const t=o.getSegmentAvailabilityStart();O.evict(t);const[i,n]=I(),s=[];for(;e<=n;){const t=R(e);s.push(t),++e}return t>m()&&!s.length?null:s}))}return Promise.resolve(O)}static createInitSegment_(e){let t=nt.inheritAttribute(e,ct.fromInheritance_,"initialization");if(!t)return null;if(t=x.htmlUnescape(t),!e.representation)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.NOT_CONFIGURED);const i=e.representation.id,n=e.bandwidth||null,s=e.representation.getBaseUris,a=lt.createQualityInfo(e);return new ye((()=>{console.assert(t,"Should have returned earler");const e=nt.fillUriTemplate(null!=t?t:"",i,null,null,n,null);return U.resolveUris(s(),[e])}),0,null,a,null,null)}}class ht extends ve{constructor(e,t,i,n,s,a,r,o,l){super([]),this.templateInfo_=e,this.representationId_=t,this.bandwidth_=i,this.getBaseUris_=n,this.periodStart_=s,this.periodEnd_=a,this.initSegmentReference_=r,this.segmentSequenceCadence_=l,o&&this.fitTimeline()}getNumReferences(){var e,t;return this.templateInfo_&&null!==(t=null===(e=this.templateInfo_.timeline)||void 0===e?void 0:e.length)&&void 0!==t?t:0}release(){super.release(),this.templateInfo_=null}evict(e){var t;if(!this.templateInfo_)return;n.debug(`${this.representationId_} Evicting at ${e}`);let i=0;const s=null!==(t=this.templateInfo_.timeline)&&void 0!==t?t:[];for(let t=0;t<s.length;t+=1){const a=s[t],r=a.end+this.periodStart_,o=a.start+this.periodStart_;if(!(r<=e))break;n.debug(`Evicting ${o} - ${r}`),i+=1}i>0&&(this.templateInfo_.timeline=s.slice(i),this.references.length>=i&&(this.references=this.references.slice(i)),this.numEvicted_+=i,0===this.getNumReferences()&&this.release())}appendTemplateInfo(e,t,i,s,a){var r,o;if(this.initSegmentReference_=a,this.templateInfo_){const t=null!==(r=this.templateInfo_.timeline)&&void 0!==r?r:[];this.templateInfo_.mediaTemplate=e.mediaTemplate;const s=t[t.length-1];let a=[];null!=s&&(a=(null!==(o=e.timeline)&&void 0!==o?o:[]).filter((e=>e.start>=s.end))),a.length>0&&(n.debug(`Appending ${a.length} entries`),null==this.templateInfo_.timeline?this.templateInfo_.timeline=a:this.templateInfo_.timeline.push(...a)),this.periodEnd_!==i&&(this.periodEnd_=i)}else this.templateInfo_=e,this.periodStart_=t,this.periodEnd_=i;s&&this.fitTimeline()}isBeforeFirstEntry(e){var t;const i=null===(t=this.templateInfo_)||void 0===t?void 0:t.timeline;return!(!i||!i.length)&&e<i[0].start+this.periodStart_}fitTimeline(){var e,t;if(this.getIsImmutable())return;const i=null!==(t=null===(e=this.templateInfo_)||void 0===e?void 0:e.timeline)&&void 0!==t?t:[];for(;i.length&&i[i.length-1].start>=this.periodEnd_;)i.pop();this.evict(this.periodStart_)}find(e){var t;if(n.debug(`Find ${e}`),this.isBeforeFirstEntry(e))return this.numEvicted_;if(!this.templateInfo_)return null;const i=null!==(t=this.templateInfo_.timeline)&&void 0!==t?t:[];if(e<this.periodStart_||e>=this.periodEnd_)return null;if(i.length>0){const t=i.length-1;for(let n=0;n<i.length;++n){const s=i[n],a=s.start+this.periodStart_;let r;if(r=n<t?i[n+1].start+this.periodStart_:this.periodEnd_===1/0?s.end+this.periodStart_:this.periodEnd_,e>=a&&e<r)return n+this.numEvicted_}}return null}get(e){var t,i;const n=e-this.numEvicted_;if(n<0||n>=this.getNumReferences()||!this.templateInfo_)return null;let s=this.references[n];if(!s){const e=null!==(t=this.templateInfo_.mediaTemplate)&&void 0!==t?t:"",a=(null!==(i=this.templateInfo_.timeline)&&void 0!==i?i:[])[n];if(a){const t=a.segmentPosition,i=this.templateInfo_.unscaledPresentationTimeOffset+a.unscaledStart,r=this.periodStart_-this.templateInfo_.scaledPresentationTimeOffset,o=this.periodStart_+a.end;let l=o;n===this.getNumReferences()-1&&this.periodEnd_!==1/0&&(l=this.periodEnd_);const d=[],c=(a.end-a.start)/a.partialSegments;for(let e=0;e<a.partialSegments;e++){const n=a.start+c*e,s=n+c,o=e+1;let l=null;const h=()=>{var e;return this.templateInfo_?(null==l&&(l=ht.createUris_(null!==(e=this.templateInfo_.mediaTemplate)&&void 0!==e?e:"",this.representationId_,t,this.bandwidth_,i,o,this.getBaseUris_)),l):[]},u=new Ee(this.periodStart_+n,this.periodStart_+s,h,0,null,this.initSegmentReference_,r,this.periodStart_,this.periodEnd_,[],"",null,null,Ee.Status.AVAILABLE);0==this.segmentSequenceCadence_?e>0&&u.markAsNonIndependent():e%this.segmentSequenceCadence_!=0&&u.markAsNonIndependent(),d.push(u)}const h=()=>a.partialSegments>0?[]:ht.createUris_(e,this.representationId_,t,this.bandwidth_,i,null,this.getBaseUris_);s=new Ee(this.periodStart_+a.start,l,h,0,null,this.initSegmentReference_,r,this.periodStart_,this.periodEnd_,d,"",null,null,Ee.Status.AVAILABLE,a.partialSegments>0),s.trueEndTime=o,this.references[n]=s}}return s}static createUris_(e,t,i,n,s,a,r){const o=nt.fillUriTemplate(e,t,i,a,n||null,s);return U.resolveUris(r(),[o]).map((e=>e.toString()))}static get[Symbol.for("___CTOR_ARGS___")](){return["SegmentTemplateInfo | null","string | null","number","() => Array<string>","number","number","InitSegmentReference | null","boolean","number"]}}class ut{constructor(e,t,i=!0){this.presentationStartTime_=e,this.presentationDelay_=t,this.duration_=1/0,this.segmentAvailabilityDuration_=1/0,this.maxSegmentDuration_=1,this.minSegmentStartTime_=null,this.maxSegmentEndTime_=null,this.clockOffset_=0,this.static_=!0,this.userSeekStart_=0,this.autoCorrectDrift_=i,this.availabilityTimeOffset_=0,this.startTimeLocked_=!1,this.initialProgramDateTime_=null}getDuration(){return this.duration_}getMaxSegmentDuration(){return this.maxSegmentDuration_}setPresentationStartTime(e){console.assert(e>=0,"presentationStartTime must be >= 0"),this.presentationStartTime_=e}setDuration(e){console.assert(e>0,"duration must be > 0"),this.duration_=e}getPresentationStartTime(){return this.presentationStartTime_}setClockOffset(e){this.clockOffset_=e}setStatic(e){this.static_=e}setSegmentAvailabilityDuration(e){console.assert(e>=0,"segmentAvailabilityDuration must be >= 0"),this.segmentAvailabilityDuration_=e}getSegmentAvailabilityDuration(){return this.segmentAvailabilityDuration_}setDelay(e){console.assert(e>=0,"delay must be >= 0"),this.presentationDelay_=e}getDelay(){return this.presentationDelay_}notifyTimeRange(e,t){if(0==e.length)return;const i=e[0].start+t,s=e[e.length-1].end+t;if(this.notifyMinSegmentStartTime(i),this.maxSegmentDuration_=e.reduce(((e,t)=>Math.max(e,t.end-t.start)),this.maxSegmentDuration_),this.maxSegmentEndTime_=Math.max(this.maxSegmentEndTime_,s),null!=this.presentationStartTime_&&this.autoCorrectDrift_&&!this.startTimeLocked_){const e=(Date.now()+this.clockOffset_)/1e3;this.presentationStartTime_=e-this.maxSegmentEndTime_-this.maxSegmentDuration_}n.v1("notifySegments:","maxSegmentDuration="+this.maxSegmentDuration_)}notifySegments(e){if(0==e.length)return;let t=e[0].startTime,i=e[0].endTime;const s=(Date.now()+this.clockOffset_)/1e3;for(const n of e)s<n.startTime||(t=Math.min(t,n.startTime),i=Math.max(i,n.endTime),this.maxSegmentDuration_=Math.max(this.maxSegmentDuration_,n.endTime-n.startTime));this.notifyMinSegmentStartTime(t),this.maxSegmentEndTime_=Math.max(this.maxSegmentEndTime_,i),null!=this.presentationStartTime_&&this.autoCorrectDrift_&&!this.startTimeLocked_&&(this.presentationStartTime_=s-this.maxSegmentEndTime_-this.maxSegmentDuration_),n.v1("notifySegments:","maxSegmentDuration="+this.maxSegmentDuration_)}lockStartTime(){this.startTimeLocked_=!0}isStartTimeLocked(){return this.startTimeLocked_}setInitialProgramDateTime(e){this.initialProgramDateTime_=e}getInitialProgramDateTime(){return this.initialProgramDateTime_}notifyMinSegmentStartTime(e){null==this.minSegmentStartTime_?this.minSegmentStartTime_=e:this.minSegmentStartTime_=Math.min(this.minSegmentStartTime_,e)}notifyMaxSegmentDuration(e){this.maxSegmentDuration_=Math.max(this.maxSegmentDuration_,e),n.v1("notifyNewSegmentDuration:","maxSegmentDuration="+this.maxSegmentDuration_)}offset(e){null!=this.minSegmentStartTime_&&(this.minSegmentStartTime_+=e),null!=this.maxSegmentEndTime_&&(this.maxSegmentEndTime_+=e)}isLive(){return this.duration_==1/0&&!this.static_}isInProgress(){return this.duration_!=1/0&&!this.static_}getSegmentAvailabilityStart(){console.assert(this.segmentAvailabilityDuration_>=0,"The availability duration should be positive");const e=this.getSegmentAvailabilityEnd()-this.segmentAvailabilityDuration_;return Math.max(this.userSeekStart_,e)}setUserSeekStart(e){this.userSeekStart_=e}getSegmentAvailabilityEnd(){return this.isLive()||this.isInProgress()?Math.min(this.getLiveEdge_()+this.availabilityTimeOffset_,this.duration_):this.maxSegmentEndTime_?Math.min(this.maxSegmentEndTime_,this.duration_):this.duration_}getSafeSeekRangeStart(e){const t=Math.max(this.minSegmentStartTime_,this.userSeekStart_);if(this.segmentAvailabilityDuration_==1/0)return Math.ceil(1e3*t)/1e3;const i=this.getSegmentAvailabilityEnd()-this.segmentAvailabilityDuration_,n=Math.min(i+e,this.getSeekRangeEnd());return Math.max(t,n)}getSeekRangeStart(){return this.getSafeSeekRangeStart(0)}getSeekRangeEnd(){const e=this.isLive()||this.isInProgress()?this.presentationDelay_:0;return Math.max(0,this.getSegmentAvailabilityEnd()-e)}usingPresentationStartTime(){return null!=this.presentationStartTime_&&(null==this.maxSegmentEndTime_||!this.autoCorrectDrift_)}getLiveEdge_(){console.assert(null!=this.presentationStartTime_,"Cannot compute timeline live edge without start time");const e=(Date.now()+this.clockOffset_)/1e3;return Math.max(0,e-this.maxSegmentDuration_-this.presentationStartTime_)}setAvailabilityTimeOffset(e){this.availabilityTimeOffset_=e}assertIsValid(){this.isLive()?console.assert(null!=this.presentationStartTime_,"Detected as live stream, but does not match our model of live!"):this.isInProgress()?console.assert(null!=this.presentationStartTime_&&this.segmentAvailabilityDuration_==1/0,"Detected as IPR stream, but does not match our model of IPR!"):console.assert(this.segmentAvailabilityDuration_==1/0&&this.duration_!=1/0&&this.static_,"Detected as VOD stream, but does not match our model of VOD!")}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0]}}class _t{constructor(){this.variants_=[],this.audioStreams_=[],this.videoStreams_=[],this.textStreams_=[],this.imageStreams_=[],this.multiTypeVariantsAllowed_=!1,this.useStreamOnce_=!1,this.usedPeriodIds_=new Set}release(){const e=this.audioStreams_.concat(this.videoStreams_,this.textStreams_,this.imageStreams_);for(const t of e)t.segmentIndex&&t.segmentIndex.release();this.audioStreams_=[],this.videoStreams_=[],this.textStreams_=[],this.imageStreams_=[],this.variants_=[]}getVariants(){return this.variants_}getTextStreams(){return this.textStreams_.slice()}getImageStreams(){return this.imageStreams_}getStreamsPerPeriod_(e,t){const i=U.ContentType,n=[],s=[],a=[],r=[];for(const o of e){const e=new Map(o.audioStreams.map((e=>[_t.generateAudioKey_(e),e]))),l=new Map(o.videoStreams.map((e=>[_t.generateVideoKey_(e),e]))),d=new Map(o.textStreams.map((e=>[_t.generateTextKey_(e),e]))),c=new Map(o.imageStreams.map((e=>[_t.generateImageKey_(e),e])));if(t){const e=_t.dummyStream_(i.TEXT);d.set(_t.generateTextKey_(e),e);const t=_t.dummyStream_(i.IMAGE);c.set(_t.generateImageKey_(t),t)}n.push(e),s.push(l),a.push(d),r.push(c)}return{audioStreamsPerPeriod:n,videoStreamsPerPeriod:s,textStreamsPerPeriod:a,imageStreamsPerPeriod:r}}async combinePeriods(e,t){const i=U.ContentType;if(t||1!=e.length){let t=-1;for(let i=0;i<e.length;i++){const n=e[i];this.usedPeriodIds_.has(n.id)||(this.usedPeriodIds_.add(n.id),-1==t&&(t=i))}if(-1==t)return;const{audioStreamsPerPeriod:i,videoStreamsPerPeriod:n,textStreamsPerPeriod:s,imageStreamsPerPeriod:a}=this.getStreamsPerPeriod_(e,!0);await Promise.all([this.combine_(this.audioStreams_,i,t,_t.cloneStream_,_t.concatenateStreams_),this.combine_(this.videoStreams_,n,t,_t.cloneStream_,_t.concatenateStreams_),this.combine_(this.textStreams_,s,t,_t.cloneStream_,_t.concatenateStreams_),this.combine_(this.imageStreams_,a,t,_t.cloneStream_,_t.concatenateStreams_)])}else{const{audioStreamsPerPeriod:t,videoStreamsPerPeriod:i,textStreamsPerPeriod:n,imageStreamsPerPeriod:s}=this.getStreamsPerPeriod_(e,!1);this.audioStreams_=Array.from(t[0].values()),this.videoStreams_=Array.from(i[0].values()),this.textStreams_=Array.from(n[0].values()),this.imageStreams_=Array.from(s[0].values())}let n=0;const s=[];if(this.videoStreams_.length&&this.audioStreams_.length)for(const e of this.audioStreams_)for(const t of this.videoStreams_){const i=n++;s.push({id:i,language:e.language,disabledUntilTime:0,primary:e.primary,audio:e,video:t,bandwidth:(e.bandwidth||0)+(t.bandwidth||0),allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]})}else{const e=this.videoStreams_.length?this.videoStreams_:this.audioStreams_;for(const t of e){const e=n++;s.push({id:e,language:t.language,disabledUntilTime:0,primary:t.primary,audio:t.type==i.AUDIO?t:null,video:t.type==i.VIDEO?t:null,bandwidth:t.bandwidth||0,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]})}}this.variants_=s}async combine_(e,t,i,s,a){const r=[];for(let e=0;e<i;e++)r.push(new Set);for(let e=i;e<t.length;e++)r.push(new Set(t[e].values()));for(const n of e)if(!await this.extendExistingOutputStream_(n,t,i,a,r))throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.PERIOD_FLATTENING_FAILED);for(const i of r)for(const n of i){const i=this.createNewOutputStream_(n,t,s,a,r);i&&e.push(i)}for(const t of r)for(const i of t)if(!_t.isDummy_(i)&&e.some((e=>this.areAVStreamsCompatible_(i,e))))throw n.error("Unused stream in period-flattening!",i,e),new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.PERIOD_FLATTENING_FAILED);return e}async extendExistingOutputStream_(e,t,i,s,a){return this.findMatchesInAllPeriods_(t,e),console.assert(e.createSegmentIndex,"outputStream should be a Stream type!"),e.matchedStreams?(e.segmentIndex&&await _t.extendOutputSegmentIndex_(e,i),_t.extendOutputStream_(e,i,s,a),!0):(n.error("No matches extending output stream!",e,t),!1)}static async extendOutputSegmentIndex_(e,t){var i;const n=[],s=null!==(i=e.matchedStreams)&&void 0!==i?i:[];console.assert(s,"matched streams should be valid");for(const e of s)n.push(e.createSegmentIndex()),e.trickModeVideo&&!e.trickModeVideo.segmentIndex&&n.push(e.trickModeVideo.createSegmentIndex());if(await Promise.all(n),e.segmentIndex instanceof Ie)for(let i=t;i<s.length;++i){const t=s[i];console.assert(t.segmentIndex,"stream should have a segmentIndex."),t.segmentIndex&&(t.segmentIndex.forEachTopLevelReference((e=>{e.codecs=t.codecs,e.mimeType=t.mimeType,e.initSegmentReference&&(e.initSegmentReference.codecs=t.codecs,e.initSegmentReference.mimeType=t.mimeType)})),e.segmentIndex.appendSegmentIndex(t.segmentIndex))}}createNewOutputStream_(e,t,i,n,s){if(_t.isDummy_(e))return null;const a=i(e);return this.findMatchesInAllPeriods_(t,a),a.createSegmentIndex&&(a.createSegmentIndex=async()=>{a.segmentIndex||(a.segmentIndex=new Ie,await _t.extendOutputSegmentIndex_(a,0))}),a.matchedStreams&&a.matchedStreams.length?(_t.extendOutputStream_(a,0,n,s),a):null}static extendOutputStream_(e,t,i,n){const s=e.matchedStreams;if(console.assert(e.matchedStreams,"matchedStreams should be non-null"),null!=s)for(let a=t;a<s.length;a++){const t=s[a];i(e,t);let r=!0;if(e.type==p.AUDIO&&0==H.relatedness(e.language,t.language)&&(r=!1),r){n[a].delete(t);const i=new Set(e.codecs.split(","));for(const e of t.codecs.split(","))e&&i.add(e);e.codecs=_t.filterDuplicateCodecs_(Array.from(i)).join(",")}}}static filterDuplicateCodecs_(e){const t=new Set,i=[];for(const s of e){const e=F.getCodecBase(s);t.has(e)?n.debug("Ignoring duplicate codec"):(i.push(s),t.add(e))}return i}static cloneStream_(e){const t=Object.assign({},e);return t.originalId=null,t.createSegmentIndex=()=>Promise.resolve(),t.closeSegmentIndex=()=>{if(t.segmentIndex&&(t.segmentIndex.release(),t.segmentIndex=null),t.matchedStreams)for(const e of t.matchedStreams)e.segmentIndex&&(e.segmentIndex.release(),e.segmentIndex=null)},t.roles=t.roles.slice(),t.segmentIndex=null,t.emsgSchemeIdUris=[],t.closedCaptions=null,t.trickModeVideo=null,t}static concatenateStreams_(e,t){var i;const n=(e,t)=>{e||(e=[]);for(const i of t)e.includes(i)||e.push(i);return e};if(e.roles=n(e.roles,t.roles),t.emsgSchemeIdUris&&(e.emsgSchemeIdUris=n(null!==(i=e.emsgSchemeIdUris)&&void 0!==i?i:[],t.emsgSchemeIdUris)),null==e.originalId?e.originalId=t.originalId:e.originalId+=","+(t.originalId||""),t.closedCaptions){e.closedCaptions||(e.closedCaptions=new Map);for(const[i,n]of t.closedCaptions)e.closedCaptions.set(i,n)}t.trickModeVideo?(e.trickModeVideo||(e.trickModeVideo=_t.cloneStream_(t.trickModeVideo),e.trickModeVideo.createSegmentIndex=()=>(console.assert(e.segmentIndex instanceof Ie,"The stream should have a MetaSegmentIndex."),e.trickModeVideo&&e.segmentIndex instanceof Ie&&(e.trickModeVideo.segmentIndex=e.segmentIndex.clone()),Promise.resolve())),_t.concatenateStreams_(e.trickModeVideo,t.trickModeVideo)):e.trickModeVideo&&_t.concatenateStreams_(e.trickModeVideo,t)}findMatchesInAllPeriods_(e,t){const i=[];for(const n of e){const e=this.findBestMatchInPeriod_(n,t);if(!e)return;i.push(e)}t.matchedStreams=i}findBestMatchInPeriod_(e,t){if(t.type===p.UNKNOWN||t.type===p.APPLICATION)return null;const i={audio:_t.generateAudioKey_,video:_t.generateVideoKey_,text:_t.generateTextKey_,image:_t.generateImageKey_}[t.type];let n=null;const s=i(t);if(e.has(s))n=e.get(s);else{const i={audio:(e,t)=>this.areAVStreamsCompatible_(e,t),video:(e,t)=>this.areAVStreamsCompatible_(e,t),text:_t.areTextStreamsCompatible_,image:_t.areImageStreamsCompatible_}[t.type],s={audio:_t.isAudioStreamBetterMatch_,video:_t.isVideoStreamBetterMatch_,text:_t.isTextStreamBetterMatch_,image:_t.isImageStreamBetterMatch_}[t.type];for(const a of e.values())i(t,a)&&t.fastSwitching==a.fastSwitching&&(n&&!s(t,n,a)||(n=a))}return n&&this.useStreamOnce_&&!_t.isDummy_(n)&&e.delete(i(n)),null!=n?n:null}static areAVStreamsExactMatch_(e,t){if(e.mimeType!=t.mimeType)return!1;const i=e=>{if(!_t.memoizedCodecs.has(e)){const t=F.getNormalizedCodec(e);_t.memoizedCodecs.set(e,t)}return _t.memoizedCodecs.get(e)};return i(e.codecs)==i(t.codecs)}setAllowMultiTypeVariants(e){this.multiTypeVariantsAllowed_=e}setUseStreamOnce(e){this.useStreamOnce_=e}areAVStreamsCompatible_(e,t){return!(!_t.areAVStreamsExactMatch_(e,t)&&!this.multiTypeVariantsAllowed_)}static areTextStreamsCompatible_(e,t){return!t.language||e.forced===t.forced&&(0!=H.relatedness(e.language,t.language)&&t.kind==e.kind)}static areImageStreamsCompatible_(e,t){return!0}static isAudioStreamBetterMatch_(e,t,i){var n,s,a,r,o,l,d,c;const h=_t.areAVStreamsExactMatch_(e,t),u=_t.areAVStreamsExactMatch_(e,i);if(h&&!u)return!1;if(!h&&u)return!0;const _=H.relatedness(e.language,t.language),m=H.relatedness(e.language,i.language);if(m>_)return!0;if(m<_)return!1;if(t.label!==i.label){if(e.label===t.label)return!1;if(e.label===i.label)return!0}if(e.roles.length){const n=t.roles.filter((t=>e.roles.includes(t))),s=i.roles.filter((t=>e.roles.includes(t)));return s.length>n.length||!(s.length<n.length)&&i.roles.length<t.roles.length}if(!i.roles.length&&t.roles.length)return!0;if(i.roles.length&&!t.roles.length)return!1;if(!t.primary&&i.primary)return!0;if(t.primary&&!i.primary)return!1;const g=_t.compareClosestPreferLower(null!==(n=e.channelsCount)&&void 0!==n?n:0,null!==(s=t.channelsCount)&&void 0!==s?s:0,null!==(a=i.channelsCount)&&void 0!==a?a:0);if(1==g)return!0;if(-1==g)return!1;const f=_t.compareClosestPreferLower(null!==(r=e.audioSamplingRate)&&void 0!==r?r:0,null!==(o=t.audioSamplingRate)&&void 0!==o?o:0,null!==(l=i.audioSamplingRate)&&void 0!==l?l:0);if(1==f)return!0;if(-1==f)return!1;if(e.bandwidth){const n=_t.compareClosestPreferMinimalAbsDiff_(e.bandwidth,null!==(d=t.bandwidth)&&void 0!==d?d:0,null!==(c=i.bandwidth)&&void 0!==c?c:0);if(1==n)return!0;if(-1==n)return!1}return!1}static isVideoStreamBetterMatch_(e,t,i){var n,s,a,r,o,l,d,c,h,u;const _=_t.areAVStreamsExactMatch_(e,t),m=_t.areAVStreamsExactMatch_(e,i);if(_&&!m)return!1;if(!_&&m)return!0;const g=_t.compareClosestPreferLower((null!==(n=e.width)&&void 0!==n?n:0)*(null!==(s=e.height)&&void 0!==s?s:0),(null!==(a=t.width)&&void 0!==a?a:0)*(null!==(r=t.height)&&void 0!==r?r:0),(null!==(o=i.width)&&void 0!==o?o:0)*(null!==(l=i.height)&&void 0!==l?l:0));if(1==g)return!0;if(-1==g)return!1;if(e.frameRate){const n=_t.compareClosestPreferLower(e.frameRate,null!==(d=t.frameRate)&&void 0!==d?d:0,null!==(c=i.frameRate)&&void 0!==c?c:0);if(1==n)return!0;if(-1==n)return!1}if(e.bandwidth){const n=_t.compareClosestPreferMinimalAbsDiff_(e.bandwidth,null!==(h=t.bandwidth)&&void 0!==h?h:0,null!==(u=i.bandwidth)&&void 0!==u?u:0);if(1==n)return!0;if(-1==n)return!1}return!1}static isTextStreamBetterMatch_(e,t,i){const n=H.relatedness(e.language,t.language),s=H.relatedness(e.language,i.language);if(s>n)return!0;if(s<n)return!1;if(!t.primary&&i.primary)return!0;if(t.primary&&!i.primary)return!1;if(t.label!==i.label){if(e.label===t.label)return!1;if(e.label===i.label)return!0}if(e.roles.length){const n=t.roles.filter((t=>e.roles.includes(t))),s=i.roles.filter((t=>e.roles.includes(t)));if(s.length>n.length)return!0;if(s.length<n.length)return!1}else{if(!i.roles.length&&t.roles.length)return!0;if(i.roles.length&&!t.roles.length)return!1}return i.mimeType==e.mimeType&&i.codecs==e.codecs&&(t.mimeType!=e.mimeType||t.codecs!=e.codecs)}static isImageStreamBetterMatch_(e,t,i){if(null==e.width||null==e.height||null==t.width||null==t.height||null==i.width||null==i.height)return!1;return 1==_t.compareClosestPreferLower(e.width*e.height,t.width*t.height,i.width*i.height)}static dummyStream_(e){return{bandwidth:null,closeSegmentIndex:null,frameRate:null,hdr:null,height:null,kind:null,matchedStreams:null,mssPrivateData:null,pixelAspectRatio:null,tilesLayout:null,videoLayout:null,width:null,id:0,originalId:"",groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:new ve([]),mimeType:"",codecs:"",language:"",originalLanguage:null,label:null,type:e,primary:!1,trickModeVideo:null,emsgSchemeIdUris:[],roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,accessibilityPurpose:null,external:!1,fastSwitching:!1}}static compareClosestPreferLower(e,t,i){if(t==e&&e!=i)return-1;if(i==e&&e!=t)return 1;if(t>e){if(i<=e)return 1;if(i-e<t-e)return 1;if(i-e>t-e)return-1}else{if(i>e)return-1;if(e-i<e-t)return 1;if(e-i>e-t)return-1}return 0}static compareClosestPreferMinimalAbsDiff_(e,t,i){const n=Math.abs(e-t),s=Math.abs(e-i);return s<n?1:n<s?-1:0}static isDummy_(e){const t=U.ContentType;switch(e.type){case t.TEXT:return!e.language;case t.IMAGE:return!e.tilesLayout;default:return!1}}static generateVideoKey_(e){return _t.generateKey_([e.fastSwitching,e.width,e.frameRate,e.codecs,e.mimeType,e.label,e.roles,e.closedCaptions?Array.from(e.closedCaptions.entries()):null,e.bandwidth])}static generateAudioKey_(e){return _t.generateKey_([e.fastSwitching,e.channelsCount,e.language,e.bandwidth,e.label,e.codecs,e.mimeType,e.roles,e.audioSamplingRate,e.primary])}static generateTextKey_(e){return _t.generateKey_([e.language,e.label,e.codecs,e.mimeType,e.bandwidth,e.roles])}static generateImageKey_(e){return _t.generateKey_([e.width,e.codecs,e.mimeType])}static generateKey_(e){return JSON.stringify(e)}}_t.memoizedCodecs=new Map;class mt{constructor(e){this.playerInterface_=e,this.config_=null,this.operationManager_=new A,this.baseUris_=[],this.defaultPathwayId_=null,this.pathwayPriority_=[],this.lastPathwayUsed_=null,this.pathwayClones_=[],this.lastTTL_=300,this.locations_=new Map,this.bannedLocations_=new Map,this.updateTimer_=null,this.manifestType_=f.UNKNOWN}configure(e){this.config_=e}destroy(){return this.config_=null,this.playerInterface_=null,this.baseUris_=[],this.defaultPathwayId_=null,this.pathwayPriority_=[],this.pathwayClones_=[],this.locations_.clear(),null!=this.updateTimer_&&(this.updateTimer_.stop(),this.updateTimer_=null),this.operationManager_.destroy()}setManifestType(e){this.manifestType_=e}setBaseUris(e){this.baseUris_=e}setDefaultPathwayId(e){this.defaultPathwayId_=e}async requestInfo(e){if(null==this.config_||null==this.playerInterface_)throw new b(c.CRITICAL,h.MANIFEST,b.Code.OPERATION_ABORTED);const t=U.resolveUris(this.baseUris_,[this.addQueryParams_(e)]),i=D.RequestType.CONTENT_STEERING,n=D.makeRequest(t,this.config_.retryParameters),s=this.playerInterface_.networkingEngine.request(i,n);this.operationManager_.manage(s);try{const e=await s.promise,t=x.fromUTF8(e.data),i=JSON.parse(t);1==i.VERSION&&this.processManifest_(i,e.uri)}catch(t){if(t&&t.code==b.Code.OPERATION_ABORTED)return;null!=this.updateTimer_&&(this.updateTimer_.stop(),this.updateTimer_=null),this.updateTimer_=new l((()=>{this.requestInfo(e)})),this.updateTimer_.tickAfter(this.lastTTL_)}}addQueryParams_(e){if(!this.pathwayPriority_.length)return e;if(!this.playerInterface_)return e;const t=new URL(e),i=this.lastPathwayUsed_||this.pathwayPriority_[0],n=Math.round(this.playerInterface_.getBandwidthEstimate()),s=t.searchParams;return this.manifestType_==_e.DASH?(s.set("_DASH_pathway",i),s.set("_DASH_throughput",String(n))):this.manifestType_==_e.HLS&&(s.set("_HLS_pathway",i),s.set("_HLS_throughput",String(n))),t.toString()}processManifest_(e,t){null!=this.updateTimer_&&(this.updateTimer_.stop(),this.updateTimer_=null);const i=e["RELOAD-URI"]||t;this.updateTimer_=new l((()=>{this.requestInfo(i)}));const n=e.TTL;n&&(this.lastTTL_=n),this.updateTimer_.tickAfter(this.lastTTL_),this.pathwayPriority_=e["PATHWAY-PRIORITY"]||[],this.pathwayClones_=e["PATHWAY-CLONES"]||[]}clearPreviousLocations(){this.locations_.clear()}addLocation(e,t,i){let n=this.locations_.get(e);n||(n=new Map),n.set(t,i),this.locations_.set(e,n)}banLocation(e){const t=Date.now()+6e4;this.bannedLocations_.set(e,t)}getLocations(e,t=!1){const i=this.locations_.get(e)||new Map;let n=[];for(const e of this.pathwayPriority_){const t=i.get(e);if(t)n.push({pathwayId:e,location:t});else{const t=this.pathwayClones_.find((t=>t.ID==e));if(t){const s=i.get(t["BASE-ID"]);if(s)if(t["URI-REPLACEMENT"].HOST){const i=new URL(s);i.host=t["URI-REPLACEMENT"].HOST,n.push({pathwayId:e,location:i.toString()})}else n.push({pathwayId:e,location:s})}}}const s=Date.now();for(const e of this.bannedLocations_.keys()){const t=this.bannedLocations_.get(e);null!=t&&s>t&&this.bannedLocations_.delete(e)}n=n.filter((e=>{for(const t of this.bannedLocations_.keys())if(t.includes(new URL(e.location).host))return!1;return!0})),n.length&&(this.lastPathwayUsed_=n[0].pathwayId);const a=n.map((e=>e.location));if(!a.length&&this.defaultPathwayId_)for(const e of this.defaultPathwayId_.split(",")){const t=i.get(e);t&&(this.lastPathwayUsed_=this.defaultPathwayId_,a.push(t))}if(!a.length)for(const e of i.values())a.push(e);return t?a:U.resolveUris(this.baseUris_,a)}static get[Symbol.for("___CTOR_ARGS___")](){return["ManifestParserPlayerInterface | null"]}}class gt{constructor(){this.config_=null,this.playerInterface_=null,this.manifestUris_=[],this.manifest_=null,this.globalId_=1,this.streamMap_={},this.periodDurations_={},this.periodCombiner_=new _t,this.updatePeriod_=0,this.averageUpdateDuration_=new Q(5),this.updateTimer_=new l((()=>{this.onUpdate_()})),this.operationManager_=new A,this.largestPeriodStartTime_=null,this.lastManifestUpdatePeriodIds_=[],this.minTotalAvailabilityTimeOffset_=1/0,this.lowLatencyMode_=!1,this.contentSteeringManager_=null}configure(e){console.assert(null!=e.dash,"DashManifestConfiguration should not be null!"),this.config_=e,this.contentSteeringManager_&&this.contentSteeringManager_.configure(this.config_),this.periodCombiner_&&(this.periodCombiner_.setAllowMultiTypeVariants(this.config_.dash.multiTypeVariantsAllowed&&G.isChangeTypeSupported()),this.periodCombiner_.setUseStreamOnce(this.config_.dash.useStreamOnceInPeriodFlattening))}async start(e,t){console.assert(this.config_,"Must call configure() before start()!"),this.lowLatencyMode_=t.isLowLatencyMode(),this.manifestUris_=[e],this.playerInterface_=t;const i=await this.requestManifest_();if(this.playerInterface_&&this.setUpdateTimer_(i),!this.playerInterface_)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.OPERATION_ABORTED);if(console.assert(this.manifest_,"Manifest should be non-null!"),!this.manifest_)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.OPERATION_ABORTED);return this.manifest_}stop(){for(const e of Object.values(this.streamMap_))e.segmentIndex&&e.segmentIndex.release();return this.periodCombiner_&&this.periodCombiner_.release(),this.playerInterface_=null,this.config_=null,this.manifestUris_=[],this.manifest_=null,this.streamMap_={},this.periodCombiner_=null,null!=this.updateTimer_&&(this.updateTimer_.stop(),this.updateTimer_=null),this.contentSteeringManager_&&this.contentSteeringManager_.destroy(),this.operationManager_.destroy()}async update(){try{await this.requestManifest_()}catch(e){if(!this.playerInterface_||!e)return;console.assert(e instanceof b,"Bad error type"),this.playerInterface_.onError(e)}}onExpirationUpdated(e,t){}onInitialVariantChosen(e){if(this.manifest_&&this.manifest_.presentationTimeline.isLive()){const t=e.video||e.audio;if(t&&t.segmentIndex){const e=this.manifest_.presentationTimeline.getSegmentAvailabilityEnd(),i=t.segmentIndex.find(e);if(null==i)return;const n=t.segmentIndex.get(i);if(!n)return;this.updatePeriod_=n.endTime-e,this.setUpdateTimer_(0)}}}banLocation(e){this.contentSteeringManager_&&this.contentSteeringManager_.banLocation(e)}async requestManifest_(){const e=D.RequestType.MANIFEST,t=D.AdvancedRequestType.MPD;let i=this.manifestUris_;if(this.manifestUris_.length>1&&this.contentSteeringManager_){const e=this.contentSteeringManager_.getLocations("Location",!0);e.length&&(i=e)}ft(this.config_);const n=D.makeRequest(i,this.config_.retryParameters),s=Date.now(),a=await this.makeNetworkRequest_(n,e,{type:t,stream:void 0,segment:void 0});if(!this.playerInterface_)return 0;a.uri&&a.uri!=a.originalUri&&!this.manifestUris_.includes(a.uri)&&this.manifestUris_.unshift(a.uri),await this.parseManifest_(a.data,a.uri);const r=(Date.now()-s)/1e3;return this.averageUpdateDuration_.sample(1,r),r}async parseManifest_(e,t){const i=it.parseXml(e,"MPD");if(!i||!it.isNode(i))throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_INVALID_XML,t);if(ft(this.config_),pt(this.playerInterface_),this.config_.dash.disableXlinkProcessing)return this.processManifest_(i,t);const n=this.config_.dash.xlinkFailGracefully,s=nt.processXlinks(i,this.config_.retryParameters,n,t,this.playerInterface_.networkingEngine);this.operationManager_.manage(s);const a=await s.promise;return this.processManifest_(a,t)}async processManifest_(e,t){var i,s,a,r,o,l,d,c,h,u,_,m,g;ft(this.config_),pt(this.playerInterface_);const f=this.config_.dash.manifestPreprocessor;f&&f(e),this.contentSteeringManager_&&this.contentSteeringManager_.clearPreviousLocations();let p=[t];const T=[],S=new Map,y=it.findChildren(e,"Location");for(const e of y){const t=e.attributes.serviceLocation,i=it.getContents(e);if(!i)continue;const n=U.resolveUris(p,[i])[0];t&&(this.contentSteeringManager_?this.contentSteeringManager_.addLocation("Location",t,n):S.set(t,n)),T.push(n)}if(this.contentSteeringManager_){const e=this.contentSteeringManager_.getLocations("Location",!0);e.length>0&&(this.manifestUris_=e,p=e)}else T.length&&(this.manifestUris_=T,p=T);let E=Promise.resolve();const v=it.findChild(e,"ContentSteering");if(v&&this.playerInterface_){const e=v.attributes.defaultServiceLocation;if(this.contentSteeringManager_)this.contentSteeringManager_.setBaseUris(p),this.contentSteeringManager_.setDefaultPathwayId(e);else{this.contentSteeringManager_=new mt(this.playerInterface_),this.contentSteeringManager_.configure(this.config_),this.contentSteeringManager_.setManifestType(_e.DASH),this.contentSteeringManager_.setBaseUris(p),this.contentSteeringManager_.setDefaultPathwayId(e);const t=it.getContents(v);t&&(it.parseAttr(v,"queryBeforeStart",it.parseBoolean,!1)?E=this.contentSteeringManager_.requestInfo(t):this.contentSteeringManager_.requestInfo(t))}for(const e of S.keys()){const t=S.get(e);this.contentSteeringManager_.addLocation("Location",e,null!=t?t:"")}}const b=it.findChildren(e,"BaseURL");let I,A=!1;if(this.contentSteeringManager_)for(const e of b){const t=e.attributes.serviceLocation,i=it.getContents(e);t&&i&&(this.contentSteeringManager_.addLocation("BaseURL",t,i),A=!0)}if(!A||!this.contentSteeringManager_){const e=b.map((e=>{var t;return null!==(t=it.getContents(e))&&void 0!==t?t:""})).filter(Boolean);I=U.resolveUris(p,e)}const w=()=>this.contentSteeringManager_&&A?this.contentSteeringManager_.getLocations("BaseURL"):I||[];let C=0;b&&b.length&&(C=it.parseAttr(b[0],"availabilityTimeOffset",it.parseFloat)||0);let M=0;this.config_.dash.ignoreMinBufferTime||(M=it.parseAttr(e,"minBufferTime",it.parseDuration)||0),this.updatePeriod_=it.parseAttrWithDefaultValue(e,"minimumUpdatePeriod",it.parseDuration,-1);const R=it.parseAttr(e,"availabilityStartTime",it.parseDate);let O=it.parseAttr(e,"timeShiftBufferDepth",it.parseDuration),D=null;this.config_.dash.ignoreSuggestedPresentationDelay||(D=it.parseAttr(e,"suggestedPresentationDelay",it.parseDuration));let P=null;this.config_.dash.ignoreMaxSegmentDuration||(P=it.parseAttr(e,"maxSegmentDuration",it.parseDuration));const N=e.attributes.type||"static";let L;if(this.manifest_){L=this.manifest_.presentationTimeline;for(const e of Object.values(this.streamMap_))e.segmentIndex&&e.segmentIndex.evict(L.getSegmentAvailabilityStart())}else{const e=this.config_.defaultPresentationDelay||1.5*M;L=new ut(R,null!=D?D:e,this.config_.dash.autoCorrectDrift)}L.setStatic("static"==N),L.isLive()&&!isNaN(this.config_.availabilityWindowOverride)&&(O=this.config_.availabilityWindowOverride),null==O&&(O=1/0),L.setSegmentAvailabilityDuration(O);const x={dynamic:"static"!=N,presentationTimeline:L,period:null,periodInfo:null,adaptationSet:null,representation:null,bandwidth:0,indexRangeWarningGiven:!1,availabilityTimeOffset:C,profiles:(e.attributes.profiles||"").split(",")},k=this.parsePeriods_(x,w,e),B=k.duration,F=k.periods;if("static"!=N&&k.durationDerivedFromPeriods||L.setDuration(B||1/0),this.minTotalAvailabilityTimeOffset_&&!this.lowLatencyMode_&&this.playerInterface_.isAutoLowLatencyMode()&&(this.playerInterface_.enableLowLatencyMode(),this.lowLatencyMode_=this.playerInterface_.isLowLatencyMode()),this.lowLatencyMode_?L.setAvailabilityTimeOffset(this.minTotalAvailabilityTimeOffset_):this.minTotalAvailabilityTimeOffset_&&n.alwaysWarn("Low-latency DASH live stream detected, but low-latency streaming mode is not enabled in Shaka Player. Set streaming.lowLatencyMode configuration to true, and see https://bit.ly/3clctcj for details."),L.notifyMaxSegmentDuration(P||1),L.assertIsValid(),await(null===(i=this.periodCombiner_)||void 0===i?void 0:i.combinePeriods(F,x.dynamic)),await E,this.lowLatencyMode_&&(M=0),this.manifest_){this.manifest_.variants=null!==(h=null===(c=this.periodCombiner_)||void 0===c?void 0:c.getVariants())&&void 0!==h?h:[];const e=null!==(_=null===(u=this.periodCombiner_)||void 0===u?void 0:u.getTextStreams())&&void 0!==_?_:[];e.length>0&&(this.manifest_.textStreams=e),this.manifest_.imageStreams=null!==(g=null===(m=this.periodCombiner_)||void 0===m?void 0:m.getImageStreams())&&void 0!==g?g:[],this.playerInterface_.filter(this.manifest_)}else{if(this.manifest_={presentationTimeline:L,variants:null!==(a=null===(s=this.periodCombiner_)||void 0===s?void 0:s.getVariants())&&void 0!==a?a:[],textStreams:null!==(o=null===(r=this.periodCombiner_)||void 0===r?void 0:r.getTextStreams())&&void 0!==o?o:[],imageStreams:null!==(d=null===(l=this.periodCombiner_)||void 0===l?void 0:l.getImageStreams())&&void 0!==d?d:[],offlineSessionIds:[],minBufferTime:M||0,sequenceMode:this.config_.dash.sequenceMode,ignoreManifestTimestampsInSegmentsMode:!1,type:_e.DASH,serviceDescription:this.parseServiceDescription_(e)},L.usingPresentationStartTime()){const t=it.findChildren(e,"UTCTiming"),i=await this.parseUtcTiming_(w,t);if(!this.playerInterface_)return;L.setClockOffset(i)}L.lockStartTime()}this.playerInterface_.makeTextStreamsForClosedCaptions(this.manifest_)}parseServiceDescription_(e){const t=it.findChild(e,"ServiceDescription");if(!t)return null;const i=it.findChild(t,"Latency"),n=it.findChild(t,"PlaybackRate");return i&&i.attributes.max||n?{maxLatency:i&&i.attributes.max?parseInt(i.attributes.max,10)/1e3:null,maxPlaybackRate:n?parseFloat(n.attributes.max):null,minLatency:i&&i.attributes.min?parseInt(i.attributes.min,10)/1e3:null,minPlaybackRate:n?parseFloat(n.attributes.min):null}:null}parsePeriods_(e,t,i){const s=it.parseAttr(i,"mediaPresentationDuration",it.parseDuration),a=[];let r=0;const o=it.findChildren(i,"Period");for(let i=0;i<o.length;++i){const l=o[i],d=o[i+1],c=it.parseAttrWithDefaultValue(l,"start",it.parseDuration,null!=r?r:0),h=l.attributes.id,u=it.parseAttr(l,"duration",it.parseDuration);let _=null;if(d){const e=it.parseAttr(d,"start",it.parseDuration);null!=e&&(_=e-c)}else null!=s&&(_=s-c);const m=U.GAP_OVERLAP_TOLERANCE_SECONDS;if(_&&u&&Math.abs(_-u)>m&&n.warning("There is a gap/overlap between Periods",l),null==_&&(_=u),null!==this.largestPeriodStartTime_&&null!==h&&null!==c&&c<this.largestPeriodStartTime_&&!this.lastManifestUpdatePeriodIds_.includes(h)&&i+1!=o.length){n.debug(`Skipping Period with ID ${h} as its start time is smaller than the largest period start time that has been seen, and ID is unseen before`);continue}null!==c&&(null===this.largestPeriodStartTime_||c>this.largestPeriodStartTime_)&&(this.largestPeriodStartTime_=c);const g={start:c,duration:_,node:l,isLastPeriod:null==_||!d},f=this.parsePeriod_(e,t,g);if(a.push(f),e.period&&e.period.id&&_&&(this.periodDurations_[e.period.id]=_),null==_){d&&n.warning("Skipping Period",i+1,"and any subsequent Periods:","Period",i+1,"does not have a valid start time.",d),r=null;break}r=c+_}return this.lastManifestUpdatePeriodIds_=a.map((e=>e.id)),null!=s?(r!=s&&n.warning("@mediaPresentationDuration does not match the total duration of ","all Periods."),{periods:a,duration:s,durationDerivedFromPeriods:!1}):{periods:a,duration:r,durationDerivedFromPeriods:!0}}parsePeriod_(e,t,i){var s,a,r;ft(this.config_),pt(this.playerInterface_),e.period=this.createFrame_(i.node,null,t),e.periodInfo=i,e.period.availabilityTimeOffset=e.availabilityTimeOffset,e.period.id||(n.info("No Period ID given for Period with start time "+i.start+", Assigning a default"),e.period.id="__shaka_period_"+i.start);const o=it.findChildren(i.node,"EventStream"),l=e.presentationTimeline.getSegmentAvailabilityStart();for(const e of o)this.parseEventStream_(i.start,i.duration,e,l);const d=it.findChildren(i.node,"AdaptationSet").map((t=>this.parseAdaptationSet_(e,t))).filter(V.isNotNull);if(e.dynamic){const e=[];for(const t of d)for(const i of t.representationIds)e.push(i);const t=new Set(e);if(e.length!=t.size)throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_DUPLICATE_REPRESENTATION_ID)}const c=d.filter((e=>!e.trickModeFor)),h=d.filter((e=>e.trickModeFor));for(const e of h){const t=null!==(a=null===(s=e.trickModeFor)||void 0===s?void 0:s.split(" "))&&void 0!==a?a:[];for(const i of c)if(t.includes(i.id))for(const t of i.streams)t.trickModeVideo=null!==(r=e.streams.find((e=>F.getNormalizedCodec(t.codecs)==F.getNormalizedCodec(e.codecs))))&&void 0!==r?r:null}const u=this.getStreamsFromSets_(this.config_.disableAudio,c,p.AUDIO),_=this.getStreamsFromSets_(this.config_.disableVideo,c,p.VIDEO),m=this.getStreamsFromSets_(this.config_.disableText,c,p.TEXT),g=this.getStreamsFromSets_(this.config_.disableThumbnails,c,p.IMAGE);if(0===_.length&&0===u.length)throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_EMPTY_PERIOD);return{id:e.period.id,audioStreams:u,videoStreams:_,textStreams:m,imageStreams:g}}getStreamsFromSets_(e,t,i){return e||!t.length?[]:t.reduce(((e,t)=>(t.contentType!=i||e.push(...t.streams),e)),[])}parseAdaptationSet_(e,t){ft(this.config_),pt(this.playerInterface_),e.adaptationSet=this.createFrame_(t,e.period,null);let i=!1;const n=it.findChildren(t,"Role"),s=n.map((e=>e.attributes.value)).filter(V.isNotNull);let a=null;const r=e.adaptationSet.contentType==p.TEXT;r&&(a=U.TextStreamKind.SUBTITLE);for(const e of n){const t=e.attributes.schemeIdUri;if(null==t||"urn:mpeg:dash:role:2011"==t)switch(e.attributes.value){case"main":i=!0;break;case"caption":case"subtitle":a=U.TextStreamKind.SUBTITLE}}let o;const l="urn:mpeg:mpegB:cicp",d=`${l}:TransferCharacteristics`,c=`${l}:ColourPrimaries`,h=`${l}:MatrixCoefficients`,u=e=>{switch(e){case 1:case 6:case 13:case 14:case 15:return y.SDR;case 16:return y.PQ;case 18:return y.HLG}return null},_=it.findChildren(t,"EssentialProperty");let m=null,g=!1,f=!1;for(const e of _){const t=e.attributes.schemeIdUri;if("http://dashif.org/guidelines/trickmode"==t)m=e.attributes.value;else if(t==d)o=u(parseInt(e.attributes.value,10));else{if(t==c||t==h)continue;"urn:mpeg:dash:ssr:2023"==t?g=!0:f=!0}}const T=it.findChildren(t,"SupplementalProperty");for(const e of T)e.attributes.schemeIdUri==d&&(o=u(parseInt(e.attributes.value,10)));const S=it.findChildren(t,"Accessibility"),E=new Map;let v;for(const e of S){const t=e.attributes.schemeIdUri,i=e.attributes.value;if("urn:scte:dash:cc:cea-608:2015"==t){let e=1;if(null!=i){const t=i.split(";");for(const i of t){let n,s;if(i.includes("=")){const e=i.split("=");n=e[0].startsWith("CC")?e[0]:`CC${e[0]}`,s=e[1]||"und"}else n=`CC${e}`,2==t.length?e+=2:e++,s=i;E.set(n,H.normalize(s))}}else E.set("CC1","und")}else if("urn:scte:dash:cc:cea-708:2015"==t){let e=1;if(null!=i)for(const t of i.split(";")){let i,n;if(t.includes("=")){const e=t.split("=");i=`svc${e[0]}`,n=e[1].split(",")[0].split(":").pop()}else i=`svc${e}`,e++,n=t;E.set(i,H.normalize(n))}else E.set("svc1","und")}else"urn:mpeg:dash:role:2011"==t?null!=i&&(s.push(i),"captions"==i&&(a=U.TextStreamKind.CLOSED_CAPTION)):"urn:tva:metadata:cs:AudioPurposeCS:2007"==t&&("1"==i?v=_e.AccessibilityPurpose.VISUALLY_IMPAIRED:"2"==i&&(v=_e.AccessibilityPurpose.HARD_OF_HEARING))}if(f)return null;const I=H.normalize(e.adaptationSet.language||"und");let A=t.attributes.label;const w=it.findChildren(t,"Label");if(w&&w.length){const e=w[0],t=it.getTextContents(e);t&&(A=t)}const C=it.findChildren(t,"Representation"),M=[];if(C.forEach((t=>{const n=this.parseRepresentation_(e,a,I,A,i,s,E,t,v);n&&(n.hdr=n.hdr||o,n.fastSwitching=g),null!=n&&M.push(n)})),0==M.length){const t=e.adaptationSet.contentType==p.IMAGE;if(this.config_.dash.ignoreEmptyAdaptationSet||r||t)return null;throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_EMPTY_ADAPTATION_SET)}if(!e.adaptationSet.contentType||e.adaptationSet.contentType==p.APPLICATION){const t=M[0];if(t){const i=t.mimeType,n=t.codecs;e.adaptationSet.contentType=gt.guessContentType_(i,n)}for(const t of M)t.type=e.adaptationSet.contentType}const R=e.adaptationSet.id||"__fake__"+this.globalId_++;for(const e of M)this.config_.dash.enableAudioGroups&&(e.groupId=R);const O=C.map((e=>e.attributes.id)).filter(V.isNotNull);return{id:R,contentType:e.adaptationSet.contentType,language:I,main:i,streams:M,trickModeFor:m,representationIds:O}}parseRepresentation_(e,t,i,s,a,r,o,l,d){var c,h,u,_,m,g;if(ft(this.config_),pt(this.playerInterface_),e.representation=this.createFrame_(l,e.adaptationSet,null),this.minTotalAvailabilityTimeOffset_=Math.min(this.minTotalAvailabilityTimeOffset_,e.representation.availabilityTimeOffset),!this.verifyRepresentation_(e.representation))return n.warning("Skipping Representation",e.representation),null;const f=null!==(h=null===(c=e.periodInfo)||void 0===c?void 0:c.start)&&void 0!==h?h:0;let T;e.bandwidth=it.parseAttr(l,"bandwidth",it.parsePositiveInt)||0;const S=e.representation.contentType,E=S==p.TEXT||S==p.APPLICATION,v=S==p.IMAGE;try{const t=this.requestSegment_.bind(this);if(e.representation.segmentBase)T=lt.createStreamInfo(e,t);else if(e.representation.segmentList)T=dt.createStreamInfo(e,this.streamMap_);else if(e.representation.segmentTemplate){const i=!!this.manifest_;T=ct.createStreamInfo(e,t,this.streamMap_,i,this.config_.dash.initialSegmentLimit,this.periodDurations_)}else{console.assert(E,"Must have Segment* with non-text streams.");const t=null!==(_=null===(u=e.periodInfo)||void 0===u?void 0:u.duration)&&void 0!==_?_:0,i=e.representation.getBaseUris;T={generateSegmentIndex:()=>Promise.resolve(ve.forSingleSegment(f,t,i()))}}}catch(e){if((E||v)&&e.code==b.Code.DASH_NO_SEGMENT_INFO)return null;throw e}if(null==T)return null;let I=!1;it.findChildren(l,"SupplementalProperty").some((e=>"tag:dolby.com,2018:dash:EC3_ExtensionType:2018"==e.attributes.schemeIdUri&&"JOC"==e.attributes.value))&&(I=!0);let A=!1;E&&(A=r.includes("forced_subtitle")||r.includes("forced-subtitle"));let w=null;if(v){const e=it.findChildren(l,"EssentialProperty").find((e=>["http://dashif.org/thumbnail_tile","http://dashif.org/guidelines/thumbnail_tile"].includes(e.attributes.schemeIdUri)));if(e&&(w=e.attributes.value),!w)return null}let C=null;const M=e.profiles,R=e.representation.codecs;M.includes("http://dashif.org/guidelines/dash-if-uhd#hevc-hdr-pq10")&&(R.includes("hvc1.2.4.L153.B0")||R.includes("hev1.2.4.L153.B0"))&&(C=y.PQ);const O=e.representation.id?(null!==(g=null===(m=e.period)||void 0===m?void 0:m.id)&&void 0!==g?g:"")+","+e.representation.id:"";let D;if(O&&this.streamMap_[O])D=this.streamMap_[O];else{if(!e.adaptationSet)return null;D={id:this.globalId_++,originalId:e.representation.id,groupId:null,createSegmentIndex:()=>Promise.resolve(),closeSegmentIndex:()=>{D.segmentIndex&&(D.segmentIndex.release(),D.segmentIndex=null)},segmentIndex:null,mimeType:e.representation.mimeType,codecs:e.representation.codecs,frameRate:e.representation.frameRate,pixelAspectRatio:e.representation.pixelAspectRatio,bandwidth:e.bandwidth,width:e.representation.width,height:e.representation.height,kind:t,language:i,originalLanguage:e.adaptationSet.language,label:s,type:e.adaptationSet.contentType,primary:a,trickModeVideo:null,emsgSchemeIdUris:e.representation.emsgSchemeIdUris,roles:r,forced:A,channelsCount:e.representation.numChannels,audioSamplingRate:e.representation.audioSamplingRate,spatialAudio:I,closedCaptions:o,hdr:C,videoLayout:null,tilesLayout:w,accessibilityPurpose:d,external:!1,fastSwitching:!1,matchedStreams:[],mssPrivateData:null}}return D.createSegmentIndex=async()=>{D.segmentIndex||(D.segmentIndex=await T.generateSegmentIndex())},O&&e.dynamic&&!this.streamMap_[O]&&(this.streamMap_[O]=D),D}async onUpdate_(){console.assert(this.updatePeriod_>=0,"There should be an update period"),n.info("Updating manifest...");let e=0;try{e=await this.requestManifest_()}catch(e){if(console.assert(e instanceof b,"Should only receive a Shaka error"),this.playerInterface_&&this.config_){if(this.config_.raiseFatalErrorOnManifestUpdateRequestFailure)return void this.playerInterface_.onError(e);e.severity=b.Severity.RECOVERABLE,this.playerInterface_.onError(e)}}this.playerInterface_&&(this.playerInterface_.onManifestUpdated(),this.setUpdateTimer_(e))}setUpdateTimer_(e){var t;if(this.updatePeriod_<0)return;const i=Math.max(this.updatePeriod_-e,this.averageUpdateDuration_.getEstimate());null===(t=this.updateTimer_)||void 0===t||t.tickAfter(i)}createFrame_(e,t,i){console.assert(t||i,"Must provide either parent or getBaseUris"),t=t||{contentType:p.UNKNOWN,mimeType:"",codecs:"",emsgSchemeIdUris:[],frameRate:null,pixelAspectRatio:null,numChannels:null,audioSamplingRate:null,availabilityTimeOffset:0,segmentSequenceCadence:0,segmentBase:null,segmentList:null,segmentTemplate:null,getBaseUris:null!=i?i:()=>[],width:null,height:null,id:null,language:null},i=i||t.getBaseUris;const n=it.parseNonNegativeInt,s=it.evalDivision,a=e.attributes.id,r=it.findChildren(e,"BaseURL");let o=null,l=!1;if(this.contentSteeringManager_)for(const e of r){const t=e.attributes.serviceLocation,i=it.getContents(e);t&&i&&(this.contentSteeringManager_.addLocation(a,t,i),l=!0)}l&&this.contentSteeringManager_||(o=r.map((e=>{var t;return null!==(t=it.getContents(e))&&void 0!==t?t:""})).filter(Boolean));const d=()=>r.length?this.contentSteeringManager_&&l?this.contentSteeringManager_.getLocations(a):o||[]:[];let c=p.UNKNOWN;switch(e.attributes.contentType||t.contentType){case p.VIDEO:c=p.VIDEO;break;case p.AUDIO:c=p.AUDIO;break;case p.TEXT:c=p.TEXT;break;case p.IMAGE:c=p.IMAGE;break;case p.APPLICATION:c=p.APPLICATION;break;default:c=p.UNKNOWN}const h=e.attributes.mimeType||t.mimeType,u=e.attributes.codecs||t.codecs,_=it.parseAttr(e,"frameRate",s)||t.frameRate,m=e.attributes.sar||t.pixelAspectRatio,g=this.emsgSchemeIdUris_(it.findChildren(e,"InbandEventStream"),t.emsgSchemeIdUris),f=it.findChildren(e,"AudioChannelConfiguration"),T=this.parseAudioChannels_(f)||t.numChannels,S=it.parseAttr(e,"audioSamplingRate",n)||t.audioSamplingRate;c===p.UNKNOWN&&(c=gt.guessContentType_(h,u));const y=it.findChild(e,"SegmentBase"),E=it.findChild(e,"SegmentTemplate"),v=y&&it.parseAttr(y,"availabilityTimeOffset",it.parseFloat)||0,b=E&&it.parseAttr(E,"availabilityTimeOffset",it.parseFloat)||0,I=r&&r.length&&it.parseAttr(r[0],"availabilityTimeOffset",it.parseFloat)||0,A=t.availabilityTimeOffset+I+v+b;let w=null;const C=it.findChild(e,"SegmentSequenceProperties");if(C){const e=it.findChild(C,"SAP");e&&(w=it.parseAttr(e,"cadence",it.parseInt))}return{getBaseUris:()=>U.resolveUris(i(),d()),segmentBase:y||t.segmentBase,segmentList:it.findChild(e,"SegmentList")||t.segmentList,segmentTemplate:E||t.segmentTemplate,width:it.parseAttr(e,"width",n)||t.width,height:it.parseAttr(e,"height",n)||t.height,contentType:c,mimeType:h,codecs:u,frameRate:_,pixelAspectRatio:m,emsgSchemeIdUris:g,id:a,language:e.attributes.lang,numChannels:T,audioSamplingRate:S,availabilityTimeOffset:A,segmentSequenceCadence:w||t.segmentSequenceCadence}}emsgSchemeIdUris_(e,t){const i=t.slice();for(const t of e){const e=t.attributes.schemeIdUri;i.includes(e)||i.push(e)}return i}parseAudioChannels_(e){for(const t of e){const e=t.attributes.schemeIdUri;if(!e)continue;const i=t.attributes.value;if(i)switch(e){case"urn:mpeg:dash:outputChannelPositionList:2012":return i.trim().split(/ +/).length;case"urn:mpeg:dash:23003:3:audio_channel_configuration:2011":case"urn:dts:dash:audio_channel_configuration:2012":{const t=parseInt(i,10);if(!t){n.warning("Channel parsing failure! Ignoring scheme and value",e,i);continue}return t}case"tag:dolby.com,2014:dash:audio_channel_configuration:2011":case"urn:dolby:dash:audio_channel_configuration:2011":{let t=parseInt(i,16);if(!t){n.warning("Channel parsing failure! Ignoring scheme and value",e,i);continue}let s=0;for(;t;)1&t&&++s,t>>=1;return s}case"urn:mpeg:mpegB:cicp:ChannelConfiguration":{const t=0,s=[t,1,2,3,4,5,6,8,2,3,4,7,8,24,8,12,10,12,14,12,14],a=parseInt(i,10);if(!a){n.warning("Channel parsing failure! Ignoring scheme and value",e,i);continue}if(a>t&&a<s.length)return s[a];continue}default:n.warning("Unrecognized audio channel scheme:",e,i);continue}}return null}verifyRepresentation_(e){const t=U.ContentType;let i=0;return i+=e.segmentBase?1:0,i+=e.segmentList?1:0,i+=e.segmentTemplate?1:0,0==i?e.contentType==t.TEXT||e.contentType==t.APPLICATION||(n.warning("Representation does not contain a segment information source:","the Representation must contain one of SegmentBase, SegmentList,",'SegmentTemplate, or explicitly indicate that it is "text".',e),!1):(1!=i&&(n.warning("Representation contains multiple segment information sources:","the Representation should only contain one of SegmentBase,","SegmentList, or SegmentTemplate.",e),e.segmentBase?(n.info("Using SegmentBase by default."),e.segmentList=null,e.segmentTemplate=null):(console.assert(e.segmentList,"There should be a SegmentList"),n.info("Using SegmentList by default."),e.segmentTemplate=null)),!0)}async requestForTiming_(e,t,i){ft(this.config_),pt(this.playerInterface_);const s=U.resolveUris(e(),[t]),a=D.makeRequest(s,this.config_.retryParameters);a.method=i;const r=D.RequestType.TIMING,o=this.playerInterface_.networkingEngine.request(r,a);this.operationManager_.manage(o);const l=await o.promise;let d;if("HEAD"==i){if(!l.headers||!l.headers.date)return n.warning("UTC timing response is missing","expected date header"),0;d=l.headers.date}else d=x.fromUTF8(l.data);const c=Date.parse(d);return isNaN(c)?(n.warning("Unable to parse date from UTC timing response"),0):c-Date.now()}async parseUtcTiming_(e,t){ft(this.config_),pt(this.playerInterface_);const i=t.map((e=>({scheme:e.attributes.schemeIdUri,value:e.attributes.value}))),s=this.config_.dash.clockSyncUri;!i.length&&s&&i.push({scheme:"urn:mpeg:dash:utc:http-head:2014",value:s});for(const t of i)try{const i=t.scheme,s=t.value;switch(i){case"urn:mpeg:dash:utc:http-head:2014":case"urn:mpeg:dash:utc:http-head:2012":return await this.requestForTiming_(e,s,"HEAD");case"urn:mpeg:dash:utc:http-xsdate:2014":case"urn:mpeg:dash:utc:http-iso:2014":case"urn:mpeg:dash:utc:http-xsdate:2012":case"urn:mpeg:dash:utc:http-iso:2012":return await this.requestForTiming_(e,s,"GET");case"urn:mpeg:dash:utc:direct:2014":case"urn:mpeg:dash:utc:direct:2012":{const e=Date.parse(s);return isNaN(e)?0:e-Date.now()}case"urn:mpeg:dash:utc:http-ntp:2014":case"urn:mpeg:dash:utc:ntp:2014":case"urn:mpeg:dash:utc:sntp:2014":n.alwaysWarn("NTP UTCTiming scheme is not supported");break;default:n.alwaysWarn("Unrecognized scheme in UTCTiming element",i)}}catch(e){n.warning("Error fetching time from UTCTiming elem",e.message)}return n.alwaysWarn("A UTCTiming element should always be given in live manifests! This content may not play on clients with bad clocks!"),0}parseEventStream_(e,t,i,n){ft(this.config_),pt(this.playerInterface_);const s=it.parseNonNegativeInt,a=i.attributes.schemeIdUri||"",r=i.attributes.value||"",o=it.parseAttr(i,"timescale",s)||1;for(const l of it.findChildren(i,"Event")){let i=(it.parseAttr(l,"presentationTime",s)||0)/o+e,d=i+(it.parseAttr(l,"duration",s)||0)/o;if(null!=t&&(i=Math.min(i,e+t),d=Math.min(d,e+t)),d<n)continue;const c={schemeIdUri:a,value:r,startTime:i,endTime:d,id:l.attributes.id||"",eventElement:l};this.playerInterface_.onTimelineRegionAdded(c)}}async requestSegment_(e,t,i,n){ft(this.config_),pt(this.playerInterface_);const s=D.RequestType.SEGMENT,a=n?D.AdvancedRequestType.INIT_SEGMENT:D.AdvancedRequestType.MEDIA_SEGMENT,r=Le.createSegmentRequest(e,t,i,this.config_.retryParameters);return(await this.makeNetworkRequest_(r,s,{type:a,stream:void 0,segment:void 0})).data}static guessContentType_(e,t){const i=F.getFullType(e,t);if(z.isTypeSupported(i))return U.ContentType.TEXT;switch(e.split("/")[0]){case p.AUDIO:return p.AUDIO;case p.VIDEO:return p.VIDEO}return p.UNKNOWN}makeNetworkRequest_(e,t,i){ft(this.config_),pt(this.playerInterface_);const n=this.playerInterface_.networkingEngine.request(t,e,i);return this.operationManager_.manage(n),n.promise}}function ft(e){if(null==e)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.NOT_CONFIGURED)}function pt(e){if(null==e)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.NOT_CONFIGURED)}_e.registerParserByMime("application/dash+xml",(()=>new gt)),_e.registerParserByMime("video/vnd.mpeg.dash.mpd",(()=>new gt));class Tt{constructor(){this.config_=null,this.playerInterface_=null,this.manifestUris_=[],this.manifest_=null,this.globalId_=1,this.streamMap_={},this.periodDurations_={},this.periodCombiner_=new _t,this.updatePeriod_=0,this.averageUpdateDuration_=new Q(5),this.updateTimer_=new l((()=>{this.onUpdate_()})),this.operationManager_=new A,this.largestPeriodStartTime_=null,this.lastManifestUpdatePeriodIds_=[],this.minTotalAvailabilityTimeOffset_=1/0,this.lowLatencyMode_=!1}configure(e){console.assert(null!=e.dash,"DashManifestConfiguration should not be null!"),this.config_=e,this.periodCombiner_&&(this.periodCombiner_.setAllowMultiTypeVariants(this.config_.dash.multiTypeVariantsAllowed&&G.isChangeTypeSupported()),this.periodCombiner_.setUseStreamOnce(this.config_.dash.useStreamOnceInPeriodFlattening))}async start(e,t){console.assert(this.config_,"Must call configure() before start()!"),this.lowLatencyMode_=t.isLowLatencyMode(),this.manifestUris_=[e],this.playerInterface_=t;const i=await this.requestManifest_();if(this.playerInterface_&&this.setUpdateTimer_(i),!this.playerInterface_)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.OPERATION_ABORTED);if(console.assert(this.manifest_,"Manifest should be non-null!"),!this.manifest_)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.OPERATION_ABORTED);return this.manifest_}stop(){for(const e of Object.values(this.streamMap_))e.segmentIndex&&e.segmentIndex.release();return this.periodCombiner_&&this.periodCombiner_.release(),this.playerInterface_=null,this.config_=null,this.manifestUris_=[],this.manifest_=null,this.streamMap_={},this.periodCombiner_=null,null!=this.updateTimer_&&(this.updateTimer_.stop(),this.updateTimer_=null),this.operationManager_.destroy()}async update(){try{await this.requestManifest_()}catch(e){if(!this.playerInterface_||!e)return;console.assert(e instanceof b,"Bad error type"),this.playerInterface_.onError(e)}}onExpirationUpdated(e,t){}onInitialVariantChosen(e){if(this.manifest_&&this.manifest_.presentationTimeline.isLive()){const t=e.video||e.audio;if(t&&t.segmentIndex){const e=this.manifest_.presentationTimeline.getSegmentAvailabilityEnd(),i=t.segmentIndex.find(e);if(null==i)return;const n=t.segmentIndex.get(i);if(!n)return;this.updatePeriod_=n.endTime-e,this.setUpdateTimer_(0)}}}banLocation(e){}async requestManifest_(){const e=D.RequestType.MANIFEST,t=D.AdvancedRequestType.MPD;let i=this.manifestUris_;St(this.config_);const n=D.makeRequest(i,this.config_.retryParameters),s=Date.now(),a=await this.makeNetworkRequest_(n,e,{type:t,stream:void 0,segment:void 0});if(!this.playerInterface_)return 0;a.uri&&a.uri!=a.originalUri&&!this.manifestUris_.includes(a.uri)&&this.manifestUris_.unshift(a.uri),await this.parseManifest_(a.data,a.uri);const r=(Date.now()-s)/1e3;return this.averageUpdateDuration_.sample(1,r),r}async parseManifest_(e,t){let i="",n=null;try{i=x.fromUTF8(e),n=JSON.parse(i)}catch(e){throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_INVALID_JSON,t,i)}const s=this.convertDashJsonDTOToAdaptiveSets_(n);return this.processManifest_(s,t)}async processManifest_(e,t){var i,s,a,r,o,l,d,c,h,u,_,m,g;St(this.config_),yt(this.playerInterface_);let f=0;this.config_.dash.ignoreMinBufferTime||(f=e.minBufferTimeMs/1e3),this.updatePeriod_=-1;let p=null,T=null;this.config_.dash.ignoreSuggestedPresentationDelay||(T=null);let S,y=null;if(this.config_.dash.ignoreMaxSegmentDuration||(y=null),this.manifest_){S=this.manifest_.presentationTimeline;for(const e of Object.values(this.streamMap_))e.segmentIndex&&e.segmentIndex.evict(S.getSegmentAvailabilityStart())}else{const e=this.config_.defaultPresentationDelay||1.5*f;S=new ut(null,null!=T?T:e,this.config_.dash.autoCorrectDrift)}S.setStatic(!0),S.isLive()&&!isNaN(this.config_.availabilityWindowOverride)&&(p=this.config_.availabilityWindowOverride),null==p&&(p=1/0),S.setSegmentAvailabilityDuration(p);const E={dynamic:!1,presentationTimeline:S,period:null,periodInfo:null,adaptationSet:null,representation:null,bandwidth:0,indexRangeWarningGiven:!1,availabilityTimeOffset:0,profiles:"urn:mpeg:dash:profile:isoff-on-demand:2011".split(",")},v=this.parsePeriods_(E,e),b=v.duration,I=v.periods;if(S.setDuration(b||1/0),this.minTotalAvailabilityTimeOffset_&&!this.lowLatencyMode_&&this.playerInterface_.isAutoLowLatencyMode()&&(this.playerInterface_.enableLowLatencyMode(),this.lowLatencyMode_=this.playerInterface_.isLowLatencyMode()),this.lowLatencyMode_?S.setAvailabilityTimeOffset(this.minTotalAvailabilityTimeOffset_):this.minTotalAvailabilityTimeOffset_&&n.alwaysWarn("Low-latency DASH live stream detected, but low-latency streaming mode is not enabled in Shaka Player. Set streaming.lowLatencyMode configuration to true, and see https://bit.ly/3clctcj for details."),S.notifyMaxSegmentDuration(y||1),S.assertIsValid(),await(null===(i=this.periodCombiner_)||void 0===i?void 0:i.combinePeriods(I,E.dynamic)),this.lowLatencyMode_&&(f=0),this.manifest_){this.manifest_.variants=null!==(h=null===(c=this.periodCombiner_)||void 0===c?void 0:c.getVariants())&&void 0!==h?h:[];const e=null!==(_=null===(u=this.periodCombiner_)||void 0===u?void 0:u.getTextStreams())&&void 0!==_?_:[];e.length>0&&(this.manifest_.textStreams=e),this.manifest_.imageStreams=null!==(g=null===(m=this.periodCombiner_)||void 0===m?void 0:m.getImageStreams())&&void 0!==g?g:[],this.playerInterface_.filter(this.manifest_)}else{if(this.manifest_={presentationTimeline:S,variants:null!==(a=null===(s=this.periodCombiner_)||void 0===s?void 0:s.getVariants())&&void 0!==a?a:[],textStreams:null!==(o=null===(r=this.periodCombiner_)||void 0===r?void 0:r.getTextStreams())&&void 0!==o?o:[],imageStreams:null!==(d=null===(l=this.periodCombiner_)||void 0===l?void 0:l.getImageStreams())&&void 0!==d?d:[],offlineSessionIds:[],minBufferTime:f||0,sequenceMode:this.config_.dash.sequenceMode,ignoreManifestTimestampsInSegmentsMode:!1,type:_e.DASH,serviceDescription:this.parseServiceDescription_(e)},S.usingPresentationStartTime()){const t=it.findChildren(e,"UTCTiming"),i=await this.parseUtcTiming_(getBaseUris,t);if(!this.playerInterface_)return;S.setClockOffset(i)}S.lockStartTime()}this.playerInterface_.makeTextStreamsForClosedCaptions(this.manifest_)}convertDashJsonDTOToAdaptiveSets_(e){var t,i;const n=new Map;let s=null!==(t=e.minBufferTimeMs)&&void 0!==t?t:0,a=null!==(i=e.approxDurationMs)&&void 0!==i?i:0,r=0,o=0;for(const t of e.adaptiveFormats){const e=this.getContentTypeEnumFromString_(t.type),i={contentType:e,containerType:this.getContainerTypeFromMimeType_(t.mimeType),lang:t.lang};let s=n.get(i);null==s&&(s=Object.assign(Object.assign({},t),{contentType:e,representations:[],id:r}),n.set(i,s),++r),s.representations.push(Object.assign(Object.assign({},t),{id:o,contentType:e,segmentBase:!0,getBaseUris:()=>[t.url]})),++o}return{minBufferTimeMs:s,approxDurationMs:a,periods:[{id:0,adaptionSets:Array.from(n.values())}]}}getContentTypeEnumFromString_(e){let t=p.UNKNOWN;switch(e){case p.VIDEO:t=p.VIDEO;break;case p.AUDIO:t=p.AUDIO;break;case p.TEXT:t=p.TEXT;break;case p.IMAGE:t=p.IMAGE;break;case p.APPLICATION:t=p.APPLICATION;break;default:t=p.UNKNOWN}return t}getContainerTypeFromMimeType_(e){var t;let i=[];return e&&(i=e.split("/")),i.length>1&&null!==(t=i[1])&&void 0!==t?t:null}parseServiceDescription_(e){const t=it.findChild(e,"ServiceDescription");if(!t)return null;const i=it.findChild(t,"Latency"),n=it.findChild(t,"PlaybackRate");return i&&i.attributes.max||n?{maxLatency:i&&i.attributes.max?parseInt(i.attributes.max,10)/1e3:null,maxPlaybackRate:n?parseFloat(n.attributes.max):null,minLatency:i&&i.attributes.min?parseInt(i.attributes.min,10)/1e3:null,minPlaybackRate:n?parseFloat(n.attributes.min):null}:null}parsePeriods_(e,t){const i=t.approxDurationMs/1e3,s=i-0,a=[this.parsePeriod_(e,{start:0,duration:s,isLastPeriod:!0,node:t.periods[0]})];return this.lastManifestUpdatePeriodIds_=a.map((e=>e.id)),null!=i?(0!=i&&n.warning("@mediaPresentationDuration does not match the total duration of ","all Periods."),{periods:a,duration:i,durationDerivedFromPeriods:!1}):{periods:a,duration:0,durationDerivedFromPeriods:!0}}parsePeriod_(e,t){var i,s,a;St(this.config_),yt(this.playerInterface_),e.period=t.node,e.periodInfo=t,e.period.availabilityTimeOffset=e.availabilityTimeOffset,e.period.id||(n.info("No Period ID given for Period with start time "+t.start+", Assigning a default"),e.period.id="__shaka_period_"+t.start);const r=t.node.adaptionSets.map((t=>this.parseAdaptationSet_(e,t))).filter(V.isNotNull);if(e.dynamic){const e=[];for(const t of r)for(const i of t.representationIds)e.push(i);const t=new Set(e);if(e.length!=t.size)throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_DUPLICATE_REPRESENTATION_ID)}const o=r.filter((e=>!e.trickModeFor)),l=r.filter((e=>e.trickModeFor));for(const e of l){const t=null!==(s=null===(i=e.trickModeFor)||void 0===i?void 0:i.split(" "))&&void 0!==s?s:[];for(const i of o)if(t.includes(i.id))for(const t of i.streams)t.trickModeVideo=null!==(a=e.streams.find((e=>F.getNormalizedCodec(t.codecs)==F.getNormalizedCodec(e.codecs))))&&void 0!==a?a:null}const d=this.getStreamsFromSets_(this.config_.disableAudio,o,p.AUDIO),c=this.getStreamsFromSets_(this.config_.disableVideo,o,p.VIDEO),h=this.getStreamsFromSets_(this.config_.disableText,o,p.TEXT),u=this.getStreamsFromSets_(this.config_.disableThumbnails,o,p.IMAGE);if(0===c.length&&0===d.length)throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_EMPTY_PERIOD);return{id:e.period.id,audioStreams:d,videoStreams:c,textStreams:h,imageStreams:u}}getStreamsFromSets_(e,t,i){return e||!t.length?[]:t.reduce(((e,t)=>(t.contentType!=i||e.push(...t.streams),e)),[])}parseAdaptationSet_(e,t){St(this.config_),yt(this.playerInterface_),e.adaptationSet=t;const i=H.normalize(e.adaptationSet.lang||"und"),n=[],s=new Map,a=[];if(t.representations.forEach((r=>{var o;const l=this.parseRepresentation_(e,null,i,null,!1,n,s,r,null);l&&(l.hdr=l.hdr||t.videoRange,l.fastSwitching=null!==(o=t.isFastSwitching)&&void 0!==o&&o),null!=l&&a.push(l)})),0==a.length){const t=e.adaptationSet.contentType==p.IMAGE;if(this.config_.dash.ignoreEmptyAdaptationSet||t)return null;throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_EMPTY_ADAPTATION_SET)}if(!e.adaptationSet.contentType||e.adaptationSet.contentType==p.APPLICATION){const t=a[0];if(t){const i=t.mimeType,n=t.codecs;e.adaptationSet.contentType=Tt.guessContentType_(i,n)}for(const t of a)t.type=e.adaptationSet.contentType}const r=String(e.adaptationSet.id||"__fake__"+this.globalId_++);for(const e of a)this.config_.dash.enableAudioGroups&&(e.groupId=r);const o=t.representations.map((e=>String(e.id))).filter(V.isNotNull);return{id:r,contentType:e.adaptationSet.contentType,language:i,main:!1,streams:a,trickModeFor:null,representationIds:o}}parseRepresentation_(e,t,i,n,s,a,r,o,l){var d,c,h,u,_,m,g,f;St(this.config_),yt(this.playerInterface_),e.representation=o;const T=null!==(c=null===(d=e.periodInfo)||void 0===d?void 0:d.start)&&void 0!==c?c:0;let S;e.bandwidth=o.bandwidth;const E=null!==(u=null===(h=e.adaptationSet)||void 0===h?void 0:h.contentType)&&void 0!==u?u:p.UNKNOWN,v=E==p.TEXT||E==p.APPLICATION,I=E==p.IMAGE;try{const t=this.requestSegment_.bind(this);if(o.initRange&&o.indexRange)S=Tt.createStreamInfo(e,o,t);else{console.assert(v,"Must have Segment* with non-text streams.");const t=null!==(m=null===(_=e.periodInfo)||void 0===_?void 0:_.duration)&&void 0!==m?m:0,i=e.representation.getBaseUris;S={generateSegmentIndex:()=>Promise.resolve(ve.forSingleSegment(T,t,i()))}}}catch(e){if((v||I)&&e.code==b.Code.DASH_NO_SEGMENT_INFO)return null;throw e}if(null==S)return null;let A=!1;v&&(A=a.includes("forced_subtitle")||a.includes("forced-subtitle"));let w=null;const C=e.profiles,M=e.representation.codecs;C.includes("http://dashif.org/guidelines/dash-if-uhd#hevc-hdr-pq10")&&(M.includes("hvc1.2.4.L153.B0")||M.includes("hev1.2.4.L153.B0"))&&(w=y.PQ);const R=e.representation.id?(null!==(f=null===(g=e.period)||void 0===g?void 0:g.id)&&void 0!==f?f:"")+","+e.representation.id:"";let O;if(R&&this.streamMap_[R])O=this.streamMap_[R];else{if(!e.adaptationSet)return null;O={id:this.globalId_++,originalId:String(e.representation.id),groupId:null,createSegmentIndex:()=>Promise.resolve(),closeSegmentIndex:()=>{O.segmentIndex&&(O.segmentIndex.release(),O.segmentIndex=null)},segmentIndex:null,mimeType:e.representation.mimeType,codecs:e.representation.codecs,frameRate:e.representation.frameRate,pixelAspectRatio:e.representation.pixelAspectRatio,bandwidth:e.bandwidth,width:e.representation.width,height:e.representation.height,kind:t,language:i,originalLanguage:e.adaptationSet.language,label:n,type:e.adaptationSet.contentType,primary:s,trickModeVideo:null,emsgSchemeIdUris:e.representation.emsgSchemeIdUris,roles:a,forced:A,channelsCount:e.representation.numChannels,audioSamplingRate:e.representation.audioSamplingRate,spatialAudio:!1,closedCaptions:r,hdr:w,videoLayout:null,tilesLayout:null,accessibilityPurpose:l,external:!1,fastSwitching:!1,matchedStreams:[],mssPrivateData:null}}return O.createSegmentIndex=async()=>{O.segmentIndex||(O.segmentIndex=await S.generateSegmentIndex())},R&&e.dynamic&&!this.streamMap_[R]&&(this.streamMap_[R]=O),O}async onUpdate_(){console.assert(this.updatePeriod_>=0,"There should be an update period"),n.info("Updating manifest...");let e=0;try{e=await this.requestManifest_()}catch(e){if(console.assert(e instanceof b,"Should only receive a Shaka error"),this.playerInterface_&&this.config_){if(this.config_.raiseFatalErrorOnManifestUpdateRequestFailure)return void this.playerInterface_.onError(e);e.severity=b.Severity.RECOVERABLE,this.playerInterface_.onError(e)}}this.playerInterface_&&(this.playerInterface_.onManifestUpdated(),this.setUpdateTimer_(e))}setUpdateTimer_(e){var t;if(this.updatePeriod_<0)return;const i=Math.max(this.updatePeriod_-e,this.averageUpdateDuration_.getEstimate());null===(t=this.updateTimer_)||void 0===t||t.tickAfter(i)}async requestForTiming_(e,t,i){St(this.config_),yt(this.playerInterface_);const s=U.resolveUris(e(),[t]),a=D.makeRequest(s,this.config_.retryParameters);a.method=i;const r=D.RequestType.TIMING,o=this.playerInterface_.networkingEngine.request(r,a);this.operationManager_.manage(o);const l=await o.promise;let d;if("HEAD"==i){if(!l.headers||!l.headers.date)return n.warning("UTC timing response is missing","expected date header"),0;d=l.headers.date}else d=x.fromUTF8(l.data);const c=Date.parse(d);return isNaN(c)?(n.warning("Unable to parse date from UTC timing response"),0):c-Date.now()}async parseUtcTiming_(e,t){St(this.config_),yt(this.playerInterface_);const i=t.map((e=>({scheme:e.attributes.schemeIdUri,value:e.attributes.value}))),s=this.config_.dash.clockSyncUri;!i.length&&s&&i.push({scheme:"urn:mpeg:dash:utc:http-head:2014",value:s});for(const t of i)try{const i=t.scheme,s=t.value;switch(i){case"urn:mpeg:dash:utc:http-head:2014":case"urn:mpeg:dash:utc:http-head:2012":return await this.requestForTiming_(e,s,"HEAD");case"urn:mpeg:dash:utc:http-xsdate:2014":case"urn:mpeg:dash:utc:http-iso:2014":case"urn:mpeg:dash:utc:http-xsdate:2012":case"urn:mpeg:dash:utc:http-iso:2012":return await this.requestForTiming_(e,s,"GET");case"urn:mpeg:dash:utc:direct:2014":case"urn:mpeg:dash:utc:direct:2012":{const e=Date.parse(s);return isNaN(e)?0:e-Date.now()}case"urn:mpeg:dash:utc:http-ntp:2014":case"urn:mpeg:dash:utc:ntp:2014":case"urn:mpeg:dash:utc:sntp:2014":n.alwaysWarn("NTP UTCTiming scheme is not supported");break;default:n.alwaysWarn("Unrecognized scheme in UTCTiming element",i)}}catch(e){n.warning("Error fetching time from UTCTiming elem",e.message)}return n.alwaysWarn("A UTCTiming element should always be given in live manifests! This content may not play on clients with bad clocks!"),0}async requestSegment_(e,t,i,n){St(this.config_),yt(this.playerInterface_);const s=D.RequestType.SEGMENT,a=n?D.AdvancedRequestType.INIT_SEGMENT:D.AdvancedRequestType.MEDIA_SEGMENT,r=Le.createSegmentRequest(e,t,i,this.config_.retryParameters);return(await this.makeNetworkRequest_(r,s,{type:a,stream:void 0,segment:void 0})).data}static guessContentType_(e,t){const i=F.getFullType(e,t);if(z.isTypeSupported(i))return U.ContentType.TEXT;switch(e.split("/")[0]){case p.AUDIO:return p.AUDIO;case p.VIDEO:return p.VIDEO}return p.UNKNOWN}makeNetworkRequest_(e,t,i){St(this.config_),yt(this.playerInterface_);const n=this.playerInterface_.networkingEngine.request(t,e,i);return this.operationManager_.manage(n),n.promise}static createInitSegment(e,t){let i=0,n=null;t.initRange&&(i=t.initRange.start,n=t.initRange.end);const s=Tt.createQualityInfo(e);return new ye((()=>[t.url]),i,n,s,null,null)}static createQualityInfo(e){var t,i,n,s,a,r,o,l,d;const c=e.representation,h=e.adaptationSet;return{bandwidth:e.bandwidth,audioSamplingRate:null!==(t=null==c?void 0:c.audioSamplingRate)&&void 0!==t?t:null,codecs:null!==(i=null==c?void 0:c.codecs)&&void 0!==i?i:"",contentType:null!==(n=null==c?void 0:c.contentType)&&void 0!==n?n:p.UNKNOWN,frameRate:null!==(s=null==h?void 0:h.fps)&&void 0!==s?s:null,height:null!==(a=null==c?void 0:c.height)&&void 0!==a?a:null,mimeType:null!==(r=null==c?void 0:c.mimeType)&&void 0!==r?r:null,channelsCount:null!==(o=null==c?void 0:c.numChannels)&&void 0!==o?o:null,pixelAspectRatio:null!==(l=null==c?void 0:c.sar)&&void 0!==l?l:null,width:null!==(d=null==c?void 0:c.width)&&void 0!==d?d:null}}static createStreamInfo(e,t,i){if(null==e.representation)return null;console.assert(e.representation.segmentBase,"Should only be called with SegmentBase");const n=(t.presentationTimeOffset||0)/(t.timescale||1)||0,s=Tt.createInitSegment(e,t);Tt.checkSegmentIndexRangeSupport_(e,s);const a=w.shallowCloneObject(e);return{generateSegmentIndex:()=>Tt.generateSegmentIndex_(a,i,s,n)}}static async generateSegmentIndexFromUris(e,t,i,n,s,a,r){var o,l,d,c,h,u,_;const m=e.presentationTimeline,g=!e.dynamic||!(null===(o=e.periodInfo)||void 0===o?void 0:o.isLastPeriod),f=null!==(d=null===(l=e.periodInfo)||void 0===l?void 0:l.start)&&void 0!==d?d:0,p=null!==(h=null===(c=e.periodInfo)||void 0===c?void 0:c.duration)&&void 0!==h?h:0,T=null!==(_=null===(u=e.representation)||void 0===u?void 0:u.mimeType.split("/")[1])&&void 0!==_?_:"";let S=t,y=null;const E=[S(n,s,a,!1),"webm"==T&&i?S(i.getUris(),i.startByte,i.endByte,!0):null];S=null;const v=await Promise.all(E),b=v[0],I=v[1]||null;let A;const w=f-r,C=f,M=p?f+p:1/0;return"mp4"==T?A=Mp4SegmentIndexParser.parse(b,s,n,i,w,C,M):(console.assert(I,"WebM requires init data"),A=WebmSegmentIndexParser.parse(b,I,n,i,w,C,M)),m.notifySegments(A),console.assert(!y,"Should not call generateSegmentIndex twice"),y=new ve(A),g&&y.fit(C,M,!0),y}static computeIndexRange_(e){var t;const i=e.representation;return null!==(t=null==i?void 0:i.indexRange)&&void 0!==t?t:null}static computeIndexUris_(e){var t,i;return null!==(i=null===(t=e.representation)||void 0===t?void 0:t.getBaseUris())&&void 0!==i?i:[]}static checkSegmentIndexRangeSupport_(e,t){if(Tt.checkSegmentIndexSupport(e,t),!Tt.computeIndexRange_(e))throw n.error("SegmentBase does not contain sufficient segment information:","the SegmentBase does not contain @indexRange","or a RepresentationIndex element.",e.representation),new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_NO_SEGMENT_INFO)}static checkSegmentIndexSupport(e,t){var i,s;const a=e.representation,r=null!==(i=a.contentType)&&void 0!==i?i:p.UNKNOWN,o=null!==(s=a.mimeType.split("/")[1])&&void 0!==s?s:"";if(r!=U.ContentType.TEXT&&"mp4"!=o&&"webm"!=o)throw n.error("SegmentBase specifies an unsupported container type.",a),new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_UNSUPPORTED_CONTAINER);if("webm"==o&&!t)throw n.error("SegmentBase does not contain sufficient segment information:","the SegmentBase uses a WebM container,","but does not contain an Initialization element.",a),new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_WEBM_MISSING_INIT)}static generateSegmentIndex_(e,t,i,n){const s=Tt.computeIndexUris_(e),a=Tt.computeIndexRange_(e);if(console.assert(a,"Index range should not be null!"),null==a)throw new b(b.Severity.CRITICAL,b.Category.MANIFEST,b.Code.DASH_EMPTY_INDEX_RANGE);return lt.generateSegmentIndexFromUris(e,t,i,s,a.start,a.end,n)}}function St(e){if(null==e)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.NOT_CONFIGURED)}function yt(e){if(null==e)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.NOT_CONFIGURED)}_e.registerParserByMime("application/json",(()=>new Tt));class Et{static parse(e,t,i,n){try{const t=Et.parseRaw(e),i={uri:e,originalUri:e,data:t.data,headers:{"content-type":t.contentType}};return M.completed(i)}catch(e){return M.failed(e)}}static parseRaw(e){const t=e.split(":");if(t.length<2||"data"!=t[0])throw n.error("Bad data URI, failed to parse scheme"),new b(b.Severity.CRITICAL,b.Category.NETWORK,b.Code.MALFORMED_DATA_URI,e);const i=t.slice(1).join(":").split(",");if(i.length<2)throw n.error("Bad data URI, failed to extract encoding and MIME type"),new b(b.Severity.CRITICAL,b.Category.NETWORK,b.Code.MALFORMED_DATA_URI,e);const s=i[0],a=window.decodeURIComponent(i.slice(1).join(",")),r=s.split(";"),o=r[0];let l,d=!1;return r.length>1&&"base64"==r[r.length-1]&&(d=!0,r.pop()),l=d?k.fromBase64(a):x.toUTF8(a),{data:l,contentType:o}}}D.registerScheme("data",Et.parse);class vt{static asMap(e){const t=new Map;for(const i of Object.keys(e))t.set(i,e[i]);return t}static asObject(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t}static hasSameElements(e,t){if(!e&&!t)return!0;if(e&&!t)return!1;if(t&&!e)return!1;if(e.size!=t.size)return!1;for(const[i,n]of e){if(!t.has(i))return!1;const e=t.get(i);if(e!=n||null==e)return!1}return!0}}class bt{static makeResponse(e,t,i,s,a,r){if(i>=200&&i<=299&&202!=i)return{uri:a||s,originalUri:s,data:t,status:i,headers:e,fromCache:!!e["x-vod-from-cache"]};{let a=null;try{a=x.fromBytesAutoDetect(t)}catch(e){}n.debug("HTTP error text:",a);const o=401==i||403==i?b.Severity.CRITICAL:b.Severity.RECOVERABLE;throw new b(o,b.Category.NETWORK,b.Code.BAD_HTTP_STATUS,s,i,a,e,r)}}}class It{static parse(e,t,i,n,s){const a=new It.Headers_;vt.asMap(t.headers).forEach(((e,t)=>{a.append(t,e)}));const r=new It.AbortController_,o={body:t.body||void 0,headers:a,method:t.method,signal:r.signal,credentials:t.allowCrossSiteCredentials?"include":void 0},d={canceled:!1,timedOut:!1},c=It.request_(e,i,o,d,n,s,t.streamDataCallback),h=new M(c,(()=>(d.canceled=!0,r.abort(),Promise.resolve()))),u=t.retryParameters.timeout;if(u){const e=new l((()=>{d.timedOut=!0,r.abort()}));e.tickAfter(u/1e3),h.finally((()=>{e.stop()}))}return h}static async request_(e,t,i,s,a,r,o){const l=It.fetch_,d=It.ReadableStream_;let c,h,u=0,_=0,m=Date.now();try{if(c=await l(e,i),r(It.headersToGenericObject_(c.headers)),"HEAD"!=i.method){console.assert(c.body,"non-HEAD responses should have a body");const e=c.clone().body.getReader(),t=c.headers.get("Content-Length"),i=t?parseInt(t,10):0;new d({start:t=>{const s=async()=>{let r;try{r=await e.read()}catch(e){return void n.v1("error reading from stream",e.message)}r.done||(u+=r.value.byteLength,o&&await o(r.value));const l=Date.now();(l-m>100||r.done)&&(a(l-m,u-_,i-u),_=u,m=l),r.done?(console.assert(!r.value,'readObj should be unset when "done" is true.'),t.close()):(t.enqueue(r.value),s())};s()}}),h=await c.arrayBuffer()}}catch(i){throw s.canceled?new b(b.Severity.RECOVERABLE,b.Category.NETWORK,b.Code.OPERATION_ABORTED,e,t):s.timedOut?new b(b.Severity.RECOVERABLE,b.Category.NETWORK,b.Code.TIMEOUT,e,t):new b(b.Severity.RECOVERABLE,b.Category.NETWORK,b.Code.HTTP_ERROR,e,i,t)}const g=It.headersToGenericObject_(c.headers);return bt.makeResponse(g,h,c.status,e,c.url,t)}static headersToGenericObject_(e){const t={};return e.forEach(((e,i)=>{t[i.trim()]=e})),t}static isSupported(){if(!window.ReadableStream)return!1;try{new ReadableStream({})}catch(e){return!1}return!!window.Response&&(!!new Response("").body&&!(!window.fetch||!window.AbortController))}}It.fetch_=window.fetch,It.AbortController_=window.AbortController,It.ReadableStream_=window.ReadableStream,It.Headers_=window.Headers,It.isSupported()&&(D.registerScheme("http",It.parse,D.PluginPriority.PREFERRED,!0),D.registerScheme("https",It.parse,D.PluginPriority.PREFERRED,!0),D.registerScheme("blob",It.parse,D.PluginPriority.PREFERRED,!0));class At{static parse(e,t,i,n,s){const a=new At.Xhr_;let r=Date.now(),o=0;const l=new Promise(((l,d)=>{a.open(t.method,e,!0),a.responseType="arraybuffer",a.timeout=t.retryParameters.timeout,a.withCredentials=t.allowCrossSiteCredentials,a.onabort=()=>{d(new b(b.Severity.RECOVERABLE,b.Category.NETWORK,b.Code.OPERATION_ABORTED,e,i))};let c=!1;a.onreadystatechange=e=>{if(2==a.readyState&&!c){const e=At.headersToGenericObject_(a);s(e),c=!0}},a.onload=t=>{const n=At.headersToGenericObject_(a);console.assert(a.response instanceof ArrayBuffer,"XHR should have a response by now!");const s=a.response;try{const t=bt.makeResponse(n,s,a.status,e,a.responseURL,i);l(t)}catch(e){console.assert(e instanceof b,"Wrong error type!"),d(e)}},a.onerror=t=>{d(new b(b.Severity.RECOVERABLE,b.Category.NETWORK,b.Code.HTTP_ERROR,e,t,i))},a.ontimeout=t=>{d(new b(b.Severity.RECOVERABLE,b.Category.NETWORK,b.Code.TIMEOUT,e,i))},a.onprogress=e=>{const t=Date.now();(t-r>100||e.lengthComputable&&e.loaded==e.total)&&(n(t-r,e.loaded-o,e.total-e.loaded),o=e.loaded,r=t)};for(const e in t.headers){const i=e.toLowerCase();a.setRequestHeader(i,t.headers[e])}a.send(t.body)}));return new M(l,(()=>(a.abort(),Promise.resolve())))}static headersToGenericObject_(e){const t=e.getAllResponseHeaders().trim().split("\r\n"),i={};for(const e of t){const t=e.split(": ");i[t[0].toLowerCase()]=t.slice(1).join(": ")}return i}}At.Xhr_=window.XMLHttpRequest,D.registerScheme("http",At.parse,D.PluginPriority.FALLBACK,!0),D.registerScheme("https",At.parse,D.PluginPriority.FALLBACK,!0),D.registerScheme("blob",At.parse,D.PluginPriority.FALLBACK,!0),D.registerScheme("vod-asset",At.parse,D.PluginPriority.FALLBACK,!0);class wt extends r{constructor(e,t){super(),this.loadMode_=wt.LoadMode.NOT_LOADED,this.video_=null,this.videoContainer_=null,this.isTextVisible_=!1,this.globalEventManager_=new ee,this.attachEventManager_=new ee,this.loadEventManager_=new ee,this.trickPlayEventManager_=new ee,this.networkingEngine_=null,this.mediaSourceEngine_=null,this.playhead_=null,this.operationId_=0,this.mutex_=new tt,this.playheadObservers_=null,this.playRateController_=null,this.bufferObserver_=null,this.regionTimeline_=null,this.cmcdManager_=null,this.cmsdManager_=null,this.lcevcCanvas_=null,this.lcevcDec_=null,this.qualityObserver_=null,this.streamingEngine_=null,this.parser_=null,this.parserFactory_=null,this.manifest_=null,this.assetUri_=null,this.mimeType_=null,this.startTime_=null,this.fullyLoaded_=!1,this.abrManager_=null,this.abrManagerFactory_=null,this.nextExternalStreamId_=1e9,this.externalSrcEqualsThumbnailsStreams_=[],this.completionPercent_=NaN,this.config_=this.defaultConfig_(),this.lastTextFactory_,this.maxHwRes_={width:1/0,height:1/0},this.manifestFilterer_=new Se(this.config_,this.maxHwRes_,null),this.stats_=null,this.currentAdaptationSetCriteria_=new Ne(this.config_.preferredAudioLanguage,this.config_.preferredVariantRole,this.config_.preferredAudioChannelCount,this.config_.preferredVideoHdrLevel,this.config_.preferSpatialAudio,this.config_.preferredVideoLayout,this.config_.preferredAudioLabel,this.config_.preferredVideoLabel,this.config_.mediaSource.codecSwitchingStrategy,this.config_.manifest.dash.enableAudioGroups),this.currentTextLanguage_=this.config_.preferredTextLanguage,this.currentTextRole_=this.config_.preferredTextRole,this.currentTextForced_=this.config_.preferForcedSubs,this.cleanupOnUnload_=[],t&&t(this),this.cmcdManager_=this.createCmcd_(),this.cmsdManager_=this.createCmsd_(),this.networkingEngine_=this.createNetworkingEngine(),this.networkingEngine_.setForceHTTPS(this.config_.streaming.forceHTTPS),this.adManager_=null,wt.adManagerFactory_&&(this.adManager_=wt.adManagerFactory_(),this.adManager_.configure(this.config_.ads)),this.globalEventManager_.listen(window,"online",(()=>{this.restoreDisabledVariants_(),this.retryStreaming()})),this.checkVariantsTimer_=new l((()=>this.checkVariants_())),e&&(re.deprecateFeature(5,"Player w/ mediaElement","Please migrate from initializing Player with a mediaElement; use the attach method instead."),this.attach(e,!0))}createLcevcDec_(e){null==this.lcevcDec_&&(this.lcevcDec_=new Te(this.video_,this.lcevcCanvas_,e),this.mediaSourceEngine_&&this.mediaSourceEngine_.updateLcevcDec(this.lcevcDec_))}closeLcevcDec_(){null!=this.lcevcDec_&&(this.lcevcDec_.hideCanvas(),this.lcevcDec_.release(),this.lcevcDec_=null)}setupLcevc_(e){if(e.lcevc.enabled){const t=this.getVariantTracks();t&&t[0]&&"video/mp2t"==t[0].videoMimeType&&(N.isEdge()||N.isLegacyEdge())&&(e.mediaSource.forceTransmux||n.alwaysWarn("LCEVC Warning: For MPEG-2 TS decoding the config.mediaSource.forceTransmux must be enabled.")),this.closeLcevcDec_(),this.createLcevcDec_(e.lcevc)}else this.closeLcevcDec_()}static makeEvent_(e,t){return new a(e,t)}async destroy(){if(this.loadMode_==wt.LoadMode.DESTROYED)return;this.closeLcevcDec_();const e=this.detach();this.loadMode_=wt.LoadMode.DESTROYED,await e,this.globalEventManager_&&(this.globalEventManager_.release(),this.globalEventManager_=null),this.attachEventManager_&&(this.attachEventManager_.release(),this.attachEventManager_=null),this.loadEventManager_&&(this.loadEventManager_.release(),this.loadEventManager_=null),this.trickPlayEventManager_&&(this.trickPlayEventManager_.release(),this.trickPlayEventManager_=null),this.abrManagerFactory_=null,this.config_=null,this.stats_=null,this.videoContainer_=null,this.cmcdManager_=null,this.cmsdManager_=null,this.networkingEngine_&&(await this.networkingEngine_.destroy(),this.networkingEngine_=null),this.abrManager_&&(this.abrManager_.release(),this.abrManager_=null),super.release()}static registerSupportPlugin(e,t){wt.supportPlugins_[e]=t}static setAdManagerFactory(e){wt.adManagerFactory_=e}static isBrowserSupported(){if(window.Promise||n.alwaysWarn("A Promise implementation or polyfill is required"),!(window.Promise&&window.Uint8Array&&Array.prototype.forEach))return!1;if(N.isIE())return!1;const e=N.safariVersion();return!(e&&e<9)&&(!!N.supportsMediaSource()||N.supportsMediaType("application/x-mpegurl"))}static async probeSupport(e=!0){console.assert(wt.isBrowserSupported(),"Must have basic support");const t={manifest:_e.probeSupport(),media:pe.probeSupport()},i=wt.supportPlugins_;for(const e in i)t[e]=i[e]();return t}makeStateChangeEvent_(e){this.dispatchEvent(wt.makeEvent_(a.EventName.OnStateChange,(new Map).set("state",e)))}async attach(e,t=!0){if(this.loadMode_==wt.LoadMode.DESTROYED)throw this.createAbortLoadError_();const i=this.video_&&this.video_==e;if(this.video_&&this.video_!=e&&await this.detach(),!await this.atomicOperationAcquireMutex_("attach"))try{if(!i){this.makeStateChangeEvent_("attach");const t=e=>this.onVideoError_(e);this.attachEventManager_.listen(e,"error",t),this.video_=e}t&&N.supportsMediaSource()&&!this.mediaSourceEngine_&&await this.initializeMediaSourceEngineInner_()}catch(e){throw await this.detach(),e}finally{this.mutex_.release()}}attachCanvas(e){this.lcevcCanvas_=e}async detach(e=!1){if(this.loadMode_==wt.LoadMode.DESTROYED)throw this.createAbortLoadError_();if(await this.unload(!1,e),!await this.atomicOperationAcquireMutex_("detach"))try{this.video_&&(this.attachEventManager_.removeAll(),this.video_=null),this.makeStateChangeEvent_("detach"),this.adManager_&&!e&&this.adManager_.release()}finally{this.mutex_.release()}}async atomicOperationAcquireMutex_(e){const t=++this.operationId_;return await this.mutex_.acquire(e),t!=this.operationId_&&(this.mutex_.release(),!0)}async unload(e=!0,t=!1){if(this.loadMode_!=wt.LoadMode.DESTROYED&&(this.loadMode_=wt.LoadMode.NOT_LOADED),!await this.atomicOperationAcquireMutex_("unload")){try{this.fullyLoaded_=!1,this.makeStateChangeEvent_("unload"),e&&!N.supportsMediaSource()&&(e=!1),this.closeLcevcDec_();const i=this.cleanupOnUnload_.map((e=>e()));if(this.cleanupOnUnload_=[],await Promise.all(i),this.dispatchEvent(wt.makeEvent_(a.EventName.Unloading)),this.regionTimeline_&&(this.regionTimeline_.release(),this.regionTimeline_=null),this.video_&&(this.loadEventManager_.removeAll(),this.trickPlayEventManager_.removeAll()),this.checkVariantsTimer_.stop(),this.playheadObservers_&&(this.playheadObservers_.release(),this.playheadObservers_=null),this.parser_&&(await this.parser_.stop(),this.parser_=null,this.parserFactory_=null),this.abrManager_&&await this.abrManager_.stop(),this.streamingEngine_&&(await this.streamingEngine_.destroy(),this.streamingEngine_=null),this.playRateController_&&(this.playRateController_.release(),this.playRateController_=null),this.playhead_&&(this.playhead_.release(),this.playhead_=null),this.mediaSourceEngine_&&(await this.mediaSourceEngine_.destroy(),this.mediaSourceEngine_=null),this.adManager_&&!t&&this.adManager_.onAssetUnload(),this.cmsdManager_&&this.cmsdManager_.reset(),this.video_&&je.removeAllChildren(this.video_),this.video_&&this.video_.src&&(await new Promise((e=>new l(e).tickAfter(.1))),this.video_.removeAttribute("src"),this.video_.load()),this.assetUri_=null,this.mimeType_=null,this.bufferObserver_=null,this.manifest_){for(const e of this.manifest_.variants)for(const t of[e.audio,e.video])t&&t.segmentIndex&&t.segmentIndex.release();for(const e of this.manifest_.textStreams)e.segmentIndex&&e.segmentIndex.release()}this.manifest_=null,this.stats_=new ne,this.lastTextFactory_=null,this.externalSrcEqualsThumbnailsStreams_=[],this.completionPercent_=NaN,this.updateBufferState_()}finally{this.mutex_.release()}e&&N.supportsMediaSource()&&!this.mediaSourceEngine_&&await this.initializeMediaSourceEngineInner_()}}updateStartTime(e){this.startTime_=e}async load(e,t=null,i){if(console.log("load"),this.loadMode_==wt.LoadMode.DESTROYED)throw this.createAbortLoadError_();let n=null,s="";if(e instanceof ke?(n=e,s=n.getAssetUri()||""):s=e||"",await this.mutex_.acquire("load"),this.mutex_.release(),!this.video_)throw new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.NO_VIDEO_ELEMENT);this.assetUri_&&await this.unload(!1);const r=++this.operationId_,o=async()=>{if(this.operationId_!=r)throw n&&await n.destroy(),this.createAbortLoadError_()},l=async(e,t)=>{try{await this.mutex_.acquire(t),await o(),await e(),await o(),n&&this.config_&&n.reconfigure(this.config_)}finally{this.mutex_.release()}};try{null==t&&n&&(t=n.getStartTime()),this.startTime_=t,this.fullyLoaded_=!1,this.dispatchEvent(wt.makeEvent_(a.EventName.Loading)),n?i=n.getMimeType():i||await l((async()=>{i=await this.guessMimeType_(s)}),"guessMimeType_");const e=!!n;n?n.setEventHandoffTarget(this):(n=await this.preloadInner_(s,t,i,!0),n&&(n.setEventHandoffTarget(this),await l((()=>n.start()),"preload")));const r=!n,o=n?n.getStartTimeOfLoad():Date.now()/1e3;if(this.stats_=n?n.getStats():new ne,this.assetUri_=s,this.mimeType_=i||null,r)await l((async()=>{console.assert(i,"We should know the mimeType by now!"),await this.srcEqualsInner_(o,i)}),"srcEqualsInner_");else{this.mediaSourceEngine_||await l((async()=>{await this.initializeMediaSourceEngineInner_()}),"initializeMediaSourceEngineInner_"),await l((()=>n.waitForManifest()),"waitForManifest"),this.config_=n.getConfiguration(),this.manifestFilterer_=n.getManifestFilterer(),this.parserFactory_=n.getParserFactory(),this.parser_=n.receiveParser(),this.regionTimeline_=n.receiveRegionTimeline(),this.qualityObserver_=n.getQualityObserver(),this.manifest_=n.getManifest();const t=n.getCurrentAdaptationSetCriteria();t&&(this.currentAdaptationSetCriteria_=t),e&&this.video_&&"AUDIO"===this.video_.nodeName&&(this.makeManifestAudioOnly_(),this.configure("manifest.disableVideo",!0)),await l((()=>n.waitForChooseInitialVariant()),"waitForChooseInitialVariant");const i=n.getAbrManagerFactory();i&&(this.abrManagerFactory_&&this.abrManagerFactory_==i||(this.abrManager_=n.receiveAbrManager(),this.abrManagerFactory_=n.getAbrManagerFactory(),"function"!=typeof this.abrManager_.setMediaElement&&(re.deprecateFeature(5,"AbrManager w/o setMediaElement","Please use an AbrManager with setMediaElement function."),this.abrManager_.setMediaElement=()=>{}),"function"!=typeof this.abrManager_.setCmsdManager&&(re.deprecateFeature(5,"AbrManager w/o setCmsdManager","Please use an AbrManager with setCmsdManager function."),this.abrManager_.setCmsdManager=()=>{}),"function"!=typeof this.abrManager_.trySuggestStreams&&(re.deprecateFeature(5,"AbrManager w/o trySuggestStreams","Please use an AbrManager with trySuggestStreams function."),this.abrManager_.trySuggestStreams=()=>{})));const s=n.receiveSegmentPrefetchesById(),a=n.getPrefetchedVariant();await l((async()=>{await this.loadInner_(o,a,s)}),"loadInner_"),n.stopQueuingLatePhaseQueuedOperations()}this.dispatchEvent(wt.makeEvent_(a.EventName.Loaded))}catch(e){throw e.code!=b.Code.LOAD_INTERRUPTED&&await this.unload(!1),e}finally{n&&await n.destroy()}}makeManifestAudioOnly_(){for(const e of this.manifest_.variants)e.video&&(e.video.closeSegmentIndex(),e.video=null),e.audio&&e.audio.bandwidth?e.bandwidth=e.audio.bandwidth:e.bandwidth=0;this.manifest_.variants=this.manifest_.variants.filter((e=>e.audio))}async unloadAndSavePreload(e=!0,t=!1){let i=null;if(this.manifest_&&this.parser_&&this.parserFactory_&&this.assetUri_){let e=this.video_.currentTime;this.isLive()&&(e=null);const t=Date.now()/1e3;i=await this.makePreloadManager_(this.assetUri_,e,this.mimeType_,t,!0,!1,!1),i.attachManifest(this.manifest_,this.parser_,this.parserFactory_),i.attachAbrManager(this.abrManager_,this.abrManagerFactory_),i.attachAdaptationSetCriteria(this.currentAdaptationSetCriteria_),i.start(),this.manifest_=null,this.parser_=null,this.parserFactory_=null,this.abrManager_=null,this.abrManagerFactory_=null}return await this.unload(e,t),i}async preload(e,t=null,i){const n=await this.preloadInner_(e,t,i);return n?n.start().catch((e=>{})):this.onError_(new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.SRC_EQUALS_PRELOAD_NOT_SUPPORTED)),n}async preloadInner_(e,t,i,n=!1){console.assert(this.networkingEngine_,"Should have a net engine!"),console.assert(this.config_,"Config must not be null!");const s=Date.now()/1e3;if(i||(i=await this.guessMimeType_(e)),this.shouldUseSrcEquals_(e,i))return null;let a=!1,r=!0;return n&&(this.abrManager_&&this.abrManagerFactory_==this.config_.abrFactory&&(r=!1),this.video_&&"AUDIO"===this.video_.nodeName&&(a=!0)),this.makePreloadManager_(e,t,i||null,s,!n,a,r)}async makePreloadManager_(e,t,i,n,s=!0,r=!1,o=!0){console.assert(this.networkingEngine_,"Must have net engine");let l=null;const d=w.cloneObject(this.config_);r&&(d.manifest.disableVideo=!0);const c=()=>(console.assert(l,"Must have preload manager"),l.hasBeenAttached()&&l.isDestroyed()?null:l),h=()=>c()?c().getConfiguration():this.config_,u=(e,t)=>{c()?l.configure(e,t):this.configure(e,t)};if(this.maxHwRes_.width==1/0&&this.maxHwRes_.height==1/0){const e=await N.detectMaxHardwareResolution();this.maxHwRes_.width=e.width,this.maxHwRes_.height=e.height}const _=new Se(d,this.maxHwRes_,null),m={networkingEngine:this.networkingEngine_,filter:async e=>{if(await _.filterManifest(e)){const e=wt.makeEvent_(a.EventName.TracksChanged);await Promise.resolve(),l.dispatchEvent(e)}},makeTextStreamsForClosedCaptions:e=>this.makeTextStreamsForClosedCaptions_(e),onTimelineRegionAdded:e=>{l.getRegionTimeline().addRegion(e)},onEvent:e=>l.dispatchEvent(e),onError:e=>l.onError(e),isLowLatencyMode:()=>h().streaming.lowLatencyMode,isAutoLowLatencyMode:()=>h().streaming.autoLowLatencyMode,enableLowLatencyMode:()=>{u("streaming.lowLatencyMode",!0)},updateDuration:()=>{this.streamingEngine_&&l.hasBeenAttached()&&this.streamingEngine_.updateDuration()},onManifestUpdated:()=>{const e=a.EventName.ManifestUpdated,t=(new Map).set("isLive",this.isLive());l.dispatchEvent(wt.makeEvent_(e,t)),l.addQueuedOperation(!1,(()=>{this.adManager_&&this.adManager_.onManifestUpdated(this.isLive())}))},getBandwidthEstimate:()=>this.abrManager_.getBandwidthEstimate()},g=new Ae((()=>this.seekRange()));g.addEventListener("regionadd",(e=>{const t=e.region;this.onRegionEvent_(a.EventName.TimelineRegionAdded,t,l),l.addQueuedOperation(!1,(()=>{this.adManager_&&this.adManager_.onDashTimedMetadata(t)}))}));let f=null;d.streaming.observeQualityChanges&&(f=new Me((()=>this.getBufferedInfo())),f.addEventListener("qualitychange",(e=>{const t=e.quality,i=e.position;this.onMediaQualityChange_(t,i)})));const p=this.createNetworkingEngine(c);return l=new ke(e,i,n,t,{config:d,manifestPlayerInterface:m,regionTimeline:g,qualityObserver:f,manifestFilterer:_,networkingEngine:p,allowPrefetch:s,allowMakeAbrManager:o}),l}async guessMimeType_(e){console.assert(this.networkingEngine_,"Should have a net engine!");const t=this.config_.manifest.retryParameters;let i=await P.getMimeType(e,this.networkingEngine_,t);return"application/x-mpegurl"==i&&N.isApple()&&(i="application/vnd.apple.mpegurl"),i}shouldUseSrcEquals_(e,t){if(!N.supportsMediaSource())return!0;if(t){const e=""!=(this.video_||N.anyMediaElement()).canPlayType(t);if(!e)return!1;const i=_e.isSupported(t);return!(i&&(console.assert(e&&i,"Both native and MSE playback should be possible!"),!F.isHlsType(t)||!this.config_.streaming.preferNativeHls))}return!1}async initializeMediaSourceEngineInner_(){console.assert(N.supportsMediaSource(),"We should not be initializing media source on a platform that does not support media source."),console.assert(this.video_,"We should have a media element when initializing media source."),console.assert(null==this.mediaSourceEngine_,"We should not have a media source engine yet."),this.makeStateChangeEvent_("media-source");const e=this.config_.textDisplayFactory,t=e();this.lastTextFactory_=e;const i=this.createMediaSourceEngine(this.video_,t,((e,t,i)=>{this.processTimedMetadataMediaSrc_(e,t,i)}),this.lcevcDec_);i.configure(this.config_.mediaSource);const{segmentRelativeVttTiming:n}=this.config_.manifest;i.setSegmentRelativeVttTiming(n),await i.open(),this.mediaSourceEngine_=i}async loadInner_(e,t,i){console.assert(this.video_,"We should have a media element by now."),console.assert(this.manifest_,"The manifest should already be parsed."),console.assert(this.assetUri_,"We should have an asset uri by now."),console.assert(this.abrManager_,"We should have an abr manager by now."),this.makeStateChangeEvent_("load");const s=this.video_;this.playRateController_=new ze({getRate:()=>s.playbackRate,getDefaultRate:()=>s.defaultPlaybackRate,setRate:e=>{s.playbackRate=e},movePlayhead:e=>{s.currentTime+=e}});const r=()=>this.updateStateHistory_();this.loadEventManager_.listen(s,"playing",r),this.loadEventManager_.listen(s,"pause",r),this.loadEventManager_.listen(s,"ended",r),this.loadEventManager_.listen(s,"ratechange",(()=>this.onRateChange_())),this.setupLcevc_(this.config_),this.currentTextLanguage_=this.config_.preferredTextLanguage,this.currentTextRole_=this.config_.preferredTextRole,this.currentTextForced_=this.config_.preferForcedSubs,wt.applyPlayRange_(this.manifest_.presentationTimeline,this.config_.playRangeStart,this.config_.playRangeEnd),this.abrManager_.init(((e,t,i)=>this.switch_(e,t,i))),this.abrManager_.setMediaElement(s),this.abrManager_.setCmsdManager(this.cmsdManager_),this.streamingEngine_=this.createStreamingEngine(),this.streamingEngine_.configure(this.config_.streaming),this.loadMode_=wt.LoadMode.MEDIA_SOURCE,s.textTracks&&this.loadEventManager_.listen(s.textTracks,"addtrack",(e=>{const t=e;if(t.track){const e=t.track;console.assert(e instanceof TextTrack,"Wrong track type!"),"chapters"===e.kind&&this.activateChaptersTrack_(e)}})),this.dispatchEvent(wt.makeEvent_(a.EventName.Streaming));let o=t;const l=this.streamingEngine_.getCurrentVariant();l||o||(o=this.chooseVariant_(!0),console.assert(o,"Must choose an initial variant!"));const d=[],c=l||o;for(const e of[c.video,c.audio])e&&!e.segmentIndex&&d.push(e.createSegmentIndex());d.length>0&&await Promise.all(d),this.parser_&&this.parser_.onInitialVariantChosen&&this.parser_.onInitialVariantChosen(c),wt.applyPlayRange_(this.manifest_.presentationTimeline,this.config_.playRangeStart,this.config_.playRangeEnd),this.playhead_=this.createPlayhead(this.startTime_),this.playheadObservers_=this.createPlayheadObserversForMSE_(e);const h=Math.max(this.manifest_.minBufferTime,this.config_.streaming.rebufferingGoal);if(this.startBufferManagement_(s,h),l||(console.assert(o,"Must have choosen an initial variant!"),this.switchVariant_(o,!0,!1,0),this.config_.streaming.startAtSegmentBoundary&&this.playhead_.setStartTime(await this.adjustStartTime_(o,this.playhead_.getTime()))),this.playhead_.ready(),!this.getTextTracks().find((e=>e.active))){const e=this.chooseTextStream_();e&&this.addTextStreamToSwitchHistory_(e,!0),o&&this.setInitialTextState_(o,e),e&&this.shouldStreamText_()&&this.streamingEngine_.switchTextStream(e)}await this.streamingEngine_.start(i),this.config_.abr.enabled&&(this.abrManager_.enable(),this.onAbrStatusChanged_()),this.onTracksChanged_(),this.updateAbrManagerVariants_();const u=this.manifest_.variants.some((e=>e.primary));this.config_.preferredAudioLanguage||u||n.warning("No preferred audio language set. We have chosen an arbitrary language initially");const _=this.isLive();if(_&&(this.config_.streaming.liveSync||this.manifest_.serviceDescription||this.config_.streaming.liveSyncPanicMode)||this.config_.streaming.vodDynamicPlaybackRate){const e=()=>this.onTimeUpdate_();this.loadEventManager_.listen(s,"timeupdate",e)}else if(!_){const e=()=>this.onVideoProgress_();this.loadEventManager_.listen(s,"timeupdate",e),this.onVideoProgress_()}this.adManager_&&this.adManager_.onManifestUpdated(_),this.fullyLoaded_=!0,this.loadEventManager_.listenOnce(s,"loadedmetadata",(()=>{const t=Date.now()/1e3-e;this.stats_.setLoadLatency(t)}))}async srcEqualsInner_(e,t){this.makeStateChangeEvent_("src-equals"),console.assert(this.video_,"We should have a media element when loading."),console.assert(this.assetUri_,"We should have a valid uri when loading.");const i=this.video_;this.playhead_=new We(i);let s=!1;this.cleanupOnUnload_.push((()=>{s=!0})),null!=this.startTime_&&this.playhead_.setStartTime(this.startTime_),this.playRateController_=new ze({getRate:()=>i.playbackRate,getDefaultRate:()=>i.defaultPlaybackRate,setRate:e=>{i.playbackRate=e},movePlayhead:e=>{i.currentTime+=e}});const r=this.config_.streaming.rebufferingGoal;this.startBufferManagement_(i,r);const o=()=>this.updateStateHistory_();this.loadEventManager_.listen(i,"playing",o),this.loadEventManager_.listen(i,"pause",o),this.loadEventManager_.listen(i,"ended",o),this.loadEventManager_.listen(i,"ratechange",(()=>this.onRateChange_())),"none"!=i.preload&&this.loadEventManager_.listenOnce(i,"loadedmetadata",(()=>{const t=Date.now()/1e3-e;this.stats_.setLoadLatency(t)})),i.audioTracks&&(this.loadEventManager_.listen(i.audioTracks,"addtrack",(()=>this.onTracksChanged_())),this.loadEventManager_.listen(i.audioTracks,"removetrack",(()=>this.onTracksChanged_())),this.loadEventManager_.listen(i.audioTracks,"change",(()=>this.onTracksChanged_()))),i.textTracks&&(this.loadEventManager_.listen(i.textTracks,"addtrack",(e=>{const t=e;if(t.track){const e=t.track;switch(console.assert(e instanceof TextTrack,"Wrong track type!"),e.kind){case"metadata":this.processTimedMetadataSrcEqls_(e);break;case"chapters":this.activateChaptersTrack_(e);break;default:this.onTracksChanged_()}}})),this.loadEventManager_.listen(i.textTracks,"removetrack",(()=>this.onTracksChanged_())),this.loadEventManager_.listen(i.textTracks,"change",(()=>this.onTracksChanged_()))),i.src=this.cmcdManager_.appendSrcData(this.assetUri_,t),(N.isTizen()||N.isWebOS())&&i.load(),this.loadMode_=wt.LoadMode.SRC_EQUALS,this.dispatchEvent(wt.makeEvent_(a.EventName.Streaming));const d=new C;Ue.waitForReadyState(i,HTMLMediaElement.HAVE_METADATA,this.loadEventManager_,(()=>{this.playhead_.ready(),d.resolve()})),Ue.waitForReadyState(i,HTMLMediaElement.HAVE_CURRENT_DATA,this.loadEventManager_,(async()=>{this.setupPreferredAudioOnSrc_();const e=this.getFilteredTextTracks_();e.find((e=>"disabled"!=e.mode))?e.length>0&&(this.isTextVisible_=!0):await new Promise((e=>{this.loadEventManager_.listenOnce(i.textTracks,"change",e),new l(e).tickAfter(1)})),s||this.setupPreferredTextOnSrc_()})),i.error?d.reject(this.videoErrorToShakaError_()):"none"==i.preload&&(n.alwaysWarn('With <video preload="none">, the browser will not load anything until play() is called. We are unable to measure load latency in a meaningful way, and we cannot provide track info yet. Please do not use preload="none" with Shaka Player.'),d.resolve()),this.loadEventManager_.listenOnce(i,"error",(()=>{d.reject(this.videoErrorToShakaError_())})),await d;const c=this.isLive();if(c&&(this.config_.streaming.liveSync||this.config_.streaming.liveSyncPanicMode)||this.config_.streaming.vodDynamicPlaybackRate){const e=()=>this.onTimeUpdate_();this.loadEventManager_.listen(i,"timeupdate",e)}else if(!c){const e=()=>this.onVideoProgress_();this.loadEventManager_.listen(i,"timeupdate",e),this.onVideoProgress_()}if(this.adManager_&&(this.adManager_.onManifestUpdated(c),c)){let e=this.seekRange().end;this.loadEventManager_.listen(i,"progress",(()=>{const t=this.seekRange().end;e!=t&&(this.adManager_.onManifestUpdated(this.isLive()),e=t)}))}this.fullyLoaded_=!0}setupPreferredAudioOnSrc_(){const e=this.config_.preferredAudioLanguage;if(""==e)return;const t=this.config_.preferredVariantRole;this.selectAudioLanguage(e,t)}setupPreferredTextOnSrc_(){const e=this.config_.preferredTextLanguage;if(""==e)return;const t=this.config_.preferForcedSubs,i=this.config_.preferredTextRole;this.selectTextLanguage(e,i,t)}processTimedMetadataSrcEqls_(e){if("metadata"!=e.kind)return;e.mode="hidden",this.loadEventManager_.listen(e,"cuechange",(()=>{if(e.activeCues)for(const t of e.activeCues)this.dispatchMetadataEvent_(t.startTime,t.endTime,t.type,t.value),this.adManager_&&this.adManager_.onCueMetadataChange(t.value)}));const t=new l((()=>{const e=this.getMetadataTracks_();for(const t of e)t.mode="hidden"})).tickNow().tickAfter(.5);this.cleanupOnUnload_.push((()=>{t.stop()}))}processTimedMetadataMediaSrc_(e,t,i){for(const n of e)if(n.data&&n.cueTime&&n.frames){const e=n.cueTime+t;let s=i;s&&e>s&&(s=e);const a="org.id3";for(const t of n.frames){const i=t;this.dispatchMetadataEvent_(e,s,a,i)}this.adManager_&&this.adManager_.onHlsTimedMetadata(n,e)}}dispatchMetadataEvent_(e,t,i,n){console.assert(!t||e<=t,"Metadata start time should be less or equal to the end time!");const s=a.EventName.Metadata,r=(new Map).set("startTime",e).set("endTime",t).set("metadataType",i).set("payload",n);this.dispatchEvent(wt.makeEvent_(s,r))}activateChaptersTrack_(e){if(!e||"chapters"!=e.kind)return;e.mode="hidden";const t=new l((()=>{e.mode="hidden"})).tickNow().tickAfter(.5);this.cleanupOnUnload_.push((()=>{t.stop()}))}releaseAllMutexes(){this.mutex_.releaseAll()}createNetworkingEngine(e){e||(e=()=>null);const t=()=>e()?e().getAbrManager():this.abrManager_,i=()=>e()?e().getParser():this.parser_,n=t=>{e()?e().addQueuedOperation(!0,t):t()},s=t=>{e()?e().dispatchEvent(t):this.dispatchEvent(t)};return new D(((e,i,n,s)=>{const a=t();a&&a.segmentDownloaded(e,i,n,s)}),((e,t,i)=>{const r=a.EventName.DownloadHeadersReceived,o=(new Map).set("headers",e).set("request",t).set("requestType",i);s(wt.makeEvent_(r,o)),n((()=>{this.cmsdManager_&&this.cmsdManager_.processHeaders(e)}))}),((e,t,i,n)=>{const r=a.EventName.DownloadFailed,o=(new Map).set("request",e).set("error",t).set("httpResponseCode",i).set("aborted",n);s(wt.makeEvent_(r,o))}),((e,t,i)=>{n((()=>{this.cmcdManager_.applyData(e,t,i)}))}),((e,t,n,s)=>{const a=i();a&&a.banLocation&&a.banLocation(s)}))}createPlayhead(e){return console.assert(this.manifest_,"Must have manifest"),console.assert(this.video_,"Must have video"),new qe(this.video_,this.manifest_,this.config_.streaming,e,(()=>this.onSeek_()),(e=>this.dispatchEvent(e)))}createPlayheadObserversForMSE_(e){console.assert(this.manifest_,"Must have manifest"),console.assert(this.regionTimeline_,"Must have region timeline"),console.assert(this.video_,"Must have video element");const t=this.isLive()||e>0,i=new Ce(this.regionTimeline_,t);i.addEventListener("enter",(e=>{const t=e.region;this.onRegionEvent_(a.EventName.TimelineRegionEnter,t)})),i.addEventListener("exit",(e=>{const t=e.region;this.onRegionEvent_(a.EventName.TimelineRegionExit,t)})),i.addEventListener("skip",(e=>{const t=e.region;e.seeking||(this.onRegionEvent_(a.EventName.TimelineRegionEnter,t),this.onRegionEvent_(a.EventName.TimelineRegionExit,t))}));const n=new we(this.video_);return n.manage(i),this.qualityObserver_&&n.manage(this.qualityObserver_),n}startBufferManagement_(e,t){console.assert(!this.bufferObserver_,"No buffering observer should exist before initialization."),this.bufferObserver_=new Xe(1,2),this.bufferObserver_.setState(Xe.State.STARVING),this.updateBufferingSettings_(t),this.updateBufferState_(),this.loadEventManager_.listen(e,"waiting",(e=>this.pollBufferState_())),this.loadEventManager_.listen(e,"stalled",(e=>this.pollBufferState_())),this.loadEventManager_.listen(e,"canplaythrough",(e=>this.pollBufferState_())),this.loadEventManager_.listen(e,"progress",(e=>this.pollBufferState_()))}updateBufferingSettings_(e){const t=e,i=Math.min(wt.TYPICAL_BUFFERING_THRESHOLD_,e/2);this.bufferObserver_.setThresholds(t,i)}pollBufferState_(){let e;switch(console.assert(this.video_,"Need a media element to update the buffering observer"),console.assert(this.bufferObserver_,"Need a buffering observer to update"),this.loadMode_){case wt.LoadMode.SRC_EQUALS:e=this.isBufferedToEndSrc_();break;case wt.LoadMode.MEDIA_SOURCE:e=this.isBufferedToEndMS_();break;default:e=!1}const t=ge.bufferedAheadOf(this.video_.buffered,this.video_.currentTime);this.bufferObserver_.update(t,e)&&this.updateBufferState_()}createMediaSourceEngine(e,t,i,n){return new pe(e,t,i,n)}createCmcd_(){return new se({getBandwidthEstimate:()=>this.abrManager_?this.abrManager_.getBandwidthEstimate():NaN,getBufferedInfo:()=>this.getBufferedInfo(),getCurrentTime:()=>this.video_?this.video_.currentTime:0,getPlaybackRate:()=>this.getPlaybackRate(),getNetworkingEngine:()=>this.getNetworkingEngine(),getVariantTracks:()=>this.getVariantTracks(),isLive:()=>this.isLive()},this.config_.cmcd)}createCmsd_(){return new ae(this.config_.cmsd)}createStreamingEngine(){console.assert(this.abrManager_&&this.mediaSourceEngine_&&this.manifest_,"Must not be destroyed");const e={getPresentationTime:()=>this.playhead_?this.playhead_.getTime():0,getBandwidthEstimate:()=>this.abrManager_.getBandwidthEstimate(),mediaSourceEngine:this.mediaSourceEngine_,netEngine:this.networkingEngine_,onError:e=>this.onError_(e),onEvent:e=>this.dispatchEvent(e),onManifestUpdate:()=>this.onManifestUpdate_(),onSegmentAppended:(e,t)=>{this.onSegmentAppended_(e.startTime,e.endTime,t.type),this.abrManager_&&t.fastSwitching&&e.isPartial()&&e.isLastPartial()&&this.abrManager_.trySuggestStreams()},onInitSegmentAppended:(e,t)=>{const i=t.getMediaQuality();i&&this.qualityObserver_&&this.qualityObserver_.addMediaQualityChange(i,e)},beforeAppendSegment:(e,t)=>{},onMetadata:(e,t,i)=>{this.processTimedMetadataMediaSrc_(e,t,i)},disableStream:(e,t)=>this.disableStream(e,t)};return new xe(this.manifest_,e)}configure(e,t){console.assert(this.config_,"Config must not be null!"),console.assert("object"==typeof e||2==arguments.length,"String configs should have values!"),2==arguments.length&&"string"==typeof e&&(e=K.convertToConfigObject(e,t)),console.assert("object"==typeof e,"Should be an object!"),e.streaming&&"forceTransmuxTS"in e.streaming&&(re.deprecateFeature(5,"streaming.forceTransmuxTS configuration","Please Use mediaSource.forceTransmux instead."),e.mediaSource.mediaSource=e.streaming.forceTransmuxTS,delete e.streaming.forceTransmuxTS),e.streaming&&"forceTransmux"in e.streaming&&(re.deprecateFeature(5,"streaming.forceTransmux configuration","Please Use mediaSource.forceTransmux instead."),e.mediaSource.mediaSource=e.streaming.forceTransmux,delete e.streaming.forceTransmux),e.streaming&&e.streaming.lowLatencyMode&&(null==e.streaming.inaccurateManifestTolerance&&(e.streaming.inaccurateManifestTolerance=0),null==e.streaming.rebufferingGoal&&(e.streaming.rebufferingGoal=.01),null==e.streaming.segmentPrefetchLimit&&(e.streaming.segmentPrefetchLimit=2),null==e.streaming.retryParameters&&(e.streaming.retryParameters={}),null==e.streaming.retryParameters.baseDelay&&(e.streaming.retryParameters.baseDelay=100),null==e.manifest&&(e.manifest={}),null==e.manifest.retryParameters&&(e.manifest.retryParameters={}),null==e.manifest.retryParameters.baseDelay&&(e.manifest.retryParameters.baseDelay=100));const i=Z.mergeConfigObjects(this.config_,e,this.defaultConfig_());return this.applyConfig_(),i}applyConfig_(){if(this.manifestFilterer_=new Se(this.config_,this.maxHwRes_),this.parser_){const e=w.cloneObject(this.config_.manifest);this.video_&&"AUDIO"===this.video_.nodeName&&(e.disableVideo=!0),this.parser_.configure(e)}if(this.streamingEngine_){this.streamingEngine_.configure(this.config_.streaming);try{this.loadMode_!=wt.LoadMode.DESTROYED&&this.manifestFilterer_.filterManifestWithRestrictions(this.manifest_)&&this.onTracksChanged_()}catch(e){this.onError_(e)}this.abrManager_&&this.updateAbrManagerVariants_();const e=this.streamingEngine_.getCurrentVariant();e&&(e.allowedByApplication&&e.allowedByKeySystem||(n.debug("Choosing new variant after changing configuration"),this.chooseVariantAndSwitch_()))}if(this.networkingEngine_&&this.networkingEngine_.setForceHTTPS(this.config_.streaming.forceHTTPS),this.mediaSourceEngine_){this.mediaSourceEngine_.configure(this.config_.mediaSource);const{segmentRelativeVttTiming:e}=this.config_.manifest;this.mediaSourceEngine_.setSegmentRelativeVttTiming(e);const t=this.config_.textDisplayFactory;if(this.lastTextFactory_!=t){const e=t();this.mediaSourceEngine_.setTextDisplayer(e),this.lastTextFactory_=t,this.streamingEngine_&&this.streamingEngine_.reloadTextStream()}}if(this.abrManager_&&(this.abrManager_.configure(this.config_.abr),this.config_.abr.enabled?this.abrManager_.enable():this.abrManager_.disable(),this.onAbrStatusChanged_()),this.bufferObserver_){let e=this.config_.streaming.rebufferingGoal;this.manifest_&&(e=Math.max(e,this.manifest_.minBufferTime)),this.updateBufferingSettings_(e)}this.manifest_&&wt.applyPlayRange_(this.manifest_.presentationTimeline,this.config_.playRangeStart,this.config_.playRangeEnd),this.adManager_&&this.adManager_.configure(this.config_.ads),this.cmcdManager_&&this.cmcdManager_.configure(this.config_.cmcd),this.cmsdManager_&&this.cmsdManager_.configure(this.config_.cmsd)}getConfiguration(){console.assert(this.config_,"Config must not be null!");const e=this.defaultConfig_();return Z.mergeConfigObjects(e,this.config_,this.defaultConfig_()),e}getSharedConfiguration(){return console.assert(this.config_,"Cannot call getSharedConfiguration after call destroy!"),this.config_}getBufferFullness(){if(this.video_){const e=this.video_.buffered.length,t=e?this.video_.buffered.end(e-1):0,i=this.getConfiguration().streaming.bufferingGoal,n=Math.min(this.video_.currentTime+i,this.seekRange().end);if(t>=n)return 1;if(t<=this.video_.currentTime)return 0;if(t<n)return(t-this.video_.currentTime)/(n-this.video_.currentTime)}return 0}resetConfiguration(){console.assert(this.config_,"Cannot be destroyed");for(const e in this.config_)delete this.config_[e];Z.mergeConfigObjects(this.config_,this.defaultConfig_(),this.defaultConfig_()),this.applyConfig_()}getLoadMode(){return this.loadMode_}getManifestType(){return this.manifest_?this.manifest_.type:null}getMediaElement(){return this.video_}getNetworkingEngine(){return this.networkingEngine_}getAssetUri(){return this.assetUri_}getAdManager(){return this.adManager_?this.adManager_:null}isLive(){return this.manifest_?this.manifest_.presentationTimeline.isLive():!(!this.video_||!this.video_.src)&&this.video_.duration==1/0}isInProgress(){return!!this.manifest_&&this.manifest_.presentationTimeline.isInProgress()}isAudioOnly(){if(this.manifest_){const e=this.manifest_.variants;return!!e.length&&!e[0].video}return!(!this.video_||!this.video_.src)&&(this.video_.videoTracks?0==this.video_.videoTracks.length:0==this.video_.videoHeight)}seekRange(){if(this.manifest_){if(!this.fullyLoaded_&&this.manifest_.type==_e.HLS)return{start:0,end:0};const e=this.manifest_.presentationTimeline;return{start:e.getSeekRangeStart(),end:e.getSeekRangeEnd()}}if(this.video_&&this.video_.src){const e=this.video_.seekable;if(e.length)return{start:e.start(0),end:e.end(e.length-1)}}return{start:0,end:0}}goToLive(){this.isLive()?this.video_.currentTime=this.seekRange().end:n.warning("goToLive is for live streams!")}getExpiration(){return 1/0}getActiveSessionsMetadata(){return[]}getKeyStatuses(){return{}}isBuffering(){const e=Xe.State;return!!this.bufferObserver_&&this.bufferObserver_.getState()==e.STARVING}getPlaybackRate(){return this.video_?this.playRateController_?this.playRateController_.getRealRate():1:0}trickPlay(e){console.assert(0!=e,"Should never set a trick play rate of 0!"),0!=e?(this.trickPlayEventManager_.removeAll(),this.video_.paused&&this.video_.play(),this.playRateController_.set(e),this.loadMode_==wt.LoadMode.MEDIA_SOURCE&&(this.abrManager_.playbackRateChanged(e),this.streamingEngine_.setTrickPlay(Math.abs(e)>1)),this.isLive()&&this.trickPlayEventManager_.listen(this.video_,"timeupdate",(()=>{const t=this.video_.currentTime,i=this.seekRange(),n=this.config_.streaming.safeSeekOffset;e>0?t>=i.end&&this.cancelTrickPlay():t<=i.start+n&&this.cancelTrickPlay()}))):n.alwaysWarn("A trick play rate of 0 is unsupported!")}cancelTrickPlay(){const e=this.playRateController_.getDefaultRate();this.loadMode_==wt.LoadMode.SRC_EQUALS&&this.playRateController_.set(e),this.loadMode_==wt.LoadMode.MEDIA_SOURCE&&(this.playRateController_.set(e),this.abrManager_.playbackRateChanged(e),this.streamingEngine_.setTrickPlay(!1)),this.trickPlayEventManager_.removeAll()}getVariantTracks(){if(this.manifest_){const e=this.streamingEngine_?this.streamingEngine_.getCurrentVariant():null,t=[];let i=0;for(const n of this.manifest_.variants){if(!j.isPlayable(n))continue;const s=j.variantToTrack(n);s.active=n==e,s.active||1==i||null==e||n.video!=e.video||n.audio!=e.audio||(s.active=!0),s.active&&i++,t.push(s)}return console.assert(i<=1,"It should only have one active track"),t}return this.video_&&this.video_.audioTracks?Array.from(this.video_.audioTracks).map((e=>j.html5AudioTrackToTrack(e))):[]}getTextTracks(){if(this.manifest_){const e=this.streamingEngine_?this.streamingEngine_.getCurrentTextStream():null,t=[];for(const i of this.manifest_.textStreams){const n=j.textStreamToTrack(i);n.active=i==e,t.push(n)}return t}if(this.video_&&this.video_.src&&this.video_.textTracks){const e=this.getFilteredTextTracks_(),t=t;return e.map((e=>t.html5TextTrackToTrack(e)))}return[]}getImageTracks(){const e=e;let t=this.externalSrcEqualsThumbnailsStreams_;return this.manifest_&&(t=this.manifest_.imageStreams),t.map((t=>e.imageStreamToTrack(t)))}async getAllThumbnails(e){if(this.loadMode_!=wt.LoadMode.MEDIA_SOURCE&&this.loadMode_!=wt.LoadMode.SRC_EQUALS)return null;let t=this.externalSrcEqualsThumbnailsStreams_;this.manifest_&&(t=this.manifest_.imageStreams);const i=t.find((t=>t.id==e));if(!i)return null;i.segmentIndex||await i.createSegmentIndex();const n=[];return i.segmentIndex.forEachTopLevelReference((t=>{const s=this.parseTilesLayout_(t.getTilesLayout()||i.tilesLayout);if(s){const i=s.rows*s.columns,a=t.trueEndTime-t.startTime;for(let s=0;s<i;s++){const r=t.startTime+a*s/i;n.push(this.getThumbnails(e,r))}}})),(await Promise.all(n)).filter((e=>e))}parseTilesLayout_(e){if(!e)return null;const t=/(\d+)x(\d+)/.exec(e);return t?{columns:parseInt(t[1],10),rows:parseInt(t[2],10)}:(n.warning("Tiles layout does not contain a valid format (columns x rows)"),null)}async getThumbnails(e,t){if(this.loadMode_!=wt.LoadMode.MEDIA_SOURCE&&this.loadMode_!=wt.LoadMode.SRC_EQUALS)return null;let i=this.externalSrcEqualsThumbnailsStreams_;this.manifest_&&(i=this.manifest_.imageStreams);const n=i.find((t=>t.id==e));if(!n)return null;n.segmentIndex||await n.createSegmentIndex();const s=n.segmentIndex.find(t);if(null==s)return null;const a=n.segmentIndex.get(s),r=this.parseTilesLayout_(a.getTilesLayout()||n.tilesLayout);if(!r)return null;const o=n.width||0,l=n.height||0;let d=o/r.columns,c=l/r.rows;const h=r.columns*r.rows,u=a.trueEndTime-a.startTime,_=a.getTileDuration()||u/h;let m=a.startTime,g=0,f=0;if(h>1){const e=Math.floor((t-a.startTime)/_);m=a.startTime+e*_,g=e%r.columns*d,f=Math.floor(e/r.columns)*c}let p=!1;const T=a.getThumbnailSprite();return T&&(p=!0,c=T.height,g=T.positionX,f=T.positionY,d=T.width),{segment:a,imageHeight:l,imageWidth:o,height:c,positionX:g,positionY:f,startTime:m,duration:_,uris:a.getUris(),width:d,sprite:p}}selectTextTrack(e){if(this.manifest_&&this.streamingEngine_){const t=this.manifest_.textStreams.find((t=>t.id==e.id));if(!t)return void n.error("No stream with id",e.id);if(t==this.streamingEngine_.getCurrentTextStream())return void n.debug("Text track already selected.");this.addTextStreamToSwitchHistory_(t,!1),this.streamingEngine_.switchTextStream(t),this.onTextChanged_(),this.currentTextLanguage_=t.language}else if(this.video_&&this.video_.src&&this.video_.textTracks){const t=this.getFilteredTextTracks_();for(const i of t)j.html5TrackId(i)==e.id?i.mode=this.isTextVisible_?"showing":"hidden":i.mode="disabled";this.onTextChanged_()}}selectVariantTrack(e,t=!1,i=0){if(this.manifest_&&this.streamingEngine_){this.config_.abr.enabled&&n.alwaysWarn("Changing tracks while abr manager is enabled will likely result in the selected track being overriden. Consider disabling abr before calling selectVariantTrack().");const s=this.manifest_.variants.find((t=>t.id==e.id));if(!s)return void n.error("No variant with id",e.id);if(!j.isPlayable(s))return void n.error("Unable to switch to restricted track",e.id);this.switchVariant_(s,!1,t,i),this.currentAdaptationSetCriteria_=new Pe(s,this.config_.mediaSource.codecSwitchingStrategy,this.config_.manifest.dash.enableAudioGroups),this.updateAbrManagerVariants_()}else if(this.video_&&this.video_.audioTracks){const t=Array.from(this.video_.audioTracks);for(const i of t)if(j.html5TrackId(i)==e.id)return void this.switchHtml5Track_(i)}}getAudioLanguagesAndRoles(){return wt.getLanguageAndRolesFrom_(this.getVariantTracks())}getTextLanguagesAndRoles(){return wt.getLanguageAndRolesFrom_(this.getTextTracks())}getAudioLanguages(){return Array.from(wt.getLanguagesFrom_(this.getVariantTracks()))}getTextLanguages(){return Array.from(wt.getLanguagesFrom_(this.getTextTracks()))}selectAudioLanguage(e,t,i=0,n=0){if(this.manifest_&&this.playhead_){this.currentAdaptationSetCriteria_=new Ne(e,t||"",i,"",!1,"","","",this.config_.mediaSource.codecSwitchingStrategy,this.config_.manifest.dash.enableAudioGroups);const s=(e,t)=>e.video||t.video?e.video&&t.video?Math.abs((e.video.height||0)-(t.video.height||0))+Math.abs((e.video.width||0)-(t.video.width||0)):1/0:0,a=this.streamingEngine_.getCurrentVariant(),r=this.currentAdaptationSetCriteria_.create(this.manifest_.variants);let o=null;for(const e of r.values())(!o||s(o,a)>s(e,a))&&(o=e);if(o){const e=j.variantToTrack(o);return void this.selectVariantTrack(e,!0,n)}this.chooseVariantAndSwitch_()}else if(this.video_&&this.video_.audioTracks){const i=j.filterStreamsByLanguageAndRole(this.getVariantTracks(),e,t||"",!1)[0];i&&this.selectVariantTrack(i)}}selectTextLanguage(e,t,i=!1){if(this.manifest_&&this.playhead_){this.currentTextLanguage_=e,this.currentTextRole_=t||"",this.currentTextForced_=i;const s=this.chooseTextStream_();if(s){if(s==this.streamingEngine_.getCurrentTextStream())return void n.debug("Text track already selected.");this.addTextStreamToSwitchHistory_(s,!1),this.shouldStreamText_()&&(this.streamingEngine_.switchTextStream(s),this.onTextChanged_())}}else{const n=j.filterStreamsByLanguageAndRole(this.getTextTracks(),e,t||"",i)[0];n&&this.selectTextTrack(n)}}selectVariantsByLabel(e,t=!0,i=0){if(this.manifest_&&this.playhead_){let s=null;for(const t of this.manifest_.variants)if(t.audio.label==e){s=t;break}if(null==s)return void n.warning("No variants were found with label: "+e+". Ignoring the request to switch.");this.currentAdaptationSetCriteria_=new Ne(s.language,"",0,"",!1,"",e,"",this.config_.mediaSource.codecSwitchingStrategy,this.config_.manifest.dash.enableAudioGroups),this.chooseVariantAndSwitch_(t,i)}else if(this.video_&&this.video_.audioTracks){const t=Array.from(this.video_.audioTracks);let i=null;for(const n of t)n.label==e&&(i=n);i&&this.switchHtml5Track_(i)}}isTextTrackVisible(){const e=this.isTextVisible_;if(this.mediaSourceEngine_&&this.loadMode_==wt.LoadMode.MEDIA_SOURCE){const t=this.mediaSourceEngine_.getTextDisplayer().isTextVisible();return console.assert(t==e,"text visibility has fallen out of sync"),t}return this.video_&&this.video_.src&&this.video_.textTracks?this.getFilteredTextTracks_().some((e=>"showing"==e.mode)):e}getChaptersTracks(){if(this.video_&&this.video_.src&&this.video_.textTracks){const e=this.getChaptersTracks_(),t=t;return e.map((e=>t.html5TextTrackToTrack(e)))}return[]}getChapters(e){if(!this.video_||!this.video_.src||!this.video_.textTracks)return[];const t=H.normalize(e),i=this.getChaptersTracks_().filter((e=>H.normalize(e.language)==t));if(!i||!i.length)return[];const n=[],s=new Set;for(const e of i)if(e&&e.cues)for(const t of e.cues){let e=t.id;e&&""!=e||(e=t.startTime+"-"+t.endTime+"-"+t.text);const i={id:e,title:t.text,startTime:t.startTime,endTime:t.endTime};s.has(e)||(n.push(i),s.add(e))}return n}getFilteredTextTracks_(){return console.assert(this.video_.textTracks,"TextTracks should be valid."),Array.from(this.video_.textTracks).filter((e=>"metadata"!=e.kind&&"chapters"!=e.kind&&e.label!=wt.TextTrackLabel))}getMetadataTracks_(){return console.assert(this.video_.textTracks,"TextTracks should be valid."),Array.from(this.video_.textTracks).filter((e=>"metadata"==e.kind))}getChaptersTracks_(){return console.assert(this.video_.textTracks,"TextTracks should be valid."),Array.from(this.video_.textTracks).filter((e=>"chapters"==e.kind))}setTextTrackVisibility(e){const t=!!e;if(this.isTextVisible_!=t){if(this.isTextVisible_=t,this.loadMode_==wt.LoadMode.MEDIA_SOURCE){if(this.mediaSourceEngine_.getTextDisplayer().setTextVisibility(t),!this.config_.streaming.alwaysStreamText)if(t)if(this.streamingEngine_.getCurrentTextStream());else{const e=j.filterStreamsByLanguageAndRole(this.manifest_.textStreams,this.currentTextLanguage_,this.currentTextRole_,this.currentTextForced_);e.length>0&&(this.streamingEngine_.switchTextStream(e[0]),this.onTextChanged_())}else this.streamingEngine_.unloadTextStream()}else if(this.video_&&this.video_.src&&this.video_.textTracks){const e=this.getFilteredTextTracks_();for(const i of e)"disabled"!=i.mode&&(i.mode=t?"showing":"hidden")}this.onTextTrackVisibility_()}}getPlayheadTimeAsDate(){if(!this.isLive())return n.warning("getPlayheadTimeAsDate is for live streams!"),null;let e=0;if(this.playhead_)e=this.playhead_.getTime();else{if(null==this.startTime_)return new Date;e=this.startTime_}if(this.manifest_){const t=this.manifest_.presentationTimeline,i=t.getInitialProgramDateTime()||t.getPresentationStartTime();return new Date(1e3*(i+e))}if(this.video_&&this.video_.getStartDate){const t=this.video_.getStartDate();return isNaN(t.getTime())?(n.warning("EXT-X-PROGRAM-DATETIME required to get playhead time as Date!"),null):new Date(t.getTime()+1e3*e)}return n.warning("No way to get playhead time as Date!"),null}getPresentationStartTimeAsDate(){if(!this.isLive())return n.warning("getPresentationStartTimeAsDate is for live streams!"),null;if(this.manifest_){const e=this.manifest_.presentationTimeline.getPresentationStartTime();return console.assert(null!=e,"Presentation start time should not be null!"),new Date(1e3*e)}if(this.video_&&this.video_.getStartDate){const e=this.video_.getStartDate();return isNaN(e.getTime())?(n.warning("EXT-X-PROGRAM-DATETIME required to get presentation start time as Date!"),null):e}return n.warning("No way to get presentation start time as Date!"),null}getSegmentAvailabilityDuration(){return this.isLive()?this.manifest_?this.manifest_.presentationTimeline.getSegmentAvailabilityDuration():(n.warning("No way to get segment segment availability duration!"),null):(n.warning("getSegmentAvailabilityDuration is for live streams!"),null)}getBufferedInfo(){if(this.loadMode_==wt.LoadMode.MEDIA_SOURCE)return this.mediaSourceEngine_.getBufferedInfo();const e={total:[],audio:[],video:[],text:[]};if(this.loadMode_==wt.LoadMode.SRC_EQUALS){const t=t;e.total=t.getBufferedInfo(this.video_.buffered)}return e}getStats(){if(this.loadMode_!=wt.LoadMode.MEDIA_SOURCE&&this.loadMode_!=wt.LoadMode.SRC_EQUALS)return ne.getEmptyBlob();this.updateStateHistory_(),console.assert(this.video_,"If we have stats, we should have video_");const e=this.video_,t=e.currentTime/e.duration;if(isNaN(t)||this.stats_.setCompletionPercent(Math.round(100*t)),this.playhead_&&(this.stats_.setGapsJumped(this.playhead_.getGapsJumped()),this.stats_.setStallsDetected(this.playhead_.getStallsDetected())),e.getVideoPlaybackQuality){const t=e.getVideoPlaybackQuality();this.stats_.setDroppedFrames(Number(t.droppedVideoFrames),Number(t.totalVideoFrames)),this.stats_.setCorruptedFrames(Number(t.corruptedVideoFrames))}if(this.loadMode_==wt.LoadMode.MEDIA_SOURCE){const t=this.streamingEngine_.getCurrentVariant(),i=this.streamingEngine_.getCurrentTextStream();if(t){const e=this.playRateController_?this.playRateController_.getRealRate():1;let n=e*t.bandwidth;i&&i.bandwidth&&(n+=e*i.bandwidth),this.stats_.setCurrentStreamBandwidth(n)}if(t&&t.video&&this.stats_.setResolution(t.video.width||NaN,t.video.height||NaN),this.isLive()){const t=this.getPresentationStartTimeAsDate().valueOf()+1e3*e.currentTime,i=(Date.now()-t)/1e3;this.stats_.setLiveLatency(i)}if(this.manifest_&&this.manifest_.presentationTimeline){const e=this.manifest_.presentationTimeline.getMaxSegmentDuration();this.stats_.setMaxSegmentDuration(e)}const n=this.abrManager_.getBandwidthEstimate();this.stats_.setBandwidthEstimate(n)}return this.loadMode_==wt.LoadMode.SRC_EQUALS&&this.stats_.setResolution(e.videoWidth||NaN,e.videoHeight||NaN),this.stats_.getBlob()}async addTextTrackAsync(e,t,i,s,a,r,o=!1){if(this.loadMode_!=wt.LoadMode.MEDIA_SOURCE&&this.loadMode_!=wt.LoadMode.SRC_EQUALS)throw n.error("Must call load() and wait for it to resolve before adding text tracks."),new b(b.Severity.RECOVERABLE,b.Category.PLAYER,b.Code.CONTENT_NOT_LOADED);"subtitles"!=i&&"captions"!=i&&n.alwaysWarn("Using a kind value different of `subtitles` or `captions` can cause unwanted issues."),s||(s=await this.getTextMimetype_(e));let l=[];if(this.adManager_&&(l=this.adManager_.getCuePoints()),this.loadMode_==wt.LoadMode.SRC_EQUALS){o&&(i="forced"),await this.addSrcTrackElement_(e,t,i,s,r||"",l);const a=a,d=a.normalize(t),c=this.getTextTracks().find((e=>a.normalize(e.language)==d&&e.label==(r||"")&&e.kind==i));if(c)return this.onTracksChanged_(),c;throw n.error("Cannot add this text when loaded with src="),new b(b.Severity.RECOVERABLE,b.Category.TEXT,b.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS)}const d=U.ContentType;let c=this.video_.duration;if(this.manifest_&&(c=this.manifest_.presentationTimeline.getDuration()),c==1/0)throw new b(b.Severity.RECOVERABLE,b.Category.MANIFEST,b.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM);if(l.length){console.assert(this.networkingEngine_,"Need networking engine.");const t=await this.getTextData_(e,this.networkingEngine_,this.config_.streaming.retryParameters),i=this.convertToWebVTT_(t,s,l),n=new Blob([i],{type:"text/vtt"});e=pe.createObjectURL(n),s="text/vtt"}const h={id:this.nextExternalStreamId_++,originalId:null,groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:ve.forSingleSegment(0,c,[e]),mimeType:s||"",codecs:a||"",kind:i,language:t,originalLanguage:t,label:r||null,type:d.TEXT,primary:!1,trickModeVideo:null,emsgSchemeIdUris:null,roles:[],forced:Boolean(o),channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,accessibilityPurpose:null,external:!0,fastSwitching:!1},u=F.getFullType(h.mimeType,h.codecs);if(!z.isTypeSupported(u))throw new b(b.Severity.CRITICAL,b.Category.TEXT,b.Code.MISSING_TEXT_PLUGIN,s);return this.manifest_.textStreams.push(h),this.onTracksChanged_(),j.textStreamToTrack(h)}async addThumbnailsTrack(e,t){if(this.loadMode_!=wt.LoadMode.MEDIA_SOURCE&&this.loadMode_!=wt.LoadMode.SRC_EQUALS)throw n.error("Must call load() and wait for it to resolve before adding image tracks."),new b(b.Severity.RECOVERABLE,b.Category.PLAYER,b.Code.CONTENT_NOT_LOADED);if(t||(t=await this.getTextMimetype_(e)),"text/vtt"!=t)throw new b(b.Severity.RECOVERABLE,b.Category.TEXT,b.Code.UNSUPPORTED_EXTERNAL_THUMBNAILS_URI,e);const i=U.ContentType;let s=this.video_.duration;if(this.manifest_&&(s=this.manifest_.presentationTimeline.getDuration()),s==1/0)throw new b(b.Severity.RECOVERABLE,b.Category.MANIFEST,b.Code.CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_LIVE_STREAM);console.assert(this.networkingEngine_,"Need networking engine.");const a=await this.getTextData_(e,this.networkingEngine_,this.config_.streaming.retryParameters),r=z.findParser(t);if(!r)throw new b(b.Severity.CRITICAL,b.Category.TEXT,b.Code.MISSING_TEXT_PLUGIN,t);const o=r(),l={periodStart:0,segmentStart:0,segmentEnd:s,vttOffset:0},c=d.toUint8(a),h=o.parseMedia(c,l,e),u=[];for(const t of h){let i=null;const n=()=>(null==i&&(i=U.resolveUris([e],[t.payload])),i||[]),s=new Ee(t.startTime,t.endTime,n,0,null,null,0,0,1/0);if(t.payload.includes("#xywh")){const e=t.payload.split("#xywh=")[1].split(",");4===e.length&&s.setThumbnailSprite({height:parseInt(e[3],10),positionX:parseInt(e[0],10),positionY:parseInt(e[1],10),width:parseInt(e[2],10)})}u.push(s)}const _={id:this.nextExternalStreamId_++,originalId:null,groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:new ve(u),mimeType:t||"",codecs:"",kind:"",language:"und",originalLanguage:null,label:null,type:i.IMAGE,primary:!1,trickModeVideo:null,emsgSchemeIdUris:null,roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,tilesLayout:"1x1",accessibilityPurpose:null,external:!0,fastSwitching:!1};return this.loadMode_==wt.LoadMode.SRC_EQUALS?this.externalSrcEqualsThumbnailsStreams_.push(_):this.manifest_.imageStreams.push(_),this.onTracksChanged_(),j.imageStreamToTrack(_)}async addChaptersTrack(e,t,i){if(this.loadMode_!=wt.LoadMode.MEDIA_SOURCE&&this.loadMode_!=wt.LoadMode.SRC_EQUALS)throw n.error("Must call load() and wait for it to resolve before adding chapters tracks."),new b(b.Severity.RECOVERABLE,b.Category.PLAYER,b.Code.CONTENT_NOT_LOADED);i||(i=await this.getTextMimetype_(e));let s=[];this.adManager_&&(s=this.adManager_.getCuePoints());const a=await this.addSrcTrackElement_(e,t,"chapters",i,"",s),r=this.getChaptersTracks().find((e=>e.language==t));if(r)return await new Promise(((e,t)=>{this.loadEventManager_.listenOnce(a,"load",e),this.loadEventManager_.listenOnce(a,"error",(e=>{t(new b(b.Severity.RECOVERABLE,b.Category.TEXT,b.Code.CHAPTERS_TRACK_FAILED))}))})),this.onTracksChanged_(),r;throw n.error("Cannot add this text when loaded with src="),new b(b.Severity.RECOVERABLE,b.Category.TEXT,b.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS)}async getTextMimetype_(e){let t;try{console.assert(this.networkingEngine_,"Need networking engine."),t=await P.getMimeType(e,this.networkingEngine_,this.config_.streaming.retryParameters)}catch(e){}if(t)return t;throw n.error("The mimeType has not been provided and it could not be deduced from its uri."),new b(b.Severity.RECOVERABLE,b.Category.TEXT,b.Code.TEXT_COULD_NOT_GUESS_MIME_TYPE,e)}async addSrcTrackElement_(e,t,i,n,s,a){if("text/vtt"!=n||a.length){console.assert(this.networkingEngine_,"Need networking engine.");const t=await this.getTextData_(e,this.networkingEngine_,this.config_.streaming.retryParameters),i=this.convertToWebVTT_(t,n,a),s=new Blob([i],{type:"text/vtt"});e=pe.createObjectURL(s),n="text/vtt"}const r=document.createElement("track");return r.src=this.cmcdManager_.appendTextTrackData(e),r.label=s,r.kind=i,r.srclang=t,this.video_.getAttribute("crossorigin")||this.video_.setAttribute("crossorigin","anonymous"),this.video_.appendChild(r),r}async getTextData_(e,t,i){const n=D.RequestType.SEGMENT,s=D.makeRequest([e],i);return s.method="GET",this.cmcdManager_.applyTextData(s),(await t.request(n,s).promise).data}convertToWebVTT_(e,t,i){const n=z.findParser(t);if(n){const t=n(),s={periodStart:0,segmentStart:0,segmentEnd:this.video_.duration,vttOffset:0},a=d.toUint8(e),r=t.parseMedia(a,s,null);return et.convert(r,i)}throw new b(b.Severity.CRITICAL,b.Category.TEXT,b.Code.MISSING_TEXT_PLUGIN,t)}setMaxHardwareResolution(e,t){this.maxHwRes_.width=e,this.maxHwRes_.height=t}retryStreaming(e=.1){return this.loadMode_==wt.LoadMode.MEDIA_SOURCE&&this.streamingEngine_.retry(e)}getManifest(){return n.alwaysWarn("Shaka Player's internal Manifest structure is NOT covered by semantic versioning compatibility guarantees. It may change at any time! Please consider filing a feature request for whatever you use getManifest() for."),this.manifest_}getManifestParserFactory(){return this.parserFactory_}addVariantToSwitchHistory_(e,t){this.stats_.getSwitchHistory().updateCurrentVariant(e,t)}addTextStreamToSwitchHistory_(e,t){this.stats_.getSwitchHistory().updateCurrentText(e,t)}defaultConfig_(){const e=Z.createDefault();return e.streaming.failureCallback=e=>{this.defaultStreamingFailureCallback_(e)},e.textDisplayFactory=()=>this.videoContainer_?new Ze(this.video_,this.videoContainer_):HTMLMediaElement.prototype.addTextTrack?new $e(this.video_,wt.TextTrackLabel):(n.warning("Text tracks are not supported by the browser, disabling."),new Je),e}setVideoContainer(e){this.videoContainer_=e}defaultStreamingFailureCallback_(e){if(!this.isLive())return;let t=null;e.code==b.Code.BAD_HTTP_STATUS||e.code==b.Code.HTTP_ERROR?t=1:e.code==b.Code.TIMEOUT&&(t=.1),null!=t&&(e.severity=b.Severity.RECOVERABLE,n.warning("Live streaming error. Retrying automatically..."),this.retryStreaming(t))}makeTextStreamsForClosedCaptions_(e){const t=U.ContentType,i=U.TextStreamKind,n=F.CEA608_CLOSED_CAPTION_MIMETYPE,s=F.CEA708_CLOSED_CAPTION_MIMETYPE,a=new Set;for(const t of e.textStreams)t.mimeType!=n&&t.mimeType!=s||a.add(t.originalId);for(const r of e.variants){const o=r.video;if(o&&o.closedCaptions)for(const r of o.closedCaptions.keys())if(!a.has(r)){const l=r.startsWith("CC")?n:s,d=new Ie,c=o.closedCaptions.get(r),h={id:this.nextExternalStreamId_++,originalId:r,groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:d,mimeType:l,codecs:"",kind:i.CLOSED_CAPTION,language:c,originalLanguage:c,label:null,type:t.TEXT,primary:!1,trickModeVideo:null,emsgSchemeIdUris:null,roles:o.roles,forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,accessibilityPurpose:null,external:!1,fastSwitching:!1};e.textStreams.push(h),a.add(r)}}}async adjustStartTime_(e,t){const i=e.audio,n=e.video,s=async(e,t)=>{if(!e)return null;await e.createSegmentIndex();const i=e.segmentIndex.getIteratorForTime(t),n=i?i.next().value:null;if(!n)return null;const s=n.startTime;return console.assert(s<=t,"Segment should start before target time!"),s},a=await s(i,t),r=await s(n,t);return null!=r&&null!=a?Math.max(r,a):null!=r?r:null!=a?a:t}updateBufferState_(){const e=this.isBuffering();n.v2("Player changing buffering state to",e),this.stats_&&this.bufferObserver_&&this.playhead_&&(this.cmcdManager_&&this.cmcdManager_.setBuffering(e),this.updateStateHistory_());const t=a.EventName.Buffering,i=(new Map).set("buffering",e);this.dispatchEvent(wt.makeEvent_(t,i))}onRateChange_(){const e=this.video_.playbackRate;if(0==e)return;this.playRateController_&&this.playRateController_.set(e);const t=wt.makeEvent_(a.EventName.RateChange);this.dispatchEvent(t)}updateStateHistory_(){if(!this.stats_)return;if(!this.bufferObserver_)return;const e=Xe.State,t=this.stats_.getStateHistory();let i="playing";if(this.bufferObserver_.getState()==e.STARVING?i="buffering":this.video_.paused?i="paused":this.video_.ended&&(i="ended"),t.update(i)){const e=a.EventName.StateChanged,t=(new Map).set("newstate",i);this.dispatchEvent(wt.makeEvent_(e,t))}}onTimeUpdate_(){const e=this.video_.playbackRate,t=this.isLive();if(this.config_.streaming.vodDynamicPlaybackRate&&!t){const t=this.config_.streaming.vodDynamicPlaybackRateLowBufferRate,i=this.getBufferFullness(),s=this.config_.streaming.vodDynamicPlaybackRateBufferRatio;i<=s?e!=t&&(n.debug("Buffer fullness ratio ("+i+") is less than the vodDynamicPlaybackRateBufferRatio ("+s+"). Updating playbackRate to "+t),this.trickPlay(t)):1==i&&e!==this.playRateController_.getDefaultRate()&&(n.debug("Buffer is full. Cancel trick play."),this.cancelTrickPlay())}if(!t)return;const i=this.seekRange();if(!Number.isFinite(i.end))return;if(this.video_.currentTime<i.start)return;let s,a,r,o;this.config_.streaming.liveSync?(s=this.config_.streaming.liveSyncMaxLatency,a=this.config_.streaming.liveSyncPlaybackRate):this.manifest_&&this.manifest_.serviceDescription&&(s=this.manifest_.serviceDescription.maxLatency||this.config_.streaming.liveSyncMaxLatency,a=this.manifest_.serviceDescription.maxPlaybackRate||this.config_.streaming.liveSyncPlaybackRate),this.config_.streaming.liveSync?(r=this.config_.streaming.liveSyncMinLatency,o=this.config_.streaming.liveSyncMinPlaybackRate):this.manifest_&&this.manifest_.serviceDescription&&(r=this.manifest_.serviceDescription.minLatency||this.config_.streaming.liveSyncMinLatency,o=this.manifest_.serviceDescription.minPlaybackRate||this.config_.streaming.liveSyncMinPlaybackRate);const l=i.end-this.video_.currentTime;let d=0;if(this.loadMode_==wt.LoadMode.SRC_EQUALS){const e=this.video_.buffered;if(e.length>0){const t=e.end(e.length-1);d=Math.max(a,t-i.end)}}const c=this.config_.streaming.liveSyncPanicMode,h=1e3*this.config_.streaming.liveSyncPanicThreshold,u=Date.now()-this.bufferObserver_.getLastRebufferTime();c&&!o&&(o=this.config_.streaming.liveSyncMinPlaybackRate),c&&o&&u<=h?e!=o&&(n.debug("Time since last rebuffer ("+u+"s) is less than the liveSyncPanicThreshold ("+h+"s). Updating playbackRate to "+o),this.trickPlay(o)):s&&a&&l-d>s?e!=a&&(n.debug("Latency ("+l+"s) is greater than liveSyncMaxLatency ("+s+"s). Updating playbackRate to "+a),this.trickPlay(a)):r&&o&&l-d<r?e!=o&&(n.debug("Latency ("+l+"s) is smaller than liveSyncMinLatency ("+r+"s). Updating playbackRate to "+o),this.trickPlay(o)):e!==this.playRateController_.getDefaultRate()&&this.cancelTrickPlay()}onVideoProgress_(){if(!this.video_)return;let e=!1;const t=this.video_.currentTime/this.video_.duration;if(!isNaN(t)){const i=Math.round(100*t);if(isNaN(this.completionPercent_))this.completionPercent_=i,e=!0;else{const t=Math.max(this.completionPercent_,i);this.completionPercent_!=t&&(this.completionPercent_=t,e=!0)}}if(e){let e;0==this.completionPercent_?e=wt.makeEvent_(a.EventName.Started):25==this.completionPercent_?e=wt.makeEvent_(a.EventName.FirstQuartile):50==this.completionPercent_?e=wt.makeEvent_(a.EventName.Midpoint):75==this.completionPercent_?e=wt.makeEvent_(a.EventName.ThirdQuartile):100==this.completionPercent_&&(e=wt.makeEvent_(a.EventName.Complete)),e&&this.dispatchEvent(e)}}onSeek_(){this.playheadObservers_&&this.playheadObservers_.notifyOfSeek(),this.streamingEngine_&&this.streamingEngine_.seeked(),this.bufferObserver_&&this.pollBufferState_()}updateAbrManagerVariants_(){try{console.assert(this.manifest_,"Manifest should exist by now!"),this.manifestFilterer_.checkRestrictedVariants(this.manifest_)}catch(e){return this.onError_(e),!1}const e=j.getPlayableVariants(this.manifest_.variants),t=this.currentAdaptationSetCriteria_.create(e);return this.abrManager_.setVariants(Array.from(t.values())),!0}chooseVariant_(e=!1){return this.updateAbrManagerVariants_()?this.abrManager_.chooseVariant(e):null}checkVariants_(){console.assert(this.manifest_,"Should have manifest!");const e=Date.now()/1e3;let t=!1;const i=e=>{let t="";return e.video&&(t+="video:"+e.video.id),e.audio&&(t+=t?"&":"",t+="audio:"+e.audio.id),t};for(const s of this.manifest_.variants)s.disabledUntilTime>0&&s.disabledUntilTime<=e&&(s.disabledUntilTime=0,t=!0,n.v2("Re-enabled variant with "+i(s)));this.manifest_.variants.every((e=>(console.assert(e.disabledUntilTime>=0,"|variant.disableTimeUntilTime| must always be >= 0"),0===e.disabledUntilTime)))&&this.checkVariantsTimer_.stop(),t&&this.chooseVariantAndSwitch_(!0,void 0,!1,!1)}chooseTextStream_(){return j.filterStreamsByLanguageAndRole(this.manifest_.textStreams,this.currentTextLanguage_,this.currentTextRole_,this.currentTextForced_)[0]||null}chooseVariantAndSwitch_(e=!0,t=0,i=!1,n=!0){console.assert(this.config_,"Must not be destroyed");const s=this.chooseVariant_();s&&this.switchVariant_(s,n,e,t,i)}switchVariant_(e,t,i,s,a=!1){const r=this.streamingEngine_.getCurrentVariant();if(e==r)return n.debug("Variant already selected."),void(i&&this.streamingEngine_.switchVariant(e,i,s,!0));this.addVariantToSwitchHistory_(e,t),this.streamingEngine_.switchVariant(e,i,s,a,t);let o=null;r&&(o=j.variantToTrack(r));const l=j.variantToTrack(e);t?this.onAdaptation_(o,l):this.onVariantChanged_(o,l)}switchHtml5Track_(e){console.assert(this.video_&&this.video_.audioTracks,"Video and video.audioTracks should not be null!");const t=Array.from(this.video_.audioTracks).find((e=>e.enabled));e.enabled=!0,e.id!==t.id&&(t.enabled=!1);const i=j.html5AudioTrackToTrack(t),n=j.html5AudioTrackToTrack(e);this.onVariantChanged_(i,n)}setInitialTextState_(e,t){t?(e.audio&&this.shouldInitiallyShowText_(e.audio,t)&&(this.isTextVisible_=!0),this.isTextVisible_&&(this.mediaSourceEngine_.getTextDisplayer().setTextVisibility(!0),console.assert(this.shouldStreamText_(),"Should be streaming text")),this.onTextTrackVisibility_()):this.isTextVisible_=!1}shouldInitiallyShowText_(e,t){if(0==this.config_.autoShowText)return!1;if(1==this.config_.autoShowText)return!0;const i=i,s=i.normalize(this.config_.preferredTextLanguage),a=i.normalize(t.language);if(2==this.config_.autoShowText)return i.areLanguageCompatible(a,s);if(3==this.config_.autoShowText){const t=i.normalize(e.language);return i.areLanguageCompatible(a,s)&&!i.areLanguageCompatible(t,a)}return n.alwaysWarn("Invalid autoShowText setting!"),!1}onManifestUpdate_(){this.parser_&&this.parser_.update&&this.parser_.update()}onSegmentAppended_(e,t,i){if(this.playhead_){this.playhead_.notifyOfBufferingChange();const e=this.mediaSourceEngine_.bufferStart(i);!this.isLive()&&this.video_.paused&&null!=e&&e>0&&this.playhead_.getTime()<e&&this.playhead_.setStartTime(e)}this.pollBufferState_();const n=(new Map).set("start",e).set("end",t).set("contentType",i);this.dispatchEvent(wt.makeEvent_(a.EventName.SegmentAppended,n))}switch_(e,t=!1,i=0){n.debug("switch_"),console.assert(this.config_.abr.enabled,"AbrManager should not call switch while disabled!"),console.assert(this.manifest_,"We need a manifest to switch variants."),this.streamingEngine_&&e!=this.streamingEngine_.getCurrentVariant()&&this.switchVariant_(e,!0,t,i)}onAdaptation_(e,t){const i=(new Map).set("oldTrack",e).set("newTrack",t);this.lcevcDec_&&this.lcevcDec_.updateVariant(t,this.getManifestType());const n=wt.makeEvent_(a.EventName.Adaptation,i);this.delayDispatchEvent_(n)}onTracksChanged_(){const e=wt.makeEvent_(a.EventName.TracksChanged);this.delayDispatchEvent_(e)}onVariantChanged_(e,t){const i=(new Map).set("oldTrack",e).set("newTrack",t);this.lcevcDec_&&this.lcevcDec_.updateVariant(t,this.getManifestType());const n=wt.makeEvent_(a.EventName.VariantChanged,i);this.delayDispatchEvent_(n)}onTextChanged_(){const e=wt.makeEvent_(a.EventName.TextChanged);this.delayDispatchEvent_(e)}onTextTrackVisibility_(){const e=wt.makeEvent_(a.EventName.TextTrackVisibility);this.delayDispatchEvent_(e)}onAbrStatusChanged_(){this.config_.abr.enabled||this.restoreDisabledVariants_();const e=(new Map).set("newStatus",this.config_.abr.enabled);this.delayDispatchEvent_(wt.makeEvent_(a.EventName.AbrStatusChanged,e))}restoreDisabledVariants_(e=!0){if(this.loadMode_==wt.LoadMode.MEDIA_SOURCE){console.assert(this.manifest_,"Should have manifest!"),n.v2("Restoring all disabled streams..."),this.checkVariantsTimer_.stop();for(const e of this.manifest_.variants)e.disabledUntilTime=0;e&&this.updateAbrManagerVariants_()}}disableStream(e,t){if(!this.config_.abr.enabled||this.loadMode_===wt.LoadMode.DESTROYED)return!1;if(!navigator.onLine)return!1;if(this.manifest_.variants.some((t=>{const i=t[e.type];return!(!i||i.id===e.id||j.isAudio(e)&&e.language!==i.language)}))){let i=!1;for(const s of this.manifest_.variants){const a=s[e.type];a&&a.id===e.id&&(s.disabledUntilTime=Date.now()/1e3+t,i=!0,n.v2("Disabled stream "+e.type+":"+e.id+" for "+t+" seconds..."))}console.assert(i,"Must have disabled stream"),this.checkVariantsTimer_.tickEvery(1);const{video:s}=this.getBufferedInfo(),a=s.reduce(((e,{start:t,end:i})=>e+i-t),0);return this.chooseVariantAndSwitch_(!0,a,!0,!1),!0}return n.warning("No alternate stream found for active "+e.type+" stream. Will ignore request to disable stream..."),!1}async onError_(e){if(console.assert(e instanceof b,"Wrong error type!"),this.loadMode_==wt.LoadMode.DESTROYED)return;let t=!0;if(this.fullyLoaded_&&this.manifest_&&this.streamingEngine_&&(e.code==b.Code.VIDEO_ERROR||e.code==b.Code.MEDIA_SOURCE_OPERATION_FAILED||e.code==b.Code.MEDIA_SOURCE_OPERATION_THREW||e.code==b.Code.TRANSMUXING_FAILED))try{t=!await this.streamingEngine_.resetMediaSource()}catch(e){t=!0}if(!t)return;e.severity===b.Severity.CRITICAL&&this.restoreDisabledVariants_(!1);const i=a.EventName.Error,n=wt.makeEvent_(i,(new Map).set("detail",e));this.dispatchEvent(n),n.defaultPrevented&&(e.handled=!0)}onRegionEvent_(e,t,i=this){const n={schemeIdUri:t.schemeIdUri,value:t.value,startTime:t.startTime,endTime:t.endTime,id:t.id,eventElement:t.eventElement},s=(new Map).set("detail",n);i.dispatchEvent(wt.makeEvent_(e,s))}onMediaQualityChange_(e,t){const i={bandwidth:e.bandwidth,audioSamplingRate:e.audioSamplingRate,codecs:e.codecs,contentType:e.contentType,frameRate:e.frameRate,height:e.height,mimeType:e.mimeType,channelsCount:e.channelsCount,pixelAspectRatio:e.pixelAspectRatio,width:e.width},n=(new Map).set("mediaQuality",i).set("position",t);this.dispatchEvent(wt.makeEvent_(a.EventName.MediaQualityChanged,n))}videoErrorToShakaError_(){if(console.assert(this.video_.error,"Video error expected, but missing!"),!this.video_.error)return null;const e=this.video_.error.code;if(1==e)return null;let t=this.video_.error.msExtendedCode;t&&(t<0&&(t+=Math.pow(2,32)),t=t.toString(16));const i=this.video_.error.message;return new b(b.Severity.CRITICAL,b.Category.MEDIA,b.Code.VIDEO_ERROR,e,t,i)}onVideoError_(e){const t=this.videoErrorToShakaError_();t&&this.onError_(t)}onKeyStatus_(e){console.assert(this.streamingEngine_,"Cannot be called in src= mode");const t=wt.makeEvent_(a.EventName.KeyStatusChanged);this.dispatchEvent(t);const i=Object.keys(e);0==i.length&&n.warning("Got a key status event without any key statuses, so we don't know the real key statuses. If we don't have all the keys, you'll need to set restrictions so we don't select those tracks."),1==i.length&&"00"==i[0]&&n.warning("Got a synthetic key status event, so we don't know the real key statuses. If we don't have all the keys, you'll need to set restrictions so we don't select those tracks.");let s=!1;if(i.length)for(const e of this.manifest_.variants){const t=j.getVariantStreams(e);for(const i of t)e.allowedByKeySystem!=e.allowedByKeySystem&&(s=!0)}if(s&&(this.onTracksChanged_(),!this.updateAbrManagerVariants_()))return;const r=this.streamingEngine_.getCurrentVariant();r&&!r.allowedByKeySystem&&(n.debug("Choosing new streams after key status changed"),this.chooseVariantAndSwitch_())}shouldStreamText_(){return this.config_.streaming.alwaysStreamText||this.isTextTrackVisible()}static applyPlayRange_(e,t,i){t>0&&(e.isLive()?n.warning("|playRangeStart| has been configured for live content. Ignoring the setting."):e.setUserSeekStart(t)),i<e.getDuration()&&(e.isLive()?n.warning("|playRangeEnd| has been configured for live content. Ignoring the setting."):e.setDuration(i))}async delayDispatchEvent_(e){await Promise.resolve(),this.loadMode_!=wt.LoadMode.DESTROYED&&this.dispatchEvent(e)}static getLanguagesFrom_(e){const t=new Set;for(const i of e)i.language?t.add(H.normalize(i.language)):t.add("und");return t}static getLanguageAndRolesFrom_(e){const t=new Map,i=new Map;for(const n of e){let e="und",s=[];n.language&&(e=H.normalize(n.language)),s="variant"==n.type?n.audioRoles:n.roles,s&&s.length||(s=[""]),t.has(e)||t.set(e,new Set);for(const a of s)t.get(e).add(a),n.label&&(i.has(e)||i.set(e,new Map),i.get(e).set(a,n.label))}const n=[];return t.forEach(((e,t)=>{for(const s of e){let e=null;i.has(t)&&i.get(t).has(s)&&(e=i.get(t).get(s)),n.push({language:t,role:s,label:e})}})),n}isBufferedToEndMS_(){if(console.assert(this.video_,"We need a video element to get buffering information"),console.assert(this.mediaSourceEngine_,"We need a media source engine to get buffering information"),console.assert(this.manifest_,"We need a manifest to get buffering information"),this.video_.ended)return!0;if(this.mediaSourceEngine_.ended())return!0;if(this.manifest_.presentationTimeline.isLive()){const e=this.manifest_.presentationTimeline.getSegmentAvailabilityEnd(),t=ge.bufferEnd(this.video_.buffered);if(null!=t&&t>=e)return!0}return!1}isBufferedToEndSrc_(){if(console.assert(this.video_,"We need a video element to get buffering information"),this.video_.ended)return!0;const e=ge.bufferEnd(this.video_.buffered);return null!=e&&e>=this.video_.duration-1}createAbortLoadError_(){return new b(b.Severity.CRITICAL,b.Category.PLAYER,b.Code.LOAD_INTERRUPTED)}static convertJsonToUri(e){const t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"});return URL.createObjectURL(t)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}wt.LoadMode={DESTROYED:0,NOT_LOADED:1,MEDIA_SOURCE:2,SRC_EQUALS:3},wt.TYPICAL_BUFFERING_THRESHOLD_=.5,wt.version="v5.0.0-uncompiled",re.init(wt.version),wt.supportPlugins_={},wt.adManagerFactory_=null,wt.TextTrackLabel="Shaka Player TextTrack";class Ct{constructor(e){Object.defineProperty(this,"video",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"timeupdate",{enumerable:!0,configurable:!0,writable:!0,value:Date.now()}),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"playingCheckerTimerId",{enumerable:!0,configurable:!0,writable:!0,value:null}),this.handleTimeUpdate=this.handleTimeUpdate.bind(this),this.video.$video.addEventListener("timeupdate",this.handleTimeUpdate)}destroy(){null!=this.playingCheckerTimerId&&window.clearTimeout(this.playingCheckerTimerId),this.video.$video.removeEventListener("timeupdate",this.handleTimeUpdate)}handleTimeUpdate(){this.timeupdate=Date.now(),null!=this.playingCheckerTimerId&&window.clearTimeout(this.playingCheckerTimerId),1!==this.state&&(this.state=1,this.triggerUpdate()),this.scheduleUpdate()}scheduleUpdate(){this.playingCheckerTimerId=window.setTimeout((()=>{Date.now()-this.timeupdate>=150&&(this.state=2,this.triggerUpdate())}),300)}triggerUpdate(){1===this.state?this.video.onPlaying():2===this.state&&this.video.onWaiting()}}var Mt;!function(e){e.Playing="playing",e.Waiting="waiting",e.Error="error"}(Mt||(Mt={}));class Rt{constructor(e,t){Object.defineProperty(this,"videoManager",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"videoEl",{enumerable:!0,configurable:!0,writable:!0,value:t}),this.parseDefaultMuted()}get $video(){return this.videoEl}get muted(){return this.videoEl.muted}get paused(){return this.videoEl.paused}async start(){this.videoEl.pause(),this.videoEl.currentTime=0,await this.play()}async play(){const e=this.videoEl.play();e?await e:await new Promise((e=>{setTimeout(e,0)}))}pause(){this.videoEl.pause()}async resume(){this.videoEl.paused&&await this.videoEl.play()}stop(){this.videoEl.pause(),this.videoEl.currentTime=0}mute(){"1"!==this.videoEl.getAttribute("data-default-muted")&&(this.videoEl.muted=!0)}unmute(){"1"!==this.videoEl.getAttribute("data-default-muted")&&(this.videoEl.muted=!1)}async load(e=!0){return new Promise((t=>{const i=this.videoEl.oncanplaythrough?"canplaythrough":"canplay";this.videoEl.addEventListener(i,(()=>{requestAnimationFrame((()=>{requestAnimationFrame((()=>{setTimeout((()=>t()),0)}))}))}),{once:!0}),e&&this.videoEl.load()}))}on(e,t){return this.videoEl.addEventListener(e,t),this}once(e,t){return this.videoEl.addEventListener(e,t,{once:!0}),this}off(e,t){return this.videoEl.removeEventListener(e,t),this}async destroy(){this.stop()}parseDefaultMuted(){null===this.videoEl.getAttribute("data-default-muted")&&(this.videoEl.muted?this.videoEl.setAttribute("data-default-muted","1"):this.videoEl.setAttribute("data-default-muted","0"))}onPlaying(){}onWaiting(){}}class Ot extends Rt{constructor(e,t){super(e,t),Object.defineProperty(this,"videoManager",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"player",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"_vodData",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isPlaying",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"isDataWaiting",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"attached",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"videoStateAdapter",{enumerable:!0,configurable:!0,writable:!0,value:null}),this.handlePlayerError=this.handlePlayerError.bind(this),this._vodData=Ot.parseData(t)}get vodData(){return this._vodData}static get isBrowserSupported(){return wt.isBrowserSupported()}static supports(e){return Ot.isBrowserSupported&&Boolean(Ot.parseData(e))}async load(){try{this.disableVideoPreload(),await this.initPlayer()}catch(e){throw this.stop(),this.player&&this.detachVideoElement(this.player).catch(console.error),e}}async destroy(){if(!this.player)return;const e=this.player;this.player=null,e.removeEventListener("error",this.handlePlayerError),this.stop(),await this.detachVideoElement(e),await e.destroy()}static parseData(e){const t=e.getAttribute("data-vod");try{return t&&JSON.parse(t)}catch(e){return null}}async stop(){var e;this.isPlaying=!1,null===(e=this.videoStateAdapter)||void 0===e||e.destroy(),super.stop()}async start(){this.isPlaying||(this.isPlaying=!0,this.videoStateAdapter=new Ct(this),await super.start())}async initPlayer(){this.player?console.warn("[IAS]: Attempt to create VOD player instance multiple times"):(this.player=new wt,this.player.addEventListener("error",this.handlePlayerError),await this.attachVideoElement(),await this.loadVideo())}disableVideoPreload(){this.videoEl.preload="none"}handlePlayerError(e){const t=e.detail,i=`[VOD]: error code ${t.code}; object ${t}`;console.error(i),this.stop(),this.player&&this.detachVideoElement(this.player).catch(console.error).finally((()=>{this.videoManager.emit(Mt.Error,t)}))}async attachVideoElement(){!this.attached&&this.player&&(await this.player.attach(this.videoEl),this.attached=!0,this.videoEl)}async loadVideo(){if(!this.player)return;const e=wt.convertJsonToUri(this.vodData);await this.player.load(e,0,"application/json")}async detachVideoElement(e){this.attached&&(await e.detach(this.videoEl),this.attached=!1,this.videoEl)}onPlaying(){this.isDataWaiting&&(this.isDataWaiting=!1,this.videoManager.emit(Mt.Playing))}onWaiting(){this.isDataWaiting=!0,this.videoManager.emit(Mt.Waiting)}}const Dt=new class{constructor(){Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ias-vod-plugin"})}install(e){e.globalProperties.$videoOnDemand={create:(e,t)=>new Ot(e,t),supports:e=>Ot.supports(e)}}uninstall(){}};return t.default})()));
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.IasVideoOnDemandPlugin=t():e.IasVideoOnDemandPlugin=t()}(self,(()=>(()=>{"use strict";var e={d:(t,i)=>{for(var n in i)e.o(i,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:i[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{default:()=>Ct});let i=class e{static alwaysError(...e){}static alwaysWarn(...e){}static warnOnce(t,...i){e.oneTimeWarningIssued_.has(t)||(e.oneTimeWarningIssued_.add(t),e.alwaysWarn(...i))}static error(...e){}static warning(...e){}static info(...e){}static debug(...e){}static v1(...e){}static v2(...e){}};i.Level={NONE:0,ERROR:1,WARNING:2,INFO:3,DEBUG:4,V1:5,V2:6},i.MAX_LOG_LEVEL=3,i.oneTimeWarningIssued_=new Set,window.console&&(i.logMap_={[i.Level.ERROR]:(...e)=>console.error(...e),[i.Level.WARNING]:(...e)=>console.warn(...e),[i.Level.INFO]:(...e)=>console.info(...e),[i.Level.DEBUG]:(...e)=>console.log(...e),[i.Level.V1]:(...e)=>console.debug(...e),[i.Level.V2]:(...e)=>console.debug(...e)},i.alwaysWarn=(...e)=>console.warn(...e),i.alwaysError=(...e)=>console.error(...e),i.setLevel=e=>{const t=t=>t<=e?(console.assert(i.logMap_[t],"Unexpected log level"),i.logMap_[t]):()=>{};i.currentLevel=e,i.error=t(i.Level.ERROR),i.warning=t(i.Level.WARNING),i.info=t(i.Level.INFO),i.debug=t(i.Level.DEBUG),i.v1=t(i.Level.V1),i.v2=t(i.Level.V2)},i.setLevel(i.MAX_LOG_LEVEL));class n{constructor(){this.map_={}}push(e,t){this.map_.hasOwnProperty(e)?this.map_[e].push(t):this.map_[e]=[t]}get(e){const t=this.map_[e];return t?t.slice():null}getAll(){const e=[];for(const t in this.map_)e.push(...this.map_[t]);return e}remove(e,t){e in this.map_&&(this.map_[e]=this.map_[e].filter((e=>e!=t)),0==this.map_[e].length&&delete this.map_[e])}clear(){this.map_={}}forEach(e){for(const t in this.map_)e(t,this.map_[t])}size(){return Object.keys(this.map_).length}keys(){return Object.keys(this.map_)}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class s{static fromRealEvent(e){const t=new s(e.type);for(const i in e)Object.defineProperty(t,i,{value:e[i],writable:!0,enumerable:!0});return t}static recastDictAsObject_(e){return console.assert(!(e instanceof Map),"dict should not be a map"),e}constructor(e,t){if(t)if(t instanceof Map)for(const e of t.keys())Object.defineProperty(this,e,{value:t.get(e),writable:!0,enumerable:!0});else{const e=s.recastDictAsObject_(t);for(const t in e)Object.defineProperty(this,t,{value:e[t],writable:!0,enumerable:!0})}this.bubbles=!1,this.cancelable=!1,this.defaultPrevented=!1,this.timeStamp=window.performance&&window.performance.now?window.performance.now():Date.now(),this.type=e,this.isTrusted=!1,this.currentTarget=null,this.target=null,this.stopped=!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopImmediatePropagation(){this.stopped=!0}stopPropagation(){}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}s.EventName={AbrStatusChanged:"abrstatuschanged",Adaptation:"adaptation",Buffering:"buffering",Complete:"complete",DownloadFailed:"downloadfailed",DownloadHeadersReceived:"downloadheadersreceived",DrmSessionUpdate:"drmsessionupdate",Emsg:"emsg",Prft:"prft",Error:"error",ExpirationUpdated:"expirationupdated",FirstQuartile:"firstquartile",GapJumped:"gapjumped",KeyStatusChanged:"keystatuschanged",Loaded:"loaded",Loading:"loading",ManifestParsed:"manifestparsed",ManifestUpdated:"manifestupdated",MediaQualityChanged:"mediaqualitychanged",Metadata:"metadata",Midpoint:"midpoint",OnStateChange:"onstatechange",RateChange:"ratechange",SegmentAppended:"segmentappended",SessionDataEvent:"sessiondata",StallDetected:"stalldetected",Started:"started",StateChanged:"statechanged",Streaming:"streaming",TextChanged:"textchanged",TextTrackVisibility:"texttrackvisibility",ThirdQuartile:"thirdquartile",TimelineRegionAdded:"timelineregionadded",TimelineRegionEnter:"timelineregionenter",TimelineRegionExit:"timelineregionexit",TracksChanged:"trackschanged",Unloading:"unloading",VariantChanged:"variantchanged"};class a{constructor(){this.listeners_=new n,this.dispatchTarget=this}addEventListener(e,t,i){this.listeners_&&this.listeners_.push(e,t)}listenToAllEvents(e){this.addEventListener(a.ALL_EVENTS_,e)}removeEventListener(e,t,i){this.listeners_&&this.listeners_.remove(e,t)}dispatchEvent(e){if(console.assert(e instanceof s,"FakeEventTarget can only dispatch FakeEvents!"),!this.listeners_)return!0;let t=this.listeners_.get(e.type)||[];const n=this.listeners_.get(a.ALL_EVENTS_);n&&(t=t.concat(n));for(const n of t){e.target=this.dispatchTarget,e.currentTarget=this.dispatchTarget;try{n.handleEvent?n.handleEvent(e):n.call(this,e)}catch(e){i.error("Uncaught exception in event handler",e,e?e.message:null,e?e.stack:null)}if(e.stopped)break}return e.defaultPrevented}release(){this.listeners_=null}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}a.ALL_EVENTS_="All";class r{constructor(e){this.onTick_=e,this.cancelPending_=null}tickAfter(e){this.stop();let t=!0,i=null;return this.cancelPending_=()=>{window.clearTimeout(i),t=!1},i=window.setTimeout((()=>{t&&this.onTick_()}),1e3*e),this}stop(){this.cancelPending_&&(this.cancelPending_(),this.cancelPending_=null)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class o{constructor(e){this.onTick_=e,this.ticker_=null}tickNow(){return this.stop(),this.onTick_(),this}tickAfter(e){return this.stop(),this.ticker_=new r((()=>{this.onTick_()})).tickAfter(e),this}tickEvery(e){var t;this.stop();{const e=null!==(t=Error("Timer created").stack)&&void 0!==t?t:"";o.activeTimers.set(this,e)}return this.ticker_=new r((()=>{var t;null===(t=this.ticker_)||void 0===t||t.tickAfter(e),this.onTick_()})).tickAfter(e),this}stop(){this.ticker_&&(this.ticker_.stop(),this.ticker_=null),o.activeTimers.delete(this)}static get[Symbol.for("___CTOR_ARGS___")](){return["() => void"]}}o.activeTimers=new Map;class l{static equal(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;if(e.byteLength!=t.byteLength)return!1;if(l.unsafeGetArrayBuffer_(e)==l.unsafeGetArrayBuffer_(t)&&(e.byteOffset||0)==(t.byteOffset||0))return!0;const i=l.toUint8(e),n=l.toUint8(t);for(let t=0;t<e.byteLength;t++)if(i[t]!=n[t])return!1;return!0}static unsafeGetArrayBuffer_(e){return e instanceof ArrayBuffer?e:e.buffer}static toArrayBuffer(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}static toUint8(e,t=0,i=1/0){return l.view_(e,t,i,Uint8Array)}static toUint16(e,t=0,i=1/0){return l.view_(e,t,i,Uint16Array)}static toDataView(e,t=0,i=1/0){return l.view_(e,t,i,DataView)}static view_(e,t,i,n){const s=l.unsafeGetArrayBuffer_(e);let a=1;"BYTES_PER_ELEMENT"in n&&(a=n.BYTES_PER_ELEMENT);const r=((e.byteOffset||0)+e.byteLength)/a,o=((e.byteOffset||0)+t)/a,d=Math.floor(Math.max(0,Math.min(o,r)));return new n(s,d,Math.floor(Math.min(d+Math.max(i,0),r))-d)}}var d,c,h,u,_,m,g,f,p,T,S,y,E;!function(e){e[e.RECOVERABLE=1]="RECOVERABLE",e[e.CRITICAL=2]="CRITICAL"}(d||(d={})),function(e){e[e.NETWORK=1]="NETWORK",e[e.TEXT=2]="TEXT",e[e.MEDIA=3]="MEDIA",e[e.MANIFEST=4]="MANIFEST",e[e.STREAMING=5]="STREAMING",e[e.DRM=6]="DRM",e[e.PLAYER=7]="PLAYER",e[e.CAST=8]="CAST",e[e.STORAGE=9]="STORAGE",e[e.ADS=10]="ADS"}(c||(c={})),function(e){e[e.UNSUPPORTED_SCHEME=1e3]="UNSUPPORTED_SCHEME",e[e.BAD_HTTP_STATUS=1001]="BAD_HTTP_STATUS",e[e.HTTP_ERROR=1002]="HTTP_ERROR",e[e.TIMEOUT=1003]="TIMEOUT",e[e.MALFORMED_DATA_URI=1004]="MALFORMED_DATA_URI",e[e.REQUEST_FILTER_ERROR=1006]="REQUEST_FILTER_ERROR",e[e.RESPONSE_FILTER_ERROR=1007]="RESPONSE_FILTER_ERROR",e[e.MALFORMED_TEST_URI=1008]="MALFORMED_TEST_URI",e[e.UNEXPECTED_TEST_REQUEST=1009]="UNEXPECTED_TEST_REQUEST",e[e.ATTEMPTS_EXHAUSTED=1010]="ATTEMPTS_EXHAUSTED",e[e.SEGMENT_MISSING=1011]="SEGMENT_MISSING",e[e.SEGMENT_DURATION_IS_NULL=1012]="SEGMENT_DURATION_IS_NULL",e[e.INVALID_TEXT_HEADER=2e3]="INVALID_TEXT_HEADER",e[e.INVALID_TEXT_CUE=2001]="INVALID_TEXT_CUE",e[e.UNABLE_TO_DETECT_ENCODING=2003]="UNABLE_TO_DETECT_ENCODING",e[e.BAD_ENCODING=2004]="BAD_ENCODING",e[e.INVALID_XML=2005]="INVALID_XML",e[e.INVALID_MP4_TTML=2007]="INVALID_MP4_TTML",e[e.INVALID_MP4_VTT=2008]="INVALID_MP4_VTT",e[e.UNABLE_TO_EXTRACT_CUE_START_TIME=2009]="UNABLE_TO_EXTRACT_CUE_START_TIME",e[e.INVALID_MP4_CEA=2010]="INVALID_MP4_CEA",e[e.TEXT_COULD_NOT_GUESS_MIME_TYPE=2011]="TEXT_COULD_NOT_GUESS_MIME_TYPE",e[e.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS=2012]="CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS",e[e.TEXT_ONLY_WEBVTT_SRC_EQUALS=2013]="TEXT_ONLY_WEBVTT_SRC_EQUALS",e[e.MISSING_TEXT_PLUGIN=2014]="MISSING_TEXT_PLUGIN",e[e.CHAPTERS_TRACK_FAILED=2015]="CHAPTERS_TRACK_FAILED",e[e.UNSUPPORTED_EXTERNAL_THUMBNAILS_URI=2017]="UNSUPPORTED_EXTERNAL_THUMBNAILS_URI",e[e.BUFFER_READ_OUT_OF_BOUNDS=3e3]="BUFFER_READ_OUT_OF_BOUNDS",e[e.JS_INTEGER_OVERFLOW=3001]="JS_INTEGER_OVERFLOW",e[e.EBML_OVERFLOW=3002]="EBML_OVERFLOW",e[e.EBML_BAD_FLOATING_POINT_SIZE=3003]="EBML_BAD_FLOATING_POINT_SIZE",e[e.MP4_SIDX_WRONG_BOX_TYPE=3004]="MP4_SIDX_WRONG_BOX_TYPE",e[e.MP4_SIDX_INVALID_TIMESCALE=3005]="MP4_SIDX_INVALID_TIMESCALE",e[e.MP4_SIDX_TYPE_NOT_SUPPORTED=3006]="MP4_SIDX_TYPE_NOT_SUPPORTED",e[e.WEBM_CUES_ELEMENT_MISSING=3007]="WEBM_CUES_ELEMENT_MISSING",e[e.WEBM_EBML_HEADER_ELEMENT_MISSING=3008]="WEBM_EBML_HEADER_ELEMENT_MISSING",e[e.WEBM_SEGMENT_ELEMENT_MISSING=3009]="WEBM_SEGMENT_ELEMENT_MISSING",e[e.WEBM_INFO_ELEMENT_MISSING=3010]="WEBM_INFO_ELEMENT_MISSING",e[e.WEBM_DURATION_ELEMENT_MISSING=3011]="WEBM_DURATION_ELEMENT_MISSING",e[e.WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING=3012]="WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING",e[e.WEBM_CUE_TIME_ELEMENT_MISSING=3013]="WEBM_CUE_TIME_ELEMENT_MISSING",e[e.MEDIA_SOURCE_OPERATION_FAILED=3014]="MEDIA_SOURCE_OPERATION_FAILED",e[e.MEDIA_SOURCE_OPERATION_THREW=3015]="MEDIA_SOURCE_OPERATION_THREW",e[e.VIDEO_ERROR=3016]="VIDEO_ERROR",e[e.QUOTA_EXCEEDED_ERROR=3017]="QUOTA_EXCEEDED_ERROR",e[e.TRANSMUXING_FAILED=3018]="TRANSMUXING_FAILED",e[e.CONTENT_TRANSFORMATION_FAILED=3019]="CONTENT_TRANSFORMATION_FAILED",e[e.MSS_MISSING_DATA_FOR_TRANSMUXING=3020]="MSS_MISSING_DATA_FOR_TRANSMUXING",e[e.MSS_TRANSMUXING_CODEC_UNKNOWN=3021]="MSS_TRANSMUXING_CODEC_UNKNOWN",e[e.MSS_TRANSMUXING_FAILED=3022]="MSS_TRANSMUXING_FAILED",e[e.TRANSMUXING_NO_VIDEO_DATA=3023]="TRANSMUXING_NO_VIDEO_DATA",e[e.UNABLE_TO_GUESS_MANIFEST_TYPE=4e3]="UNABLE_TO_GUESS_MANIFEST_TYPE",e[e.DASH_INVALID_XML=4001]="DASH_INVALID_XML",e[e.DASH_NO_SEGMENT_INFO=4002]="DASH_NO_SEGMENT_INFO",e[e.DASH_EMPTY_ADAPTATION_SET=4003]="DASH_EMPTY_ADAPTATION_SET",e[e.DASH_EMPTY_PERIOD=4004]="DASH_EMPTY_PERIOD",e[e.DASH_WEBM_MISSING_INIT=4005]="DASH_WEBM_MISSING_INIT",e[e.DASH_UNSUPPORTED_CONTAINER=4006]="DASH_UNSUPPORTED_CONTAINER",e[e.DASH_PSSH_BAD_ENCODING=4007]="DASH_PSSH_BAD_ENCODING",e[e.DASH_NO_COMMON_KEY_SYSTEM=4008]="DASH_NO_COMMON_KEY_SYSTEM",e[e.DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED=4009]="DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED",e[e.DASH_CONFLICTING_KEY_IDS=4010]="DASH_CONFLICTING_KEY_IDS",e[e.RESTRICTIONS_CANNOT_BE_MET=4012]="RESTRICTIONS_CANNOT_BE_MET",e[e.HLS_PLAYLIST_HEADER_MISSING=4015]="HLS_PLAYLIST_HEADER_MISSING",e[e.INVALID_HLS_TAG=4016]="INVALID_HLS_TAG",e[e.HLS_INVALID_PLAYLIST_HIERARCHY=4017]="HLS_INVALID_PLAYLIST_HIERARCHY",e[e.DASH_DUPLICATE_REPRESENTATION_ID=4018]="DASH_DUPLICATE_REPRESENTATION_ID",e[e.HLS_MULTIPLE_MEDIA_INIT_SECTIONS_FOUND=4020]="HLS_MULTIPLE_MEDIA_INIT_SECTIONS_FOUND",e[e.HLS_REQUIRED_ATTRIBUTE_MISSING=4023]="HLS_REQUIRED_ATTRIBUTE_MISSING",e[e.HLS_REQUIRED_TAG_MISSING=4024]="HLS_REQUIRED_TAG_MISSING",e[e.HLS_COULD_NOT_GUESS_CODECS=4025]="HLS_COULD_NOT_GUESS_CODECS",e[e.HLS_KEYFORMATS_NOT_SUPPORTED=4026]="HLS_KEYFORMATS_NOT_SUPPORTED",e[e.DASH_UNSUPPORTED_XLINK_ACTUATE=4027]="DASH_UNSUPPORTED_XLINK_ACTUATE",e[e.DASH_XLINK_DEPTH_LIMIT=4028]="DASH_XLINK_DEPTH_LIMIT",e[e.CONTENT_UNSUPPORTED_BY_BROWSER=4032]="CONTENT_UNSUPPORTED_BY_BROWSER",e[e.CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM=4033]="CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM",e[e.NO_VARIANTS=4036]="NO_VARIANTS",e[e.PERIOD_FLATTENING_FAILED=4037]="PERIOD_FLATTENING_FAILED",e[e.INCONSISTENT_DRM_ACROSS_PERIODS=4038]="INCONSISTENT_DRM_ACROSS_PERIODS",e[e.HLS_VARIABLE_NOT_FOUND=4039]="HLS_VARIABLE_NOT_FOUND",e[e.HLS_MSE_ENCRYPTED_MP2T_NOT_SUPPORTED=4040]="HLS_MSE_ENCRYPTED_MP2T_NOT_SUPPORTED",e[e.HLS_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED=4041]="HLS_MSE_ENCRYPTED_LEGACY_APPLE_MEDIA_KEYS_NOT_SUPPORTED",e[e.NO_WEB_CRYPTO_API=4042]="NO_WEB_CRYPTO_API",e[e.CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_LIVE_STREAM=4045]="CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_LIVE_STREAM",e[e.MSS_INVALID_XML=4046]="MSS_INVALID_XML",e[e.MSS_LIVE_CONTENT_NOT_SUPPORTED=4047]="MSS_LIVE_CONTENT_NOT_SUPPORTED",e[e.AES_128_INVALID_IV_LENGTH=4048]="AES_128_INVALID_IV_LENGTH",e[e.AES_128_INVALID_KEY_LENGTH=4049]="AES_128_INVALID_KEY_LENGTH",e[e.DASH_CONFLICTING_AES_128=4050]="DASH_CONFLICTING_AES_128",e[e.DASH_UNSUPPORTED_AES_128=4051]="DASH_UNSUPPORTED_AES_128",e[e.DASH_EMPTY_INDEX_RANGE=4052]="DASH_EMPTY_INDEX_RANGE",e[e.DASH_INVALID_JSON=4053]="DASH_INVALID_JSON",e[e.STREAMING_ENGINE_STARTUP_INVALID_STATE=5006]="STREAMING_ENGINE_STARTUP_INVALID_STATE",e[e.NO_RECOGNIZED_KEY_SYSTEMS=6e3]="NO_RECOGNIZED_KEY_SYSTEMS",e[e.REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE=6001]="REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE",e[e.FAILED_TO_CREATE_CDM=6002]="FAILED_TO_CREATE_CDM",e[e.FAILED_TO_ATTACH_TO_VIDEO=6003]="FAILED_TO_ATTACH_TO_VIDEO",e[e.INVALID_SERVER_CERTIFICATE=6004]="INVALID_SERVER_CERTIFICATE",e[e.FAILED_TO_CREATE_SESSION=6005]="FAILED_TO_CREATE_SESSION",e[e.FAILED_TO_GENERATE_LICENSE_REQUEST=6006]="FAILED_TO_GENERATE_LICENSE_REQUEST",e[e.LICENSE_REQUEST_FAILED=6007]="LICENSE_REQUEST_FAILED",e[e.LICENSE_RESPONSE_REJECTED=6008]="LICENSE_RESPONSE_REJECTED",e[e.ENCRYPTED_CONTENT_WITHOUT_DRM_INFO=6010]="ENCRYPTED_CONTENT_WITHOUT_DRM_INFO",e[e.NO_LICENSE_SERVER_GIVEN=6012]="NO_LICENSE_SERVER_GIVEN",e[e.OFFLINE_SESSION_REMOVED=6013]="OFFLINE_SESSION_REMOVED",e[e.EXPIRED=6014]="EXPIRED",e[e.SERVER_CERTIFICATE_REQUIRED=6015]="SERVER_CERTIFICATE_REQUIRED",e[e.INIT_DATA_TRANSFORM_ERROR=6016]="INIT_DATA_TRANSFORM_ERROR",e[e.SERVER_CERTIFICATE_REQUEST_FAILED=6017]="SERVER_CERTIFICATE_REQUEST_FAILED",e[e.MIN_HDCP_VERSION_NOT_MATCH=6018]="MIN_HDCP_VERSION_NOT_MATCH",e[e.ERROR_CHECKING_HDCP_VERSION=6019]="ERROR_CHECKING_HDCP_VERSION",e[e.LOAD_INTERRUPTED=7e3]="LOAD_INTERRUPTED",e[e.OPERATION_ABORTED=7001]="OPERATION_ABORTED",e[e.NO_VIDEO_ELEMENT=7002]="NO_VIDEO_ELEMENT",e[e.OBJECT_DESTROYED=7003]="OBJECT_DESTROYED",e[e.CONTENT_NOT_LOADED=7004]="CONTENT_NOT_LOADED",e[e.SRC_EQUALS_PRELOAD_NOT_SUPPORTED=7005]="SRC_EQUALS_PRELOAD_NOT_SUPPORTED",e[e.NOT_CONFIGURED=7001]="NOT_CONFIGURED",e[e.CAST_API_UNAVAILABLE=8e3]="CAST_API_UNAVAILABLE",e[e.NO_CAST_RECEIVERS=8001]="NO_CAST_RECEIVERS",e[e.ALREADY_CASTING=8002]="ALREADY_CASTING",e[e.UNEXPECTED_CAST_ERROR=8003]="UNEXPECTED_CAST_ERROR",e[e.CAST_CANCELED_BY_USER=8004]="CAST_CANCELED_BY_USER",e[e.CAST_CONNECTION_TIMED_OUT=8005]="CAST_CONNECTION_TIMED_OUT",e[e.CAST_RECEIVER_APP_UNAVAILABLE=8006]="CAST_RECEIVER_APP_UNAVAILABLE",e[e.STORAGE_NOT_SUPPORTED=9e3]="STORAGE_NOT_SUPPORTED",e[e.INDEXED_DB_ERROR=9001]="INDEXED_DB_ERROR",e[e.DEPRECATED_OPERATION_ABORTED=9002]="DEPRECATED_OPERATION_ABORTED",e[e.REQUESTED_ITEM_NOT_FOUND=9003]="REQUESTED_ITEM_NOT_FOUND",e[e.MALFORMED_OFFLINE_URI=9004]="MALFORMED_OFFLINE_URI",e[e.CANNOT_STORE_LIVE_OFFLINE=9005]="CANNOT_STORE_LIVE_OFFLINE",e[e.NO_INIT_DATA_FOR_OFFLINE=9007]="NO_INIT_DATA_FOR_OFFLINE",e[e.LOCAL_PLAYER_INSTANCE_REQUIRED=9008]="LOCAL_PLAYER_INSTANCE_REQUIRED",e[e.NEW_KEY_OPERATION_NOT_SUPPORTED=9011]="NEW_KEY_OPERATION_NOT_SUPPORTED",e[e.KEY_NOT_FOUND=9012]="KEY_NOT_FOUND",e[e.MISSING_STORAGE_CELL=9013]="MISSING_STORAGE_CELL",e[e.STORAGE_LIMIT_REACHED=9014]="STORAGE_LIMIT_REACHED",e[e.DOWNLOAD_SIZE_CALLBACK_ERROR=9015]="DOWNLOAD_SIZE_CALLBACK_ERROR",e[e.MODIFY_OPERATION_NOT_SUPPORTED=9016]="MODIFY_OPERATION_NOT_SUPPORTED",e[e.INDEXED_DB_INIT_TIMED_OUT=9017]="INDEXED_DB_INIT_TIMED_OUT",e[e.CS_IMA_SDK_MISSING=1e4]="CS_IMA_SDK_MISSING",e[e.CS_AD_MANAGER_NOT_INITIALIZED=10001]="CS_AD_MANAGER_NOT_INITIALIZED",e[e.SS_IMA_SDK_MISSING=10002]="SS_IMA_SDK_MISSING",e[e.SS_AD_MANAGER_NOT_INITIALIZED=10003]="SS_AD_MANAGER_NOT_INITIALIZED",e[e.CURRENT_DAI_REQUEST_NOT_FINISHED=10004]="CURRENT_DAI_REQUEST_NOT_FINISHED",e[e.MT_AD_MANAGER_NOT_INITIALIZED=10005]="MT_AD_MANAGER_NOT_INITIALIZED"}(h||(h={}));class v{constructor(e,t,i,...n){this.severity=e,this.category=t,this.code=i,this.data=n,this.handled=!1;let s="Shaka Error "+this.code;{let e="UNKNOWN",t="UNKNOWN";for(const t in v.Category)v.Category[t]==this.category&&(e=t);for(const e in v.Code)v.Code[e]==this.code&&(t=e);s="Player Error "+e+"."+t+" ("+this.data.toString()+")"}if(this.message=s,v.createStack)try{throw new Error(this.message||"Player Error")}catch(e){this.stack=e.stack}}toString(){return"PlayerError "+JSON.stringify(this,null," ")}static get[Symbol.for("___CTOR_ARGS___")](){return["PlayerErrorSeverity","PlayerErrorCategory","PlayerErrorCode","any[]"]}}v.Severity=d,v.Category=c,v.Code=h,v.createStack=!0;class I{static defaultEquals(e,t){return!("number"!=typeof e||"number"!=typeof t||!isNaN(e)||!isNaN(t))||e===t}static remove(e,t){const i=e.indexOf(t);i>-1&&e.splice(i,1)}static count(e,t){let i=0;for(const n of e)i+=t(n)?1:0;return i}static hasSameElements(e,t,i=I.defaultEquals){if(i||(i=I.defaultEquals),e.length!=t.length)return!1;const n=t.slice();for(const t of e){const e=n.findIndex((e=>i(t,e)));if(-1==e)return!1;n[e]=n[n.length-1],n.pop()}return 0==n.length}static equal(e,t,i=I.defaultEquals){if(i||(i=I.defaultEquals),e.length!=t.length)return!1;for(let n=0;n<e.length;++n)if(!i(e[n],t[n]))return!1;return!0}}class A{constructor(){this.operations_=[]}manage(e){this.operations_.push(e.finally((()=>{I.remove(this.operations_,e)})))}destroy(){const e=[];for(const t of this.operations_)t.promise.catch((()=>{})),e.push(t.abort());return this.operations_=[],Promise.all(e)}}class b{static cloneObject(e){const t=new WeakSet,i=e=>{switch(typeof e){case"undefined":case"boolean":case"number":case"string":case"symbol":case"function":return e;default:{if(!e)return e;if(e.buffer&&e.buffer.constructor==ArrayBuffer)return e;if(t.has(e))return null;const n=e.constructor==Array;if(e.constructor!=Object&&!n)return null;t.add(e);const s=n?[]:{};for(const t in e)s[t]=i(e[t]);return n&&(s.length=e.length),s}}};return i(e)}static shallowCloneObject(e){const t={};for(const i in e)t[i]=e[i];return t}}class C extends Promise{constructor(){let e=null,t=null;super(((e,t)=>{}));const i=new Promise(((i,n)=>{e=i,t=n}));return i.resolve=e,i.reject=t,i}resolve(e){}reject(e){}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class w{constructor(e,t){this.onAbort_=t,this.aborted_=!1,this.promise=e}static failed(e){return new w(Promise.reject(e),(()=>Promise.resolve()))}static aborted(){const e=Promise.reject(w.abortError());return e.catch((()=>{})),new w(e,(()=>Promise.resolve()))}static abortError(){return new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.OPERATION_ABORTED)}static completed(e){return new w(Promise.resolve(e),(()=>Promise.resolve()))}static notAbortable(e){return new w(e,(()=>e.catch((()=>{}))))}abort(){return this.aborted_=!0,this.onAbort_()}static all(e){return new w(Promise.all(e.map((e=>e.promise))),(()=>Promise.all(e.map((e=>e.abort())))))}finally(e){return this.promise.then((t=>e(!0)),(t=>e(!1))),this}chain(e,t){const i=new C,n=w.abortError();let s=()=>(i.reject(n),this.abort());const a=a=>r=>{if(this.aborted_&&a)return void i.reject(n);const o=a?e:t;o?s=w.wrapChainCallback_(o,r,i):(a?i.resolve:i.reject)(r)};return this.promise.then(a(!0),a(!1)),new w(i,(()=>s()))}static wrapChainCallback_(e,t,i){try{const n=e(t);return n&&n.promise&&n.abort?(i.resolve(n.promise),()=>n.abort()):(i.resolve(n),()=>Promise.resolve(n).then((()=>{}),(()=>{})))}catch(e){return i.reject(e),()=>Promise.resolve()}}static get[Symbol.for("___CTOR_ARGS___")](){return["Promise","() => Promise<void>"]}}class M{constructor(e,t=!1){const i=M.defaultRetryParameters();this.maxAttempts_=null==e.maxAttempts?i.maxAttempts:e.maxAttempts,console.assert(this.maxAttempts_>=1,"maxAttempts should be >= 1"),this.baseDelay_=null==e.baseDelay?i.baseDelay:e.baseDelay,console.assert(this.baseDelay_>=0,"baseDelay should be >= 0"),this.fuzzFactor_=null==e.fuzzFactor?i.fuzzFactor:e.fuzzFactor,console.assert(this.fuzzFactor_>=0,"fuzzFactor should be >= 0"),this.backoffFactor_=null==e.backoffFactor?i.backoffFactor:e.backoffFactor,console.assert(this.backoffFactor_>=0,"backoffFactor should be >= 0"),this.numAttempts_=0,this.nextUnfuzzedDelay_=this.baseDelay_,this.autoReset_=t,this.autoReset_&&(console.assert(this.maxAttempts_>=2,"maxAttempts must be >= 2 for autoReset == true"),this.numAttempts_=1)}async attempt(){if(this.numAttempts_>=this.maxAttempts_){if(!this.autoReset_)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.ATTEMPTS_EXHAUSTED);this.reset_()}const e=this.numAttempts_;if(this.numAttempts_++,0==e)return void console.assert(!this.autoReset_,"Failed to delay with auto-reset!");const t=M.fuzz_(this.nextUnfuzzedDelay_,this.fuzzFactor_);await new Promise((e=>{M.defer(t,e)})),this.nextUnfuzzedDelay_*=this.backoffFactor_}static defaultRetryParameters(){return{maxAttempts:2,baseDelay:1e3,backoffFactor:2,fuzzFactor:.5,timeout:3e4,stallTimeout:5e3,connectionTimeout:1e4}}static fuzz_(e,t){return e*(1+(2*Math.random()-1)*t)}reset_(){console.assert(this.autoReset_,"Should only be used for auto-reset!"),this.numAttempts_=1,this.nextUnfuzzedDelay_=this.baseDelay_}static defer(e,t){new o(t).tickAfter(e/1e3)}static get[Symbol.for("___CTOR_ARGS___")](){return["RetryParameters","boolean"]}}!function(e){e[e.MANIFEST=0]="MANIFEST",e[e.SEGMENT=1]="SEGMENT",e[e.LICENSE=2]="LICENSE",e[e.APP=3]="APP",e[e.TIMING=4]="TIMING",e[e.SERVER_CERTIFICATE=5]="SERVER_CERTIFICATE",e[e.KEY=6]="KEY",e[e.ADS=7]="ADS",e[e.CONTENT_STEERING=8]="CONTENT_STEERING"}(u||(u={})),function(e){e[e.INIT_SEGMENT=0]="INIT_SEGMENT",e[e.MEDIA_SEGMENT=1]="MEDIA_SEGMENT",e[e.MEDIA_PLAYLIST=2]="MEDIA_PLAYLIST",e[e.MASTER_PLAYLIST=3]="MASTER_PLAYLIST",e[e.MPD=4]="MPD",e[e.MSS=5]="MSS"}(_||(_={})),function(e){e[e.FALLBACK=1]="FALLBACK",e[e.PREFERRED=2]="PREFERRED",e[e.APPLICATION=3]="APPLICATION"}(m||(m={}));class R extends w{constructor(e,t,i){super(e,t),this.bytesRemaining_=i}getBytesRemaining(){return this.bytesRemaining_.getBytes()}static get[Symbol.for("___CTOR_ARGS___")](){return["Promise","() => Promise<void>","NumBytesRemainingClass"]}}class O extends a{constructor(e,t,i,n,s){super(),this.destroyed_=!1,this.operationManager_=new A,this.requestFilters_=new Set,this.responseFilters_=new Set,this.onProgressUpdated_=e||null,this.onHeadersReceived_=t||null,this.onDownloadFailed_=i||null,this.onRequest_=n||null,this.onRetry_=s||null,this.forceHTTPS_=!1}setForceHTTPS(e){this.forceHTTPS_=e}static registerScheme(e,t,i,n=!1){console.assert(null==i||i>0,"explicit priority must be > 0"),i=i||O.PluginPriority.APPLICATION;const s=O.schemes_[e];(!s||i>=s.priority)&&(O.schemes_[e]={priority:i,plugin:t,progressSupport:n})}static unregisterScheme(e){delete O.schemes_[e]}registerRequestFilter(e){this.requestFilters_.add(e)}unregisterRequestFilter(e){this.requestFilters_.delete(e)}clearAllRequestFilters(){this.requestFilters_.clear()}registerResponseFilter(e){this.responseFilters_.add(e)}unregisterResponseFilter(e){this.responseFilters_.delete(e)}clearAllResponseFilters(){this.responseFilters_.clear()}static defaultRetryParameters(){return M.defaultRetryParameters()}static makeRequest(e,t,i=null){return{contentType:null,packetNumber:null,requestStartTime:null,timeToFirstByte:null,uris:e,method:"GET",body:null,headers:{},allowCrossSiteCredentials:!1,retryParameters:t,licenseRequestType:null,sessionId:null,drmInfo:null,initData:null,initDataType:null,streamDataCallback:i}}destroy(){return this.destroyed_=!0,this.requestFilters_.clear(),this.responseFilters_.clear(),super.release(),this.operationManager_.destroy()}request(e,t,i=null){const n=new O.NumBytesRemainingClass;if(this.destroyed_){const e=Promise.reject(new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.OPERATION_ABORTED));return e.catch((()=>{})),new O.PendingRequest(e,(()=>Promise.resolve()),n)}console.assert(t.uris&&t.uris.length,"Request without URIs!"),t.method=t.method||"GET",t.headers=t.headers||{},t.retryParameters=t.retryParameters?b.cloneObject(t.retryParameters):O.defaultRetryParameters(),t.uris=b.cloneObject(t.uris);const s=this.filterRequest_(e,t,i),a=s.chain((()=>this.makeRequestWithRetry_(e,t,i,n))),r=a.chain((t=>this.filterResponse_(e,t,i))),o=Date.now();let l=0;s.promise.then((()=>{l=Date.now()-o}),(()=>{}));let d=0;a.promise.then((()=>{d=Date.now()}),(()=>{}));const c=r.chain((n=>{var s;const a=Date.now()-d,r=n.response;if(null!=r.timeMs&&(r.timeMs+=l,r.timeMs+=a),!n.gotProgress&&this.onProgressUpdated_&&!r.fromCache&&"HEAD"!=t.method&&e==O.RequestType.SEGMENT){const e=this.allowSwitch_(i);this.onProgressUpdated_(null!==(s=r.timeMs)&&void 0!==s?s:0,r.data.byteLength,e,t)}return r}),(e=>{throw e&&(console.assert(e instanceof v,"Wrong error type"),e.severity=v.Severity.CRITICAL),e})),h=new O.PendingRequest(c.promise,(()=>c.abort()),n);return this.operationManager_.manage(h),h}filterRequest_(e,t,i){let n=w.completed(void 0);const s=s=>{n=n.chain((n=>(t.body&&(t.body=l.toArrayBuffer(t.body)),s(e,t,i))))};this.onRequest_&&s(this.onRequest_);for(const e of this.requestFilters_)s(e);return n.chain(void 0,(e=>{if(e&&e instanceof v&&e.code==v.Code.OPERATION_ABORTED)throw e;throw new v(v.Severity.CRITICAL,v.Category.NETWORK,v.Code.REQUEST_FILTER_ERROR,e)}))}makeRequestWithRetry_(e,t,i,n){const s=new M(t.retryParameters,!1);return this.send_(e,t,i,s,0,null,n)}send_(e,t,i,n,a,r,l){if(this.forceHTTPS_&&(t.uris[a]=t.uris[a].replace("http://","https://")),a>0&&this.onRetry_){const n=t.uris[a],s=t.uris[a-1];this.onRetry_(e,i,n,s)}const d=new URL(t.uris[a]),c=d.protocol;console.assert(":"==c[c.length-1],"uri.protocol expected to end with a colon!");let h=c.slice(0,-1),u=!1;h||(h=O.getLocationProtocol_(),console.assert(":"==h[h.length-1],"location.protocol expected to end with a colon!"),h=h.slice(0,-1),d.protocol=h,t.uris[a]=d.toString()),h=h.toLowerCase();const _=O.schemes_[h],m=_?_.plugin:null;if(!m)return w.failed(new v(v.Severity.CRITICAL,v.Category.NETWORK,v.Code.UNSUPPORTED_SCHEME,d));const g=_.progressSupport,f=w.notAbortable(n.attempt());let p,T=null,S=null,y=!1,E=!1;return f.chain((n=>{if(this.destroyed_)return w.aborted();p=Date.now();const s=O.RequestType.SEGMENT;let r=0;t.requestStartTime=Date.now();const d=m(t.uris[a],t,e,((n,a,o)=>{if(T&&T.stop(),S&&S.tickAfter(h/1e3),this.onProgressUpdated_&&e==s){r++,t.packetNumber=r;const e=this.allowSwitch_(i);this.onProgressUpdated_(n,a,e,t),u=!0,l.setBytes(o)}}),(i=>{this.onHeadersReceived_&&this.onHeadersReceived_(i,t,e),E=!0,t.timeToFirstByte=Date.now()-t.requestStartTime}));if(!g)return d;const c=t.retryParameters.connectionTimeout;c&&(T=new o((()=>{y=!0,d.abort()})),T.tickAfter(c/1e3));const h=t.retryParameters.stallTimeout;return h&&(S=new o((()=>{y=!0,d.abort()}))),d})).chain((i=>{T&&T.stop(),S&&S.stop(),null==i.timeMs&&(i.timeMs=Date.now()-p);const n={response:i,gotProgress:u};return E||this.onHeadersReceived_&&this.onHeadersReceived_(i.headers,t,e),n}),(o=>{if(T&&T.stop(),S&&S.stop(),this.onDownloadFailed_){let e=null,i=0;o instanceof v&&(e=o,o.code==v.Code.BAD_HTTP_STATUS&&(i=o.data[1])),this.onDownloadFailed_(t,e,i,y)}if(this.destroyed_)return w.aborted();if(y&&(o=new v(v.Severity.RECOVERABLE,v.Category.NETWORK,v.Code.TIMEOUT,t.uris[a],e)),o instanceof v){if(o.code==v.Code.OPERATION_ABORTED)throw o;if(o.code==v.Code.ATTEMPTS_EXHAUSTED)throw console.assert(r,"Should have last error"),r;if(o.severity==v.Severity.RECOVERABLE){const r=(new Map).set("error",o),d=new s("retry",r);return this.dispatchEvent(d),a=(a+1)%t.uris.length,this.send_(e,t,i,n,a,o,l)}}throw o}))}filterResponse_(e,t,i){let n=w.completed(void 0);for(const s of this.responseFilters_)n=n.chain((()=>{const n=t.response;return n.data&&(n.data=l.toArrayBuffer(n.data)),s(e,n,i)}));return n.chain((()=>t),(e=>{let t=v.Severity.CRITICAL;if(e instanceof v){if(e.code==v.Code.OPERATION_ABORTED)throw e;t=e.severity}throw new v(t,v.Category.NETWORK,v.Code.RESPONSE_FILTER_ERROR,e)}))}allowSwitch_(e){if(e){const t=e.segment,i=e.stream;if(t&&i&&i.fastSwitching&&t.isPartial())return!1}return!0}static getLocationProtocol_(){return location.protocol}static get[Symbol.for("___CTOR_ARGS___")](){return["NetworkOnProgressUpdated","NetworkOnHeadersReceived","NetworkOnDownloadFailed","NetworkOnRequest","NetworkOnRetry"]}}O.RequestType=u,O.AdvancedRequestType=_,O.PluginPriority=m,O.PendingRequest=R,O.NumBytesRemainingClass=class{constructor(){this.bytesToLoad_=0}setBytes(e){this.bytesToLoad_=e}getBytes(){return this.bytesToLoad_}},O.schemes_={};class D{static async getMimeType(e,t,i){const n=D.getExtension_(e);let s=D.EXTENSIONS_TO_MIME_TYPES_[n];if(s)return s;const a=O.RequestType.MANIFEST,r=O.makeRequest([e],i);try{r.method="HEAD",s=(await t.request(a,r).promise).headers["content-type"]}catch(e){!e||e.code!=v.Code.HTTP_ERROR&&e.code!=v.Code.BAD_HTTP_STATUS||(r.method="GET",s=(await t.request(a,r).promise).headers["content-type"])}return s?s.toLowerCase().split(";").shift():""}static getExtension_(e){const t=new URL(e).pathname.split("/").pop().split(".");return 1==t.length?"":t.pop().toLowerCase()}}D.EXTENSIONS_TO_MIME_TYPES_={mp4:"video/mp4",m4v:"video/mp4",m4a:"audio/mp4",webm:"video/webm",weba:"audio/webm",mkv:"video/webm",ts:"video/mp2t",ogv:"video/ogg",ogg:"audio/ogg",mpg:"video/mpeg",mpeg:"video/mpeg",m3u8:"application/x-mpegurl",mpd:"application/dash+xml",ism:"application/vnd.ms-sstr+xml",mp3:"audio/mpeg",aac:"audio/aac",flac:"audio/flac",wav:"audio/wav",sbv:"text/x-subviewer",srt:"text/srt",vtt:"text/vtt",webvtt:"text/vtt",ttml:"application/ttml+xml",lrc:"application/x-subtitle-lrc",ssa:"text/x-ssa",ass:"text/x-ssa"};class P{static supportsMediaSource(){const e=window.ManagedMediaSource||window.MediaSource;return!!e&&!!e.isTypeSupported}static supportsMediaType(e){return""!=P.anyMediaElement().canPlayType(e)}static isEdge(){return!!navigator.userAgent.match(/Edge?\//)}static isLegacyEdge(){return!!navigator.userAgent.match(/Edge\//)}static isIE(){return P.userAgentContains_("Trident/")}static isXboxOne(){return P.userAgentContains_("Xbox One")}static isTizen(){return P.userAgentContains_("Tizen")}static isTizen4(){return P.userAgentContains_("Tizen 4")}static isTizen3(){return P.userAgentContains_("Tizen 3")}static isTizen2(){return P.userAgentContains_("Tizen 2")}static isWebOS(){return P.userAgentContains_("Web0S")}static isWebOS3(){return P.userAgentContains_("Web0S")&&P.userAgentContains_("Chrome/38.0.2125.122 Safari/537.36")}static isWebOS4(){return!!navigator.userAgent.match(/webOS\/4/i)}static isWebOS5(){return!!navigator.userAgent.match(/webOS\/5/i)}static isChromecast(){return P.userAgentContains_("CrKey")}static chromeVersion(){if(!P.isChrome())return null;const e=navigator.userAgent.match(/Chrome\/(\d+)/);return e?parseInt(e[1],10):null}static isChrome(){return P.userAgentContains_("Chrome")&&!P.isLegacyEdge()}static isFirefox(){return P.userAgentContains_("Firefox")}static isApple(){return!!navigator.vendor&&navigator.vendor.includes("Apple")&&!P.isTizen()&&!P.isEOS()&&!P.isAPL()&&!P.isVirginMedia()&&!P.isOrange()&&!P.isPS4()&&!P.isAmazonFireTV()&&!P.isWPE()}static isPS5(){return P.userAgentContains_("PlayStation 5")}static isPS4(){return P.userAgentContains_("PlayStation 4")}static isHisense(){return P.userAgentContains_("Hisense")||P.userAgentContains_("VIDAA")}static isVirginMedia(){return P.userAgentContains_("VirginMedia")}static isOrange(){return P.userAgentContains_("SOPOpenBrowser")}static isAmazonFireTV(){return P.userAgentContains_("AFT")}static isWPE(){return P.userAgentContains_("WPE")}static safariVersion(){if(!P.isApple())return null;let e=navigator.userAgent.match(/Version\/(\d+)/);return e?parseInt(e[1],10):(e=navigator.userAgent.match(/OS (\d+)(?:_\d+)?/),e?parseInt(e[1],10):null)}static isSafari(){return!!P.safariVersion()}static isEOS(){return P.userAgentContains_("PC=EOS")}static isAPL(){return P.userAgentContains_("PC=APL")}static isMobile(){return!!/(?:iPhone|iPad|iPod|Android)/.test(navigator.userAgent)||P.isApple()&&navigator.maxTouchPoints>1}static isMac(){return navigator.userAgentData&&navigator.userAgentData.platform?"macos"==navigator.userAgentData.platform.toLowerCase():navigator.platform.toLowerCase().includes("mac")}static isWindows(){return navigator.userAgentData&&navigator.userAgentData.platform?"windows"==navigator.userAgentData.platform.toLowerCase():navigator.platform.toLowerCase().includes("windows")}static isAndroid(){return P.userAgentContains_("Android")}static userAgentContains_(e){return(navigator.userAgent||"").includes(e)}static anyMediaElement(){return P.cachedMediaElement_||(P.cacheExpirationTimer_||(P.cacheExpirationTimer_=new o((()=>{P.cachedMediaElement_=null}))),P.cachedMediaElement_=document.getElementsByTagName("video")[0]||document.getElementsByTagName("audio")[0],P.cachedMediaElement_||(P.cachedMediaElement_=document.createElement("video")),P.cacheExpirationTimer_.tickAfter(1)),P.cachedMediaElement_}static requiresEncryptionInfoInAllInitSegments(){return P.isTizen()||P.isXboxOne()||P.isOrange()}static supportsSequenceMode(){return!(P.isTizen3()||P.isTizen2()||P.isWebOS3()||P.isPS4())}static supportsSmoothCodecSwitching(){return!(P.isTizen2()||P.isTizen3()||P.isTizen4()||P.isWebOS3()||P.isWebOS4()||P.isWebOS5()||P.isWindows()&&P.isEdge())}static isMediaKeysPolyfilled(){return!!window.shakaMediaKeysPolyfill}static async detectMaxHardwareResolution(){const e={width:1/0,height:1/0};if(P.isChromecast())window.cast&&cast.__platform__&&cast.__platform__.canDisplayType&&cast.__platform__.canDisplayType('video/mp4; codecs="avc1.640028"; width=3840; height=2160')?(e.width=3840,e.height=2160):(e.width=1920,e.height=1080);else if(P.isTizen()){e.width=1920,e.height=1080;try{if(webapis.systeminfo&&webapis.systeminfo.getMaxVideoResolution){const t=webapis.systeminfo.getMaxVideoResolution();e.width=t.width,e.height=t.height}else webapis.productinfo.is8KPanelSupported&&webapis.productinfo.is8KPanelSupported()?(e.width=7680,e.height=4320):webapis.productinfo.isUdPanelSupported&&webapis.productinfo.isUdPanelSupported()&&(e.width=3840,e.height=2160)}catch(e){i.alwaysWarn("Tizen: Error detecting screen size, default screen size 1920x1080.")}}else if(P.isXboxOne()){const t=new Windows.Media.Protection.ProtectionCapabilities,i=Windows.Media.Protection.ProtectionCapabilityResult;let n=null;try{const e='video/mp4;codecs="hvc1,mp4a";features="decode-res-x=3840,decode-res-y=2160,decode-bitrate=20000,decode-fps=30,decode-bpc=10,display-res-x=3840,display-res-y=2160,display-bpc=8"',s="com.microsoft.playready.recommendation";do{n=t.isTypeSupported(e,s)}while(n===i.maybe)}catch(e){n=i.notSupported}n===i.probably?(e.width=3840,e.height=2160):(e.width=1920,e.height=1080)}else if(P.isWebOS())try{const t=JSON.parse(window.PalmSystem.deviceInfo);e.width=Math.max(1920,t.screenWidth),e.height=Math.max(1080,t.screenHeight)}catch(t){i.alwaysWarn("WebOS: Error detecting screen size, default screen size 1920x1080."),e.width=1920,e.height=1080}else if(P.isHisense())window.Hisense_Get4KSupportState&&window.Hisense_Get4KSupportState()?(e.width=3840,e.height=2160):(e.width=1920,e.height=1080);else if(P.isPS4()||P.isPS5()){let t=!1;try{t="4K"===(await window.msdk.device.getDisplayInfo()).resolution}catch(e){try{t="4K"===(await window.msdk.device.getDisplayInfoImmediate()).resolution}catch(e){i.alwaysWarn("PlayStation: Failed to get the display info:",e)}}t?(e.width=3840,e.height=2160):(e.width=1920,e.height=1080)}return e}}P.cacheExpirationTimer_=null,P.cachedMediaElement_=null;class N{constructor(e){this.gen_=e,this.value_=void 0}value(){return null==this.value_&&(this.value_=this.gen_(),console.assert(null!=this.value_,"Unable to create lazy value")),this.value_}reset(){this.value_=void 0}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class L{static fromUTF8(e){if(!e)return"";let t=l.toUint8(e);if(239==t[0]&&187==t[1]&&191==t[2]&&(t=t.subarray(3)),window.TextDecoder&&!P.isPS4()){const e=(new TextDecoder).decode(t);return e.includes("�")&&i.alwaysError('Decoded string contains an "unknown character" codepoint. That probably means the UTF8 encoding was incorrect!'),e}{let e="";for(let i=0;i<t.length;++i){let n=65533;if(0==(128&t[i])?n=t[i]:t.length>=i+2&&192==(224&t[i])&&128==(192&t[i+1])?(n=(31&t[i])<<6|63&t[i+1],i+=1):t.length>=i+3&&224==(240&t[i])&&128==(192&t[i+1])&&128==(192&t[i+2])?(n=(15&t[i])<<12|(63&t[i+1])<<6|63&t[i+2],i+=2):t.length>=i+4&&240==(241&t[i])&&128==(192&t[i+1])&&128==(192&t[i+2])&&128==(192&t[i+3])&&(n=(7&t[i])<<18|(63&t[i+1])<<12|(63&t[i+2])<<6|63&t[i+3],i+=3),n<=65535)e+=String.fromCharCode(n);else{const t=n-65536,i=t>>10,s=1023&t;e+=String.fromCharCode(55296+i),e+=String.fromCharCode(56320+s)}}return e}}static fromUTF16(e,t,n){if(!e)return"";if(!n&&e.byteLength%2!=0)throw i.error("Data has an incorrect length, must be even."),new v(v.Severity.CRITICAL,v.Category.TEXT,v.Code.BAD_ENCODING);const s=Math.floor(e.byteLength/2),a=new Uint16Array(s),r=l.toDataView(e);for(let e=0;e<s;e++)a[e]=r.getUint16(2*e,t);return L.fromCharCode(a)}static fromBytesAutoDetect(e){if(!e)return"";const t=l.toUint8(e);if(239==t[0]&&187==t[1]&&191==t[2])return L.fromUTF8(t);if(254==t[0]&&255==t[1])return L.fromUTF16(t.subarray(2),!1);if(255==t[0]&&254==t[1])return L.fromUTF16(t.subarray(2),!0);const n=e=>t.byteLength<=e||t[e]>=32&&t[e]<=126;if(i.debug("Unable to find byte-order-mark, making an educated guess."),0==t[0]&&0==t[2])return L.fromUTF16(e,!1);if(0==t[1]&&0==t[3])return L.fromUTF16(e,!0);if(n(0)&&n(1)&&n(2)&&n(3))return L.fromUTF8(e);throw new v(v.Severity.CRITICAL,v.Category.TEXT,v.Code.UNABLE_TO_DETECT_ENCODING)}static toUTF8(e){if(window.TextEncoder&&!P.isPS4()){const t=new TextEncoder;return l.toArrayBuffer(t.encode(e))}{const t=encodeURIComponent(e),i=unescape(t),n=new Uint8Array(i.length);for(let e=0;e<i.length;e++){const t=i[e];n[e]=t.charCodeAt(0)}return l.toArrayBuffer(n)}}static toUTF16(e,t){const i=new ArrayBuffer(2*e.length),n=new DataView(i);for(let i=0;i<e.length;++i){const s=e.charCodeAt(i);n.setUint16(2*i,s,t)}return i}static fromCharCode(e){return L.fromCharCodeImpl_.value()(e)}static resetFromCharCode(){L.fromCharCodeImpl_.reset()}static htmlUnescape(e){const t={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&apos;":"'","&nbsp;":" ","&lrm;":"‎","&rlm;":"‏"},i=/&(?:amp|lt|gt|quot|apos|#(0+)?39|nbsp|lrm|rlm);/g,n=RegExp(i.source);return e&&n.test(e)?e.replace(i,(e=>t[e]||"'")):e||""}}L.fromCharCodeImpl_=new N((()=>{const e=e=>{try{const t=new Uint8Array(e),i=String.fromCharCode.apply(null,t);return console.assert(i,"Should get value"),i.length>0}catch(e){return!1}};for(let t=65536;t>0;t/=2)if(e(t))return e=>{let i="";for(let n=0;n<e.length;n+=t){const s=e.subarray(n,n+t);i+=String.fromCharCode.apply(null,s)}return i};return console.assert(!1,"Unable to create a fromCharCode method"),null}));class x{static toStandardBase64(e){const t=L.fromCharCode(l.toUint8(e));return btoa(t)}static toBase64(e,t){t=null==t||t;const i=x.toStandardBase64(e).replace(/\+/g,"-").replace(/\//g,"_");return t?i:i.replace(/[=]*$/,"")}static fromBase64(e){const t=window.atob(e.replace(/-/g,"+").replace(/_/g,"/")),i=new Uint8Array(t.length);for(let e=0;e<t.length;++e)i[e]=t.charCodeAt(e);return i}static fromHex(e){const t=e.length/2,i=new Uint8Array(t);for(let n=0;n<t;n++)i[n]=window.parseInt(e.substr(2*n,2),16);return i}static toHex(e){const t=l.toUint8(e);let i="";for(let e of t)e=e.toString(16),1==e.length&&(e="0"+e),i+=e;return i}static concat(...e){let t=0;for(let i=0;i<e.length;++i)t+=e[i].byteLength;const i=new Uint8Array(t);let n=0;for(let t=0;t<e.length;++t){const s=e[t];s instanceof Uint8Array?i.set(s,n):i.set(l.toUint8(s),n),n+=s.byteLength}return i}}!function(e){e.HLS="HLS",e.DASH="DASH",e.MSS="MSS",e.UNKNOWN="UNKNOWN"}(g||(g={})),function(e){e.VIDEO="video",e.AUDIO="audio",e.TEXT="text",e.IMAGE="image",e.APPLICATION="application",e.UNKNOWN="UNKNOWN"}(f||(f={})),function(e){e.SUBTITLE="subtitle",e.CLOSED_CAPTION="caption"}(p||(p={})),function(e){e.VISUALLY_IMPAIRED="visually impaired",e.HARD_OF_HEARING="hard of hearing"}(T||(T={})),function(e){e.SDR="SDR",e.PQ="PQ",e.HLG="HLG"}(S||(S={}));class k{static resolveUris(e,t){if(0==t.length)return e;if(1==e.length&&1==t.length){const i=new URL(e[0]);return[new URL(t[0],i).toString()]}const i=[];for(const n of e){const e=new URL(n);for(const n of t)i.push(new URL(n,e).toString())}return i}static createDrmInfo(e,t){return{keySystem:e,licenseServerUri:"",distinctiveIdentifierRequired:!1,persistentStateRequired:!1,audioRobustness:"",videoRobustness:"",serverCertificate:null,serverCertificateUri:"",sessionType:"",initData:t||[],keyIds:new Set}}static createDrmInfoFromClearKeys(e){const t=[],i=[],n=[];e.forEach(((e,s)=>{let a=s;22!=a.length&&(a=x.toBase64(x.fromHex(s),!1));let r=e;22!=r.length&&(r=x.toBase64(x.fromHex(e),!1));const o={kty:"oct",kid:a,k:r};t.push(o),i.push(o.kid),n.push(s)}));const s={keys:t},a=JSON.stringify(s),r=JSON.stringify({kids:i}),o=[{initData:l.toUint8(L.toUTF8(r)),initDataType:"keyids",keyId:null}];return{keySystem:"org.w3.clearkey",licenseServerUri:"data:application/json;base64,"+window.btoa(a),distinctiveIdentifierRequired:!1,persistentStateRequired:!1,audioRobustness:"",videoRobustness:"",serverCertificate:null,serverCertificateUri:"",sessionType:"",initData:o,keyIds:new Set(n)}}static guessCodecs(e,t){if(1==t.length)return t[0];const i=k.guessCodecsSafe(e,t);if(null!=i)return i;throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.HLS_COULD_NOT_GUESS_CODECS,t)}static guessCodecsSafe(e,t){const i=k.CODEC_REGEXPS_BY_CONTENT_TYPE_[e];for(const e of i)for(const i of t)if(e.test(i.trim()))return i.trim();return e==k.ContentType.TEXT?"":null}static guessAllCodecsSafe(e,t){const i=[],n=k.CODEC_REGEXPS_BY_CONTENT_TYPE_[e];for(const e of n)for(const n of t)e.test(n.trim())&&i.push(n.trim());return i}}k.ContentType=f,k.TextStreamKind=p,k.GAP_OVERLAP_TOLERANCE_SECONDS=1/15,k.VIDEO_CODEC_REGEXPS_=[/^avc/,/^hev/,/^hvc/,/^vvc/,/^vvi/,/^vp0?[89]/,/^av01/,/^dvh/,/^dva/,/^dav/],k.AUDIO_CODEC_REGEXPS_=[/^vorbis$/,/^Opus$/,/^opus$/,/^fLaC$/,/^flac$/,/^mp4a/,/^[ae]c-3$/,/^ac-4$/,/^dts[cex]$/,/^iamf/],k.TEXT_CODEC_REGEXPS_=[/^vtt$/,/^wvtt/,/^stpp/],k.CODEC_REGEXPS_BY_CONTENT_TYPE_={[f.AUDIO]:k.AUDIO_CODEC_REGEXPS_,[f.VIDEO]:k.VIDEO_CODEC_REGEXPS_,[f.TEXT]:k.TEXT_CODEC_REGEXPS_};class U{destroy(){}static registerTransmuxer(e,t,i){const n=U.normalizeMimeType_(e)+"-"+i;U.transmuxerMap_[n]={priority:i,plugin:t}}static unregisterTransmuxer(e,t){const i=U.normalizeMimeType_(e)+"-"+t;delete U.transmuxerMap_[i]}static findTransmuxer(e,t){const i=U.normalizeMimeType_(e),n=[U.PluginPriority.APPLICATION,U.PluginPriority.PREFERRED,U.PluginPriority.PREFERRED_SECONDARY,U.PluginPriority.FALLBACK];for(const s of n){const n=i+"-"+s,a=U.transmuxerMap_[n];if(a){const i=a.plugin(),n=i.isSupported(e,t);if(i.destroy(),n)return a.plugin}}return null}static normalizeMimeType_(e){return e.toLowerCase().split(";")[0]}static isSupported(e,t){return!!U.findTransmuxer(e)}static convertCodecs(e,t){const i=U.findTransmuxer(t);if(!i)return t;const n=i(),s=n.convertCodecs(e,t);return n.destroy(),s}}U.transmuxerMap_={},U.PluginPriority={FALLBACK:1,PREFERRED_SECONDARY:2,PREFERRED:3,APPLICATION:4};class B{static getFullType(e,t){let i=e;return t&&!B.RAW_FORMATS.includes(e)&&(i+='; codecs="'+t+'"'),i}static getFullTypeWithAllCodecs(e,t){let i=e;return t&&(i+='; codecs="'+t+'"'),i}static getFullOrConvertedType(e,t,i){const n=B.getFullType(e,t),s=B.getFullTypeWithAllCodecs(e,t),a=k.ContentType;return U.isSupported(s,i)?U.convertCodecs(i,s):"video/mp2t"!=e&&i==a.AUDIO?n.replace("video","audio"):n}static getExtendedType(e){const t=[e.mimeType];return B.EXTENDED_MIME_PARAMETERS_.forEach(((i,n)=>{const s=e[n];"codecs"==n&&B.RAW_FORMATS.includes(e.mimeType)||s&&t.push(i+'="'+s+'"')})),e.hdr===S.PQ&&t.push('eotf="smpte2084"'),t.join(";")}static getContainerType(e){return e.split(";")[0].split("/")[1]}static splitCodecs(e){return e.split(",")}static getNormalizedCodec(e){const t=B.getCodecParts_(e),i=t[0],n=t[1].toLowerCase();switch(!0){case"mp4a"===i&&"69"===n:case"mp4a"===i&&"6b"===n:case"mp4a"===i&&"40.34"===n:return"mp3";case"mp4a"===i&&"66"===n:case"mp4a"===i&&"67"===n:case"mp4a"===i&&"68"===n:case"mp4a"===i&&"40.2"===n:case"mp4a"===i&&"40.02"===n:case"mp4a"===i&&"40.5"===n:case"mp4a"===i&&"40.05"===n:case"mp4a"===i&&"40.29"===n:case"mp4a"===i&&"40.42"===n:return"aac";case"mp4a"===i&&"a5"===n:return"ac-3";case"mp4a"===i&&"a6"===n:return"ec-3";case"mp4a"===i&&"b2"===n:return"dtsx";case"mp4a"===i&&"a9"===n:return"dtsc";case"avc1"===i:case"avc3"===i:return"avc";case"hvc1"===i:case"hev1"===i:return"hevc";case"dvh1"===i:case"dvhe"===i:return"dovi"}return i}static getCodecBase(e){const t=[];for(const i of e.split(",")){const e=B.getCodecParts_(i);t.push(e[0])}return t.sort().join(",")}static getBasicType(e){return e.split(";")[0]}static getCodecs(e){const t=e.split(/ *; */);t.shift();const i=t.find((e=>e.startsWith("codecs=")));return i?i.split("=")[1].replace(/^"|"$/g,""):""}static isHlsType(e){return"application/x-mpegurl"===e||"application/vnd.apple.mpegurl"===e}static getCodecParts_(e){const t=e.split("."),i=t[0];return t.shift(),[i,t.join(".")]}}B.EXTENDED_MIME_PARAMETERS_=(new Map).set("codecs","codecs").set("frameRate","framerate").set("bandwidth","bitrate").set("width","width").set("height","height").set("channelsCount","channels"),B.CEA608_CLOSED_CAPTION_MIMETYPE="application/cea-608",B.CEA708_CLOSED_CAPTION_MIMETYPE="application/cea-708",B.RAW_FORMATS=["audio/aac","audio/ac3","audio/ec3","audio/mpeg"];class F{static createFallbackPromiseChain(e,t){return e.reduce(((e,i)=>e.catch((()=>t(i)))),Promise.reject())}static collapseArrays(e,t){return e.concat(t)}static ignored(...e){}static noop(){}static isNotNull(e){return null!=e}}class V{static isTypeSupported(e){const t=V.MediaSourceTypeSupportMap;if(t.has(e))return t.get(e);if(window.ManagedMediaSource){const i=ManagedMediaSource.isTypeSupported(e);return t.set(e,i),i}if(window.MediaSource){const i=MediaSource.isTypeSupported(e);return t.set(e,i),i}return!1}static isChangeTypeSupported(){return!!window.SourceBuffer&&!!SourceBuffer.prototype&&!!SourceBuffer.prototype.changeType}}V.MediaSourceTypeSupportMap=new Map;class G{static areLocaleCompatible(e,t){const i=i;return(e=i.normalize(e))==i.normalize(t)}static areLanguageCompatible(e,t){const i=i;e=i.normalize(e),t=i.normalize(t);const n=i.disassembleLocale_(e),s=i.disassembleLocale_(t);return n[0]==s[0]}static isParentOf(e,t){e=G.normalize(e),t=G.normalize(t);const i=G.disassembleLocale_(e),n=G.disassembleLocale_(t);return i[0]==n[0]&&1==i.length&&2==n.length}static isSiblingOf(e,t){e=G.normalize(e),t=G.normalize(t);const i=G.disassembleLocale_(e),n=G.disassembleLocale_(t);return 2==i.length&&2==n.length&&i[0]==n[0]}static normalize(e){const[t="",i=""]=e.split("-x-"),[n="",s=""]=t.split("-"),a=i?`x-${i}`:"";let r=n.toLowerCase();r=G.isoMap_.get(r)||r;const o=s.toUpperCase();return`${o?`${r}-${o}`:r}${a?`-${a}`:""}`}static areSiblings(e,t){const i=i,n=i.getBase(e),s=i.getBase(t);return e!=n&&t!=s&&n==s}static relatedness(e,t){const i=i;return e=i.normalize(e),(t=i.normalize(t))==e?4:i.isParentOf(t,e)?3:i.isSiblingOf(t,e)?2:i.isParentOf(e,t)?1:0}static getBase(e){const t=t,i=e.indexOf("-");let n;return n=i>=0?e.substring(0,i):e,n=n.toLowerCase(),n=t.isoMap_.get(n)||n,n}static getLocaleForText(e){const t=t,i=k.ContentType;console.assert(e.type==i.TEXT,"Can only get language from text streams");const n=e.language||"und";return t.normalize(n)}static getLocaleForVariant(e){return e.language?G.normalize(e.language):e.audio&&e.audio.language?G.normalize(e.audio.language):e.video&&e.video.language?G.normalize(e.video.language):"und"}static findClosestLocale(e,t){const i=G.normalize(e),n=new Set;for(const e of t)n.add(G.normalize(e));for(const e of n)if(e==i)return e;for(const e of n)if(G.isParentOf(e,i))return e;for(const e of n)if(G.isSiblingOf(e,i))return e;for(const e of n)if(G.isParentOf(i,e))return e;return null}static disassembleLocale_(e){const t=e.split("-");return console.assert(t.length<=2,["Locales should not have more than 2 components. ",e," has too many components."].join()),t}}G.isoMap_=new Map([["aar","aa"],["abk","ab"],["afr","af"],["aka","ak"],["alb","sq"],["amh","am"],["ara","ar"],["arg","an"],["arm","hy"],["asm","as"],["ava","av"],["ave","ae"],["aym","ay"],["aze","az"],["bak","ba"],["bam","bm"],["baq","eu"],["bel","be"],["ben","bn"],["bih","bh"],["bis","bi"],["bod","bo"],["bos","bs"],["bre","br"],["bul","bg"],["bur","my"],["cat","ca"],["ces","cs"],["cha","ch"],["che","ce"],["chi","zh"],["chu","cu"],["chv","cv"],["cor","kw"],["cos","co"],["cre","cr"],["cym","cy"],["cze","cs"],["dan","da"],["deu","de"],["div","dv"],["dut","nl"],["dzo","dz"],["ell","el"],["eng","en"],["epo","eo"],["est","et"],["eus","eu"],["ewe","ee"],["fao","fo"],["fas","fa"],["fij","fj"],["fin","fi"],["fra","fr"],["fre","fr"],["fry","fy"],["ful","ff"],["geo","ka"],["ger","de"],["gla","gd"],["gle","ga"],["glg","gl"],["glv","gv"],["gre","el"],["grn","gn"],["guj","gu"],["hat","ht"],["hau","ha"],["heb","he"],["her","hz"],["hin","hi"],["hmo","ho"],["hrv","hr"],["hun","hu"],["hye","hy"],["ibo","ig"],["ice","is"],["ido","io"],["iii","ii"],["iku","iu"],["ile","ie"],["ina","ia"],["ind","id"],["ipk","ik"],["isl","is"],["ita","it"],["jav","jv"],["jpn","ja"],["kal","kl"],["kan","kn"],["kas","ks"],["kat","ka"],["kau","kr"],["kaz","kk"],["khm","km"],["kik","ki"],["kin","rw"],["kir","ky"],["kom","kv"],["kon","kg"],["kor","ko"],["kua","kj"],["kur","ku"],["lao","lo"],["lat","la"],["lav","lv"],["lim","li"],["lin","ln"],["lit","lt"],["ltz","lb"],["lub","lu"],["lug","lg"],["mac","mk"],["mah","mh"],["mal","ml"],["mao","mi"],["mar","mr"],["may","ms"],["mkd","mk"],["mlg","mg"],["mlt","mt"],["mon","mn"],["mri","mi"],["msa","ms"],["mya","my"],["nau","na"],["nav","nv"],["nbl","nr"],["nde","nd"],["ndo","ng"],["nep","ne"],["nld","nl"],["nno","nn"],["nob","nb"],["nor","no"],["nya","ny"],["oci","oc"],["oji","oj"],["ori","or"],["orm","om"],["oss","os"],["pan","pa"],["per","fa"],["pli","pi"],["pol","pl"],["por","pt"],["pus","ps"],["que","qu"],["roh","rm"],["ron","ro"],["rum","ro"],["run","rn"],["rus","ru"],["sag","sg"],["san","sa"],["sin","si"],["slk","sk"],["slo","sk"],["slv","sl"],["sme","se"],["smo","sm"],["sna","sn"],["snd","sd"],["som","so"],["sot","st"],["spa","es"],["sqi","sq"],["srd","sc"],["srp","sr"],["ssw","ss"],["sun","su"],["swa","sw"],["swe","sv"],["tah","ty"],["tam","ta"],["tat","tt"],["tel","te"],["tgk","tg"],["tgl","tl"],["tha","th"],["tib","bo"],["tir","ti"],["ton","to"],["tsn","tn"],["tso","ts"],["tuk","tk"],["tur","tr"],["twi","tw"],["uig","ug"],["ukr","uk"],["urd","ur"],["uzb","uz"],["ven","ve"],["vie","vi"],["vol","vo"],["wel","cy"],["wln","wa"],["wol","wo"],["xho","xh"],["yid","yi"],["yor","yo"],["zha","za"],["zho","zh"],["zul","zu"]]);class H{init(e){}parse(e){return[]}}class W{extract(e,t){}decode(){return[]}clear(){}getStreams(){return[]}}class q{constructor(e){this.ceaParser_=new H;const t=q.findParser(e.toLowerCase());t&&(this.ceaParser_=t()),this.ceaDecoder_=new W;const i=q.findDecoder();i&&(this.ceaDecoder_=i())}init(e){this.ceaParser_.init(e)}parseFrom(e){const t=this.ceaParser_.parse(e);for(const e of t){const t=l.toUint8(e.packet);t.length>0&&this.ceaDecoder_.extract(t,e.pts)}return this.ceaDecoder_.decode()}reset(){this.ceaDecoder_.clear()}getStreams(){return this.ceaDecoder_.getStreams()}static registerParser(e,t){q.parserMap_[e]=t}static unregisterParser(e){delete q.parserMap_[e]}static findParser(e){return q.parserMap_[e]}static registerDecoder(e){q.decoderFactory_=e}static unregisterDecoder(){q.decoderFactory_=null}static findDecoder(){return q.decoderFactory_}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}q.parserMap_={},q.decoderFactory_=null;class X{constructor(e){this.parser_=null,this.displayer_=e,this.segmentRelativeVttTiming_=!1,this.timestampOffset_=0,this.appendWindowStart_=0,this.appendWindowEnd_=1/0,this.bufferStart_=null,this.bufferEnd_=null,this.selectedClosedCaptionId_="",this.modifyCueCallback_=(e,t)=>{},this.closedCaptionsMap_=new Map}static registerParser(e,t){X.parserMap_[e]=t}static unregisterParser(e){delete X.parserMap_[e]}static findParser(e){return X.parserMap_[e]}static isTypeSupported(e){return!!X.parserMap_[e]||(e==B.CEA608_CLOSED_CAPTION_MIMETYPE||e==B.CEA708_CLOSED_CAPTION_MIMETYPE)&&Boolean(q.findDecoder())}destroy(){return this.parser_=null,this.displayer_=null,this.closedCaptionsMap_.clear(),Promise.resolve()}setDisplayer(e){this.displayer_=e}initParser(e,t,n,s){if(e==B.CEA608_CLOSED_CAPTION_MIMETYPE||e==B.CEA708_CLOSED_CAPTION_MIMETYPE)return void(this.parser_=null);const a=X.parserMap_[e];console.assert(a,"Text type negotiation should have happened already"),this.parser_=a(),this.parser_.setSequenceMode?this.parser_.setSequenceMode(t):i.alwaysWarn('Text parsers should have a "setSequenceMode" method!'),this.parser_.setManifestType?this.parser_.setManifestType(s):i.alwaysWarn('Text parsers should have a "setManifestType" method!'),this.segmentRelativeVttTiming_=n}setModifyCueCallback(e){this.modifyCueCallback_=e}async appendBuffer(e,t,i,n){if(console.assert(this.parser_,"The parser should already be initialized"),await Promise.resolve(),!this.parser_||!this.displayer_)return;if(null==t||null==i)return void this.parser_.parseInit(l.toUint8(e));const s=this.segmentRelativeVttTiming_?t:this.timestampOffset_,a={periodStart:this.timestampOffset_,segmentStart:t,segmentEnd:i,vttOffset:s},r=this.parser_.parseMedia(l.toUint8(e),a,n);for(const e of r)this.modifyCueCallback_(e,n||null,a);const o=r.filter((e=>e.startTime>=this.appendWindowStart_&&e.startTime<this.appendWindowEnd_));this.displayer_.append(o),null==this.bufferStart_?this.bufferStart_=Math.max(t,this.appendWindowStart_):(console.assert(null!=this.bufferEnd_,"There should already be a buffered range end."),console.assert(t-this.bufferEnd_<=1,"There should not be a gap in text references >1s")),this.bufferEnd_=Math.min(i,this.appendWindowEnd_)}async remove(e,t){await Promise.resolve(),this.displayer_&&this.displayer_.remove(e,t)&&(null==this.bufferStart_?console.assert(null==this.bufferEnd_,"end must be null if startTime is null"):(console.assert(null!=this.bufferEnd_,"end must be non-null if startTime is non-null"),t<=this.bufferStart_||e>=this.bufferEnd_||(e<=this.bufferStart_&&t>=this.bufferEnd_?this.bufferStart_=this.bufferEnd_=null:e<=this.bufferStart_&&t<this.bufferEnd_?this.bufferStart_=t:e>this.bufferStart_&&t>=this.bufferEnd_?this.bufferEnd_=e:console.assert(!1,"removal from the middle is not supported by TextEngine"))))}setTimestampOffset(e){this.timestampOffset_=e}setAppendWindow(e,t){this.appendWindowStart_=e,this.appendWindowEnd_=t}bufferStart(){return this.bufferStart_}bufferEnd(){return this.bufferEnd_}isBuffered(e){return null!=this.bufferStart_&&null!=this.bufferEnd_&&e>=this.bufferStart_&&e<this.bufferEnd_}bufferedAheadOf(e){return null==this.bufferEnd_||this.bufferEnd_<e?0:(console.assert(null!=this.bufferStart_,"start should not be null if end is not null"),this.bufferEnd_-Math.max(e,this.bufferStart_))}setSelectedClosedCaptionId(e,t){this.selectedClosedCaptionId_=e;const i=this.closedCaptionsMap_.get(e);if(i)for(const e of i.keys()){const n=i.get(e).filter((e=>e.endTime<=t));n&&this.displayer_.append(n)}}applyVideoTimestampOffsetRecursive_(e,t){e.startTime+=t,e.endTime+=t;for(const i of e.nestedCues)this.applyVideoTimestampOffsetRecursive_(i,t)}storeAndAppendClosedCaptions(e,t,i,n){const s=t+" "+i,a=new Map;for(const t of e){const e=t.stream,i=t.cue;a.has(e)||a.set(e,new Map),a.get(e).has(s)||a.get(e).set(s,[]),this.applyVideoTimestampOffsetRecursive_(i,n),i.startTime>=this.appendWindowStart_&&i.startTime<this.appendWindowEnd_&&(a.get(e).get(s).push(i),e==this.selectedClosedCaptionId_&&this.displayer_.append([i]))}for(const e of a.keys()){this.closedCaptionsMap_.has(e)||this.closedCaptionsMap_.set(e,new Map);for(const t of a.get(e).keys()){const i=a.get(e).get(t);this.closedCaptionsMap_.get(e).set(t,i)}}null==this.bufferStart_?this.bufferStart_=Math.max(t,this.appendWindowStart_):this.bufferStart_=Math.min(this.bufferStart_,Math.max(t,this.appendWindowStart_)),this.bufferEnd_=Math.max(this.bufferEnd_,Math.min(i,this.appendWindowEnd_))}getNumberOfClosedCaptionChannels(){return this.closedCaptionsMap_.size}getNumberOfClosedCaptionsInChannel(e){const t=this.closedCaptionsMap_.get(e);return t?t.size:0}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}X.parserMap_={};class z{static chooseCodecsAndFilterManifest(e,t,s,a){let r=e.variants;if((t.length||s.length)&&(r=z.choosePreferredCodecs(r,t,s)),a.length){const e=new n;for(const t of r)e.push(String(t.video.width||0),t);const t=[];e.forEach(((e,i)=>{let n=0,s=[];for(const e of i){const t=a.filter((t=>e.decodingInfos[0][t])).length;t>n?(n=t,s=[e]):t==n&&s.push(e)}t.push(...s)})),r=t}const o=new Set,l=new Set;for(const e of r)e.audio&&o.add(e.audio),e.video&&l.add(e.video);const d=Array.from(o).sort(((e,t)=>e.bandwidth-t.bandwidth)),c=[],h=new Map,u=e=>e.language+(e.channelsCount||0)+(e.audioSamplingRate||0)+e.roles.join(",")+e.label+e.groupId+e.fastSwitching;for(const e of d){const t=u(e),i=h.get(t)||[];if(i.length){const t=i[i.length-1];B.getNormalizedCodec(t.codecs)==B.getNormalizedCodec(e.codecs)&&e.bandwidth>t.bandwidth&&(i.push(e),c.push(e.id))}else i.push(e),c.push(e.id);h.set(t,i)}const _=Array.from(l).sort(((e,t)=>e.bandwidth&&t.bandwidth?e.bandwidth-t.bandwidth:e.width-t.width)),m=V.isChangeTypeSupported(),g=[],f=new Map,p=e=>Math.round(e.frameRate||0)+(e.hdr||"")+e.fastSwitching;for(const e of _){const t=p(e),i=f.get(t)||[];if(i.length){const t=i[i.length-1];if(!m&&B.getNormalizedCodec(t.codecs)!==B.getNormalizedCodec(e.codecs))continue;(e.width>t.width||e.height>t.height||e.width==t.width&&e.height==t.height&&B.getNormalizedCodec(t.codecs)==B.getNormalizedCodec(e.codecs)&&e.bandwidth>t.bandwidth)&&(i.push(e),g.push(e.id))}else i.push(e),g.push(e.id);f.set(t,i)}e.variants=e.variants.filter((e=>{const t=e.audio,n=e.video;return t&&!c.includes(t.id)?(i.debug("Dropping Variant (better codec available)",e),!1):!(n&&!g.includes(n.id)&&(i.debug("Dropping Variant (better codec available)",e),1))}))}static choosePreferredCodecs(e,t,i){let n=e;for(const e of t){const t=n.filter((t=>t.video&&t.video.codecs.startsWith(e)));if(t.length){n=t;break}}for(const e of i){const t=n.filter((t=>t.audio&&t.audio.codecs.startsWith(e)));if(t.length){n=t;break}}return n}static filterByRestrictions(e,t,i){e.variants=e.variants.filter((e=>z.meetsRestrictions(e,t,i)))}static meetsRestrictions(e,t,i){const n=(e,t,i)=>e>=t&&e<=i,s=e.video;if(s&&s.width&&s.height){let e=s.width,a=s.height;if(a>e&&([e,a]=[a,e]),!n(e,t.minWidth,Math.min(t.maxWidth,i.width)))return!1;if(!n(a,t.minHeight,Math.min(t.maxHeight,i.height)))return!1;if(!n(s.width*s.height,t.minPixels,t.maxPixels))return!1}return!(e&&e.video&&e.video.frameRate&&!n(e.video.frameRate,t.minFrameRate,t.maxFrameRate)||!n(e.bandwidth,t.minBandwidth,t.maxBandwidth))}static applyRestrictions(e,t,i){let n=!1;for(const s of e){const e=s.allowedByApplication;s.allowedByApplication=z.meetsRestrictions(s,t,i),e!=s.allowedByApplication&&(n=!0)}return n}static async filterManifest(e){await z.filterManifestByMediaCapabilities(e,e.offlineSessionIds.length>0),z.filterTextStreams_(e),await z.filterImageStreams_(e)}static async filterManifestByMediaCapabilities(e,t){console.assert(navigator.mediaCapabilities,"MediaCapabilities should be valid."),await z.getDecodingInfosForVariants(e.variants,t,!1,[]);const n=k.ContentType,s=P.isXboxOne(),a=P.isFirefox()&&P.isAndroid();e.variants=e.variants.filter((e=>{const t=e.video,r=t&&t.width||0,o=t&&t.height||0;if(s&&t&&(r>1920||o>1080)&&(t.codecs.includes("avc1.")||t.codecs.includes("avc3.")))return i.debug("Dropping variant - not compatible with platform",z.getVariantSummaryString_(e)),!1;if(t){let e=z.getCorrectVideoCodecs_(t.codecs);if(t.codecs.includes(",")){const i=t.codecs.split(",");e=k.guessCodecs(n.VIDEO,i),e=z.getCorrectVideoCodecs_(e);let s=k.guessCodecs(n.AUDIO,i);s=z.getCorrectAudioCodecs_(s);const a=B.getFullOrConvertedType(t.mimeType,s,n.AUDIO);if(!Capabilities.isTypeSupported(a))return!1;e=[e,s].join(",")}const i=B.getFullOrConvertedType(t.mimeType,e,n.VIDEO);if(!V.isTypeSupported(i))return!1;t.codecs=e}const l=e.audio;if(a&&l&&l.encrypted&&l.codecs.toLowerCase().includes("opus"))return i.debug("Dropping variant - not compatible with platform",z.getVariantSummaryString_(e)),!1;if(l){const e=z.getCorrectAudioCodecs_(l.codecs),t=B.getFullOrConvertedType(l.mimeType,e,n.AUDIO);if(!V.isTypeSupported(t))return!1;l.codecs=e}const d=e.decodingInfos.some((e=>!!e.supported));return d||i.debug("Dropping variant - not compatible with platform",z.getVariantSummaryString_(e)),d}))}static alphabeticalKeyOrderStringify_(e){const t=[];for(const i in e)t.push(i);t.sort();const i=[];for(const n of t){const t=JSON.stringify(n),s=e[n];if(s instanceof Object){const e=z.alphabeticalKeyOrderStringify_(s);i.push(t+":"+e)}else{const e=JSON.stringify(s);i.push(t+":"+e)}}return"{"+i.join(",")+"}"}static async getDecodingInfosForVariant_(e,t){const n=z.alphabeticalKeyOrderStringify_(t),s=z.decodingConfigCache_;if(s[n])i.v2("Using cached results of mediaCapabilities.decodingInfo","for key",n),e.decodingInfos.push(s[n]);else{const i=await z.checkEachDecodingConfigCombination_(t);if(i&&i.length){let t=null;for(const e of i)t?(t.supported=t.supported&&e.supported,t.powerEfficient=t.powerEfficient&&e.powerEfficient,t.smooth=t.smooth&&e.smooth,e.keySystemAccess||(t.keySystemAccess=null)):t=e;t&&(s[n]=t,e.decodingInfos.push(t))}}}static checkEachDecodingConfigCombination_(e){let t=[""];e.video&&(t=B.getCodecs(e.video.contentType).split(","));let n=[""];e.audio&&(n=B.getCodecs(e.audio.contentType).split(","));const s=[];for(const i of t)for(const t of n){const n=b.cloneObject(e);if(e.video){const e=B.getBasicType(n.video.contentType);n.video.contentType=B.getFullType(e,i)}if(e.audio){const e=B.getBasicType(n.audio.contentType);n.audio.contentType=B.getFullType(e,t)}s.push(new Promise(((e,t)=>{navigator.mediaCapabilities.decodingInfo(n).then((t=>{e(t)})).catch(t)})))}return Promise.all(s).catch((t=>(i.info("MediaCapabilities.decodingInfo() failed.",JSON.stringify(e),t),null)))}static async getDecodingInfosForVariants(e,t,n,s){if(e.some((e=>e.decodingInfos.length)))i.debug("Already got the variants' decodingInfo.");else{for(const i of s){let s=!1;for(const a of e){const e=z.getDecodingConfigs_(a,t,n).filter((e=>(e.keySystemConfiguration&&e.keySystemConfiguration.keySystem)===i));for(const t of e)await z.getDecodingInfosForVariant_(a,t);a.decodingInfos.length&&(s=!0)}if(s)return}for(const i of e){const e=z.getDecodingConfigs_(i,t,n).filter((e=>{const t=e.keySystemConfiguration&&e.keySystemConfiguration.keySystem;return!t||!s.includes(t)}));for(const t of e)await z.getDecodingInfosForVariant_(i,t)}}}static getDecodingConfigs_(e,t,n){const s=e.audio,a=e.video,r=k.ContentType,o={type:n?"file":"media-source"};if(a){let t=a.codecs;if(a.codecs.includes(",")){const i=a.codecs.split(",");t=k.guessCodecs(r.VIDEO,i),t=z.getCorrectVideoCodecs_(t);let n=k.guessCodecs(r.AUDIO,i);n=z.getCorrectAudioCodecs_(n);const s=B.getFullOrConvertedType(a.mimeType,n,r.AUDIO);o.audio={contentType:s,channels:2,bitrate:e.bandwidth||1,samplerate:1,spatialRendering:!1}}t=z.getCorrectVideoCodecs_(t);const i=B.getFullOrConvertedType(a.mimeType,t,r.VIDEO);if(o.video={contentType:i,width:a.width||64,height:a.height||64,bitrate:a.bandwidth||e.bandwidth||1,framerate:a.frameRate||1},a.hdr)switch(a.hdr){case"SDR":o.video.transferFunction="srgb";break;case"PQ":o.video.transferFunction="pq";break;case"HLG":o.video.transferFunction="hlg"}}if(s){const t=z.getCorrectAudioCodecs_(s.codecs),i=B.getFullOrConvertedType(s.mimeType,t,r.AUDIO);o.audio={contentType:i,channels:s.channelsCount||2,bitrate:s.bandwidth||e.bandwidth||1,samplerate:s.audioSamplingRate||1,spatialRendering:s.spatialAudio}}const l=e.video?e.video.drmInfos:[],d=e.audio?e.audio.drmInfos:[],c=l.concat(d);if(!c.length)return[o];const h=[],u=new Map;for(const e of c)u.get(e.keySystem)||u.set(e.keySystem,[]),u.get(e.keySystem).push(e);const _=t?"required":"optional",m=t?["persistent-license"]:["temporary"];for(const e of u.keys()){const t=Object.assign({},o),n=u.get(e),r={keySystem:e,initDataType:"cenc",persistentState:_,distinctiveIdentifier:"optional",sessionTypes:m};for(const e of n){if(e.initData&&e.initData.length){const t=new Set;for(const i of e.initData)t.add(i.initDataType);t.size>1&&i.v2("DrmInfo contains more than one initDataType,","and we use the initDataType of the first initData.",e),r.initDataType=e.initData[0].initDataType}e.distinctiveIdentifierRequired&&(r.distinctiveIdentifier="required"),e.persistentStateRequired&&(r.persistentState="required"),e.sessionType&&(r.sessionTypes=[e.sessionType]),s&&(""!=e.audioRobustness?r.audio?r.audio.robustness=r.audio.robustness||e.audioRobustness:r.audio={robustness:e.audioRobustness}:r.audio||(r.audio={})),a&&(""!=e.videoRobustness?r.video?r.video.robustness=r.video.robustness||e.videoRobustness:r.video={robustness:e.videoRobustness}:r.video||(r.video={}))}t.keySystemConfiguration=r,h.push(t)}return h}static getCorrectAudioCodecs_(e){return"fLaC"!==e||P.isSafari()?"Opus"===e?"opus":e:"flac"}static getCorrectVideoCodecs_(e){if(e.includes("avc1")){const t=e.split(".");if(3==t.length){let e=t.shift()+".";return e+=parseInt(t.shift(),10).toString(16),e+=("000"+parseInt(t.shift(),10).toString(16)).slice(-4),e}}else if("vp9"==e)return"vp09.00.41.08";return e}static filterManifestByCurrentVariant(e,t){const n=n;t.variants=t.variants.filter((t=>{const s=t.audio,a=t.video;return s&&e&&e.audio&&!n.areStreamsCompatible_(s,e.audio)?(i.debug("Dropping variant - not compatible with active audio","active audio",n.getStreamSummaryString_(e.audio),"variant.audio",n.getStreamSummaryString_(s)),!1):!(a&&e&&e.video&&!n.areStreamsCompatible_(a,e.video)&&(i.debug("Dropping variant - not compatible with active video","active video",n.getStreamSummaryString_(e.video),"variant.video",n.getStreamSummaryString_(a)),1))}))}static filterTextStreams_(e){e.textStreams=e.textStreams.filter((e=>{const t=B.getFullType(e.mimeType,e.codecs),n=X.isTypeSupported(t);return n||i.debug("Dropping text stream. Is not supported by the platform.",e),n}))}static async filterImageStreams_(e){const t=[];for(const n of e.imageStreams){let e=n.mimeType;if("application/mp4"==e&&"mjpg"==n.codecs&&(e="image/jpg"),!z.supportedImageMimeTypes_.has(e)){const t=z.minImage_.get(e);if(t){const i=await z.isImageSupported_(t);z.supportedImageMimeTypes_.set(e,i)}else z.supportedImageMimeTypes_.set(e,!1)}z.supportedImageMimeTypes_.get(e)?t.push(n):i.debug("Dropping image stream. Is not supported by the platform.",n)}e.imageStreams=t}static isImageSupported_(e){return new Promise((t=>{const i=new Image;i.src=e,"decode"in i?i.decode().then((()=>{t(!0)})).catch((()=>{t(!1)})):i.onload=i.onerror=()=>{t(2===i.height)}}))}static areStreamsCompatible_(e,t){return e.mimeType==t.mimeType&&e.codecs.split(".")[0]==t.codecs.split(".")[0]}static variantToTrack(e){const t=e.audio,i=e.video,n=t?t.mimeType:null,s=i?i.mimeType:null,a=t?t.codecs:null,r=i?i.codecs:null,o=[];r&&o.push(r),a&&o.push(a);const l=[];i&&l.push(i.mimeType),t&&l.push(t.mimeType);const d=l[0]||null,c=[];t&&c.push(t.kind),i&&c.push(i.kind);const h=c[0]||null,u=new Set;if(t)for(const e of t.roles)u.add(e);if(i)for(const e of i.roles)u.add(e);const _={id:e.id,active:!1,type:"variant",bandwidth:e.bandwidth,language:e.language,label:null,kind:h,width:null,height:null,frameRate:null,pixelAspectRatio:null,hdr:null,videoLayout:null,mimeType:d,audioMimeType:n,videoMimeType:s,codecs:o.join(", "),audioCodec:a,videoCodec:r,primary:e.primary,roles:Array.from(u),audioRoles:null,forced:!1,videoId:null,audioId:null,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,tilesLayout:null,audioBandwidth:null,videoBandwidth:null,originalVideoId:null,originalAudioId:null,originalTextId:null,originalImageId:null,accessibilityPurpose:null,originalLanguage:null};return i&&(_.videoId=i.id,_.originalVideoId=i.originalId,_.width=i.width||null,_.height=i.height||null,_.frameRate=i.frameRate||null,_.pixelAspectRatio=i.pixelAspectRatio||null,_.videoBandwidth=i.bandwidth||null,_.hdr=i.hdr||null,_.videoLayout=i.videoLayout||null),t&&(_.audioId=t.id,_.originalAudioId=t.originalId,_.channelsCount=t.channelsCount,_.audioSamplingRate=t.audioSamplingRate,_.audioBandwidth=t.bandwidth||null,_.spatialAudio=t.spatialAudio,_.label=t.label,_.audioRoles=t.roles,_.accessibilityPurpose=t.accessibilityPurpose,_.originalLanguage=t.originalLanguage),_}static textStreamToTrack(e){const t=k.ContentType;return{id:e.id,active:!1,type:t.TEXT,bandwidth:0,language:e.language,label:e.label,kind:e.kind||null,width:null,height:null,frameRate:null,pixelAspectRatio:null,hdr:null,videoLayout:null,mimeType:e.mimeType,audioMimeType:null,videoMimeType:null,codecs:e.codecs||null,audioCodec:null,videoCodec:null,primary:e.primary,roles:e.roles,audioRoles:null,forced:e.forced,videoId:null,audioId:null,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,tilesLayout:null,audioBandwidth:null,videoBandwidth:null,originalVideoId:null,originalAudioId:null,originalTextId:e.originalId,originalImageId:null,accessibilityPurpose:e.accessibilityPurpose,originalLanguage:e.originalLanguage}}static imageStreamToTrack(e){const t=k.ContentType;let i=e.width||null,n=e.height||null,s=null;e.segmentIndex&&(s=e.segmentIndex.get(0));let a=e.tilesLayout;return s&&(a=s.getTilesLayout()||a),a&&null!=i&&(i/=Number(a.split("x")[0])),a&&null!=n&&(n/=Number(a.split("x")[1])),{id:e.id,active:!1,type:t.IMAGE,bandwidth:e.bandwidth||0,language:"",label:null,kind:null,width:i,height:n,frameRate:null,pixelAspectRatio:null,hdr:null,videoLayout:null,mimeType:e.mimeType,audioMimeType:null,videoMimeType:null,codecs:e.codecs||null,audioCodec:null,videoCodec:null,primary:!1,roles:[],audioRoles:null,forced:!1,videoId:null,audioId:null,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,tilesLayout:a||null,audioBandwidth:null,videoBandwidth:null,originalVideoId:null,originalAudioId:null,originalTextId:null,originalImageId:e.originalId,accessibilityPurpose:null,originalLanguage:null}}static html5TrackId(e){return e.__shaka_id||(e.__shaka_id=z.nextTrackId_++),e.__shaka_id}static html5TextTrackToTrack(e){const t=B.CEA608_CLOSED_CAPTION_MIMETYPE,i=i,n=i.html5TrackToGenericShakaTrack_(e);return n.active="disabled"!=e.mode,n.type="text",n.originalTextId=e.id,"captions"==e.kind&&(n.mimeType=t),"subtitles"==e.kind&&(n.mimeType="text/vtt"),e.kind&&(n.roles=[e.kind]),"forced"==e.kind&&(n.forced=!0),n}static html5AudioTrackToTrack(e){const t=t,i=t.html5TrackToGenericShakaTrack_(e);return i.active=e.enabled,i.type="variant",i.originalAudioId=e.id,"main"==e.kind&&(i.primary=!0),e.kind&&(i.roles=[e.kind],i.audioRoles=[e.kind],i.label=e.label),i}static html5TrackToGenericShakaTrack_(e){const t=e.language;return{id:z.html5TrackId(e),active:!1,type:"",bandwidth:0,language:G.normalize(t||"und"),label:e.label,kind:e.kind,width:null,height:null,frameRate:null,pixelAspectRatio:null,hdr:null,videoLayout:null,mimeType:null,audioMimeType:null,videoMimeType:null,codecs:null,audioCodec:null,videoCodec:null,primary:!1,roles:[],forced:!1,audioRoles:null,videoId:null,audioId:null,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,tilesLayout:null,audioBandwidth:null,videoBandwidth:null,originalVideoId:null,originalAudioId:null,originalTextId:null,originalImageId:null,accessibilityPurpose:null,originalLanguage:t}}static isPlayable(e){return e.allowedByApplication&&e.allowedByKeySystem&&0==e.disabledUntilTime}static getPlayableVariants(e){return e.filter((e=>z.isPlayable(e)))}static filterStreamsByLanguageAndRole(e,t,n,s){let a=e;const r=e.filter((e=>e.primary));r.length&&(a=r);const o=a.length?a[0].language:"";if(a=a.filter((e=>e.language==o)),t){const i=G.findClosestLocale(G.normalize(t),e.map((e=>e.language)));i&&(a=e.filter((e=>G.normalize(e.language)==i)))}if(a=a.filter((e=>e.forced==s)),n){const e=z.filterStreamsByRole_(a,n);if(e.length)return e;i.warning("No exact match for the text role could be found.")}else{const e=a.filter((e=>0==e.roles.length));if(e.length)return e}const l=a.map((e=>e.roles)).reduce(F.collapseArrays,[]);return l.length?z.filterStreamsByRole_(a,l[0]):a}static filterStreamsByRole_(e,t){return e.filter((e=>e.roles.includes(t)))}static isAudio(e){const t=k.ContentType;return e.type==t.AUDIO}static isVideo(e){const t=k.ContentType;return e.type==t.VIDEO}static getVariantStreams(e){const t=[];return e.audio&&t.push(e.audio),e.video&&t.push(e.video),t}static isFastSwitching(e){return!(!e.audio||!e.audio.fastSwitching)||!(!e.video||!e.video.fastSwitching)}static getVariantSummaryString_(e){const t=[];return e.audio&&t.push(z.getStreamSummaryString_(e.audio)),e.video&&t.push(z.getStreamSummaryString_(e.video)),t.join(", ")}static getStreamSummaryString_(e){return z.isAudio(e)?"type=audio codecs="+e.codecs+" bandwidth="+e.bandwidth+" channelsCount="+e.channelsCount+" audioSamplingRate="+e.audioSamplingRate:z.isVideo(e)?"type=video codecs="+e.codecs+" bandwidth="+e.bandwidth+" frameRate="+e.frameRate+" width="+e.width+" height="+e.height:"unexpected stream type"}}z.decodingConfigCache_={},z.nextTrackId_=0,z.DecodingAttributes={SMOOTH:"smooth",POWER:"powerEfficient"},z.supportedImageMimeTypes_=(new Map).set("image/svg+xml",!0).set("image/png",!0).set("image/jpeg",!0).set("image/jpg",!0),z.minWebPImage_="data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA",z.minAvifImage_="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A=",z.minImage_=(new Map).set("image/webp",z.minWebPImage_).set("image/avif",z.minAvifImage_);class Y{static async isFairPlaySupported(){const e={initDataTypes:["cenc","sinf","skd"],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42E01E"'}]};try{return await navigator.requestMediaKeySystemAccess("com.apple.fps",[e]),!0}catch(e){return!1}}static defaultGetContentId(e){const t=L.fromBytesAutoDetect(e);return new URL(t).hostname}static initDataTransform(e,t,i){if(!i||!i.byteLength)throw new v(v.Severity.CRITICAL,v.Category.DRM,v.Code.SERVER_CERTIFICATE_REQUIRED);let n;n="string"==typeof t?L.toUTF16(t,!0):t;const s=L.fromBytesAutoDetect(e),a=L.toUTF16(s,!0),r=new Uint8Array(12+a.byteLength+n.byteLength+i.byteLength);let o=0;const d=e=>{const t=l.toDataView(r),i=e.byteLength;t.setUint32(o,i,!0),o+=4,(e=>{r.set(l.toUint8(e),o),o+=e.byteLength})(e)};return d(a),d(n),d(i),console.assert(o==r.length,"Inconsistent init data length"),r}static basicInitDataTransform_(e,t,i){if("skd"!==t)return e;const n=n,s=s,a=i.serverCertificate,r=n.fromBytesAutoDetect(e).split("skd://").pop();return s.initDataTransform(e,r,a)}static verimatrixInitDataTransform(e,t,i){return Y.basicInitDataTransform_(e,t,i)}static ezdrmInitDataTransform(e,t,i){if("skd"!==t)return e;const n=n,s=s,a=i.serverCertificate,r=n.fromBytesAutoDetect(e).split(";").pop();return s.initDataTransform(e,r,a)}static conaxInitDataTransform(e,t,i){if("skd"!==t)return e;const n=n,s=s,a=i.serverCertificate,r=n.fromBytesAutoDetect(e).split("skd://").pop().split("?").shift(),o=(e=>{const t=new ArrayBuffer(2*e.length),i=l.toUint16(t);for(let t=0,n=e.length;t<n;t++)i[t]=e.charCodeAt(t);return i})(window.atob(r));return s.initDataTransform(e,o,a)}static expressplayInitDataTransform(e,t,i){return Y.basicInitDataTransform_(e,t,i)}static verimatrixFairPlayRequest(e,t,i){if(e!==O.RequestType.LICENSE)return;const n=t.body,s=l.toUint8(n),a=x.toBase64(s);t.headers["Content-Type"]="application/x-www-form-urlencoded",t.body=L.toUTF8("spc="+a)}static octetStreamFairPlayRequest_(e,t,i){e===O.RequestType.LICENSE&&(t.headers["Content-Type"]="application/octet-stream")}static ezdrmFairPlayRequest(e,t,i){Y.octetStreamFairPlayRequest_(e,t)}static conaxFairPlayRequest(e,t,i){Y.octetStreamFairPlayRequest_(e,t)}static expressplayFairPlayRequest(e,t,i){Y.octetStreamFairPlayRequest_(e,t)}static commonFairPlayResponse(e,t,i){if(e!==O.RequestType.LICENSE)return;let n;try{n=L.fromUTF8(t.data)}catch(e){return}let s=!1;n=n.trim(),"<ckc>"===n.substr(0,5)&&"</ckc>"===n.substr(-6)&&(n=n.slice(5,-6),s=!0);try{const e=JSON.parse(n);e.ckc&&(n=e.ckc,s=!0),e.CkcMessage&&(n=e.CkcMessage,s=!0),e.License&&(n=e.License,s=!0)}catch(e){}s&&(t.data=l.toArrayBuffer(x.fromBase64(n)))}}class j{static mergeConfigObjects(e,t,n,s,a){console.assert(e,"Destination config must not be null!");const r=a in s;let o=!0;for(const l in t){const d=a+"."+l,c=r?s[a]:n[l];if(r||l in n)if(void 0===t[l])void 0===c||r?delete e[l]:e[l]=b.cloneObject(c);else if(c.constructor==Object&&t[l]&&t[l].constructor==Object){e[l]||(e[l]=b.cloneObject(c));const i=j.mergeConfigObjects(e[l],t[l],c,s,d);o=o&&i}else typeof t[l]!=typeof c||null==t[l]||"function"!=typeof t[l]&&t[l].constructor!=c.constructor?(i.alwaysError("Invalid config, wrong type for "+d),o=!1):"function"==typeof n[l]&&n[l].length!=t[l].length?(i.alwaysWarn("Unexpected number of arguments for "+d),e[l]=t[l]):e[l]=t[l];else i.alwaysError("Invalid config, unrecognized key "+d),o=!1}return o}static convertToConfigObject(e,t){const i={};let n=i,s=0,a=0;for(;;){const t=e.indexOf(".",s);if(t<0)break;if(0==t||"\\"!=e[t-1]){const i=e.substring(a,t).replace(/\\\./g,".");n[i]={},n=n[i],a=t+1}s=t+1}return n[e.substring(a).replace(/\\\./g,".")]=t,i}static referenceParametersAndReturn(e,t){return e&&t}}class K{constructor(e){console.assert(e>0,"expected halfLife to be positive"),this.alpha_=Math.exp(Math.log(.5)/e),this.estimate_=0,this.totalWeight_=0}updateAlpha(e){console.assert(e>0,"expected halfLife to be positive"),this.alpha_=Math.exp(Math.log(.5)/e)}sample(e,t){const i=Math.pow(this.alpha_,e),n=t*(1-i)+i*this.estimate_;isNaN(n)||(this.estimate_=n,this.totalWeight_+=e)}getEstimate(){const e=1-Math.pow(this.alpha_,this.totalWeight_);return this.estimate_/e}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class Q{constructor(){this.fast_=new K(2),this.slow_=new K(5),this.bytesSampled_=0,this.minTotalBytes_=128e3,this.minBytes_=16e3}configure(e){this.minTotalBytes_=e.minTotalBytes,this.minBytes_=e.minBytes,this.fast_.updateAlpha(e.fastHalfLife),this.slow_.updateAlpha(e.slowHalfLife)}sample(e,t){if(t<this.minBytes_)return;const i=8e3*t/e,n=e/1e3;this.bytesSampled_+=t,this.fast_.sample(n,i),this.slow_.sample(n,i)}getBandwidthEstimate(e){return this.bytesSampled_<this.minTotalBytes_?e:Math.min(this.fast_.getEstimate(),this.slow_.getEstimate())}hasGoodEstimate(){return this.bytesSampled_>=this.minTotalBytes_}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class ${constructor(){this.switch_=null,this.enabled_=!1,this.bandwidthEstimator_=new Q,this.onNetworkInformationChange_=null,navigator.connection&&navigator.connection.addEventListener&&(this.onNetworkInformationChange_=()=>{if(this.enabled_&&this.config_.useNetworkInformation){this.bandwidthEstimator_=new Q,this.config_&&this.bandwidthEstimator_.configure(this.config_.advanced);const e=this.chooseVariant();e&&navigator.onLine&&this.switch_(e,this.config_.clearBufferSwitch,this.config_.safeMarginSwitch)}},navigator.connection.addEventListener("change",this.onNetworkInformationChange_)),this.variants_=[],this.playbackRate_=1,this.startupComplete_=!1,this.lastTimeChosenMs_=null,this.config_=null,this.mediaElement_=null,this.resizeObserver_=null,this.resizeObserverTimer_=new o((()=>{if(this.config_.restrictToElementSize){const e=this.chooseVariant();e&&this.switch_(e,this.config_.clearBufferSwitch,this.config_.safeMarginSwitch)}})),this.cmsdManager_=null}stop(){this.switch_=null,this.enabled_=!1,this.variants_=[],this.playbackRate_=1,this.lastTimeChosenMs_=null,this.mediaElement_=null,this.resizeObserver_&&(this.resizeObserver_.disconnect(),this.resizeObserver_=null),this.resizeObserverTimer_.stop(),this.cmsdManager_=null}release(){navigator.connection&&navigator.connection.removeEventListener&&(navigator.connection.removeEventListener("change",this.onNetworkInformationChange_),this.onNetworkInformationChange_=null),this.resizeObserverTimer_=null}init(e){this.switch_=e}chooseVariant(e=!1){let t=1/0,n=1/0;if(this.config_.restrictToScreenSize){const e=this.config_.ignoreDevicePixelRatio?1:window.devicePixelRatio;t=window.screen.height*e,n=window.screen.width*e}if(this.resizeObserver_&&this.config_.restrictToElementSize){const e=this.config_.ignoreDevicePixelRatio?1:window.devicePixelRatio;t=Math.min(t,this.mediaElement_.clientHeight*e),n=Math.min(n,this.mediaElement_.clientWidth*e)}let s=this.variants_.filter((e=>!z.isFastSwitching(e)));s.length||(s=this.variants_);let a=s;e&&s.length!=this.variants_.length&&(a=this.variants_.filter((e=>z.isFastSwitching(e))));let r=this.filterAndSortVariants_(this.config_.restrictions,a,1/0,1/0);if(t!=1/0||n!=1/0){const e=this.getResolutionList_(r);for(const i of e)if(i.height>=t&&i.width>=n){t=i.height,n=i.width;break}r=this.filterAndSortVariants_(this.config_.restrictions,a,t,n)}const o=this.getBandwidthEstimate();a.length&&!r.length&&(i.warning("No variants met the ABR restrictions. Choosing a variant by lowest bandwidth."),r=this.filterAndSortVariants_(null,a,1/0,1/0),r=[r[0]]);let l=r[0]||null;for(let e=0;e<r.length;e++){const t=r[e],n=isNaN(this.playbackRate_)?1:Math.abs(this.playbackRate_),s=n*t.bandwidth,a=s/this.config_.bandwidthDowngradeTarget;let d={bandwidth:1/0};for(let i=e+1;i<r.length;i++)if(t.bandwidth!=r[i].bandwidth){d=r[i];break}const c=n*d.bandwidth/this.config_.bandwidthUpgradeTarget;i.v2("Bandwidth ranges:",(s/1e6).toFixed(3),(a/1e6).toFixed(3),(c/1e6).toFixed(3)),o>=a&&o<=c&&l.bandwidth!=t.bandwidth&&(l=t)}return this.lastTimeChosenMs_=Date.now(),l}enable(){this.enabled_=!0}disable(){this.enabled_=!1}segmentDownloaded(e,t,n,s){i.v2("Segment downloaded:","contentType="+(s&&s.contentType),"deltaTimeMs="+e,"numBytes="+t,"lastTimeChosenMs="+this.lastTimeChosenMs_,"enabled="+this.enabled_),console.assert(e>=0,"expected a non-negative duration"),this.bandwidthEstimator_.sample(e,t),n&&null!=this.lastTimeChosenMs_&&this.enabled_&&this.suggestStreams_()}trySuggestStreams(){null!=this.lastTimeChosenMs_&&this.enabled_&&this.suggestStreams_()}getBandwidthEstimate(){const e=this.getDefaultBandwidth_(),t=this.bandwidthEstimator_.getBandwidthEstimate(e);return this.cmsdManager_?this.cmsdManager_.getBandwidthEstimate(t):t}setVariants(e){this.variants_=e}playbackRateChanged(e){this.playbackRate_=e}setMediaElement(e){this.mediaElement_=e,this.resizeObserver_&&(this.resizeObserver_.disconnect(),this.resizeObserver_=null),this.mediaElement_&&"ResizeObserver"in window&&(this.resizeObserver_=new ResizeObserver((()=>{this.resizeObserverTimer_.tickAfter($.RESIZE_OBSERVER_BATCH_TIME)})),this.resizeObserver_.observe(this.mediaElement_))}setCmsdManager(e){this.cmsdManager_=e}configure(e){this.config_=e,this.bandwidthEstimator_&&this.config_&&this.bandwidthEstimator_.configure(this.config_.advanced)}suggestStreams_(){if(i.v2("Suggesting Streams..."),console.assert(null!=this.lastTimeChosenMs_,"lastTimeChosenMs_ should not be null"),this.startupComplete_){if(Date.now()-this.lastTimeChosenMs_<1e3*this.config_.switchInterval)return void i.v2("Still within switch interval...")}else{if(!this.bandwidthEstimator_.hasGoodEstimate())return void i.v2("Still waiting for a good estimate...");this.startupComplete_=!0}const e=this.chooseVariant(),t=this.getBandwidthEstimate(),n=Math.round(t/1e3);e&&(i.debug("Calling switch_(), bandwidth="+n+" kbps"),this.switch_(e,this.config_.clearBufferSwitch,this.config_.safeMarginSwitch))}getDefaultBandwidth_(){let e=this.config_.defaultBandwidthEstimate;return navigator.connection&&navigator.connection.downlink&&this.config_.useNetworkInformation&&(e=1e6*navigator.connection.downlink),e}filterAndSortVariants_(e,t,i,n){if(this.cmsdManager_){const e=this.cmsdManager_.getMaxBitrate();e&&(t=t.filter((t=>!t.bandwidth||!e||t.bandwidth<=e)))}return e&&(t=t.filter((t=>(console.assert(e,"Restrictions should exist!"),z.meetsRestrictions(t,e,{width:n,height:i}))))),t.sort(((e,t)=>e.bandwidth-t.bandwidth))}getResolutionList_(e){const t=[];for(const i of e){const e=i.video;e&&e.height&&e.width&&t.push({height:e.height,width:e.width})}return t.sort(((e,t)=>e.width-t.width))}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}$.RESIZE_OBSERVER_BATCH_TIME=1;class J{static createDefault(){let e=1/0;navigator.connection&&navigator.connection.saveData&&(e=360);const t={retryParameters:O.defaultRetryParameters(),servers:{},clearKeys:{},advanced:{},delayLicenseRequestUntilPlayed:!1,persistentSessionOnlinePlayback:!1,persistentSessionsMetadata:[],initDataTransform:(e,t,i)=>{if(P.isMediaKeysPolyfilled()&&"skd"==t){const t=i.serverCertificate,n=Y.defaultGetContentId(e);e=Y.initDataTransform(e,n,t)}return e},logLicenseExchange:!1,updateExpirationTime:1,preferredKeySystems:[],keySystemsMapping:{},parseInbandPsshEnabled:P.isXboxOne(),minHdcpVersion:"",ignoreDuplicateInitData:!P.isTizen2()};let n="reload",s=!1;P.supportsSmoothCodecSwitching()&&(n="smooth",s=!0);const a={retryParameters:O.defaultRetryParameters(),availabilityWindowOverride:NaN,disableAudio:!1,disableVideo:!1,disableText:!1,disableThumbnails:!1,defaultPresentationDelay:0,segmentRelativeVttTiming:!1,raiseFatalErrorOnManifestUpdateRequestFailure:!1,dash:{clockSyncUri:"",ignoreDrmInfo:!1,disableXlinkProcessing:!1,xlinkFailGracefully:!1,ignoreMinBufferTime:!1,autoCorrectDrift:!0,initialSegmentLimit:1e3,ignoreSuggestedPresentationDelay:!1,ignoreEmptyAdaptationSet:!1,ignoreMaxSegmentDuration:!1,keySystemsByURI:{"urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b":"org.w3.clearkey","urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e":"org.w3.clearkey","urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed":"com.widevine.alpha","urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","urn:uuid:79f0049a-4098-8642-ab92-e65be0885f95":"com.microsoft.playready"},manifestPreprocessor:e=>j.referenceParametersAndReturn([e],e),sequenceMode:!1,enableAudioGroups:!1,multiTypeVariantsAllowed:s,useStreamOnceInPeriodFlattening:!1},hls:{ignoreTextStreamFailures:!1,ignoreImageStreamFailures:!1,defaultAudioCodec:"mp4a.40.2",defaultVideoCodec:"avc1.42E01E",ignoreManifestProgramDateTime:!1,ignoreManifestProgramDateTimeForTypes:[],mediaPlaylistFullMimeType:'video/mp2t; codecs="avc1.42E01E, mp4a.40.2"',useSafariBehaviorForLive:!0,liveSegmentsDelay:3,sequenceMode:P.supportsSequenceMode(),ignoreManifestTimestampsInSegmentsMode:!1,disableCodecGuessing:!1,allowLowLatencyByteRangeOptimization:!0},mss:{manifestPreprocessor:e=>j.referenceParametersAndReturn([e],e),sequenceMode:!1,keySystemsBySystemId:{"9a04f079-9840-4286-ab92-e65be0885f95":"com.microsoft.playready","79f0049a-4098-8642-ab92-e65be0885f95":"com.microsoft.playready"}}},r={retryParameters:O.defaultRetryParameters(),failureCallback:e=>(i.error("Unhandled streaming error",e),j.referenceParametersAndReturn([e],void 0)),rebufferingGoal:2,bufferingGoal:10,bufferBehind:30,evictionGoal:1,ignoreTextStreamFailures:!1,alwaysStreamText:!1,startAtSegmentBoundary:!1,gapDetectionThreshold:.5,gapJumpTimerTime:.25,durationBackoff:1,safeSeekOffset:5,stallEnabled:!0,stallThreshold:1,stallSkip:.1,useNativeHlsForFairPlay:!0,inaccurateManifestTolerance:2,lowLatencyMode:!1,autoLowLatencyMode:!1,forceHTTPS:!1,preferNativeHls:!1,updateIntervalSeconds:1,dispatchAllEmsgBoxes:!1,observeQualityChanges:!1,maxDisabledTime:30,parsePrftBox:!1,segmentPrefetchLimit:0,prefetchAudioLanguages:[],disableAudioPrefetch:!1,disableTextPrefetch:!1,disableVideoPrefetch:!1,liveSync:!1,liveSyncMaxLatency:1,liveSyncPlaybackRate:1.1,liveSyncMinLatency:0,liveSyncMinPlaybackRate:1,liveSyncPanicMode:!1,liveSyncPanicThreshold:60,allowMediaSourceRecoveries:!0,minTimeBetweenRecoveries:5,vodDynamicPlaybackRate:!1,vodDynamicPlaybackRateLowBufferRate:.95,vodDynamicPlaybackRateBufferRatio:.5,infiniteLiveStreamDuration:!1};(P.isWebOS()||P.isTizen()||P.isChromecast()||P.isHisense())&&(r.stallSkip=0);const o={trackSelectionCallback:async e=>e,downloadSizeCallback:async e=>{if(navigator.storage&&navigator.storage.estimate){const t=await navigator.storage.estimate();return t.usage+e<.95*t.quota}return!0},progressCallback:(e,t)=>j.referenceParametersAndReturn([e,t],void 0),usePersistentLicense:!0,numberOfParallelDownloads:5},l={drm:t,manifest:a,streaming:r,mediaSource:{codecSwitchingStrategy:n,addExtraFeaturesToSourceBuffer:e=>j.referenceParametersAndReturn([e],""),forceTransmux:!1,insertFakeEncryptionInInit:!0,modifyCueCallback:(e,t)=>j.referenceParametersAndReturn([e,t],void 0)},offline:o,abrFactory:()=>new $,abr:{enabled:!0,useNetworkInformation:!0,defaultBandwidthEstimate:1e6,switchInterval:8,bandwidthUpgradeTarget:.85,bandwidthDowngradeTarget:.95,restrictions:{minWidth:0,maxWidth:1/0,minHeight:0,maxHeight:e,minPixels:0,maxPixels:1/0,minFrameRate:0,maxFrameRate:1/0,minBandwidth:0,maxBandwidth:1/0},advanced:{minTotalBytes:128e3,minBytes:16e3,fastHalfLife:2,slowHalfLife:5},restrictToElementSize:!1,restrictToScreenSize:!1,ignoreDevicePixelRatio:!1,clearBufferSwitch:!1,safeMarginSwitch:0},autoShowText:3,preferredAudioLanguage:"",preferredAudioLabel:"",preferredTextLanguage:"",preferredVariantRole:"",preferredTextRole:"",preferredAudioChannelCount:2,preferredVideoHdrLevel:"AUTO",preferredVideoLayout:"",preferredVideoLabel:"",preferredVideoCodecs:[],preferredAudioCodecs:[],preferForcedSubs:!1,preferSpatialAudio:!1,preferredDecodingAttributes:[],restrictions:{minWidth:0,maxWidth:1/0,minHeight:0,maxHeight:1/0,minPixels:0,maxPixels:1/0,minFrameRate:0,maxFrameRate:1/0,minBandwidth:0,maxBandwidth:1/0},playRangeStart:0,playRangeEnd:1/0,textDisplayFactory:()=>null,cmcd:{enabled:!1,sessionId:"",contentId:"",rtpSafetyFactor:5,useHeaders:!1,includeKeys:[]},cmsd:{enabled:!0,applyMaximumSuggestedBitrate:!0,estimatedThroughputWeightRatio:.5},lcevc:{enabled:!1,dynamicPerformanceScaling:!0,logLevel:0,drawLogo:!1},ads:{customPlayheadTracker:!1}};return o.trackSelectionCallback=async e=>J.defaultTrackSelect(e,l.preferredAudioLanguage,l.preferredVideoHdrLevel),l}static mergeConfigObjects(e,t,i){const n={".drm.keySystemsMapping":"",".drm.servers":"",".drm.clearKeys":"",".drm.advanced":{distinctiveIdentifierRequired:!1,persistentStateRequired:!1,videoRobustness:"",audioRobustness:"",sessionType:"",serverCertificate:new Uint8Array(0),serverCertificateUri:"",individualizationServer:""}};return j.mergeConfigObjects(e,t,i||J.createDefault(),n,"")}static defaultTrackSelect(e,t,n){const s=k.ContentType;let a=n;"AUTO"==a&&(a=window.matchMedia("(color-gamut: p3)").matches?"PQ":"SDR");const r=e.filter((e=>"variant"==e.type&&(!e.hdr||e.hdr==a)));let o=[];const l=G.findClosestLocale(t,r.map((e=>e.language)));l&&(o=r.filter((e=>G.normalize(e.language)==l))),0==o.length&&(o=r.filter((e=>e.primary))),0==o.length&&(new Set(r.map((e=>e.language))).size>1&&i.warning("Could not choose a good audio track based on language preferences or primary tracks. An arbitrary language will be stored!"),o=r);const d=o.filter((e=>e.height&&e.height<=480));d.length&&(d.sort(((e,t)=>(console.assert(null!=e.height,"Null height"),console.assert(null!=t.height,"Null height"),t.height-e.height))),o=d.filter((e=>e.height==d[0].height)));const c=[];if(o.length){const e=Math.floor(o.length/2);o.sort(((e,t)=>e.bandwidth-t.bandwidth)),c.push(o[e])}for(const t of e)t.type!=s.TEXT&&t.type!=s.IMAGE||c.push(t);return c}}class Z{constructor(){this.bindingMap_=new n}release(){this.removeAll(),this.bindingMap_=null}listen(e,t,i,n){if(!this.bindingMap_)return;const s=new Z.Binding_(e,t,i,n);this.bindingMap_.push(t,s)}listenOnce(e,t,i,n){const s=n=>{this.unlisten(e,t,s),i(n)};this.listen(e,t,s,n)}unlisten(e,t,i){if(!this.bindingMap_)return;const n=this.bindingMap_.get(t)||[];for(const s of n)s.target==e&&(i!=s.listener&&i||(s.unlisten(),this.bindingMap_.remove(t,s)))}removeAll(){if(!this.bindingMap_)return;const e=this.bindingMap_.getAll();for(const t of e)t.unlisten();this.bindingMap_.clear()}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}Z.Binding_=class{constructor(e,t,i,n){this.target=e,this.type=t,this.listener=i,this.options=Z.Binding_.convertOptions_(e,n),this.target.addEventListener(t,i,this.options)}unlisten(){console.assert(this.target,"Missing target"),this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static convertOptions_(e,t){if(null==t)return!1;if("boolean"==typeof t)return t;{const i=new Set(["passive","capture"]),n=Object.keys(t).filter((e=>!i.has(e)));return console.assert(0==n.length,"Unsupported flag(s) to addEventListener: "+n.join(",")),Z.Binding_.doesSupportObject_(e)?t:t.capture||!1}}static doesSupportObject_(e){let t=Z.Binding_.supportsObject_;if(null==t){t=!1;try{const i={},n={get:()=>(t=!0,!1)};Object.defineProperty(i,"passive",n),Object.defineProperty(i,"capture",n);const s=()=>{};e.addEventListener("test",s,i),e.removeEventListener("test",s,i)}catch(e){t=!1}Z.Binding_.supportsObject_=t}return t||!1}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0]}},Z.Binding_.supportsObject_=void 0;class ee{constructor(){this.open_=null,this.closed_=[]}update(e){return null==this.open_?(this.start_(e),!0):this.update_(e)}getTimeSpentIn(e){let t=0;this.open_&&this.open_.state==e&&(t+=this.open_.duration);for(const i of this.closed_)t+=i.state==e?i.duration:0;return t}getCopy(){const e=e=>({timestamp:e.timestamp,state:e.state,duration:e.duration}),t=[];for(const i of this.closed_)t.push(e(i));return this.open_&&t.push(e(this.open_)),t}start_(e){console.assert(null==this.open_,"There must be no open entry in order when we start"),i.v1("Changing Player state to",e),this.open_={timestamp:this.getNowInSeconds_(),state:e,duration:0}}update_(e){console.assert(this.open_,"There must be an open entry in order to update it");const t=this.getNowInSeconds_();return this.open_.duration=t-this.open_.timestamp,this.open_.state!=e&&(i.v1("Changing Player state to",e),this.closed_.push(this.open_),this.open_={timestamp:t,state:e,duration:0},!0)}getNowInSeconds_(){return Date.now()/1e3}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class te{constructor(){this.currentVariant_=null,this.currentText_=null,this.history_=[]}updateCurrentVariant(e,t){this.currentVariant_!=e&&(this.currentVariant_=e,this.history_.push({timestamp:this.getNowInSeconds_(),id:e.id,type:"variant",fromAdaptation:t,bandwidth:e.bandwidth}))}updateCurrentText(e,t){this.currentText_!=e&&(this.currentText_=e,this.history_.push({timestamp:this.getNowInSeconds_(),id:e.id,type:"text",fromAdaptation:t,bandwidth:null}))}getCopy(){const e=[];for(const t of this.history_)e.push(this.clone_(t));return e}getNowInSeconds_(){return Date.now()/1e3}clone_(e){return{timestamp:e.timestamp,id:e.id,type:e.type,fromAdaptation:e.fromAdaptation,bandwidth:e.bandwidth}}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class ie{constructor(){this.width_=NaN,this.height_=NaN,this.totalDroppedFrames_=NaN,this.totalDecodedFrames_=NaN,this.totalCorruptedFrames_=NaN,this.totalStallsDetected_=NaN,this.totalGapsJumped_=NaN,this.completionPercent_=NaN,this.loadLatencySeconds_=NaN,this.manifestTimeSeconds_=NaN,this.drmTimeSeconds_=NaN,this.licenseTimeSeconds_=NaN,this.liveLatencySeconds_=NaN,this.maxSegmentDurationSeconds_=NaN,this.currentStreamBandwidth_=NaN,this.bandwidthEstimate_=NaN,this.stateHistory_=new ee,this.switchHistory_=new te}setDroppedFrames(e,t){this.totalDroppedFrames_=e,this.totalDecodedFrames_=t}setCorruptedFrames(e){this.totalCorruptedFrames_=e}setStallsDetected(e){this.totalStallsDetected_=e}setGapsJumped(e){this.totalGapsJumped_=e}setResolution(e,t){this.width_=e,this.height_=t}setLoadLatency(e){this.loadLatencySeconds_=e}setManifestTime(e){this.manifestTimeSeconds_=e}setCompletionPercent(e){isNaN(this.completionPercent_)?this.completionPercent_=e:this.completionPercent_=Math.max(this.completionPercent_,e)}setDrmTime(e){this.drmTimeSeconds_=e}setLicenseTime(e){this.licenseTimeSeconds_=e}setLiveLatency(e){this.liveLatencySeconds_=e}setMaxSegmentDuration(e){this.maxSegmentDurationSeconds_=e}setCurrentStreamBandwidth(e){this.currentStreamBandwidth_=e}setBandwidthEstimate(e){this.bandwidthEstimate_=e}getStateHistory(){return this.stateHistory_}getSwitchHistory(){return this.switchHistory_}getBlob(){return{width:this.width_,height:this.height_,streamBandwidth:this.currentStreamBandwidth_,decodedFrames:this.totalDecodedFrames_,droppedFrames:this.totalDroppedFrames_,corruptedFrames:this.totalCorruptedFrames_,stallsDetected:this.totalStallsDetected_,gapsJumped:this.totalGapsJumped_,estimatedBandwidth:this.bandwidthEstimate_,completionPercent:this.completionPercent_,loadLatency:this.loadLatencySeconds_,manifestTimeSeconds:this.manifestTimeSeconds_,drmTimeSeconds:this.drmTimeSeconds_,playTime:this.stateHistory_.getTimeSpentIn("playing"),pauseTime:this.stateHistory_.getTimeSpentIn("paused"),bufferingTime:this.stateHistory_.getTimeSpentIn("buffering"),licenseTime:this.licenseTimeSeconds_,liveLatency:this.liveLatencySeconds_,maxSegmentDuration:this.maxSegmentDurationSeconds_,stateHistory:this.stateHistory_.getCopy(),switchHistory:this.switchHistory_.getCopy()}}static getEmptyBlob(){return{width:NaN,height:NaN,streamBandwidth:NaN,decodedFrames:NaN,droppedFrames:NaN,corruptedFrames:NaN,stallsDetected:NaN,gapsJumped:NaN,estimatedBandwidth:NaN,completionPercent:NaN,loadLatency:NaN,manifestTimeSeconds:NaN,drmTimeSeconds:NaN,playTime:NaN,pauseTime:NaN,bufferingTime:NaN,licenseTime:NaN,liveLatency:NaN,maxSegmentDuration:NaN,switchHistory:[],stateHistory:[]}}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class ne{constructor(e,t){this.playerInterface_=e,this.config_=t,this.sf_=void 0,this.playbackStarted_=!1,this.buffering_=!0,this.starved_=!1}configure(e){this.config_=e}setBuffering(e){e||this.playbackStarted_||(this.playbackStarted_=!0),this.playbackStarted_&&e&&(this.starved_=!0),this.buffering_=e}applyData(e,t,i={}){if(!this.config_.enabled)return;if("HEAD"===t.method)return void this.apply_(t);const n=O.RequestType,s=ne.ObjectType;switch(e){case n.MANIFEST:this.applyManifestData(t,i);break;case n.SEGMENT:this.applySegmentData(t,i);break;case n.LICENSE:case n.SERVER_CERTIFICATE:case n.KEY:this.apply_(t,{ot:s.KEY});break;case n.TIMING:this.apply_(t,{ot:s.OTHER})}}applyManifestData(e,t){try{if(!this.config_.enabled)return;t.type&&(this.sf_=this.getStreamFormat_(t.type)),this.apply_(e,{ot:ne.ObjectType.MANIFEST,su:!this.playbackStarted_})}catch(e){i.warnOnce("CMCD_MANIFEST_ERROR","Could not generate manifest CMCD data.",e)}}applySegmentData(e,t){try{if(!this.config_.enabled)return;const i=t.segment;let n=0;i&&(n=i.endTime-i.startTime);const s={d:1e3*n,st:this.getStreamType_()};s.ot=this.getObjectType_(t);const a=ne.ObjectType,r=s.ot===a.VIDEO||s.ot===a.AUDIO||s.ot===a.MUXED||s.ot===a.TIMED_TEXT,o=t.stream;if(o){if(r&&(s.bl=this.getBufferLength_(o.type),s.ot!==a.TIMED_TEXT)){const e=this.getRemainingBufferLength_(o.type),t=this.playerInterface_.getPlaybackRate();s.dl=t?e/Math.abs(t):e}if(o.bandwidth&&(s.br=o.bandwidth/1e3),o.segmentIndex&&i){const t=o.segmentIndex.getIteratorForTime(i.endTime,!0);if(t){const n=t.next().value;if(n&&n!=i&&(I.equal(i.getUris(),n.getUris())||(s.nor=this.urlToRelativePath_(n.getUris()[0],e.uris[0])),(n.startByte||n.endByte)&&(i.startByte!=n.startByte||i.endByte!=n.endByte))){let e=n.startByte+"-";n.endByte&&(e+=n.endByte),s.nrr=e}}const n=this.calculateRtp_(o,i);isNaN(n)||(s.rtp=n)}}r&&s.ot!==a.TIMED_TEXT&&(s.tb=this.getTopBandwidth_(s.ot)/1e3),this.apply_(e,s)}catch(e){i.warnOnce("CMCD_SEGMENT_ERROR","Could not generate segment CMCD data.",e)}}applyTextData(e){try{if(!this.config_.enabled)return;this.apply_(e,{ot:ne.ObjectType.CAPTION,su:!0})}catch(e){i.warnOnce("CMCD_TEXT_ERROR","Could not generate text CMCD data.",e)}}appendSrcData(e,t){try{if(!this.config_.enabled)return e;const i=this.createData_();i.ot=this.getObjectTypeFromMimeType_(t),i.su=!0;const n=ne.toQuery(i);return ne.appendQueryToUri(e,n)}catch(t){return i.warnOnce("CMCD_SRC_ERROR","Could not generate src CMCD data.",t),e}}appendTextTrackData(e){try{if(!this.config_.enabled)return e;const t=this.createData_();t.ot=ne.ObjectType.CAPTION,t.su=!0;const i=ne.toQuery(t);return ne.appendQueryToUri(e,i)}catch(t){return i.warnOnce("CMCD_TEXT_TRACK_ERROR","Could not generate text track CMCD data.",t),e}}createData_(){return this.config_.sessionId||(this.config_.sessionId=window.crypto.randomUUID()),{v:ne.Version,sf:this.sf_,sid:this.config_.sessionId,cid:this.config_.contentId,mtp:this.playerInterface_.getBandwidthEstimate()/1e3}}apply_(e,t={},i=this.config_.useHeaders){if(!this.config_.enabled)return;Object.assign(t,this.createData_()),t.pr=this.playerInterface_.getPlaybackRate();const n=t.ot===ne.ObjectType.VIDEO||t.ot===ne.ObjectType.MUXED;this.starved_&&n&&(t.bs=!0,t.su=!0,this.starved_=!1),null==t.su&&(t.su=this.buffering_);const s=this.filterKeys_(t);if(i){const t=ne.toHeaders(s);if(!Object.keys(t).length)return;Object.assign(e.headers,t)}else{const t=ne.toQuery(s);if(!t)return;e.uris=e.uris.map((e=>ne.appendQueryToUri(e,t)))}}filterKeys_(e){const t=this.config_.includeKeys;return t.length?Object.keys(e).reduce(((i,n)=>(t.includes(n)&&(i[n]=e[n]),i)),{}):e}getObjectType_(e){if(e.type===O.AdvancedRequestType.INIT_SEGMENT)return ne.ObjectType.INIT;const t=e.stream;if(!t)return;const i=t.type;return"video"==i?t.codecs&&t.codecs.includes(",")?ne.ObjectType.MUXED:ne.ObjectType.VIDEO:"audio"==i?ne.ObjectType.AUDIO:"text"==i?"application/mp4"===t.mimeType?ne.ObjectType.TIMED_TEXT:ne.ObjectType.CAPTION:void 0}getObjectTypeFromMimeType_(e){switch(e.toLowerCase()){case"audio/mp4":case"audio/webm":case"audio/ogg":case"audio/mpeg":case"audio/aac":case"audio/flac":case"audio/wav":return ne.ObjectType.AUDIO;case"video/webm":case"video/mp4":case"video/mpeg":case"video/mp2t":return ne.ObjectType.MUXED;case"application/x-mpegurl":case"application/vnd.apple.mpegurl":case"application/dash+xml":case"video/vnd.mpeg.dash.mpd":case"application/vnd.ms-sstr+xml":return ne.ObjectType.MANIFEST;default:return}}getBufferLength_(e){const t=this.playerInterface_.getBufferedInfo()[e];if(!t.length)return NaN;const i=this.playerInterface_.getCurrentTime(),n=t.find((e=>e.start<=i&&e.end>=i));return n?1e3*(n.end-i):NaN}getRemainingBufferLength_(e){const t=this.playerInterface_.getBufferedInfo()[e];if(!t.length)return 0;const i=this.playerInterface_.getCurrentTime(),n=t.find((e=>e.start<=i&&e.end>=i));return n?1e3*(n.end-i):0}urlToRelativePath_(e,t){const i=new URL(e),n=new URL(t);if(i.origin!==n.origin)return e;const s=i.pathname.split("/").slice(1),a=n.pathname.split("/").slice(1,-1);for(;s[0]===a[0];)s.shift(),a.shift();for(;a.length;)a.shift(),s.unshift("..");return s.join("/")}calculateRtp_(e,t){const i=this.playerInterface_.getPlaybackRate()||1,n=this.getRemainingBufferLength_(e.type)||500,s=e.bandwidth;return s?s*(t.endTime-t.startTime)/1e3/(n/i/1e3)*this.config_.rtpSafetyFactor:NaN}getStreamFormat_(e){const t=O.AdvancedRequestType;switch(e){case t.MPD:return ne.StreamingFormat.DASH;case t.MASTER_PLAYLIST:case t.MEDIA_PLAYLIST:return ne.StreamingFormat.HLS;case t.MSS:return ne.StreamingFormat.SMOOTH}}getStreamType_(){return this.playerInterface_.isLive()?ne.StreamType.LIVE:ne.StreamType.VOD}getTopBandwidth_(e){const t=this.playerInterface_.getVariantTracks();if(!t.length)return NaN;let i=t[0];for(const e of t)"variant"===e.type&&e.bandwidth>i.bandwidth&&(i=e);const n=ne.ObjectType;switch(e){case n.VIDEO:return i.videoBandwidth||NaN;case n.AUDIO:return i.audioBandwidth||NaN;default:return i.bandwidth}}static serialize(e){const t=[],i=e=>!Number.isNaN(e)&&null!=e&&""!==e&&!1!==e,n=e=>Math.round(e),s=e=>100*n(e/100),a={br:n,d:n,bl:s,dl:s,mtp:s,nor:e=>encodeURIComponent(e),rtp:s,tb:n},r=Object.keys(e||{}).sort();for(const n of r){let s=e[n];if(!i(s))continue;if("v"===n&&1===s)continue;if("pr"==n&&1===s)continue;const r=a[n];r&&(s=r(s));const o=typeof s;let l;l="string"===o&&"ot"!==n&&"sf"!==n&&"st"!==n?`${n}=${JSON.stringify(s)}`:"boolean"===o?n:"symbol"===o?`${n}=${s.description}`:`${n}=${s}`,t.push(l)}return t.join(",")}static toHeaders(e){const t=Object.keys(e),i={},n=["Object","Request","Session","Status"],s=[{},{},{},{}],a={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const i of t)s[null!=a[i]?a[i]:1][i]=e[i];for(let e=0;e<s.length;e++){const t=ne.serialize(s[e]);t&&(i[`CMCD-${n[e]}`]=t)}return i}static toQuery(e){return ne.serialize(e)}static appendQueryToUri(e,t){if(!t)return e;if(e.includes("offline:"))return e;const i=new URL(e);return i.searchParams.set("CMCD",t),i.toString()}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}ne.PlayerInterface,ne.ObjectType={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},ne.StreamType={VOD:"v",LIVE:"l"},ne.StreamingFormat={DASH:"d",HLS:"h",SMOOTH:"s",OTHER:"o"},ne.Version=1;class se{constructor(e){this.config_=e,this.staticParams_=null,this.dynamicParams_=null}configure(e){this.config_=e}reset(){this.staticParams_=null,this.dynamicParams_=null}processHeaders(e){if(!this.config_.enabled)return;const t=e[se.CMSD_STATIC_HEADER_NAME_];if(t){const e=this.parseCMSDStatic_(t);e&&(this.staticParams_=e)}const i=e[se.CMSD_DYNAMIC_HEADER_NAME_];if(i){const e=this.parseCMSDDynamic_(i);e&&(this.dynamicParams_=e)}}getMaxBitrate(){const e=se.KEYS_.MAX_SUGGESTED_BITRATE;return this.config_.enabled&&this.config_.applyMaximumSuggestedBitrate&&this.dynamicParams_&&this.dynamicParams_.has(e)?1e3*this.dynamicParams_.get(e):null}getEstimatedThroughput(){const e=se.KEYS_.ESTIMATED_THROUGHPUT;return this.config_.enabled&&this.dynamicParams_&&this.dynamicParams_.has(e)?1e3*this.dynamicParams_.get(e):null}getResponseDelay(){const e=se.KEYS_.RESPONSE_DELAY;return this.config_.enabled&&this.dynamicParams_&&this.dynamicParams_.has(e)?this.dynamicParams_.get(e):null}getRoundTripTime(){const e=se.KEYS_.ROUND_TRIP_TIME;return this.config_.enabled&&this.dynamicParams_&&this.dynamicParams_.has(e)?this.dynamicParams_.get(e):null}getBandwidthEstimate(e){const t=this.getEstimatedThroughput();if(!t)return e;const i=this.config_.estimatedThroughputWeightRatio;return i>0&&i<=1?e*(1-i)+t*i:e}parseCMSDStatic_(e){try{const t=new Map,i=e.split(",");for(let e=0;e<i.length;e++){const n=i[e].split("="),s=n[0],a=this.parseParameterValue_(n[1]);t.set(s,a)}return t}catch(e){return i.warning("Failed to parse CMSD-Static response header value:",e),null}}parseCMSDDynamic_(e){try{const t=new Map,i=e.split(";");for(let e=1;e<i.length;e++){const n=i[e].split("="),s=n[0],a=this.parseParameterValue_(n[1]);t.set(s,a)}return t}catch(e){return i.warning("Failed to parse CMSD-Dynamic response header value:",e),null}}parseParameterValue_(e){return!e||"false"!==e.toLowerCase()&&(/^[-0-9]/.test(e)?parseInt(e,10):e.replace(/["]+/g,""))}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}se.CMSD_STATIC_HEADER_NAME_="cmsd-static",se.CMSD_DYNAMIC_HEADER_NAME_="cmsd-dynamic",se.KEYS_={AVAILABILITY_TIME:"at",DURESS:"du",ENCODED_BITRATE:"br",ESTIMATED_THROUGHPUT:"etp",HELD_TIME:"ht",INTERMEDIARY_IDENTIFIER:"n",MAX_SUGGESTED_BITRATE:"mb",NEXT_OBJECT_RESPONSE:"nor",NEXT_RANGE_RESPONSE:"nrr",OBJECT_DURATION:"d",OBJECT_TYPE:"ot",RESPONSE_DELAY:"rd",ROUND_TRIP_TIME:"rtt",STARTUP:"su",STREAM_TYPE:"st",STREAMING_FORMAT:"sf",VERSION:"v"};class ae{static init(e){console.assert(null==ae.enforcer_,"Deprecate.init should only be called once."),ae.enforcer_=new ae.Enforcer(ae.Version.parse(e),ae.onPending_,ae.onExpired_)}static deprecateFeature(e,t,i){const n=ae.enforcer_;console.assert(n,"Missing deprecation enforcer. Was |init| called?");const s=new ae.Version(e,0);n.enforce(s,t,i)}static onPending_(e,t,n,s){i.alwaysWarn([n,"has been deprecated and will be removed in",t,". We are currently at version",e,". Additional information:",s].join(" "))}static onExpired_(e,t,n,s){const a=[n,"has been deprecated and has been removed in",t,". We are now at version",e,". Additional information:",s].join(" ");i.alwaysError(a),console.assert(!1,a)}}ae.enforcer_=null,ae.Version=class{constructor(e,t){this.major_=e,this.minor_=t}major(){return this.major_}minor(){return this.minor_}compareTo(e){const t=this.major_-e.major_,i=this.minor_-e.minor_;return t||i}toString(){return"v"+this.major_+"."+this.minor_}static parse(e){const t=e.substring(1).split(".",2);return new ae.Version(Number(t[0]),Number(t[1]))}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}},ae.Enforcer=class{constructor(e,t,i){this.libraryVersion_=e,this.onPending_=t,this.onExpired_=i}enforce(e,t,i){(e.compareTo(this.libraryVersion_)>0?this.onPending_:this.onExpired_)(this.libraryVersion_,e,t,i)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0]}};class re{constructor(e,t){this.dataView_=l.toDataView(e),this.littleEndian_=t==re.Endianness.LITTLE_ENDIAN,this.position_=0}getDataView(){return this.dataView_}hasMoreData(){return this.position_<this.dataView_.byteLength}getPosition(){return this.position_}getLength(){return this.dataView_.byteLength}readUint8(){try{const e=this.dataView_.getUint8(this.position_);return this.position_+=1,e}catch(e){throw this.outOfBounds_()}}readUint16(){try{const e=this.dataView_.getUint16(this.position_,this.littleEndian_);return this.position_+=2,e}catch(e){throw this.outOfBounds_()}}readUint32(){try{const e=this.dataView_.getUint32(this.position_,this.littleEndian_);return this.position_+=4,e}catch(e){throw this.outOfBounds_()}}readInt32(){try{const e=this.dataView_.getInt32(this.position_,this.littleEndian_);return this.position_+=4,e}catch(e){throw this.outOfBounds_()}}readUint64(){let e,t;try{this.littleEndian_?(e=this.dataView_.getUint32(this.position_,!0),t=this.dataView_.getUint32(this.position_+4,!0)):(t=this.dataView_.getUint32(this.position_,!1),e=this.dataView_.getUint32(this.position_+4,!1))}catch(e){throw this.outOfBounds_()}if(t>2097151)throw new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.JS_INTEGER_OVERFLOW);return this.position_+=8,t*Math.pow(2,32)+e}readBytes(e){if(console.assert(e>=0,"Bad call to DataViewReader.readBytes"),this.position_+e>this.dataView_.byteLength)throw this.outOfBounds_();const t=l.toUint8(this.dataView_,this.position_,e);return this.position_+=e,t}skip(e){if(console.assert(e>=0,"Bad call to DataViewReader.skip"),this.position_+e>this.dataView_.byteLength)throw this.outOfBounds_();this.position_+=e}rewind(e){if(console.assert(e>=0,"Bad call to DataViewReader.rewind"),this.position_<e)throw this.outOfBounds_();this.position_-=e}seek(e){if(console.assert(e>=0,"Bad call to DataViewReader.seek"),e<0||e>this.dataView_.byteLength)throw this.outOfBounds_();this.position_=e}readTerminatedString(){const e=this.position_;for(;this.hasMoreData()&&0!=this.dataView_.getUint8(this.position_);)this.position_+=1;const t=l.toUint8(this.dataView_,e,this.position_-e);return this.position_+=1,L.fromUTF8(t)}outOfBounds_(){return new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.BUFFER_READ_OUT_OF_BOUNDS)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}re.Endianness={BIG_ENDIAN:0,LITTLE_ENDIAN:1};class oe{constructor(){this.headers_=[],this.boxDefinitions_=[],this.done_=!1}box(e,t){const i=oe.typeFromString_(e);return this.headers_[i]=oe.BoxType_.BASIC_BOX,this.boxDefinitions_[i]=t,this}fullBox(e,t){const i=oe.typeFromString_(e);return this.headers_[i]=oe.BoxType_.FULL_BOX,this.boxDefinitions_[i]=t,this}stop(){this.done_=!0}parse(e,t,i){const n=new re(e,re.Endianness.BIG_ENDIAN);for(this.done_=!1;n.hasMoreData()&&!this.done_;)this.parseNext(0,n,t,i)}parseNext(e,t,n,s){const a=t.getPosition();if(s&&a+8>t.getLength())return void(this.done_=!0);let r=t.readUint32();const o=t.readUint32(),l=oe.typeToString(o);let d=!1;switch(i.v2("Parsing MP4 box",l),r){case 0:r=t.getLength()-a;break;case 1:if(s&&t.getPosition()+8>t.getLength())return void(this.done_=!0);r=t.readUint64(),d=!0}const c=this.boxDefinitions_[o];if(c){let i=null,h=null;if(this.headers_[o]==oe.BoxType_.FULL_BOX){if(s&&t.getPosition()+4>t.getLength())return void(this.done_=!0);const e=t.readUint32();i=e>>>24,h=16777215&e}let u=a+r;if(n&&u>t.getLength()&&(u=t.getLength()),s&&u>t.getLength())return void(this.done_=!0);const _=u-t.getPosition(),m=_>0?t.readBytes(_):new Uint8Array(0);c({name:l,parser:this,partialOkay:n||!1,version:i,flags:h,reader:new re(m,re.Endianness.BIG_ENDIAN),size:r,start:a+e,has64BitSize:d})}else{const e=Math.min(a+r-t.getPosition(),t.getLength()-t.getPosition());t.skip(e)}}static children(e){const t=oe.headerSize(e);for(;e.reader.hasMoreData()&&!e.parser.done_;)e.parser.parseNext(e.start+t,e.reader,e.partialOkay)}static sampleDescription(e){const t=oe.headerSize(e),i=e.reader.readUint32();for(let n=0;n<i&&(e.parser.parseNext(e.start+t,e.reader,e.partialOkay),!e.parser.done_);n++);}static visualSampleEntry(e){const t=oe.headerSize(e);for(e.reader.skip(78);e.reader.hasMoreData()&&!e.parser.done_;)e.parser.parseNext(e.start+t,e.reader,e.partialOkay)}static audioSampleEntry(e){const t=oe.headerSize(e);e.reader.skip(8);const i=e.reader.readUint16();for(e.reader.skip(6),2==i?e.reader.skip(48):e.reader.skip(12),1==i&&e.reader.skip(16);e.reader.hasMoreData()&&!e.parser.done_;)e.parser.parseNext(e.start+t,e.reader,e.partialOkay)}static allData(e){return t=>{const i=t.reader.getLength()-t.reader.getPosition();e(t.reader.readBytes(i))}}static typeFromString_(e){console.assert(4==e.length,"Mp4 box names must be 4 characters long");let t=0;for(const i of e)t=t<<8|i.charCodeAt(0);return t}static typeToString(e){return String.fromCharCode(e>>24&255,e>>16&255,e>>8&255,255&e)}static headerSize(e){return 8+(e.has64BitSize?8:0)+(null!=e.flags?4:0)}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}oe.CallbackType,oe.BoxType_={BASIC_BOX:0,FULL_BOX:1};class le{static parseTFHD(e,t){let i=null,n=null,s=null;const a=e.readUint32();return 1&t&&(s=e.readUint64()),2&t&&e.skip(4),8&t&&(i=e.readUint32()),16&t&&(n=e.readUint32()),{trackId:a,defaultSampleDuration:i,defaultSampleSize:n,baseDataOffset:s}}static parseTFDT(e,t){return{baseMediaDecodeTime:1==t?e.readUint64():e.readUint32()}}static parseTFDTInaccurate(e,t){if(1==t){const t=e.readUint32(),i=e.readUint32();return{baseMediaDecodeTime:t*Math.pow(2,32)+i}}return{baseMediaDecodeTime:e.readUint32()}}static parsePRFTInaccurate(e,t){e.readUint32();const i=1e3*e.readUint32()+e.readUint32()/2**32*1e3;let n;if(0===t)n=e.readUint32();else{const t=e.readUint32(),i=e.readUint32();n=t*Math.pow(2,32)+i}return{mediaTime:n,ntpTimestamp:i}}static parseMDHD(e,t){1==t?(e.skip(8),e.skip(8)):(e.skip(4),e.skip(4));const i=e.readUint32();e.skip(4);const n=e.readUint16();return{timescale:i,language:String.fromCharCode(96+(n>>10))+String.fromCharCode(96+((960&n)>>5))+String.fromCharCode(96+(31&n))}}static parseTREX(e){return e.skip(4),e.skip(4),{defaultSampleDuration:e.readUint32(),defaultSampleSize:e.readUint32()}}static parseTRUN(e,t,i){const n=e.readUint32(),s=[];let a=null;1&i&&(a=e.readUint32()),4&i&&e.skip(4);for(let a=0;a<n;a++){const n={sampleDuration:null,sampleSize:null,sampleCompositionTimeOffset:null};256&i&&(n.sampleDuration=e.readUint32()),512&i&&(n.sampleSize=e.readUint32()),1024&i&&e.skip(4),2048&i&&(n.sampleCompositionTimeOffset=0==t?e.readUint32():e.readInt32()),s.push(n)}return{sampleCount:n,sampleData:s,dataOffset:a}}static parseTKHD(e,t){1==t?(e.skip(8),e.skip(8)):(e.skip(4),e.skip(4));const i=e.readUint32();return 1==t?e.skip(8):e.skip(4),e.skip(4),e.skip(8),e.skip(2),e.skip(2),e.skip(2),e.skip(2),e.skip(36),{trackId:i,width:e.readUint16()+e.readUint16()/16,height:e.readUint16()+e.readUint16()/16}}static parseMP4A(e){e.skip(6),e.skip(2),e.skip(8);const t=e.readUint16();return e.skip(2),e.skip(2),e.skip(2),{channelCount:t,sampleRate:e.readUint16()+e.readUint16()/65536}}static parseESDS(e){let t,i,n="mp4a";for(;e.hasMoreData();){t=e.readUint8();let n=e.readUint8();for(;128&n;)n=e.readUint8();if(3==t){e.readUint16();const t=e.readUint8();128&t&&e.readUint16(),64&t&&e.skip(e.readUint8()),32&t&&e.readUint16()}else if(4==t)i=e.readUint8(),e.skip(12);else if(5==t)break}if(i&&(n+="."+le.toHex_(i),5==t&&e.hasMoreData())){const t=e.readUint8();let i=(248&t)>>3;31===i&&e.hasMoreData()&&(i=32+((7&t)<<3)+((224&e.readUint8())>>5)),n+="."+i}return{codec:n}}static parseAVCC(e,t,i){const n=n;return t.skip(1),{codec:e+"."+n.toHex_(t.readUint8())+n.toHex_(t.readUint8())+n.toHex_(t.readUint8())}}static parseHVCC(e,t,i){const n=n;t.skip(1);const s=t.readUint8(),a=["","A","B","C"][s>>6],r=31&s,o=t.readUint32(),l=(32&s)>>5?"H":"L",d=[t.readUint8(),t.readUint8(),t.readUint8(),t.readUint8(),t.readUint8(),t.readUint8()],c=t.readUint8();let h=e;h+="."+a+r,h+="."+n.toHex_(n.reverseBits_(o),!0),h+="."+l+c;let u="";for(let e=d.length;e--;){const t=d[e];(t||u)&&(u="."+t.toString(16).toUpperCase()+u)}return h+=u,{codec:h}}static parseDVCC(e,t,i){const n=n;t.skip(2);const s=t.readUint8(),a=s>>1&127,r=s<<5&32|t.readUint8()>>3&31;return{codec:e+"."+n.addLeadingZero_(a)+"."+n.addLeadingZero_(r)}}static parseVPCC(e,t,i){const n=n,s=t.readUint8(),a=t.readUint8(),r=t.readUint8()>>4&15;return{codec:e+"."+n.addLeadingZero_(s)+"."+n.addLeadingZero_(a)+"."+n.addLeadingZero_(r)}}static parseAV1C(e,t,i){const n=n;t.skip(1);const s=t.readUint8(),a=t.readUint8(),r=s>>>5,o=31&s,l=a>>>7?"H":"M",d=(64&a)>>6,c=2===r&&d?(32&a)>>5?12:10:d?10:8,h=(16&a)>>4,u=(8&a)>>3,_=(4&a)>>2,m=3&a;return{codec:e+"."+r+"."+n.addLeadingZero_(o)+l+"."+n.addLeadingZero_(c)+"."+h+"."+u+_+m+"."+n.addLeadingZero_(1)+"."+n.addLeadingZero_(1)+"."+n.addLeadingZero_(1)+".0"}}static parseFRMA(e){const t=e.readUint32();return{codec:oe.typeToString(t)}}static parseTENC(e){return e.readUint8(),e.readUint8(),e.readUint8(),e.readUint8(),{defaultKID:x.toHex(e.readBytes(16))}}static parseHDLR(e){e.skip(8);const t=e.readBytes(4);let i="";return i+=String.fromCharCode(t[0]),i+=String.fromCharCode(t[1]),i+=String.fromCharCode(t[2]),i+=String.fromCharCode(t[3]),{handlerType:i}}static toHex_(e,t=!1){const i=e.toString(16).toUpperCase();return t?i:("0"+i).slice(-2)}static reverseBits_(e){let t=e,i=0;for(let e=0;e<32&&(i|=1&t,31!=e);e++)i<<=1,t>>=1;return i}static addLeadingZero_(e){return(e<10?"0":"")+e}}class de{static isHeader_(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}static isFooter_(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}static readSize_(e,t){let i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3],i}static getFrameData_(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=de.readSize_(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}static decodeFrame_(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if("APIC"===e.type){if(e.size<2)return null;if(e.data[0]!==de.UTF8_encoding)return i.warning("Ignore frame with unrecognized character encoding"),null;const n=e.data.subarray(1).indexOf(0);if(-1===n)return null;const s=L.fromUTF8(l.toUint8(e.data,1,n)),a=e.data[2+n],r=e.data.subarray(3+n).indexOf(0);if(-1===r)return null;const o=L.fromUTF8(l.toUint8(e.data,3+n,r));let d;return d="--\x3e"===s?L.fromUTF8(l.toUint8(e.data,4+n+r)):l.toArrayBuffer(e.data.subarray(4+n+r)),t.mimeType=s,t.pictureType=a,t.description=o,t.data=d,t}if("TXXX"===e.type){if(e.size<2)return null;if(e.data[0]!==de.UTF8_encoding)return i.warning("Ignore frame with unrecognized character encoding"),null;const n=e.data.subarray(1).indexOf(0);if(-1===n)return null;const s=L.fromUTF8(l.toUint8(e.data,1,n)),a=L.fromUTF8(l.toUint8(e.data,2+n)).replace(/\0*$/,"");return t.description=s,t.data=a,t}if("WXXX"===e.type){if(e.size<2)return null;if(e.data[0]!==de.UTF8_encoding)return i.warning("Ignore frame with unrecognized character encoding"),null;const n=e.data.subarray(1).indexOf(0);if(-1===n)return null;const s=L.fromUTF8(l.toUint8(e.data,1,n)),a=L.fromUTF8(l.toUint8(e.data,2+n)).replace(/\0*$/,"");return t.description=s,t.data=a,t}if("PRIV"===e.type){if(e.size<2)return null;const i=e.data.indexOf(0);if(-1===i)return null;const n=L.fromUTF8(l.toUint8(e.data,0,i));if(t.description=n,"com.apple.streaming.transportStreamTimestamp"==n){const i=e.data.subarray(n.length+1),s=1&i[3];let a=(i[4]<<23)+(i[5]<<15)+(i[6]<<7)+i[7];a/=45,s&&(a+=47721858.84),t.data=a}else{const i=l.toArrayBuffer(e.data.subarray(n.length+1));t.data=i}return t}if("T"===e.type[0]){if(e.size<2)return null;if(e.data[0]!==de.UTF8_encoding)return i.warning("Ignore frame with unrecognized character encoding"),null;const n=L.fromUTF8(e.data.subarray(1)).replace(/\0*$/,"");return t.data=n,t}if("W"===e.type[0]){const i=L.fromUTF8(e.data).replace(/\0*$/,"");return t.data=i,t}return e.data?(i.warning("Unrecognized ID3 frame type:",e.type),t.data=l.toArrayBuffer(e.data),t):null}static getID3Frames(e){const t=t;let i=0;const n=[];for(;t.isHeader_(e,i);){const s=t.readSize_(e,i+6);e[i+5]>>6&1&&(i+=10),i+=10;const a=i+s;for(;i+10<a;){const s=t.getFrameData_(e.subarray(i)),a=t.decodeFrame_(s);a&&n.push(a),i+=s.size+10}t.isFooter_(e,i)&&(i+=10)}return n}static getID3Data(e,t=0){const i=i,n=t;let s=0;for(;i.isHeader_(e,t);)e[t+5]>>6&1&&(s+=10),s+=10,s+=i.readSize_(e,t+6),i.isFooter_(e,t+10)&&(s+=10),t+=s;return s>0?e.subarray(n,n+s):new Uint8Array([])}}de.UTF8_encoding=3;class ce{constructor(e,t=!1){this.data_=e,t&&(this.data_=this.ebsp2rbsp_(e)),this.workingBytesAvailable_=this.data_.byteLength,this.workingWord_=0,this.workingBitsAvailable_=0}ebsp2rbsp_(e){const t=new Uint8Array(e.byteLength);let i=0;for(let n=0;n<e.byteLength;n++)n>=2&&3==e[n]&&0==e[n-1]&&0==e[n-2]||(t[i]=e[n],i++);return l.toUint8(t,0,i)}loadWord_(){const e=this.data_.byteLength-this.workingBytesAvailable_,t=new Uint8Array(4),i=Math.min(4,this.workingBytesAvailable_);if(0===i)return;t.set(this.data_.subarray(e,e+i));const n=new re(t,re.Endianness.BIG_ENDIAN);this.workingWord_=n.readUint32(),this.workingBitsAvailable_=8*i,this.workingBytesAvailable_-=i}skipBits(e){if(this.workingBitsAvailable_<=e){e-=this.workingBitsAvailable_;const t=Math.floor(e/8);e-=8*t,this.workingBitsAvailable_-=t,this.loadWord_()}this.workingWord_<<=e,this.workingBitsAvailable_-=e}readBits(e){let t=Math.min(this.workingBitsAvailable_,e);const i=this.workingWord_>>>32-t;return this.workingBitsAvailable_-=t,this.workingBitsAvailable_>0?this.workingWord_<<=t:this.workingBytesAvailable_>0&&this.loadWord_(),t=e-t,t>0?i<<t|this.readBits(t):i}skipLeadingZeros_(){let e;for(e=0;e<this.workingBitsAvailable_;++e)if(0!=(this.workingWord_&2147483648>>>e))return this.workingWord_<<=e,this.workingBitsAvailable_-=e,e;return this.loadWord_(),e+this.skipLeadingZeros_()}skipExpGolomb(){this.skipBits(1+this.skipLeadingZeros_())}readUnsignedExpGolomb(){const e=this.skipLeadingZeros_();return this.readBits(e+1)-1}readExpGolomb(){const e=this.readUnsignedExpGolomb();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUnsignedByte(){return this.readBits(8)}skipScalingList(e){let t=8,i=8;for(let n=0;n<e;n++)0!==i&&(i=(t+this.readExpGolomb()+256)%256),t=0===i?t:i}readSliceType(){return this.readUnsignedByte(),this.readUnsignedExpGolomb(),this.readUnsignedExpGolomb()}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}class he{constructor(){this.pmtId_=null,this.pmtParsed_=!1,this.videoPid_=null,this.videoCodec_=null,this.videoData_=[],this.videoPes_=[],this.audioPid_=null,this.audioCodec_=null,this.audioData_=[],this.audioPes_=[],this.id3Pid_=null,this.id3Data_=[],this.referencePts_=null,this.referenceDts_=null}clearData(){this.videoData_=[],this.videoPes_=[],this.audioData_=[],this.audioPes_=[],this.id3Data_=[]}parse(e){const t=he.PacketLength_;if(e.length<3*t)return this;const n=Math.max(0,he.syncOffset(e)),s=e.length-(e.length+n)%t;let a=!1;for(let r=n;r<s;r+=t)if(71==e[r]){const s=!!(64&e[r+1]),o=((31&e[r+1])<<8)+e[r+2];let l;if((48&e[r+3])>>4>1){if(l=r+5+e[r+4],l==r+t)continue}else l=r+4;switch(o){case 0:s&&(l+=e[l]+1),this.pmtId_=this.getPmtId_(e,l);break;case 17:case 8191:break;case this.pmtId_:{s&&(l+=e[l]+1);const o=this.parsePMT_(e,l);-1!=o.video&&(this.videoPid_=o.video,this.videoCodec_=o.videoCodec),-1!=o.audio&&(this.audioPid_=o.audio,this.audioCodec_=o.audioCodec),-1!=o.id3&&(this.id3Pid_=o.id3),a&&!this.pmtParsed_&&(i.debug("reparse from beginning"),a=!1,r=n-t),this.pmtParsed_=!0;break}case this.videoPid_:{const i=e.subarray(l,r+t);s?this.videoData_.push([i]):this.videoData_.length&&this.videoData_[this.videoData_.length-1]&&this.videoData_[this.videoData_.length-1].push(i);break}case this.audioPid_:{const i=e.subarray(l,r+t);s?this.audioData_.push([i]):this.audioData_.length&&this.audioData_[this.audioData_.length-1]&&this.audioData_[this.audioData_.length-1].push(i);break}case this.id3Pid_:{const i=e.subarray(l,r+t);s?this.id3Data_.push([i]):this.id3Data_.length&&this.id3Data_[this.id3Data_.length-1]&&this.id3Data_[this.id3Data_.length-1].push(i);break}default:a=!0}}else i.warning("Found TS packet that do not start with 0x47");return this}getPmtId_(e,t){return(31&e[t+10])<<8|e[t+11]}parsePMT_(e,t){const i={audio:-1,video:-1,id3:-1,audioCodec:"",videoCodec:""},n=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<n;){const n=(31&e[t+1])<<8|e[t+2],s=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 6:if(s>0){let a=t+5,r=s;for(;r>2;){const t=e[a],s=e[a+1]+2;switch(t){case 5:{const t=e.subarray(a+2,a+s),r=L.fromCharCode(t);-1==i.audio&&"Opus"===r?(i.audio=n,i.audioCodec="opus"):-1==i.video&&"AV01"===r&&(i.video=n,i.videoCodec="av1");break}case 106:-1==i.audio&&(i.audio=n,i.audioCodec="ac3");break;case 122:-1==i.audio&&(i.audio=n,i.audioCodec="ec3");break;case 124:-1==i.audio&&(i.audio=n,i.audioCodec="aac")}a+=s,r-=s}}break;case 207:case 219:break;case 15:-1==i.audio&&(i.audio=n,i.audioCodec="aac");break;case 17:-1==i.audio&&(i.audio=n,i.audioCodec="aac-loas");break;case 21:-1==i.id3&&(i.id3=n);break;case 27:-1==i.video&&(i.video=n,i.videoCodec="avc");break;case 3:case 4:-1==i.audio&&(i.audio=n,i.audioCodec="mp3");break;case 36:-1==i.video&&(i.video=n,i.videoCodec="hvc");break;case 129:-1==i.audio&&(i.audio=n,i.audioCodec="ac3");break;case 132:case 135:-1==i.audio&&(i.audio=n,i.audioCodec="ec3")}t+=s+5}return i}parsePES_(e){if(1!=(e[0]<<16|e[1]<<8|e[2]))return null;const t={data:new Uint8Array(0),packetLength:e[4]<<8|e[5],pts:null,dts:null,nalus:[]};if(t.packetLength&&t.packetLength>e.byteLength-6)return null;const i=e[7];if(192&i){const n=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2;if(null==this.referencePts_&&(this.referencePts_=n),t.pts=this.handleRollover_(n,this.referencePts_),this.referencePts_=t.pts,t.dts=t.pts,64&i){const i=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2;null==this.referenceDts_&&(this.referenceDts_=i),t.dts=this.handleRollover_(i,this.referenceDts_)}this.referenceDts_=t.dts}const n=e[8]+9;return e.byteLength<=n?null:(t.data=e.subarray(n),t)}parseAvcNalus(e,t){return ae.deprecateFeature(5,"TsParser.parseAvcNalus","Please use parseNalus function instead."),this.parseNalus(e)}parseNalus(e,t,n){const s=he.Timescale,a=e.pts?e.pts/s:null,r=e.data,o=r.byteLength;let l=1;"hvc"==this.videoCodec_&&(l=2);let d=n||0;const c=[];let h,u=-1,_=0;for(let e=0;e<o;++e){const s=r[e];if(s)if(d>=2&&1==s){if(t&&!c.length&&-1==u){const i=e-(d>3?3:d);if(n&&0!=i){const e=r.subarray(0,i);t.data=x.concat(t.data,e),t.fullData=x.concat(t.fullData,e)}}if(u>=0){const t=u+l,i=e-((d>3?3:d)+1),n={data:r.subarray(t,i+1),fullData:r.subarray(u,i+1),type:_,time:a};c.push(n)}else if(t&&!c.length){const i=e-d;if(i>0){const e=r.subarray(0,i);t.data=x.concat(t.data,e),t.fullData=x.concat(t.fullData,e)}}if(e>=o-l)return i.warning("Malformed TS, incomplete NALU, ignoring."),c;e++,u=e,_="hvc"==this.videoCodec_?r[e]>>1&63:31&r[e],d=0}else d=0;else d++;if(e>=o-1&&u>=0&&d>=0){const e=u+l;h={data:r.subarray(e,o),fullData:r.subarray(u,o),type:_,time:a}}}return h&&c.push(h),!c.length&&t&&(t.data=x.concat(t.data,r),t.fullData=x.concat(t.fullData,r)),n=Math.min(3,d),c}getMetadata(){const e=he.Timescale,t=[];for(const i of this.id3Data_){const n=x.concat(...i),s=this.parsePES_(n);s&&t.push({cueTime:s.pts?s.pts/e:null,data:s.data,frames:de.getID3Frames(s.data),dts:s.dts,pts:s.pts})}return t}getAudioData(){if(this.audioData_.length&&!this.audioPes_.length){let e=!1;for(const t of this.audioData_){const i=x.concat(...t),n=this.parsePES_(i);let s=this.audioPes_.length?this.audioPes_[this.audioPes_.length-1]:null;if(n&&null!=n.pts&&null!=n.dts&&(!s||s.pts!=n.pts&&s.dts!=n.dts))this.audioPes_.length&&n.dts<(s.dts||0)&&(e=!0),this.audioPes_.push(n);else if(this.audioPes_.length){const e=n?n.data:i;if(!e)continue;s=this.audioPes_.pop(),s.data=x.concat(s.data,e),this.audioPes_.push(s)}}e&&(this.audioPes_=this.audioPes_.sort(((e,t)=>{const i=(e.dts||0)-(t.dts||0),n=(e.pts||0)-(t.pts||0);return i||n})))}return this.audioPes_}getVideoData(e=!0){if(this.videoData_.length&&!this.videoPes_.length){let t=!1;for(const e of this.videoData_){const i=x.concat(...e),n=this.parsePES_(i);let s=this.videoPes_.length?this.videoPes_[this.videoPes_.length-1]:null;if(n&&null!=n.pts&&null!=n.dts&&(!s||s.pts!=n.pts&&s.dts!=n.dts))this.videoPes_.length&&n.dts<(s.dts||0)&&(t=!0),this.videoPes_.push(n);else if(this.videoPes_.length){const e=n?n.data:i;if(!e)continue;s=this.videoPes_.pop(),s.data=x.concat(s.data,e),this.videoPes_.push(s)}}if(e){let e,t;for(const i of this.videoPes_)i.nalus=this.parseNalus(i,e,t),i.nalus.length&&(e=i.nalus[i.nalus.length-1]);this.videoPes_=this.videoPes_.filter((e=>e.nalus.length))}t&&(this.videoPes_=this.videoPes_.sort(((e,t)=>{const i=(e.dts||0)-(t.dts||0),n=(e.pts||0)-(t.pts||0);return i||n})))}if(!e){const e=this.videoPes_;return this.videoPes_=[],e}return this.videoPes_}getStartTime(e){const t=he.Timescale;if("audio"==e){let e=null;const i=this.getAudioData();if(i.length){const n=i[0];e=Math.min(n.dts,n.pts)/t}return e}if("video"==e){let e=null;const i=this.getVideoData(!1);if(i.length){const n=i[0];e=Math.min(n.dts,n.pts)/t}return e}return null}getCodecs(){return{audio:this.audioCodec_,video:this.videoCodec_}}getVideoNalus(){const e=[];for(const t of this.getVideoData())e.push(...t.nalus);return e}getVideoResolution(){ae.deprecateFeature(5,"TsParser.getVideoResolution","Please use getVideoInfo function instead.");const e=this.getVideoInfo();return{height:e.height,width:e.width}}getVideoInfo(){return"hvc"==this.videoCodec_?this.getHvcInfo_():this.getAvcInfo_()}getAvcInfo_(){const e=e,t={height:null,width:null,codec:null},i=this.getVideoNalus();if(!i.length)return t;const n=i.find((t=>t.type==e.H264_NALU_TYPE_SPS_));if(!n)return t;const s=new ce(n.data),a=s.readUnsignedByte(),r=s.readUnsignedByte(),o=s.readUnsignedByte();if(s.skipExpGolomb(),e.PROFILES_WITH_OPTIONAL_SPS_DATA_.includes(a)){const e=s.readUnsignedExpGolomb();if(3===e&&s.skipBits(1),s.skipExpGolomb(),s.skipExpGolomb(),s.skipBits(1),s.readBoolean()){const t=3!==e?8:12;for(let e=0;e<t;e++)s.readBoolean()&&(e<6?s.skipScalingList(16):s.skipScalingList(64))}}s.skipExpGolomb();const l=s.readUnsignedExpGolomb();if(0===l)s.readUnsignedExpGolomb();else if(1===l){s.skipBits(1),s.skipExpGolomb(),s.skipExpGolomb();const e=s.readUnsignedExpGolomb();for(let t=0;t<e;t++)s.skipExpGolomb()}s.skipExpGolomb(),s.skipBits(1);const d=s.readUnsignedExpGolomb(),c=s.readUnsignedExpGolomb(),h=s.readBits(1);0===h&&s.skipBits(1),s.skipBits(1);let u=0,_=0,m=0,g=0;return s.readBoolean()&&(u=s.readUnsignedExpGolomb(),_=s.readUnsignedExpGolomb(),m=s.readUnsignedExpGolomb(),g=s.readUnsignedExpGolomb()),t.height=String((2-h)*(c+1)*16-2*m-2*g),t.width=String(16*(d+1)-2*u-2*_),t.codec="avc1."+this.byteToHex_(a)+this.byteToHex_(r)+this.byteToHex_(o),t}getHvcInfo_(){const e=e,t={height:null,width:null,codec:null},i=this.getVideoNalus();if(!i.length)return t;const n=i.find((t=>t.type==e.H265_NALU_TYPE_SPS_));if(!n)return t;const s=new ce(n.fullData,!0);s.readUnsignedByte(),s.readUnsignedByte(),s.readBits(4);const a=s.readBits(3);s.readBoolean();const r=s.readBits(2),o=s.readBits(1),l=s.readBits(5),d=s.readBits(32),c=s.readUnsignedByte(),h=s.readUnsignedByte(),u=s.readUnsignedByte(),_=s.readUnsignedByte(),m=s.readUnsignedByte(),g=s.readUnsignedByte(),f=s.readUnsignedByte(),p=[],T=[];for(let e=0;e<a;e++)p.push(s.readBoolean()),T.push(s.readBoolean());if(a>0)for(let e=a;e<8;e++)s.readBits(2);for(let e=0;e<a;e++)p[e]&&s.readBits(88),T[e]&&s.readUnsignedByte();s.readUnsignedExpGolomb();const S=s.readUnsignedExpGolomb();3==S&&s.readBits(1);const y=s.readUnsignedExpGolomb(),E=s.readUnsignedExpGolomb();let v=0,I=0,A=0,b=0;s.readBoolean()&&(v+=s.readUnsignedExpGolomb(),I+=s.readUnsignedExpGolomb(),A+=s.readUnsignedExpGolomb(),b+=s.readUnsignedExpGolomb());const C=1===S||2===S?2:1,w=1===S?2:1;t.width=String(y-(v+I)*C),t.height=String(E-(A+b)*w);const M=1==o?"H":"L";let R="hvc1";return R+="."+["","A","B","C"][r]+l,R+="."+(e=>{let t=0;for(let i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0})(d).toString(16).toUpperCase(),R+="."+M+f,g&&(R+="."+g.toString(16).toUpperCase()),m&&(R+="."+m.toString(16).toUpperCase()),_&&(R+="."+_.toString(16).toUpperCase()),u&&(R+="."+u.toString(16).toUpperCase()),h&&(R+="."+h.toString(16).toUpperCase()),c&&(R+="."+c.toString(16).toUpperCase()),t.codec=R,t}byteToHex_(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}handleRollover_(e,t){let i=1;for(e>t&&(i=-1);Math.abs(t-e)>4294967296;)e+=8589934592*i;return e}static probe(e){const t=he.syncOffset(e);return!(t<0||(t>0&&i.warning("MPEG2-TS detected but first sync word found @ offset "+t+", junk ahead ?"),0))}static syncOffset(e){const t=he.PacketLength_,i=Math.min(1e3,e.length-3*t);let n=0;for(;n<i;){if(71==e[n]&&71==e[n+t]&&71==e[n+2*t])return n;n++}return-1}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}he.Timescale=9e4,he.PacketLength_=188,he.H264_NALU_TYPE_SPS_=7,he.H265_NALU_TYPE_SPS_=33,he.PROFILES_WITH_OPTIONAL_SPS_DATA_=[100,110,122,244,44,83,86,118,128,138,139,134];class ue{static registerParserByMime(e,t){y.parsersByMime[e]=t}static unregisterParserByMime(e){delete y.parsersByMime[e]}static probeSupport(){const e={};if(P.supportsMediaSource())for(const t in y.parsersByMime)e[t]=!0;const t=["application/dash+xml","application/x-mpegurl","application/vnd.apple.mpegurl","application/vnd.ms-sstr+xml"];for(const i of t)P.supportsMediaSource()?e[i]=!!y.parsersByMime[i]:e[i]=P.supportsMediaType(i);return e}static getFactory(e,t){if(t){const e=y.parsersByMime[t.toLowerCase()];if(e)return e;i.warning("Could not determine manifest type using MIME type ",t)}throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.UNABLE_TO_GUESS_MANIFEST_TYPE,e,t)}static isSupported(e){return!!P.supportsMediaSource()&&e in y.parsersByMime}}y=ue,ue.ManifestType=g,ue.HLS=y.ManifestType.HLS,ue.DASH=y.ManifestType.HLS,ue.MSS=y.ManifestType.MSS,ue.UNKNOWN=y.ManifestType.UNKNOWN,ue.AccessibilityPurpose=T,ue.parsersByMime={};class _e{constructor(e){this.destroyed_=!1,this.waitOnDestroy_=new C,this.onDestroy_=e}destroyed(){return this.destroyed_}destroy(){return this.destroyed_?this.waitOnDestroy_:(this.destroyed_=!0,this.onDestroy_().then((()=>{this.waitOnDestroy_.resolve()}),(()=>{this.waitOnDestroy_.resolve()})))}ensureNotDestroyed(e){if(this.destroyed_){if(e instanceof v&&e.code==v.Code.OBJECT_DESTROYED)throw e;throw _e.destroyedError(e)}}static destroyedError(e){return new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.OBJECT_DESTROYED,e)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class me{static bufferStart(e){return e?1==e.length&&e.end(0)-e.start(0)<1e-6?null:1==e.length&&e.start(0)<0?0:e.length?e.start(0):null:null}static bufferEnd(e){return e?1==e.length&&e.end(0)-e.start(0)<1e-6?null:e.length?e.end(e.length-1):null:null}static isBuffered(e,t){return!(!e||!e.length||1==e.length&&e.end(0)-e.start(0)<1e-6||t>e.end(e.length-1)||!(t>=e.start(0)))}static bufferedAheadOf(e,t){if(!e||!e.length)return 0;if(1==e.length&&e.end(0)-e.start(0)<1e-6)return 0;let i=0;for(const{start:n,end:s}of me.getBufferedInfo(e))s>t&&(i+=s-Math.max(n,t));return i}static getGapIndex(e,t,i){if(!e||!e.length)return null;if(1==e.length&&e.end(0)-e.start(0)<1e-6)return null;const n=me.getBufferedInfo(e).findIndex(((e,n,s)=>e.start>t&&(0==n||s[n-1].end-t<=i)));return n>=0?n:null}static getBufferedInfo(e){if(!e)return[];const t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static computeAddedRange(e,t){var i;if(!e||!e.length)return null;if(!t||!t.length)return null!==(i=me.getBufferedInfo(t).pop())&&void 0!==i?i:null;const n=me.getBufferedInfo(t).reverse(),s=me.getBufferedInfo(e).reverse();for(const e of n){let t=!1;for(const i of s)if(i.end>=e.start&&i.end<=e.end&&(t=!0,e.end>i.end))return{start:i.end,end:e.end};if(!t)return e}return null}}class ge{static fakeEncryption(e){let t,n=l.toUint8(e),s=!1;const a=[],r=e=>{a.push(e),oe.children(e)},o=e=>{s=!0},d=[];if((new oe).box("moov",r).box("trak",r).box("mdia",r).box("minf",r).box("stbl",r).fullBox("stsd",(e=>{t=e,a.push(e),oe.sampleDescription(e)})).fullBox("encv",o).fullBox("enca",o).fullBox("dvav",(e=>{d.push({box:e,newType:ge.BOX_TYPE_ENCV_})})).fullBox("dva1",(e=>{d.push({box:e,newType:ge.BOX_TYPE_ENCV_})})).fullBox("dvh1",(e=>{d.push({box:e,newType:ge.BOX_TYPE_ENCV_})})).fullBox("dvhe",(e=>{d.push({box:e,newType:ge.BOX_TYPE_ENCV_})})).fullBox("hev1",(e=>{d.push({box:e,newType:ge.BOX_TYPE_ENCV_})})).fullBox("hvc1",(e=>{d.push({box:e,newType:ge.BOX_TYPE_ENCV_})})).fullBox("avc1",(e=>{d.push({box:e,newType:ge.BOX_TYPE_ENCV_})})).fullBox("avc3",(e=>{d.push({box:e,newType:ge.BOX_TYPE_ENCV_})})).fullBox("ac-3",(e=>{d.push({box:e,newType:ge.BOX_TYPE_ENCA_})})).fullBox("ec-3",(e=>{d.push({box:e,newType:ge.BOX_TYPE_ENCA_})})).fullBox("ac-4",(e=>{d.push({box:e,newType:ge.BOX_TYPE_ENCA_})})).fullBox("mp4a",(e=>{d.push({box:e,newType:ge.BOX_TYPE_ENCA_})})).parse(n),s)return i.debug("Init segment already indicates encryption."),n;if(0==d.length||!t)throw i.error("Failed to find boxes needed to fake encryption!"),i.v2("Failed init segment (hex):",x.toHex(n)),new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.CONTENT_TRANSFORMATION_FAILED);d.reverse();for(const e of d){const s=oe.typeToString(e.newType);i.debug(`Inserting "${s}" box into init segment.`),n=ge.insertEncryptionMetadata_(n,t,e.box,a,e.newType)}return n}static insertEncryptionMetadata_(e,t,i,n,s){const a=ge.createEncryptionMetadata_(e,i,s),r=new Uint8Array(e.byteLength+a.byteLength),o=P.isXboxOne()?i.start:i.start+i.size,d=e.subarray(0,o),c=e.subarray(o);r.set(d),r.set(a,o),r.set(c,o+a.byteLength);for(const e of n)console.assert(e.start<o,"Ancestor MP4 box found in the wrong location! Modified init segment will not make sense!"),ge.updateBoxSize_(r,e.start,e.size+a.byteLength);const h=l.toDataView(r,t.start),u=oe.headerSize(t),_=h.getUint32(u);return h.setUint32(u,_+1),r}static createEncryptionMetadata_(e,t,i){const n=ge.CANNED_SINF_BOX_.value(),s=e.subarray(t.start,t.start+t.size),a=l.toDataView(s),r=new Uint8Array(t.size+n.byteLength);r.set(s,0);const o=l.toDataView(r);o.setUint32(ge.BOX_TYPE_OFFSET_,i),r.set(n,t.size);const d=a.getUint32(ge.BOX_TYPE_OFFSET_);return o.setUint32(t.size+ge.CANNED_SINF_BOX_FORMAT_OFFSET_,d),ge.updateBoxSize_(r,0,r.byteLength),r}static updateBoxSize_(e,t,i){const n=l.toDataView(e,t),s=n.getUint32(ge.BOX_SIZE_OFFSET_);0==s||(1==s?(n.setUint32(ge.BOX_SIZE_64_OFFSET_,i>>32),n.setUint32(ge.BOX_SIZE_64_OFFSET_+4,4294967295&i)):n.setUint32(ge.BOX_SIZE_OFFSET_,i))}}ge.CANNED_SINF_BOX_=new N((()=>new Uint8Array([0,0,0,80,115,105,110,102,0,0,0,12,102,114,109,97,0,0,0,0,0,0,0,20,115,99,104,109,0,0,0,0,99,101,110,99,0,1,0,0,0,0,0,40,115,99,104,105,0,0,0,32,116,101,110,99,0,0,0,0,0,0,1,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]))),ge.CANNED_SINF_BOX_FORMAT_OFFSET_=16,ge.BOX_SIZE_OFFSET_=0,ge.BOX_TYPE_OFFSET_=4,ge.BOX_SIZE_64_OFFSET_=8,ge.BOX_TYPE_ENCV_=1701733238,ge.BOX_TYPE_ENCA_=1701733217;class fe{constructor(e,t,i,n){this.video_=e,this.config_=null,this.textDisplayer_=t,this.sourceBuffers_={},this.sourceBufferTypes_={},this.expectedEncryption_={},this.textEngine_=null,this.segmentRelativeVttTiming_=!1,this.onMetadata_=i||((e,t,i)=>{}),this.lcevcDec_=n||null,this.queues_={},this.eventManager_=new Z,this.transmuxers_={},this.captionParser_=null,this.mediaSourceOpen_=new C,this.url_="",this.playbackHasBegun_=!1,this.mediaSource_=this.createMediaSource(this.mediaSourceOpen_),this.reloadingMediaSource_=!1,this.destroyer_=new _e((()=>this.doDestroy_())),this.sequenceMode_=!1,this.manifestType_=ue.UNKNOWN,this.ignoreManifestTimestampsInSegmentsMode_=!1,this.attemptTimestampOffsetCalculation_=!1,this.textSequenceModeOffset_=new C,this.needSplitMuxedContent_=!1,this.streamingAllowed_=!0,this.lastDuration_=null,this.tsParser_=null}createMediaSource(e){if(window.ManagedMediaSource){this.video_.disableRemotePlayback=!0;const t=new ManagedMediaSource;return this.eventManager_.listen(t,"startstreaming",(()=>{this.streamingAllowed_=!0})),this.eventManager_.listen(t,"endstreaming",(()=>{this.streamingAllowed_=!1})),this.eventManager_.listenOnce(t,"sourceopen",(()=>this.onSourceOpen_(e))),this.eventManager_.listenOnce(this.video_,"playing",(()=>{this.playbackHasBegun_=!0})),this.url_=fe.createObjectURL(t),this.video_.src=this.url_,t}{const t=new MediaSource;return this.eventManager_.listenOnce(t,"sourceopen",(()=>this.onSourceOpen_(e))),this.eventManager_.listenOnce(this.video_,"playing",(()=>{this.playbackHasBegun_=!0})),this.url_=fe.createObjectURL(t),this.video_.src=this.url_,t}}onSourceOpen_(e){console.assert(this.url_,"Must have object URL"),URL.revokeObjectURL(this.url_),e.resolve()}static isStreamSupported(e){const t=B.getFullType(e.mimeType,e.codecs),i=B.getExtendedType(e),n=B.getFullTypeWithAllCodecs(e.mimeType,e.codecs);return X.isTypeSupported(t)||V.isTypeSupported(i)||U.isSupported(n,e.type)}static probeSupport(){const e=['video/mp4; codecs="avc1.42E01E"','video/mp4; codecs="avc3.42E01E"','video/mp4; codecs="hev1.1.6.L93.90"','video/mp4; codecs="hvc1.1.6.L93.90"','video/mp4; codecs="hev1.2.4.L153.B0"; eotf="smpte2084"','video/mp4; codecs="hvc1.2.4.L153.B0"; eotf="smpte2084"','video/mp4; codecs="vp9"','video/mp4; codecs="vp09.00.10.08"','video/mp4; codecs="av01.0.01M.08"','video/mp4; codecs="dvh1.20.01"','audio/mp4; codecs="mp4a.40.2"','audio/mp4; codecs="ac-3"','audio/mp4; codecs="ec-3"','audio/mp4; codecs="ac-4"','audio/mp4; codecs="opus"','audio/mp4; codecs="flac"','audio/mp4; codecs="dtsc"','audio/mp4; codecs="dtse"','audio/mp4; codecs="dtsx"','video/webm; codecs="vp8"','video/webm; codecs="vp9"','video/webm; codecs="vp09.00.10.08"','audio/webm; codecs="vorbis"','audio/webm; codecs="opus"','video/mp2t; codecs="avc1.42E01E"','video/mp2t; codecs="avc3.42E01E"','video/mp2t; codecs="hvc1.1.6.L93.90"','video/mp2t; codecs="mp4a.40.2"','video/mp2t; codecs="ac-3"','video/mp2t; codecs="ec-3"',"text/vtt",'application/mp4; codecs="wvtt"',"application/ttml+xml",'application/mp4; codecs="stpp"',...B.RAW_FORMATS],t={};for(const i of e){P.supportsMediaSource()?X.isTypeSupported(i)?t[i]=!0:t[i]=V.isTypeSupported(i)||U.isSupported(i):t[i]=P.supportsMediaType(i);const e=i.split(";")[0];t[e]=t[e]||t[i]}return t}destroy(){return this.destroyer_.destroy()}async doDestroy_(){const e=[];for(const t in this.queues_){const i=this.queues_[t],n=i[0];this.queues_[t]=i.slice(0,1),n&&e.push(n.p.catch(F.noop));for(const e of i.slice(1))e.p.reject(_e.destroyedError())}this.textEngine_&&e.push(this.textEngine_.destroy()),this.textDisplayer_&&e.push(this.textDisplayer_.destroy());for(const t in this.transmuxers_)e.push(this.transmuxers_[t].destroy());await Promise.all(e),this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null),this.video_&&(this.video_.removeAttribute("src"),this.video_.load(),this.video_=null),this.config_=null,this.mediaSource_=null,this.textEngine_=null,this.textDisplayer_=null,this.sourceBuffers_={},this.transmuxers_={},this.captionParser_=null;for(const e in this.queues_)console.assert(0==this.queues_[e].length,e+" queue should be empty after destroy!");this.queues_={},this.lcevcDec_=null,this.tsParser_=null}open(){return this.mediaSourceOpen_}async init(e,t=!1,i=ue.UNKNOWN,n=!1){const s=k.ContentType;await this.mediaSourceOpen_,this.sequenceMode_=t,this.manifestType_=i,this.ignoreManifestTimestampsInSegmentsMode_=n,this.attemptTimestampOffsetCalculation_=!this.sequenceMode_&&this.manifestType_==ue.HLS&&!this.ignoreManifestTimestampsInSegmentsMode_,this.tsParser_=null;for(const t of e.keys()){const i=e.get(t);this.initSourceBuffer_(t,i,i.codecs),this.needSplitMuxedContent_?(this.queues_[s.AUDIO]=[],this.queues_[s.VIDEO]=[]):this.queues_[t]=[]}}initSourceBuffer_(e,t,i){const n=k.ContentType;console.assert(fe.isStreamSupported(t),"Type negotiation should happen before MediaSourceEngine.init!");let s=B.getFullType(t.mimeType,i);if(e==n.TEXT)this.reinitText(s,this.sequenceMode_,t.external);else{let a=this.config_.forceTransmux;(!V.isTypeSupported(s)||!this.sequenceMode_&&B.RAW_FORMATS.includes(s))&&(a=!0);const r=B.getFullTypeWithAllCodecs(t.mimeType,i);if(a){const a=k.guessCodecsSafe(n.AUDIO,(i||"").split(",")),o=k.guessCodecsSafe(n.VIDEO,(i||"").split(","));if(a&&o)return this.needSplitMuxedContent_=!0,this.initSourceBuffer_(n.AUDIO,t,a),void this.initSourceBuffer_(n.VIDEO,t,o);const l=U.findTransmuxer(r);if(l){const t=l();this.transmuxers_[e]=t,s=t.convertCodecs(e,r)}}const o=this.addExtraFeaturesToMimeType_(s);let l;this.destroyer_.ensureNotDestroyed();try{l=this.mediaSource_.addSourceBuffer(o)}catch(e){throw new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.MEDIA_SOURCE_OPERATION_THREW,e,"The mediaSource_ status was "+this.mediaSource_.readyState+" expected 'open'")}this.sequenceMode_&&(l.mode=fe.SourceBufferMode_.SEQUENCE),this.eventManager_.listen(l,"error",(()=>this.onError_(e))),this.eventManager_.listen(l,"updateend",(()=>this.onUpdateEnd_(e))),this.sourceBuffers_[e]=l,this.sourceBufferTypes_[e]=s,this.expectedEncryption_[e]=!1}}configure(e){this.config_=e,this.textEngine_&&this.textEngine_.setModifyCueCallback(e.modifyCueCallback)}isStreamingAllowed(){return this.streamingAllowed_}reinitText(e,t,i){this.textEngine_||(this.textEngine_=new X(this.textDisplayer_),this.textEngine_&&this.textEngine_.setModifyCueCallback(this.config_.modifyCueCallback)),this.textEngine_.initParser(e,t,i||this.segmentRelativeVttTiming_,this.manifestType_)}ended(){return!(this.reloadingMediaSource_||this.mediaSource_&&"ended"!=this.mediaSource_.readyState)}bufferStart(e){return this.reloadingMediaSource_||!Object.keys(this.sourceBuffers_).length?null:e==k.ContentType.TEXT?this.textEngine_.bufferStart():me.bufferStart(this.getBuffered_(e))}bufferEnd(e){return this.reloadingMediaSource_?null:e==k.ContentType.TEXT?this.textEngine_.bufferEnd():me.bufferEnd(this.getBuffered_(e))}isBuffered(e,t){if(this.reloadingMediaSource_)return!1;if(e==k.ContentType.TEXT)return this.textEngine_.isBuffered(t);{const i=this.getBuffered_(e);return me.isBuffered(i,t)}}bufferedAheadOf(e,t){if(this.reloadingMediaSource_)return 0;if(e==k.ContentType.TEXT)return this.textEngine_.bufferedAheadOf(t);{const i=this.getBuffered_(e);return me.bufferedAheadOf(i,t)}}getBufferedInfo(){const e=k.ContentType,t={total:this.reloadingMediaSource_?[]:me.getBufferedInfo(this.video_.buffered),audio:this.reloadingMediaSource_?[]:me.getBufferedInfo(this.getBuffered_(e.AUDIO)),video:this.reloadingMediaSource_?[]:me.getBufferedInfo(this.getBuffered_(e.VIDEO)),text:[]};if(this.textEngine_){const e=this.textEngine_.bufferStart(),i=this.textEngine_.bufferEnd();null!=e&&null!=i&&t.text.push({start:e,end:i})}return t}getBuffered_(e){try{return this.sourceBuffers_[e].buffered}catch(t){return e in this.sourceBuffers_&&i.error("failed to get buffered range for "+e,t),null}}getCaptionParser(e){return new q(e)}getTimestampAndDispatchMetadata_(e,t,i,n,s){let a=null;const r=l.toUint8(t);if(B.RAW_FORMATS.includes(n)){const e=de.getID3Frames(r);if(e.length&&i){const t=e.find((e=>"com.apple.streaming.transportStreamTimestamp"===e.description));t&&t.data&&(a=Math.round(t.data)/1e3);const n={cueTime:i.startTime,data:r,frames:e,dts:i.startTime,pts:i.startTime};this.onMetadata_([n],0,i.endTime)}}else if(n.includes("/mp4")&&i&&0==i.timestampOffset&&i.initSegmentReference&&i.initSegmentReference.timescale){const e=i.initSegmentReference.timescale;if(!isNaN(e)){let i=0,n=!1;(new oe).box("moof",oe.children).box("traf",oe.children).fullBox("tfdt",(t=>{console.assert(0==t.version||1==t.version,"TFDT version can only be 0 or 1");const s=le.parseTFDTInaccurate(t.reader,t.version);i=s.baseMediaDecodeTime/e,n=!0,t.parser.stop()})).parse(t,!0),n&&(a=i)}}else if(!n.includes("/mp4")&&!n.includes("/webm")&&he.probe(r)){this.tsParser_?this.tsParser_.clearData():this.tsParser_=new he;const t=this.tsParser_.parse(r),n=t.getStartTime(e);null!=n&&(a=n);const o=t.getMetadata();o.length&&this.onMetadata_(o,s,i?i.endTime:null)}return a}async appendBuffer(e,t,n,s,a,r=!1,o=!1,l=!1,d=!1){const c=k.ContentType;if(e==c.TEXT){if(this.sequenceMode_){const e=await this.textSequenceModeOffset_;this.textEngine_.setTimestampOffset(e)}return void await this.textEngine_.appendBuffer(t,n?n.startTime:null,n?n.endTime:null,n?n.getUris()[0]:null)}if(!d&&this.needSplitMuxedContent_)return await this.appendBuffer(c.AUDIO,t,n,s,a,r,o,l,!0),void await this.appendBuffer(c.VIDEO,t,n,s,a,r,o,l,!0);if(!this.sourceBuffers_[e])return void i.warning("Attempted to restore a non-existent source buffer");let h=this.sourceBuffers_[e].timestampOffset,u=this.sourceBufferTypes_[e];if(this.transmuxers_[e]&&(u=this.transmuxers_[e].getOriginalMimeType()),n){const i=this.getTimestampAndDispatchMetadata_(e,t,n,u,h);if(null!=i){const t=n.startTime-i;(Math.abs(h-t)>=.001||r||o)&&(!l||t>0||!h)&&(h=t,this.attemptTimestampOffsetCalculation_&&(this.enqueueOperation_(e,(()=>this.abort_(e))),this.enqueueOperation_(e,(()=>this.setTimestampOffset_(e,h)))));const s=e==c.VIDEO||!(c.VIDEO in this.sourceBuffers_);this.sequenceMode_&&s&&this.textSequenceModeOffset_.resolve(h)}}if(a&&e==c.VIDEO){if(this.textEngine_||this.reinitText(B.CEA608_CLOSED_CAPTION_MIMETYPE,this.sequenceMode_,!1),!this.captionParser_){const e=u.split(";",1)[0];this.captionParser_=this.getCaptionParser(e)}if(n){const e=this.captionParser_.parseFrom(t);e.length&&this.textEngine_.storeAndAppendClosedCaptions(e,n.startTime,n.endTime,h)}else this.captionParser_.init(t)}if(this.transmuxers_[e]&&(t=await this.transmuxers_[e].transmux(t,s,n,this.mediaSource_.duration,e)),t=this.workAroundBrokenPlatforms_(t,n?n.startTime:null,e),n&&this.sequenceMode_&&e!=c.TEXT&&(r||o)){const t=n.startTime;this.enqueueOperation_(e,(()=>this.abort_(e))),this.enqueueOperation_(e,(()=>this.setTimestampOffset_(e,t)))}let _=null;if(await this.enqueueOperation_(e,(()=>{!n||n.isPreload()||l||(_=this.getBuffered_(e)),this.append_(e,t,h)})),n&&!n.isPreload()&&!l){const t=this.getBuffered_(e),s=me.computeAddedRange(_,t);if(s){const e=n.endTime-n.startTime,t=Math.abs(s.end-n.endTime);e>.1&&t>e/2&&i.error("Possible encoding problem detected!","Unexpected buffered range for reference",n,"from URIs",n.getUris(),"should be",{start:n.startTime,end:n.endTime},"but got",s)}}}setSelectedClosedCaptionId(e){const t=k.ContentType.VIDEO,i=this.bufferEnd(t)||0;this.textEngine_.setSelectedClosedCaptionId(e,i)}clearSelectedClosedCaptionId(){this.textEngine_&&this.textEngine_.setSelectedClosedCaptionId("",0)}async remove(e,t,i){const n=k.ContentType;e==n.TEXT?await this.textEngine_.remove(t,i):(await this.enqueueOperation_(e,(()=>this.remove_(e,t,i))),this.needSplitMuxedContent_&&await this.enqueueOperation_(n.AUDIO,(()=>this.remove_(n.AUDIO,t,i))))}async clear(e){const t=k.ContentType;if(e==t.TEXT){if(!this.textEngine_)return;await this.textEngine_.remove(0,1/0)}else await this.enqueueOperation_(e,(()=>this.remove_(e,0,this.mediaSource_.duration))),this.needSplitMuxedContent_&&await this.enqueueOperation_(t.AUDIO,(()=>this.remove_(t.AUDIO,0,this.mediaSource_.duration)))}resetCaptionParser(){this.captionParser_&&this.captionParser_.reset()}async flush(e){const t=k.ContentType;e!=t.TEXT&&(await this.enqueueOperation_(e,(()=>this.flush_(e))),this.needSplitMuxedContent_&&await this.enqueueOperation_(t.AUDIO,(()=>this.flush_(t.AUDIO))))}async setStreamProperties(e,t,i,n,s,a,r,o){const l=k.ContentType;if(e==l.TEXT)return s||this.textEngine_.setTimestampOffset(t),void this.textEngine_.setAppendWindow(i,n);const d=[];await this.codecSwitchIfNecessary_(e,a,r,o)||(d.push(this.enqueueOperation_(e,(()=>this.abort_(e)))),this.needSplitMuxedContent_&&d.push(this.enqueueOperation_(l.AUDIO,(()=>this.abort_(l.AUDIO))))),s||(d.push(this.enqueueOperation_(e,(()=>this.setTimestampOffset_(e,t)))),this.needSplitMuxedContent_&&d.push(this.enqueueOperation_(l.AUDIO,(()=>this.setTimestampOffset_(l.AUDIO,t))))),d.push(this.enqueueOperation_(e,(()=>this.setAppendWindow_(e,i,n)))),this.needSplitMuxedContent_&&d.push(this.enqueueOperation_(l.AUDIO,(()=>this.setAppendWindow_(l.AUDIO,i,n)))),await Promise.all(d)}async resync(e,t){const i=k.ContentType;e!=i.TEXT&&(this.enqueueOperation_(e,(()=>this.abort_(e))),this.needSplitMuxedContent_&&this.enqueueOperation_(i.AUDIO,(()=>this.abort_(i.AUDIO))),await this.enqueueOperation_(e,(()=>this.setTimestampOffset_(e,t))),this.needSplitMuxedContent_&&await this.enqueueOperation_(i.AUDIO,(()=>this.setTimestampOffset_(i.AUDIO,t))))}async endOfStream(e){await this.enqueueBlockingOperation_((()=>{this.ended()||"closed"===this.mediaSource_.readyState||(e?this.mediaSource_.endOfStream(e):this.mediaSource_.endOfStream())}))}async setDuration(e){await this.enqueueBlockingOperation_((()=>{if(e<this.mediaSource_.duration)for(const e in this.sourceBuffers_){const t={start:()=>{},p:new C};this.queues_[e].unshift(t)}this.mediaSource_.duration=e,this.lastDuration_=e}))}getDuration(){return this.mediaSource_.duration}append_(e,t,i){e==k.ContentType.VIDEO&&this.lcevcDec_&&this.lcevcDec_.appendBuffer(t,i),this.sourceBuffers_[e].appendBuffer(t)}remove_(e,t,i){i<=t?this.onUpdateEnd_(e):this.sourceBuffers_[e].remove(t,i)}abort_(e){const t=this.sourceBuffers_[e].appendWindowStart,i=this.sourceBuffers_[e].appendWindowEnd;this.sourceBuffers_[e].abort(),this.sourceBuffers_[e].appendWindowStart=t,this.sourceBuffers_[e].appendWindowEnd=i,this.onUpdateEnd_(e)}flush_(e){console.assert(0==this.video_.buffered.length,"MediaSourceEngine.flush_ should only be used after clearing all data!"),this.video_.currentTime-=.001,this.onUpdateEnd_(e)}setTimestampOffset_(e,t){t<0&&(t+=.001),this.sourceBuffers_[e].timestampOffset=t,this.onUpdateEnd_(e)}setAppendWindow_(e,t,i){this.sourceBuffers_[e].appendWindowStart=0,this.sourceBuffers_[e].appendWindowEnd=i,this.sourceBuffers_[e].appendWindowStart=t,this.onUpdateEnd_(e)}onError_(e){const t=this.queues_[e][0];console.assert(t,"Spurious error event!"),console.assert(!this.sourceBuffers_[e].updating,"SourceBuffer should not be updating on error!");const i=this.video_.error?this.video_.error.code:0;t.p.reject(new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.MEDIA_SOURCE_OPERATION_FAILED,i))}onUpdateEnd_(e){if(this.reloadingMediaSource_)return;const t=this.queues_[e][0];console.assert(t,"Spurious updateend event!"),t&&(console.assert(!this.sourceBuffers_[e].updating,"SourceBuffer should not be updating on updateend!"),t.p.resolve(),this.popFromQueue_(e))}enqueueOperation_(e,t){this.destroyer_.ensureNotDestroyed();const i={start:t,p:new C};return this.queues_[e].push(i),1==this.queues_[e].length&&this.startOperation_(e),i.p}async enqueueBlockingOperation_(e){this.destroyer_.ensureNotDestroyed();const t=[];for(const e in this.sourceBuffers_){const i=new C,n={start:()=>i.resolve(),p:i};this.queues_[e].push(n),t.push(i),1==this.queues_[e].length&&n.start()}try{await Promise.all(t)}catch(e){console.assert(this.destroyer_.destroyed(),"Should be destroyed by now");for(const e in this.sourceBuffers_)this.queues_[e].length&&(console.assert(1==this.queues_[e].length,"Should be at most one item in queue!"),console.assert(t.includes(this.queues_[e][0].p),"The item in queue should be one of our waiters!"),this.queues_[e].shift());throw e}for(const e in this.sourceBuffers_)console.assert(0==this.sourceBuffers_[e].updating,"SourceBuffers should not be updating after a blocking op!");try{await e()}catch(e){throw new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.MEDIA_SOURCE_OPERATION_THREW,e,this.video_.error||"No error in the media element")}finally{for(const e in this.sourceBuffers_)this.popFromQueue_(e)}}popFromQueue_(e){this.queues_[e].shift(),this.startOperation_(e)}startOperation_(e){const t=this.queues_[e][0];if(t)try{t.start()}catch(i){"QuotaExceededError"==i.name?t.p.reject(new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.QUOTA_EXCEEDED_ERROR,e)):t.p.reject(new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.MEDIA_SOURCE_OPERATION_THREW,i,this.video_.error||"No error in the media element")),this.popFromQueue_(e)}}getTextDisplayer(){return console.assert(this.textDisplayer_,"TextDisplayer should only be null when this is destroyed"),this.textDisplayer_}setTextDisplayer(e){const t=this.textDisplayer_;this.textDisplayer_=e,t&&(e.setTextVisibility(t.isTextVisible()),t.destroy()),this.textEngine_&&this.textEngine_.setDisplayer(e)}setSegmentRelativeVttTiming(e){this.segmentRelativeVttTiming_=e}workAroundBrokenPlatforms_(e,t,n){const s=null==t,a=this.expectedEncryption_[n];return this.config_.insertFakeEncryptionInInit&&s&&a&&P.requiresEncryptionInfoInAllInitSegments()&&"mp4"==B.getContainerType(this.sourceBufferTypes_[n])&&(i.debug("Forcing fake encryption information in init segment."),e=ge.fakeEncryption(e)),e}change_(e,t,n){if(e!==k.ContentType.TEXT){if(i.debug(`Change Type: ${this.sourceBufferTypes_[e]} -> ${t}`),V.isChangeTypeSupported()){this.transmuxers_[e]&&(this.transmuxers_[e].destroy(),delete this.transmuxers_[e]),n&&(this.transmuxers_[e]=n);const i=this.addExtraFeaturesToMimeType_(t);this.sourceBuffers_[e].changeType(i),this.sourceBufferTypes_[e]=t}else i.debug("Change Type not supported");this.onUpdateEnd_(e)}else i.debug(`Change not supported for ${e}`)}changeType(e,t,i){return this.enqueueOperation_(e,(()=>this.change_(e,t,i)))}async reset_(e){const t=t,i=k.ContentType;this.reloadingMediaSource_=!0,this.needSplitMuxedContent_=!1;const n=this.video_.currentTime,s=this.video_.autoplay,a=this.video_.paused;this.playbackHasBegun_&&(this.video_.autoplay=!1);try{this.eventManager_.removeAll();const s=[];for(const e in this.transmuxers_)s.push(this.transmuxers_[e].destroy());for(const e in this.queues_){const i=this.queues_[e],n=i[0];this.queues_[e]=i.slice(0,1),n&&s.push(n.p.catch(t.noop));for(const e of i.slice(1))e.p.reject(_e.destroyedError())}for(const t in this.sourceBuffers_){const i=this.sourceBuffers_[t];try{this.mediaSource_.removeSourceBuffer(i)}catch(e){}}await Promise.all(s),this.transmuxers_={},this.sourceBuffers_={};const a=this.mediaSource_.duration;this.mediaSourceOpen_=new C,this.mediaSource_=this.createMediaSource(this.mediaSourceOpen_),await this.mediaSourceOpen_,!isNaN(a)&&a?this.mediaSource_.duration=a:!isNaN(this.lastDuration_)&&this.lastDuration_&&(this.mediaSource_.duration=this.lastDuration_);const r=new C,o=this.mediaSource_.sourceBuffers,l=e.size;let d=0;this.eventManager_.listen(o,"addsourcebuffer",(e=>{d++,d===l&&r.resolve()}));for(const t of e.keys()){const n=e.get(t);this.initSourceBuffer_(t,n,n.codecs),this.needSplitMuxedContent_?(this.queues_[i.AUDIO]=[],this.queues_[i.VIDEO]=[]):this.queues_[t]=[]}this.video_.currentTime=n,await r}finally{this.reloadingMediaSource_=!1,this.destroyer_.ensureNotDestroyed(),this.eventManager_.listenOnce(this.video_,"canplaythrough",(()=>{this.destroyer_.ensureNotDestroyed(),this.video_.autoplay=s,a||this.video_.play()}))}}reset(e){return this.enqueueBlockingOperation_((()=>this.reset_(e)))}async codecSwitchIfNecessary_(e,t,i,n){const s=k.ContentType;if(e==s.TEXT)return!1;const a=B.getCodecBase(B.getCodecs(this.sourceBufferTypes_[e])),r=B.getBasicType(this.sourceBufferTypes_[e]);let o,l=!1,d=B.getFullType(t,i),c=this.config_.forceTransmux;if((!V.isTypeSupported(d)||!this.sequenceMode_&&B.RAW_FORMATS.includes(d))&&(c=!0),c){const n=B.getFullTypeWithAllCodecs(t,i),a=U.findTransmuxer(n);if(a){o=a();const r=k.guessCodecsSafe(s.AUDIO,(i||"").split(",")),c=k.guessCodecsSafe(s.VIDEO,(i||"").split(","));if(r&&c){l=!0;let i=c;e==s.AUDIO&&(i=r),d=o.convertCodecs(e,B.getFullTypeWithAllCodecs(t,i))}else d=o.convertCodecs(e,n)}}const h=B.getCodecBase(B.getCodecs(d)),u=B.getBasicType(d);if(a===h&&r===u)return!1;let _=!0;return(this.needSplitMuxedContent_||l&&o&&!this.transmuxers_[e])&&(_=!1),_&&"smooth"===this.config_.codecSwitchingStrategy&&V.isChangeTypeSupported()?await this.changeType(e,d,o):(o&&o.destroy(),await this.reset(n)),!0}isCodecSwitchNecessary_(e,t){if(e==k.ContentType.TEXT)return!1;const i=B.getCodecBase(B.getCodecs(this.sourceBufferTypes_[e])),n=B.getBasicType(this.sourceBufferTypes_[e]);let s=B.getFullType(t.mimeType,t.codecs),a=this.config_.forceTransmux;(!V.isTypeSupported(s)||!this.sequenceMode_&&B.RAW_FORMATS.includes(s))&&(a=!0);const r=B.getFullTypeWithAllCodecs(t.mimeType,t.codecs);if(a){const t=U.findTransmuxer(r);if(t){const i=t();s=i.convertCodecs(e,r),i.destroy()}}const o=B.getCodecBase(B.getCodecs(s)),l=B.getBasicType(s);return i!==o||n!==l}isResetMediaSourceNecessary(e,t){return!!this.isCodecSwitchNecessary_(e,t)&&("smooth"!==this.config_.codecSwitchingStrategy||!V.isChangeTypeSupported()||this.needSplitMuxedContent_)}updateLcevcDec(e){this.lcevcDec_=e}addExtraFeaturesToMimeType_(e){const t=e+this.config_.addExtraFeaturesToSourceBuffer(e);return i.debug("Using full mime type",t),t}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,"LCEVCDecoder"]}}fe.createObjectURL=window.URL.createObjectURL,fe.Operation,fe.SourceBufferMode_={SEQUENCE:"sequence",SEGMENTS:"segments"};class pe{constructor(e,t,i){this.lcevcLib_,this.dec_=null,this.variantId_=-1,this.media_=e,this.canvas_=t,this.decConfig_=i,this.toBeDeprecated_=!1,this.create_()}appendBuffer(e,t){this.dec_&&this.dec_.appendBuffer(e,"video",this.variantId_,-t)}hideCanvas(){this.dec_&&this.canvas_.classList.add("shaka-hidden")}create_(){this.isSupported_()&&!this.dec_&&this.lcevcLib_.SupportObject.webGLSupport(this.canvas_)&&(this.canvas_.classList.remove("shaka-hidden"),this.toBeDeprecated_?this.dec_=new this.lcevcLib_.LcevcDil(this.media_,this.canvas_,this.decConfig_):this.dec_=new this.lcevcLib_.LCEVCdec(this.media_,this.canvas_,this.decConfig_))}release(){this.dec_&&(this.dec_.close(),this.dec_=null)}isSupported_(){if("undefined"==typeof libDPIModule&&i.alwaysWarn("Could not find LCEVC Library dependencies on this page"),"undefined"!=typeof LCEVCdec)this.lcevcLib_=LCEVCdec;else{if("undefined"==typeof LcevcDil)return i.alwaysWarn("Could not find LCEVC Library on this page"),!1;this.lcevcLib_=LcevcDil,this.toBeDeprecated_=!0,ae.deprecateFeature(5,"LcevcDil","lcevc_dil.js is deprecated, please use lcevc_dec.js instead")}return void 0===this.lcevcLib_.SupportObject?(i.alwaysWarn("Could not find LCEVC Library on this page"),!1):(this.lcevcLib_.SupportObject.SupportStatus||i.alwaysWarn(this.lcevcLib_.SupportObject.SupportError),void 0!==this.lcevcLib_&&"undefined"!=typeof libDPIModule&&this.canvas_ instanceof HTMLCanvasElement&&this.lcevcLib_.SupportObject.SupportStatus)}updateVariant(e,t){let i=pe.ContainerFormat.MPEG2_TS,n=pe.StreamingFormat.OTHER;switch(e.mimeType){case"video/webm":i=pe.ContainerFormat.WEBM;break;case"video/mp4":i=pe.ContainerFormat.MP4}switch(t){case"DASH":n=pe.StreamingFormat.DASH;break;case"HLS":n=pe.StreamingFormat.HLS}this.dec_&&(this.variantId_=e.id,this.dec_.setLevelSwitching(e.id,!0),this.dec_.setContainerFormat(i),this.toBeDeprecated_||this.dec_.setStreamingFormat(n))}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0]}}pe.ContainerFormat={MPEG2_TS:0,WEBM:1,MP4:2},pe.StreamingFormat={HLS:0,DASH:1,OTHER:-1};class Te{constructor(e,t){console.assert(e,"Must have config"),this.config_=e,this.maxHwRes_=t}async filterManifest(e){return await this.filterManifestWithStreamUtils_(e),this.filterManifestWithRestrictions(e)}async filterManifestWithStreamUtils_(e){console.assert(e,"Manifest should exist!"),await z.filterManifest(e),this.checkPlayableVariants_(e)}applyRestrictions(e){return z.applyRestrictions(e.variants,this.config_.restrictions,this.maxHwRes_)}filterManifestWithRestrictions(e){const t=this.applyRestrictions(e);if(e){const t=this.drmEngine_?this.drmEngine_.getDrmInfo():null;if(t&&this.drmEngine_.getMediaKeys())for(const i of e.variants)this.processDrmInfos(t.keySystem,i.video),this.processDrmInfos(t.keySystem,i.audio);this.checkRestrictedVariants(e)}return t}checkPlayableVariants_(e){if(!e.variants.some(z.isPlayable))throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.CONTENT_UNSUPPORTED_BY_BROWSER)}processDrmInfos(e,t){if(t)for(const i of t.drmInfos)if(i.keySystem==e)for(const e of i.initData||[])this.drmEngine_.newInitData(e.initDataType,e.initData)}checkRestrictedVariants(e){const t=this.drmEngine_?this.drmEngine_.getKeyStatuses():{},i=Object.keys(t);i.length&&i[0];let n=!1,s=!1;const a=new Set,r=new Set;for(const t of e.variants){const e=[];t.audio&&e.push(t.audio),t.video&&e.push(t.video),t.allowedByApplication?t.allowedByKeySystem&&(n=!0):s=!0}if(!n){const e={hasAppRestrictions:s,missingKeys:Array.from(a),restrictedKeyStatuses:Array.from(r)};throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.RESTRICTIONS_CANNOT_BE_MET,e)}}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}Te.restrictedStatuses=["output-restricted","internal-error"];class Se{constructor(e,t,i,n=null,s=null,a=null){this.getUris=e,this.startByte=t,this.endByte=i,this.mediaQuality=n,this.timescale=s,this.segmentData=a,this.codecs=null,this.mimeType=null}getStartByte(){return this.startByte}getEndByte(){return this.endByte}getSize(){return this.endByte?this.endByte-this.startByte:null}getMediaQuality(){return this.mediaQuality}getSegmentData(){return this.segmentData}static equal(e,t){return e===t||(e&&t?e.getStartByte()==t.getStartByte()&&e.getEndByte()==t.getEndByte()&&I.equal(e.getUris().sort(),t.getUris().sort())&&l.equal(e.getSegmentData(),t.getSegmentData()):e==t)}static get[Symbol.for("___CTOR_ARGS___")](){return["() => Array<string>","number","number | null","MediaQualityInfo | null","number | null","BufferSource | null"]}}!function(e){e[e.AVAILABLE=0]="AVAILABLE",e[e.UNAVAILABLE=1]="UNAVAILABLE",e[e.MISSING=2]="MISSING"}(E||(E={}));class ye{constructor(e,t,i,n,s,a,r,o,l,d=[],c="",h=null,u=null,_=ye.Status.AVAILABLE,m=!1){this.endByte=null,this.initSegmentReference=null,this.tilesLayout=null,this.tileDuration=null,this.syncTime=null,this.thumbnailSprite=null,this.codecs=null,this.mimeType=null,this.segmentData=null,console.assert(e<=t,"startTime must be less than or equal to endTime"),console.assert(null==s||n<s,"startByte must be < endByte"),this.startTime=e,this.endTime=t,this.trueEndTime=t,this.getUrisInner=i,this.startByte=n,this.endByte=s,this.initSegmentReference=a,this.timestampOffset=r,this.appendWindowStart=o,this.appendWindowEnd=l,this.partialReferences=d,this.tilesLayout=c,this.tileDuration=h,this.syncTime=u,this.status=_,this.preload=!1,this.independent=!0,this.byterangeOptimization=!1,this.thumbnailSprite=null,this.discontinuitySequence=0,this.allPartialSegments=m,this.partial=!1,this.lastPartial=!1;for(const e of this.partialReferences)e.markAsPartial();this.allPartialSegments&&this.partialReferences.length&&this.partialReferences[this.partialReferences.length-1].markAsLastPartial(),this.codecs=null,this.mimeType=null,this.segmentData=null}getUris(){return this.getUrisInner()}getStartTime(){return this.startTime}getEndTime(){return this.endTime}getStartByte(){return this.startByte}getEndByte(){return this.endByte}getSize(){return this.endByte?this.endByte-this.startByte:null}hasPartialSegments(){return this.partialReferences.length>0}hasAllPartialSegments(){return this.allPartialSegments}getTilesLayout(){return this.tilesLayout}getTileDuration(){return this.tileDuration}getStatus(){return this.status}markAsUnavailable(){this.status=ye.Status.UNAVAILABLE}markAsPreload(){this.preload=!0}isPreload(){return this.preload}markAsNonIndependent(){this.independent=!1}isIndependent(){return this.independent}markAsPartial(){this.partial=!0}isPartial(){return this.partial}markAsLastPartial(){this.lastPartial=!0}isLastPartial(){return this.lastPartial}markAsByterangeOptimization(){this.byterangeOptimization=!0}hasByterangeOptimization(){return this.byterangeOptimization}setThumbnailSprite(e){this.thumbnailSprite=e}getThumbnailSprite(){return this.thumbnailSprite}offset(e){this.startTime+=e,this.endTime+=e,this.trueEndTime+=e;for(const t of this.partialReferences)t.startTime+=e,t.endTime+=e,t.trueEndTime+=e}syncAgainst(e){if(null==this.syncTime)return void i.alwaysError("Sync attempted without sync time!");const t=this.syncTime-e-this.startTime;Math.abs(t)>=.001&&this.offset(t)}setSegmentData(e){this.segmentData=e}getSegmentData(){return this.segmentData}static get[Symbol.for("___CTOR_ARGS___")](){return["number","number","() => Array<string>","number","number | null","InitSegmentReference | null","number","number","number","Array","string | null","number | null","number | null","SegmentReferenceStatus","boolean"]}}ye.Status=E;class Ee{constructor(e){this.timer_=null,this.numEvicted_=0,this.immutable_=!1,Ee.assertCorrectReferences_(e),this.references=e}getIsImmutable(){return this.immutable_}getNumReferences(){return this.references.length}getNumEvicted(){return this.numEvicted_}release(){this.immutable_||(this.references=[],this.timer_&&this.timer_.stop(),this.timer_=null)}markImmutable(){this.immutable_=!0}forEachTopLevelReference(e){for(const t of this.references)e(t)}earliestReference(){var e;return null!==(e=this.references[0])&&void 0!==e?e:null}dropFirstReferences(e){this.references.splice(0,e)}find(e){const t=this.references.length-1;for(let i=t;i>=0;--i){const n=this.references[i],s=n.startTime,a=i<t?this.references[i+1].startTime:n.endTime;if(e>=s&&e<a)return i+this.numEvicted_}return this.references.length&&e<this.references[0].startTime?this.numEvicted_:null}get(e){if(0==this.references.length)return null;const t=e-this.numEvicted_;return t<0||t>=this.references.length?null:this.references[t]}offset(e){if(!this.immutable_)for(const t of this.references)t.offset(e)}merge(e){if(Ee.assertCorrectReferences_(e),this.immutable_)return;if(!e.length)return;const t=Math.round(1e3*e[0].startTime)/1e3;this.references=this.references.filter((e=>Math.round(1e3*e.startTime)/1e3<t)),this.references.push(...e),Ee.assertCorrectReferences_(this.references)}mergeAndEvict(e,t){e=e.filter((e=>e.endTime>t&&(0==this.references.length||e.endTime>this.references[0].startTime)));const i=this.references[0];this.merge(e);const n=this.references[0];i&&console.assert(i.startTime==n.startTime,"SegmentIndex.merge should not change the first reference time!"),this.evict(t)}evict(e){if(this.immutable_)return;const t=this.references.length;this.references=this.references.filter((t=>t.endTime>e));const i=t-this.references.length;this.numEvicted_+=i}fit(e,t,i=!1){if(console.assert(null!=t,"Content duration must be known for static content!"),console.assert(t!=1/0,"Content duration must be finite for static content!"),this.immutable_||null==t)return;for(;this.references.length&&this.references[this.references.length-1].startTime>=t;)this.references.pop();for(;this.references.length&&this.references[0].endTime<=e;)this.references.shift(),i||this.numEvicted_++;if(0==this.references.length)return;const n=this.references[this.references.length-1];this.references[this.references.length-1]=new ye(n.startTime,t,n.getUrisInner,n.startByte,n.endByte,n.initSegmentReference,n.timestampOffset,n.appendWindowStart,n.appendWindowEnd,n.partialReferences,n.tilesLayout,n.tileDuration,n.syncTime,n.status),this.references[this.references.length-1].discontinuitySequence=n.discontinuitySequence}updateEvery(e,t){console.assert(!this.timer_,"SegmentIndex timer already started!"),this.immutable_||(this.timer_&&this.timer_.stop(),this.timer_=new o((()=>{var e;const i=t();i?this.references.push(...i):(null===(e=this.timer_)||void 0===e||e.stop(),this.timer_=null)})),this.timer_.tickEvery(e))}[Symbol.iterator](){const e=this.getIteratorForTime(0);return console.assert(null!=e,"Iterator for 0 should never be null!"),e}getIteratorForTime(e,t=!1){let n=this.find(e);if(null==n)return null;--n;const s=this.get(n+1);let a=-1;if(s&&s.hasPartialSegments())for(let r=s.partialReferences.length-1;r>=0;--r){let o=s.partialReferences[r];if(e>=o.startTime&&e<o.endTime){if(!t){for(;r&&!o.isIndependent();)--r,o=s.partialReferences[r];if(!o.isIndependent())return i.alwaysError("No independent partial segment found!"),null}++n,a=r-1;break}}return new ve(this,n,a)}isEmpty(){return 0==this.getNumReferences()}static forSingleSegment(e,t,i){const n=new ye(e,e+t,(()=>i),0,null,null,e,e,e+t);return new Ee([n])}static get[Symbol.for("___CTOR_ARGS___")](){return["Array"]}}Ee.assertCorrectReferences_=e=>{console.assert(e.every(((t,i)=>{if(0==i)return!0;const n=e[i-1];return n.startTime<t.startTime||!(n.startTime>t.startTime)&&n.endTime<=t.endTime})),"SegmentReferences are incorrect")};class ve{constructor(e,t,i){this.segmentIndex_=e,this.currentPosition_=t,this.currentPartialPosition_=i}currentPosition(){return this.currentPosition_}current(){let e=this.segmentIndex_.get(this.currentPosition_);return e&&e.hasPartialSegments()&&e.hasAllPartialSegments()&&this.currentPartialPosition_>=e.partialReferences.length&&(this.currentPosition_++,this.currentPartialPosition_=0,e=this.segmentIndex_.get(this.currentPosition_)),e&&e.hasPartialSegments()?e.partialReferences[this.currentPartialPosition_]:e}next(){const e=this.segmentIndex_.get(this.currentPosition_);e&&e.hasPartialSegments()?(this.currentPartialPosition_++,e.hasAllPartialSegments()&&this.currentPartialPosition_==e.partialReferences.length&&(this.currentPosition_++,this.currentPartialPosition_=0)):(this.currentPosition_++,this.currentPartialPosition_=0);const t=this.current();return{value:t,done:!t}}static get[Symbol.for("___CTOR_ARGS___")](){return["SegmentIndex","number","number"]}}class Ie extends Ee{constructor(){super([]),this.indexes_=[]}appendSegmentIndex(e){console.assert(0==this.indexes_.length||0==e.getNumEvicted(),"Should not append a new segment index with already-evicted segments"),this.indexes_.push(e)}clone(){const e=new Ie;return e.indexes_=this.indexes_.slice(),e}release(){for(const e of this.indexes_)e.release();this.indexes_=[]}find(e){let t=0;for(const i of this.indexes_){const n=i.find(e);if(null!=n)return n+t;t+=i.getNumEvicted()+i.getNumReferences()}return null}get(e){let t=0,i=!1;for(const n of this.indexes_){console.assert(!i||0==n.getNumEvicted(),"Should not see evicted segments after available segments");const s=n.get(e-t);if(s)return s;const a=n.getNumReferences();t+=n.getNumEvicted()+a,i=i||0!=a}return null}offset(e){console.assert(!1,"offset() should not be used in MetaSegmentIndex!")}merge(e){console.assert(!1,"merge() should not be used in MetaSegmentIndex!")}evict(e){console.assert(!1,"evict() should not be used in MetaSegmentIndex!")}mergeAndEvict(e,t){console.assert(!1,"mergeAndEvict() should not be used in MetaSegmentIndex!")}fit(e,t,i=!1){console.assert(!1,"fit() should not be used in MetaSegmentIndex!")}updateEvery(e,t){console.assert(!1,"updateEvery() should not be used in MetaSegmentIndex!")}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class Ae extends a{constructor(e){super(),this.regions_=new Set,this.getSeekRange_=e,this.filterTimer_=new o((()=>{this.filterBySeekRange_()})).tickEvery(Ae.REGION_FILTER_INTERVAL)}release(){this.regions_.clear(),this.filterTimer_.stop(),super.release()}addRegion(e){if(null==this.findSimilarRegion_(e)){this.regions_.add(e);const t=new s("regionadd",new Map([["region",e]]));this.dispatchEvent(t)}}filterBySeekRange_(){const e=this.getSeekRange_();for(const t of this.regions_)if(t.endTime<e.start){this.regions_.delete(t);const e=new s("regionremove",new Map([["region",t]]));this.dispatchEvent(e)}}findSimilarRegion_(e){for(const t of this.regions_)if(t.schemeIdUri==e.schemeIdUri&&t.id==e.id&&t.startTime==e.startTime&&t.endTime==e.endTime)return t;return null}regions(){return this.regions_}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}Ae.REGION_FILTER_INTERVAL=2;class be{constructor(e){this.mediaElement_=e,this.observers_=new Set,this.pollingLoop_=new o((()=>{this.pollAllObservers_(!1)})).tickEvery(.25)}release(){this.pollingLoop_.stop();for(const e of this.observers_)e.release();this.observers_.clear()}manage(e){this.observers_.add(e)}notifyOfSeek(){this.pollAllObservers_(!0)}pollAllObservers_(e){for(const t of this.observers_)t.poll(this.mediaElement_.currentTime,e)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class Ce extends a{constructor(e,t){super(),this.timeline_=e,this.startsPastZero_=t,this.oldPosition_=new Map;const i=Ce.RelativePosition_,n=i.BEFORE_THE_REGION,s=i.IN_THE_REGION,a=i.AFTER_THE_REGION;this.rules_=[{weWere:null,weAre:s,invoke:(e,t)=>this.onEvent_("enter",e,t)},{weWere:n,weAre:s,invoke:(e,t)=>this.onEvent_("enter",e,t)},{weWere:a,weAre:s,invoke:(e,t)=>this.onEvent_("enter",e,t)},{weWere:s,weAre:n,invoke:(e,t)=>this.onEvent_("exit",e,t)},{weWere:s,weAre:a,invoke:(e,t)=>this.onEvent_("exit",e,t)},{weWere:n,weAre:a,invoke:(e,t)=>this.onEvent_("skip",e,t)},{weWere:a,weAre:n,invoke:(e,t)=>this.onEvent_("skip",e,t)}],this.eventManager_=new Z,this.eventManager_.listen(this.timeline_,"regionremove",(e=>{const t=e.region;this.oldPosition_.delete(t)}))}release(){this.timeline_=null,this.oldPosition_.clear(),this.eventManager_.release(),this.eventManager_=null,super.release()}poll(e,t){if(!this.startsPastZero_||0!=e){this.startsPastZero_=!1;for(const i of this.timeline_.regions()){const n=this.oldPosition_.get(i),s=Ce.determinePositionRelativeTo_(i,e);this.oldPosition_.set(i,s);for(const e of this.rules_)e.weWere==n&&e.weAre==s&&e.invoke(i,t)}}}onEvent_(e,t,i){const n=new s(e,new Map([["region",t],["seeking",i]]));this.dispatchEvent(n)}static determinePositionRelativeTo_(e,t){const i=Ce.RelativePosition_;return t<e.startTime?i.BEFORE_THE_REGION:t>e.endTime?i.AFTER_THE_REGION:i.IN_THE_REGION}static get[Symbol.for("___CTOR_ARGS___")](){return["RegionTimeline","boolean"]}}Ce.RelativePosition_={BEFORE_THE_REGION:1,IN_THE_REGION:2,AFTER_THE_REGION:3};class we extends a{constructor(e){super(),this.contentTypeStates_=new Map,this.getBufferedInfo_=e}release(){this.contentTypeStates_.clear(),super.release()}getContentTypeState_(e){let t=this.contentTypeStates_.get(e);return t||(t={qualityChangePositions:[],currentQuality:null,contentType:e},this.contentTypeStates_.set(e,t)),t}addMediaQualityChange(e,t){const i=this.getContentTypeState_(e.contentType);this.purgeQualityChangePositions_(i);const n={mediaQuality:e,position:t},s=i.qualityChangePositions,a=s.findIndex((e=>e.position>=t));if(a>=0){const e=s[a].position==t?1:0;s.splice(a,e,n)}else s.push(n)}static getMediaQualityAtPosition_(e,t){const i=t.qualityChangePositions;for(let t=i.length-1;t>=0;t--){const n=i[t];if(n.position<=e)return n.mediaQuality}return null}static mediaQualitiesAreTheSame_(e,t){return e===t||!(!e||!t)&&e.bandwidth==t.bandwidth&&e.audioSamplingRate==t.audioSamplingRate&&e.codecs==t.codecs&&e.contentType==t.contentType&&e.frameRate==t.frameRate&&e.height==t.height&&e.mimeType==t.mimeType&&e.channelsCount==t.channelsCount&&e.pixelAspectRatio==t.pixelAspectRatio&&e.width==t.width}poll(e,t){for(const t of this.contentTypeStates_.values()){const n=we.getMediaQualityAtPosition_(e,t);if(n&&!we.mediaQualitiesAreTheSame_(t.currentQuality,n)&&this.positionIsBuffered_(e,n.contentType)){t.currentQuality=n,i.debug("Media quality changed at position "+e+" "+JSON.stringify(n));const a=new s("qualitychange",new Map([["quality",n],["position",e]]));this.dispatchEvent(a)}}}positionIsBuffered_(e,t){const i=this.getBufferedInfo_()[t];if(i&&i.length>0){const t=i[0].start,n=i[i.length-1].end;if(e>=t&&e<n)return!0}return!1}purgeQualityChangePositions_(e){const t=this.getBufferedInfo_()[e.contentType];if(t&&t.length>0){const i=t[0].start,n=t[t.length-1].end,s=e.qualityChangePositions;e.qualityChangePositions=s.filter(((e,t)=>!(e.position<=i&&t+1<s.length&&s[t+1].position<=i||e.position>=n)))}else e.qualityChangePositions=[]}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}we.QualityChangePosition,we.ContentTypeState;class Me{constructor(e,t,i,n=!0){this.prefetchLimit_=e,this.stream_=t,this.prefetchPosTime_=0,this.fetchDispatcher_=i,this.deleteOnGet_=n,this.segmentPrefetchMap_=new Map,this.initSegmentPrefetchMap_=new Map}replaceFetchDispatcher(e){this.fetchDispatcher_=e;for(const t of this.segmentPrefetchMap_.values())t.replaceFetchDispatcher(e)}getLastKnownPosition(){return this.prefetchPosTime_}prefetchSegmentsByTime(e,t=!1){console.assert(this.prefetchLimit_>0,"SegmentPrefetch can not be used when prefetchLimit <= 0.");const n=Me.logPrefix_(this.stream_);if(!this.stream_.segmentIndex)return void i.debug(n,"missing segmentIndex");const s=Math.max(e,this.prefetchPosTime_),a=this.stream_.segmentIndex.getIteratorForTime(s,!0);if(!a)return;let r=a.next().value;if(t&&(r=a.next().value),r){for(;this.segmentPrefetchMap_.size<this.prefetchLimit_&&null!=r;){let e=!0;if(r.isPreload()&&null!=r.endByte&&(e=!1),r.getStatus()==ye.Status.MISSING&&(e=!1),e&&r.initSegmentReference&&this.prefetchInitSegment(r.initSegmentReference),e&&!this.segmentPrefetchMap_.has(r)){const e=new Re(this.fetchDispatcher_);e.dispatchFetch(r,this.stream_),this.segmentPrefetchMap_.set(r,e)}if(this.prefetchPosTime_=r.startTime,this.stream_.fastSwitching&&r.isPartial()&&r.isLastPartial())break;r=a.next().value}this.clearInitSegments_()}}prefetchInitSegment(e){console.assert(this.prefetchLimit_>0,"SegmentPrefetch can not be used when prefetchLimit <= 0.");const t=Me.logPrefix_(this.stream_);if(this.stream_.segmentIndex){if(!this.initSegmentPrefetchMap_.has(e)){const t=new Re(this.fetchDispatcher_);t.dispatchFetch(e,this.stream_),this.initSegmentPrefetchMap_.set(e,t)}}else i.debug(t,"missing segmentIndex")}getPrefetchedSegment(e,t){console.assert(this.prefetchLimit_>0,"SegmentPrefetch can not be used when prefetchLimit <= 0.");const n=Me.logPrefix_(this.stream_);let s=this.segmentPrefetchMap_;if(e instanceof Se&&(s=this.initSegmentPrefetchMap_),s.has(e)){const a=s.get(e);return t&&a.setStreamDataCallback(t),this.deleteOnGet_&&s.delete(e),e instanceof ye?i.debug(n,"reused prefetched segment at time:",e.startTime,"mapSize",s.size):i.debug(n,"reused prefetched init segment at time, mapSize",s.size),a.getOperation()}return e instanceof ye?i.debug(n,"missed segment at time:",e.startTime,"mapSize",s.size):i.debug(n,"missed init segment at time, mapSize",s.size),null}clearMap_(e){for(const t of e.keys())t&&this.abortPrefetchedSegment_(t)}clearAll(){this.clearMap_(this.segmentPrefetchMap_),this.clearMap_(this.initSegmentPrefetchMap_);const e=Me.logPrefix_(this.stream_);i.debug(e,"cleared all"),this.prefetchPosTime_=0}evict(e){for(const t of this.segmentPrefetchMap_.keys())e>t.endTime&&this.abortPrefetchedSegment_(t);this.clearInitSegments_()}clearInitSegments_(){const e=Array.from(this.segmentPrefetchMap_.keys());for(const t of this.initSegmentPrefetchMap_.keys())e.some((e=>e.initSegmentReference===t))||this.abortPrefetchedSegment_(t)}resetLimit(e){console.assert(e>=0,"The new prefetch limit must be >= 0.");const t=Me.logPrefix_(this.stream_);i.debug(t,"resetting prefetch limit to",e),this.prefetchLimit_=e;const n=Array.from(this.segmentPrefetchMap_.keys());for(;n.length>e;){const e=n.pop();e&&this.abortPrefetchedSegment_(e)}this.clearInitSegments_()}deleteOnGet(e){this.deleteOnGet_=e}switchStream(e){console.assert(this.deleteOnGet_,"switchStream should only be used if deleteOnGet is true"),e&&e!==this.stream_&&(this.clearAll(),this.stream_=e)}getStream(){return this.stream_}abortPrefetchedSegment_(e){const t=Me.logPrefix_(this.stream_);let n=this.segmentPrefetchMap_;e instanceof Se&&(n=this.initSegmentPrefetchMap_);const s=n.get(e);n.delete(e),s&&(s.abort(),e instanceof ye?i.debug(t,"pop and abort prefetched segment at time:",e.startTime):i.debug(t,"pop and abort prefetched init segment"))}static logPrefix_(e){return"SegmentPrefetch("+e.type+":"+e.id+")"}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0]}}class Re{constructor(e){this.fetchDispatcher_=e,this.streamDataCallback_=null,this.operation_=null}replaceFetchDispatcher(e){this.fetchDispatcher_=e}dispatchFetch(e,t){let i=new Uint8Array(0);this.operation_=this.fetchDispatcher_(e,t,(async e=>{i=i.byteLength>0?x.concat(i,e):e,this.streamDataCallback_&&(await this.streamDataCallback_(i),i=new Uint8Array(0))}))}getOperation(){return this.operation_}setStreamDataCallback(e){this.streamDataCallback_=e}abort(){this.operation_&&this.operation_.abort()}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}Me.FetchDispatcher;class Oe{constructor(e,t,i=!0,n=!1){this.root_=e,this.variants_=new Set([e]),t=t||[];for(const e of t)this.add(e,i,n)}add(e,t,n){return this.canInclude(e,t,n)?(this.variants_.add(e),!0):(i.warning("Rejecting variant - not compatible with root."),!1)}canInclude(e,t=!0,i=!1){return Oe.areAdaptable(this.root_,e,t,i)}static areAdaptable(e,t,i,n){return!!e.audio==!!t.audio&&!!e.video==!!t.video&&e.language==t.language&&(console.assert(!!e.audio==!!t.audio,"Both should either have audio or not have audio."),!(e.audio&&t.audio&&!Oe.areAudiosCompatible_(e.audio,t.audio,i,n)||(console.assert(!!e.video==!!t.video,"Both should either have video or not have video."),e.video&&t.video&&!Oe.areVideosCompatible_(e.video,t.video,i))))}values(){return this.variants_.values()}static areAudiosCompatible_(e,t,i,n){return!((!e.channelsCount||!t.channelsCount||e.channelsCount>2||t.channelsCount>2)&&e.channelsCount!=t.channelsCount||i&&!Oe.canTransitionBetween_(e,t)||!Oe.areRolesEqual_(e.roles,t.roles)||n&&e.groupId!==t.groupId)}static areVideosCompatible_(e,t,i){return!(i&&!Oe.canTransitionBetween_(e,t)||!Oe.areRolesEqual_(e.roles,t.roles))}static canTransitionBetween_(e,t){if(e.mimeType!=t.mimeType)return!1;const i=B.splitCodecs(e.codecs).map((e=>B.getCodecBase(e))),n=B.splitCodecs(t.codecs).map((e=>B.getCodecBase(e)));if(i.length!=n.length)return!1;i.sort(),n.sort();for(let e=0;e<i.length;e++)if(i[e]!=n[e])return!1;return!0}static areRolesEqual_(e,t){const i=new Set(e),n=new Set(t),s="main";if(i.delete(s),n.delete(s),i.size!=n.size)return!1;for(const e of i)if(!n.has(e))return!1;return!0}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0]}}class De{constructor(e,t="reload",i=!1){this.example_=e,this.codecSwitchingStrategy_=t,this.enableAudioGroups_=i;const n=e.audio&&e.audio.channelsCount?e.audio.channelsCount:0;this.fallback_=new Pe(e.language,"",n,"",!1,"","","",t,i)}create(e){const t="smooth"==this.codecSwitchingStrategy_&&V.isChangeTypeSupported(),i=e.filter((e=>Oe.areAdaptable(this.example_,e,!t,this.enableAudioGroups_)));return i.length?new Oe(i[0],i,!t,this.enableAudioGroups_):this.fallback_.create(e)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0]}}class Pe{constructor(e,t,i,n,s,a,r="",o="",l="reload",d=!1){this.language_=e,this.role_=t,this.channelCount_=i,this.hdrLevel_=n,this.spatialAudio_=s,this.videoLayout_=a,this.audioLabel_=r,this.videoLabel_=o,this.codecSwitchingStrategy_=l,this.enableAudioGroups_=d}create(e){const t=Pe;let n=[];const s=t.filterByLanguage_(e,this.language_),a=e.filter((e=>e.primary));n=s.length?s:a.length?a:e;const r=t.filterVariantsByRole_(n,this.role_);if(r.length?n=r:i.warning("No exact match for variant role could be found."),this.videoLayout_){const e=t.filterVariantsByVideoLayout_(n,this.videoLayout_);e.length?n=e:i.warning("No exact match for the video layout could be found.")}if(this.hdrLevel_){const e=t.filterVariantsByHDRLevel_(n,this.hdrLevel_);e.length?n=e:i.warning("No exact match for the hdr level could be found.")}if(this.channelCount_){const e=t.filterVariantsByAudioChannelCount_(n,this.channelCount_);e.length?n=e:i.warning("No exact match for the channel count could be found.")}if(this.audioLabel_){const e=t.filterVariantsByAudioLabel_(n,this.audioLabel_);e.length?n=e:i.warning("No exact match for audio label could be found.")}if(this.videoLabel_){const e=t.filterVariantsByVideoLabel_(n,this.videoLabel_);e.length?n=e:i.warning("No exact match for video label could be found.")}const o=t.filterVariantsBySpatialAudio_(n,this.spatialAudio_);o.length?n=o:i.warning("No exact match for spatial audio could be found.");const l="smooth"==this.codecSwitchingStrategy_&&V.isChangeTypeSupported();return new Oe(n[0],n,!l,this.enableAudioGroups_)}static filterByLanguage_(e,t){const i=G.normalize(t),n=G.findClosestLocale(i,e.map((e=>G.getLocaleForVariant(e))));return n?e.filter((e=>n==G.getLocaleForVariant(e))):[]}static filterVariantsByRole_(e,t){return e.filter((e=>!!e.audio&&(t?e.audio.roles.includes(t):0==e.audio.roles.length)))}static filterVariantsByAudioLabel_(e,t){return e.filter((e=>!(!e.audio||!e.audio.label)&&e.audio.label.toLowerCase()==t.toLowerCase()))}static filterVariantsByVideoLabel_(e,t){return e.filter((e=>!(!e.video||!e.video.label)&&e.video.label.toLowerCase()==t.toLowerCase()))}static filterVariantsByAudioChannelCount_(e,t){return e.filter((e=>!e.audio||!e.audio.channelsCount||e.audio.channelsCount==t))}static filterVariantsByHDRLevel_(e,t){return"AUTO"==t&&(t=window.matchMedia("(color-gamut: p3)").matches?"PQ":"SDR"),e.filter((e=>!e.video||!e.video.hdr||e.video.hdr==t))}static filterVariantsByVideoLayout_(e,t){return e.filter((e=>!e.video||!e.video.videoLayout||e.video.videoLayout==t))}static filterVariantsBySpatialAudio_(e,t){return e.filter((e=>!e.audio||e.audio.spatialAudio==t))}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0]}}class Ne{static createSegmentRequest(e,t,i,n,s=null){const a=O.makeRequest(e,n,s);return 0==t&&null==i||(a.headers.Range=i?"bytes="+t+"-"+i:"bytes="+t+"-"),a}}class Le{constructor(e,t){this.playerInterface_=t,this.manifest_=e,this.config_=null,this.bufferingGoalScale_=1,this.currentVariant_=null,this.currentTextStream_=null,this.textStreamSequenceId_=0,this.parsedPrftEventRaised_=!1,this.mediaStates_=new Map,this.startupComplete_=!1,this.failureCallbackBackoff_=null,this.fatalError_=!1,this.destroyer_=new _e((()=>this.doDestroy_())),this.lastMediaSourceReset_=Date.now()/1e3,this.audioPrefetchMap_=new Map}destroy(){return this.destroyer_.destroy()}async doDestroy_(){const e=[];for(const t of this.mediaStates_.values())this.cancelUpdate_(t),e.push(this.abortOperations_(t));for(const e of this.audioPrefetchMap_.values())e.clearAll();await Promise.all(e),this.mediaStates_.clear(),this.audioPrefetchMap_.clear(),this.playerInterface_=null,this.manifest_=null,this.config_=null}configure(e){this.config_=e;const t={maxAttempts:Math.max(e.retryParameters.maxAttempts,2),baseDelay:e.retryParameters.baseDelay,backoffFactor:e.retryParameters.backoffFactor,fuzzFactor:e.retryParameters.fuzzFactor,timeout:0,stallTimeout:0,connectionTimeout:0};this.failureCallbackBackoff_=new M(t,!0);const i=k.ContentType;if(e.disableAudioPrefetch){const e=this.mediaStates_.get(i.AUDIO);e&&e.segmentPrefetch&&(e.segmentPrefetch.clearAll(),e.segmentPrefetch=null);for(const e of this.audioPrefetchMap_.keys())this.audioPrefetchMap_.get(e).clearAll(),this.audioPrefetchMap_.delete(e)}if(e.disableTextPrefetch){const e=this.mediaStates_.get(i.TEXT);e&&e.segmentPrefetch&&(e.segmentPrefetch.clearAll(),e.segmentPrefetch=null)}if(e.disableVideoPrefetch){const e=this.mediaStates_.get(i.VIDEO);e&&e.segmentPrefetch&&(e.segmentPrefetch.clearAll(),e.segmentPrefetch=null)}for(const t of this.mediaStates_.keys()){const i=this.mediaStates_.get(t);i.segmentPrefetch?(i.segmentPrefetch.resetLimit(e.segmentPrefetchLimit),e.segmentPrefetchLimit>0||(i.segmentPrefetch=null)):e.segmentPrefetchLimit>0&&(i.segmentPrefetch=this.createSegmentPrefetch_(i.stream))}e.disableAudioPrefetch||this.updatePrefetchMapForAudio_()}async start(e){console.assert(this.config_,"StreamingEngine configure() must be called before init()!"),await this.initStreams_(e||new Map),this.destroyer_.ensureNotDestroyed(),i.debug("init: completed initial Stream setup"),this.startupComplete_=!0}getCurrentVariant(){return this.currentVariant_}getCurrentTextStream(){return this.currentTextStream_}async loadNewTextStream_(e){const t=k.ContentType;console.assert(!this.mediaStates_.has(t.TEXT),"Should not call loadNewTextStream_ while streaming text!"),this.textStreamSequenceId_++;const i=this.textStreamSequenceId_;try{await this.playerInterface_.mediaSourceEngine.clear(t.TEXT)}catch(e){this.playerInterface_&&this.playerInterface_.onError(e)}const n=B.getFullType(e.mimeType,e.codecs);if(this.playerInterface_.mediaSourceEngine.reinitText(n,this.manifest_.sequenceMode,e.external),(this.playerInterface_.mediaSourceEngine.getTextDisplayer().isTextVisible()||this.config_.alwaysStreamText)&&this.textStreamSequenceId_==i){const i=this.createMediaState_(e);this.mediaStates_.set(t.TEXT,i),this.scheduleUpdate_(i,0)}}unloadTextStream(){const e=k.ContentType,t=this.mediaStates_.get(e.TEXT);t&&(this.cancelUpdate_(t),this.abortOperations_(t).catch((()=>{})),this.mediaStates_.delete(e.TEXT)),this.currentTextStream_=null}setTrickPlay(e){const t=k.ContentType,n=this.mediaStates_.get(t.VIDEO);if(!n)return;const s=n.stream;if(s)if(i.debug("setTrickPlay",e),e){const e=s.trickModeVideo;if(!e)return;if(n.restoreStreamAfterTrickPlay)return;i.debug("Engaging trick mode stream",e),this.switchInternal_(e,!1,0,!1),n.restoreStreamAfterTrickPlay=s}else{const e=n.restoreStreamAfterTrickPlay;if(!e)return;i.debug("Restoring non-trick-mode stream",e),n.restoreStreamAfterTrickPlay=null,this.switchInternal_(e,!0,0,!1)}}switchVariant(e,t=!1,i=0,n=!1,s=!1){this.currentVariant_=e,this.startupComplete_&&(e.video&&this.switchInternal_(e.video,t,i,n,s),e.audio&&this.switchInternal_(e.audio,t,i,n,s))}async switchTextStream(e){if(this.currentTextStream_=e,!this.startupComplete_)return;const t=k.ContentType;console.assert(e&&e.type==t.TEXT,"Wrong stream type passed to switchTextStream!"),e.segmentIndex||await e.createSegmentIndex(),this.switchInternal_(e,!0,0,!1)}reloadTextStream(){const e=k.ContentType,t=this.mediaStates_.get(e.TEXT);t&&this.switchInternal_(t.stream,!0,0,!0)}switchInternal_(e,t,n,s,a){const r=k.ContentType,o=e.type,l=this.mediaStates_.get(o);if(!l&&e.type==r.TEXT)return void this.loadNewTextStream_(e);if(console.assert(l,"switch: expected mediaState to exist"),!l)return;if(l.restoreStreamAfterTrickPlay&&(i.debug("switch during trick play mode",e),e.trickModeVideo?(l.restoreStreamAfterTrickPlay=e,e=e.trickModeVideo,i.debug("switch found trick play stream",e)):(l.restoreStreamAfterTrickPlay=null,i.debug("switch found no special trick play stream"))),l.stream==e&&!s){const e=Le.logPrefix_(l);return void i.debug("switch: Stream "+e+" already active")}if(this.audioPrefetchMap_.has(e)?l.segmentPrefetch=this.audioPrefetchMap_.get(e):l.segmentPrefetch&&l.segmentPrefetch.switchStream(e),e.type==r.TEXT){const t=B.getFullType(e.mimeType,e.codecs);this.playerInterface_.mediaSourceEngine.reinitText(t,this.manifest_.sequenceMode,e.external)}this.audioPrefetchMap_.has(l.stream)||l.stream.closeSegmentIndex&&l.stream.closeSegmentIndex(),l.stream=e,l.segmentIterator=null,l.adaptation=!!a;const d=Le.logPrefix_(l);i.debug("switch: switching to Stream "+d),t&&(l.clearingBuffer?l.waitingToFlushBuffer=!0:l.performingUpdate?(l.waitingToClearBuffer=!0,l.clearBufferSafeMargin=n,l.waitingToFlushBuffer=!0):(this.cancelUpdate_(l),this.clearBuffer_(l,!0,n).catch((e=>{this.playerInterface_&&(console.assert(e instanceof v,"Wrong error type!"),this.playerInterface_.onError(e))})))),this.makeAbortDecision_(l).catch((e=>{this.playerInterface_&&(console.assert(e instanceof v,"Wrong error type!"),this.playerInterface_.onError(e))}))}async makeAbortDecision_(e){if(!e.operation)return;const t=e.stream,n=e.operation;t.segmentIndex||await t.createSegmentIndex(),e.operation==n&&e.stream==t&&(console.assert(e.stream.segmentIndex,"Segment index should exist by now!"),this.shouldAbortCurrentRequest_(e)&&(i.info("Aborting current segment request."),e.operation.abort()))}shouldAbortCurrentRequest_(e){console.assert(e.operation,"Abort logic requires an ongoing operation!"),console.assert(e.stream&&e.stream.segmentIndex,"Abort logic requires a segment index");const t=this.playerInterface_.getPresentationTime(),i=this.playerInterface_.mediaSourceEngine.bufferEnd(e.type),n=this.getTimeNeeded_(e,t),s=e.stream.segmentIndex.find(n),a=null==s?null:e.stream.segmentIndex.get(s);let r=a?a.getSize():null;if(a&&!r&&(r=(a.getEndTime()-a.getStartTime())*(e.stream.bandwidth||0)/8),!r)return!1;const o=a.initSegmentReference;return o&&(r+=o.getSize()||0),8*r/this.playerInterface_.getBandwidthEstimate()<(i||0)-t-Math.max(this.manifest_.minBufferTime||0,this.config_.rebufferingGoal)||e.operation.getBytesRemaining()>r}seeked(){if(!this.playerInterface_)return;const e=this.playerInterface_.getPresentationTime(),t=k.ContentType,n=t=>this.playerInterface_.mediaSourceEngine.isBuffered(t,e);let s=!1;for(const a of this.mediaStates_.keys()){const r=this.mediaStates_.get(a),o=Le.logPrefix_(r);let l=null;r.segmentIterator&&(l=r.segmentIterator.current()),(!l||l.startTime>e||l.endTime<e)&&(r.segmentIterator=null),n(a)||((null!=this.playerInterface_.mediaSourceEngine.bufferEnd(a)||r.performingUpdate)&&(this.forceClearBuffer_(r),s=!0),r.operation&&(r.operation.abort(),i.debug(o,"Aborting operation due to seek"),r.operation=null),a===t.TEXT&&this.playerInterface_.mediaSourceEngine.resetCaptionParser(),r.seeked=!0)}s||i.debug("(all): seeked: buffered seek: presentationTime="+e)}forceClearBuffer_(e){const t=Le.logPrefix_(e);if(e.clearingBuffer)return void i.debug(t,"clear: already clearing the buffer");if(e.waitingToClearBuffer)return void i.debug(t,"clear: already waiting");if(e.performingUpdate)return i.debug(t,"clear: currently updating"),e.waitingToClearBuffer=!0,void(e.clearBufferSafeMargin=0);const n=e.type;if(null==this.playerInterface_.mediaSourceEngine.bufferStart(n))return i.debug(t,"clear: nothing buffered"),void(null==e.updateTimer&&this.scheduleUpdate_(e,0));i.debug(t,"clear: handling right now"),this.cancelUpdate_(e),this.clearBuffer_(e,!1,0).catch((e=>{this.playerInterface_&&(console.assert(e instanceof v,"Wrong error type!"),this.playerInterface_.onError(e))}))}async initStreams_(e){const t=k.ContentType;if(console.assert(this.config_,"StreamingEngine configure() must be called before init()!"),!this.currentVariant_)throw i.error("init: no Streams chosen"),new v(v.Severity.CRITICAL,v.Category.STREAMING,v.Code.STREAMING_ENGINE_STARTUP_INVALID_STATE);const n=new Map,s=new Set;this.currentVariant_.audio&&(n.set(t.AUDIO,this.currentVariant_.audio),s.add(this.currentVariant_.audio)),this.currentVariant_.video&&(n.set(t.VIDEO,this.currentVariant_.video),s.add(this.currentVariant_.video)),this.currentTextStream_&&(n.set(t.TEXT,this.currentTextStream_),s.add(this.currentTextStream_));const a=this.playerInterface_.mediaSourceEngine;await a.init(n,this.manifest_.sequenceMode,this.manifest_.type,this.manifest_.ignoreManifestTimestampsInSegmentsMode),this.destroyer_.ensureNotDestroyed(),this.updateDuration();for(const t of n.keys()){const i=n.get(t);if(!this.mediaStates_.has(t)){const n=this.createMediaState_(i);if(e.has(i.id)){const t=e.get(i.id);t.replaceFetchDispatcher(((e,t,i)=>this.dispatchFetch_(e,t,i))),n.segmentPrefetch=t}this.mediaStates_.set(t,n),this.scheduleUpdate_(n,0)}}}createMediaState_(e){return{stream:e,type:e.type,segmentIterator:null,segmentPrefetch:this.createSegmentPrefetch_(e),lastSegmentReference:null,lastInitSegmentReference:null,lastTimestampOffset:null,lastAppendWindowStart:null,lastAppendWindowEnd:null,restoreStreamAfterTrickPlay:null,endOfStream:!1,performingUpdate:!1,updateTimer:null,waitingToClearBuffer:!1,clearBufferSafeMargin:0,waitingToFlushBuffer:!1,clearingBuffer:!1,seeked:!0,needsResync:!1,recovering:!1,hasError:!1,operation:null}}createSegmentPrefetch_(e){const t=k.ContentType;if(e.type===t.VIDEO&&this.config_.disableVideoPrefetch)return null;if(e.type===t.AUDIO&&this.config_.disableAudioPrefetch)return null;const i=B.CEA608_CLOSED_CAPTION_MIMETYPE,n=B.CEA708_CLOSED_CAPTION_MIMETYPE;if(e.type===t.TEXT&&(e.mimeType==i||e.mimeType==n))return null;if(e.type===t.TEXT&&this.config_.disableTextPrefetch)return null;if(this.audioPrefetchMap_.has(e))return this.audioPrefetchMap_.get(e);const s=e.type,a=this.mediaStates_.get(s),r=a&&a.segmentPrefetch;return r&&e===r.getStream()?r:this.config_.segmentPrefetchLimit>0?new Me(this.config_.segmentPrefetchLimit,e,((e,t,i)=>this.dispatchFetch_(e,t,i))):null}updatePrefetchMapForAudio_(){const e=this.config_.segmentPrefetchLimit,t=this.config_.prefetchAudioLanguages;for(const i of this.manifest_.variants){if(!i.audio)continue;if(this.audioPrefetchMap_.has(i.audio)){const n=this.audioPrefetchMap_.get(i.audio);if(n.resetLimit(e),!(e>0&&t.some((e=>G.areLanguageCompatible(i.audio.language,e))))){n.deleteOnGet(!0);const e=i.audio.type,t=this.mediaStates_.get(e);n!==(t&&t.segmentPrefetch)&&n.clearAll(),this.audioPrefetchMap_.delete(i.audio)}continue}if(e<=0)continue;if(!t.some((e=>G.areLanguageCompatible(i.audio.language,e))))continue;const n=this.createSegmentPrefetch_(i.audio);n.deleteOnGet(!1),n&&(i.audio.segmentIndex||i.audio.createSegmentIndex(),this.audioPrefetchMap_.set(i.audio,n))}}updateDuration(){const e=this.manifest_.presentationTimeline.getDuration();if(e<1/0)this.playerInterface_.mediaSourceEngine.setDuration(e);else{const e=this.config_.infiniteLiveStreamDuration?1/0:Math.pow(2,32);this.playerInterface_.mediaSourceEngine.setDuration(e)}}async onUpdate_(e){this.destroyer_.ensureNotDestroyed();const t=Le.logPrefix_(e);if(console.assert(!e.performingUpdate&&null!=e.updateTimer,t+" unexpected call to onUpdate_()"),e.performingUpdate||null==e.updateTimer)return;if(console.assert(!e.clearingBuffer,t+" onUpdate_() should not be called when clearing the buffer"),e.clearingBuffer)return;if(e.updateTimer=null,e.waitingToClearBuffer)return i.debug(t,"skipping update and clearing the buffer"),void await this.clearBuffer_(e,e.waitingToFlushBuffer,e.clearBufferSafeMargin);if(!e.stream.segmentIndex){const t=e.stream;if(await e.stream.createSegmentIndex(),t!=e.stream)return t.closeSegmentIndex&&(console.assert(!e.stream.segmentIndex,"mediastate.stream should not have segmentIndex yet."),t.closeSegmentIndex()),void(e.performingUpdate||e.updateTimer||this.scheduleUpdate_(e,0))}try{const t=this.update_(e);null!=t&&(this.scheduleUpdate_(e,t),e.hasError=!1)}catch(t){return void await this.handleStreamingError_(e,t)}const n=Array.from(this.mediaStates_.values());if(this.startupComplete_&&n.every((e=>e.endOfStream))){i.v1(t,"calling endOfStream()..."),await this.playerInterface_.mediaSourceEngine.endOfStream(),this.destroyer_.ensureNotDestroyed();const e=this.playerInterface_.mediaSourceEngine.getDuration();0!=e&&e<this.manifest_.presentationTimeline.getDuration()&&this.manifest_.presentationTimeline.setDuration(e)}}update_(e){console.assert(this.manifest_,"manifest_ should not be null"),console.assert(this.config_,"config_ should not be null");const t=k.ContentType;if(Le.isEmbeddedText_(e))return this.playerInterface_.mediaSourceEngine.setSelectedClosedCaptionId(e.stream.originalId||""),null;if(e.type==t.TEXT&&this.playerInterface_.mediaSourceEngine.clearSelectedClosedCaptionId(),!this.playerInterface_.mediaSourceEngine.isStreamingAllowed()&&e.type!=t.TEXT)return this.config_.updateIntervalSeconds/2;const n=Le.logPrefix_(e),s=this.playerInterface_.getPresentationTime();if(e.type===t.AUDIO)for(const e of this.audioPrefetchMap_.keys()){const t=this.audioPrefetchMap_.get(e);t.evict(s),t.prefetchSegmentsByTime(s)}const a=this.getTimeNeeded_(e,s);i.v2(n,"timeNeeded="+a);const r=this.playerInterface_.mediaSourceEngine.bufferedAheadOf(e.type,s);i.v2(n,"update_:","presentationTime="+s,"bufferedAhead="+r);const o=Math.max(this.manifest_.minBufferTime||0,this.config_.rebufferingGoal,this.config_.bufferingGoal),l=Math.max(1,o*this.bufferingGoalScale_),d=this.manifest_.presentationTimeline.getDuration()-a,c=this.playerInterface_.mediaSourceEngine.bufferEnd(e.type);if(d<1e-6&&c){if(i.debug(n,"buffered to end of presentation"),e.endOfStream=!0,e.type==t.VIDEO){const e=this.mediaStates_.get(t.TEXT);e&&Le.isEmbeddedText_(e)&&(e.endOfStream=!0)}return null}if(e.endOfStream=!1,r>=l)return i.v2(n,"buffering goal met"),this.config_.updateIntervalSeconds/2;const h=this.getSegmentReferenceNeeded_(e,s,c);if(!h)return this.config_.updateIntervalSeconds;let u=1/0;const _=Array.from(this.mediaStates_.values());for(const e of _){if(Le.isEmbeddedText_(e))continue;if(e.segmentIterator&&!e.segmentIterator.current())continue;const t=this.getTimeNeeded_(e,s);u=Math.min(u,t)}return a>=u+this.manifest_.presentationTimeline.getMaxSegmentDuration()*Le.MAX_RUN_AHEAD_SEGMENTS_?(i.v2(n,"waiting for other streams to buffer"),this.config_.updateIntervalSeconds):(e.segmentPrefetch&&e.segmentIterator&&!this.audioPrefetchMap_.has(e.stream)&&e.segmentPrefetch.prefetchSegmentsByTime(h.startTime),this.fetchAndAppend_(e,s,h).catch((()=>{})),null)}getTimeNeeded_(e,t){return e.lastSegmentReference?e.lastSegmentReference.endTime:t}getSegmentReferenceNeeded_(e,t,n){const s=Le.logPrefix_(e);if(console.assert(e.stream.segmentIndex,"segment index should have been generated already"),e.segmentIterator)return e.segmentIterator.current();if(e.lastSegmentReference||n){const t=e.lastSegmentReference?e.lastSegmentReference.endTime:n;console.assert(null!=t,"Should have a time to search"),i.v1(s,"looking up segment from new stream endTime:",t),e.needsResync=!0,e.segmentIterator=e.stream.segmentIndex.getIteratorForTime(t);const a=e.segmentIterator&&e.segmentIterator.next().value;return null==a&&i.warning(s,"cannot find segment","endTime:",t),a}{const n=this.config_.inaccurateManifestTolerance,a=Math.max(t-n,0);i.v1(s,"looking up segment","lookupTime:",a,"presentationTime:",t);let r=null;return n&&(e.segmentIterator=e.stream.segmentIndex.getIteratorForTime(a),r=e.segmentIterator&&e.segmentIterator.next().value),r||(e.segmentIterator=e.stream.segmentIndex.getIteratorForTime(t),r=e.segmentIterator&&e.segmentIterator.next().value),null==r&&i.warning(s,"cannot find segment","lookupTime:",a,"presentationTime:",t),r}}async fetchAndAppend_(e,t,n){const s=k.ContentType,a=Le.logPrefix_(e);i.v1(a,"fetchAndAppend_:","presentationTime="+t,"reference.startTime="+n.startTime,"reference.endTime="+n.endTime);const r=e.stream,o=e.segmentIterator;e.performingUpdate=!0;try{if(n.getStatus()==ye.Status.MISSING)throw new v(v.Severity.RECOVERABLE,v.Category.NETWORK,v.Code.SEGMENT_MISSING);if(await this.initSourceBuffer_(e,n),this.destroyer_.ensureNotDestroyed(),this.fatalError_)return;i.v2(a,"fetching segment");const s="video/mp4"==r.mimeType||"audio/mp4"==r.mimeType,l=window.ReadableStream;if(this.config_.lowLatencyMode&&l&&s&&(this.manifest_.type!=ue.HLS||n.hasByterangeOptimization())){let s,o=new Uint8Array(0),l=!1,d=!1;const c=async i=>{if(!l&&(d=!0,this.destroyer_.ensureNotDestroyed(),!this.fatalError_))try{o=this.concatArray_(o,i);let s=!1,a=0;if((new oe).box("mdat",(e=>{a=e.size+e.start,s=!0})).parse(o,!1,!0),s){const i=o.subarray(0,a);o=o.subarray(a),await this.append_(e,t,r,n,i,!0),e.segmentPrefetch&&e.segmentIterator&&e.segmentPrefetch.prefetchSegmentsByTime(n.startTime,!0)}}catch(e){s=e}},h=await this.fetch_(e,n,c);if(s)throw s;if(!d){if(l=!0,this.destroyer_.ensureNotDestroyed(),this.fatalError_)return;if(e.waitingToClearBuffer)return i.info(a,"waitingToClearBuffer, skip append"),e.performingUpdate=!1,void this.scheduleUpdate_(e,0);await this.append_(e,t,r,n,h)}e.segmentPrefetch&&e.segmentIterator&&e.segmentPrefetch.prefetchSegmentsByTime(n.startTime,!0)}else{this.config_.lowLatencyMode&&!l&&i.warning("Low latency streaming mode is enabled, but ReadableStream is not supported by the browser.");const s=this.fetch_(e,n),o=await s;if(this.destroyer_.ensureNotDestroyed(),this.fatalError_)return;if(this.destroyer_.ensureNotDestroyed(),e.waitingToClearBuffer)return i.info(a,"waitingToClearBuffer, skip append"),e.performingUpdate=!1,void this.scheduleUpdate_(e,0);await this.append_(e,t,r,n,o)}if(this.destroyer_.ensureNotDestroyed(),this.fatalError_)return;e.lastSegmentReference=n;const d=o.next().value;i.v2(a,"advancing to next segment",d),e.performingUpdate=!1,e.recovering=!1;const c=this.playerInterface_.mediaSourceEngine.getBufferedInfo()[e.type];i.v1(a,"finished fetch and append",JSON.stringify(c)),e.waitingToClearBuffer||this.playerInterface_.onSegmentAppended(n,e.stream),this.scheduleUpdate_(e,0)}catch(t){if(this.destroyer_.ensureNotDestroyed(t),this.fatalError_)return;console.assert(t instanceof v,"Should only receive a Shaka error"),e.performingUpdate=!1,t.code==v.Code.OPERATION_ABORTED?(e.performingUpdate=!1,this.cancelUpdate_(e),this.scheduleUpdate_(e,0)):e.type==s.TEXT&&this.config_.ignoreTextStreamFailures?(t.code==v.Code.BAD_HTTP_STATUS?i.warning(a,"Text stream failed to download. Proceeding without it."):i.warning(a,"Text stream failed to parse. Proceeding without it."),this.mediaStates_.delete(s.TEXT)):t.code==v.Code.QUOTA_EXCEEDED_ERROR?this.handleQuotaExceeded_(e,t):(i.error(a,"failed fetch and append: code="+t.code),e.hasError=!0,t.severity=v.Severity.CRITICAL,await this.handleStreamingError_(e,t))}}async aesDecrypt_(e,t,i){const n=t;n.cryptoKey||(console.assert(n.fetchKey,"If AES cryptoKey was not preloaded, fetchKey function should be provided"),await n.fetchKey(),console.assert(n.cryptoKey,"AES cryptoKey should now be set"));let s,a=n.iv;if(!a){a=l.toUint8(new ArrayBuffer(16));let e=n.firstMediaSequenceNumber+i;for(let t=a.byteLength-1;t>=0;t--)a[t]=255&e,e>>=8}return s="CBC"==t.blockCipherMode?{name:"AES-CBC",iv:a}:{name:"AES-CTR",counter:a,length:64},window.crypto.subtle.decrypt(s,n.cryptoKey,e)}retry(e){if(this.destroyer_.destroyed())return i.error("Unable to retry after StreamingEngine is destroyed!"),!1;if(this.fatalError_)return i.error("Unable to retry after StreamingEngine encountered a fatal error!"),!1;for(const t of this.mediaStates_.values()){const n=Le.logPrefix_(t);!t.hasError||t.performingUpdate||t.updateTimer||(i.info(n,"Retrying after failure..."),t.hasError=!1,this.scheduleUpdate_(t,e))}return!0}concatArray_(e,t){const i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}handleQuotaExceeded_(e,t){const n=Le.logPrefix_(e);if(Array.from(this.mediaStates_.values()).some((t=>t!=e&&t.recovering)))i.debug(n,"MediaSource threw QuotaExceededError:","waiting for another stream to recover...");else{if(this.config_.maxDisabledTime>0&&this.playerInterface_.disableStream(e.stream,this.config_.maxDisabledTime))return;const s=Math.round(100*this.bufferingGoalScale_);if(s>20)this.bufferingGoalScale_-=.2;else{if(!(s>4))return i.error(n,"MediaSource threw QuotaExceededError too many times"),e.hasError=!0,this.fatalError_=!0,void this.playerInterface_.onError(t);this.bufferingGoalScale_-=.04}const a=Math.round(100*this.bufferingGoalScale_);i.warning(n,"MediaSource threw QuotaExceededError:","reducing buffering goals by "+(100-a)+"%"),e.recovering=!0}this.scheduleUpdate_(e,4)}async initSourceBuffer_(e,t){const n=k.ContentType,s=Le.logPrefix_(e),a=[],r=Math.max(0,t.appendWindowStart-Le.APPEND_WINDOW_START_FUDGE_),o=t.appendWindowEnd+Le.APPEND_WINDOW_END_FUDGE_;console.assert(t.startTime<=o,s+" segment should start before append window end");const l=B.getCodecBase(e.stream.codecs),d=B.getBasicType(e.stream.mimeType),c=t.timestampOffset;if(c!=e.lastTimestampOffset||r!=e.lastAppendWindowStart||o!=e.lastAppendWindowEnd||l!=e.lastCodecs||d!=e.lastMimeType){i.v1(s,"setting timestamp offset to "+c),i.v1(s,"setting append window start to "+r),i.v1(s,"setting append window end to "+o);const a=e.lastCodecs&&e.lastMimeType&&this.playerInterface_.mediaSourceEngine.isResetMediaSourceNecessary(e.type,e.stream);if(a){let t=null;e.type===n.VIDEO?t=this.mediaStates_.get(n.AUDIO):e.type===n.AUDIO&&(t=this.mediaStates_.get(n.VIDEO)),t&&(t.lastInitSegmentReference=null,this.forceClearBuffer_(t),this.abortOperations_(t).catch((()=>{})))}const h=async()=>{const i=new Map;this.currentVariant_.audio&&i.set(n.AUDIO,this.currentVariant_.audio),this.currentVariant_.video&&i.set(n.VIDEO,this.currentVariant_.video);try{e.lastAppendWindowStart=r,e.lastAppendWindowEnd=o,e.lastCodecs=l,e.lastMimeType=d,e.lastTimestampOffset=c;const s=this.manifest_.sequenceMode||this.manifest_.type==ue.HLS;if(await this.playerInterface_.mediaSourceEngine.setStreamProperties(e.type,c,r,o,s,t.mimeType||e.stream.mimeType,t.codecs||e.stream.codecs,i),a){let t=null;e.type===n.VIDEO?t=this.mediaStates_.get(n.AUDIO):e.type===n.AUDIO&&(t=this.mediaStates_.get(n.VIDEO)),t&&(t.waitingToClearBuffer=!1,t.performingUpdate=!1,this.forceClearBuffer_(t))}}catch(t){throw e.lastAppendWindowStart=null,e.lastAppendWindowEnd=null,e.lastCodecs=null,e.lastTimestampOffset=null,t}};await h()}if(!Se.equal(t.initSegmentReference,e.lastInitSegmentReference)&&(e.lastInitSegmentReference=t.initSegmentReference,t.isIndependent()&&t.initSegmentReference)){i.v1(s,"fetching init segment");const r=this.fetch_(e,t.initSegmentReference),o=async()=>{try{const a=await r;this.destroyer_.ensureNotDestroyed();let o=null;const l=new Map;(new oe).box("moov",oe.children).box("trak",oe.children).box("mdia",oe.children).fullBox("mdhd",(e=>{console.assert(null!=e.version,"MDHD is a full box and should have a valid version.");const t=le.parseMDHD(e.reader,e.version);o=t.timescale})).box("hdlr",(e=>{switch(le.parseHDLR(e.reader).handlerType){case"soun":l.set(n.AUDIO,o);break;case"vide":l.set(n.VIDEO,o)}o=null})).parse(a),l.has(e.type)?t.initSegmentReference.timescale=l.get(e.type):null!=o&&(t.initSegmentReference.timescale=o),i.v1(s,"appending init segment");const d=e.stream.closedCaptions&&e.stream.closedCaptions.size>0;await this.playerInterface_.beforeAppendSegment(e.type,a),await this.playerInterface_.mediaSourceEngine.appendBuffer(e.type,a,null,e.stream,d)}catch(t){throw e.lastInitSegmentReference=null,t}};this.playerInterface_.onInitSegmentAppended(t.startTime,t.initSegmentReference),a.push(o())}if(this.manifest_.sequenceMode){const i=e.lastSegmentReference?e.lastSegmentReference.discontinuitySequence:null;(t.discontinuitySequence!=i||e.needsResync)&&(e.needsResync=!1,a.push(this.playerInterface_.mediaSourceEngine.resync(e.type,t.startTime)))}await Promise.all(a)}async append_(e,t,n,s,a,r=!1){const o=Le.logPrefix_(e),l=n.closedCaptions&&n.closedCaptions.size>0;let d;const c=null!=n.emsgSchemeIdUris&&n.emsgSchemeIdUris.length>0||this.config_.dispatchAllEmsgBoxes,h=this.config_.parsePrftBox&&!this.parsedPrftEventRaised_;(c||h)&&(d=new oe),c&&d.fullBox("emsg",(e=>this.parseEMSG_(s,n.emsgSchemeIdUris,e))),h&&d.fullBox("prft",(e=>this.parsePrft_(s,e))),(c||h)&&d.parse(a),await this.evict_(e,t),this.destroyer_.ensureNotDestroyed();const u=e.seeked;e.seeked=!1;const _=e.adaptation;e.adaptation=!1,await this.playerInterface_.beforeAppendSegment(e.type,a),await this.playerInterface_.mediaSourceEngine.appendBuffer(e.type,a,s,n,l,u,_,r),this.destroyer_.ensureNotDestroyed(),i.v2(o,"appended media segment")}parseEMSG_(e,t,i){let n,a,r,o,l,d,c;0===i.version?(o=i.reader.readTerminatedString(),c=i.reader.readTerminatedString(),n=i.reader.readUint32(),d=i.reader.readUint32(),r=i.reader.readUint32(),a=i.reader.readUint32(),l=e.startTime+d/n):(n=i.reader.readUint32(),l=i.reader.readUint64()/n+e.timestampOffset,d=l-e.startTime,r=i.reader.readUint32(),a=i.reader.readUint32(),o=i.reader.readTerminatedString(),c=i.reader.readTerminatedString());const h=i.reader.readBytes(i.reader.getLength()-i.reader.getPosition());if(t&&t.includes(o)||this.config_.dispatchAllEmsgBoxes)if("urn:mpeg:dash:event:2012"==o)this.playerInterface_.onManifestUpdate();else{const t={startTime:l,endTime:l+r/n,schemeIdUri:o,value:c,timescale:n,presentationTimeDelta:d,eventDuration:r,id:a,messageData:h},i=s.EventName.Emsg,u=(new Map).set("detail",t),_=new s(i,u);if(_.cancelable=!0,this.playerInterface_.onEvent(_),_.defaultPrevented)return;if("https://aomedia.org/emsg/ID3"==o||"https://developer.apple.com/streaming/emsg-id3"==o){const t=de.getID3Frames(h);if(t.length&&e){const i={cueTime:e.startTime,data:h,frames:t,dts:e.startTime,pts:e.startTime};this.playerInterface_.onMetadata([i],0,e.endTime)}}}}parsePrft_(e,t){if(this.parsedPrftEventRaised_||!e.initSegmentReference.timescale)return;console.assert(0==t.version||1==t.version,"PRFT version can only be 0 or 1");const i=le.parsePRFTInaccurate(t.reader,t.version),n=e.initSegmentReference.timescale,a=this.convertNtp(i.ntpTimestamp),r={wallClockTime:a,programStartDate:new Date(a-i.mediaTime/n*1e3)},o=s.EventName.Prft,l=(new Map).set("detail",r),d=new s(o,l);this.playerInterface_.onEvent(d),this.parsedPrftEventRaised_=!0}convertNtp(e){const t=new Date(Date.UTC(1900,0,1,0,0,0));return new Date(t.getTime()+e).getTime()}async evict_(e,t){const n=Le.logPrefix_(e);i.v2(n,"checking buffer length");const s=Math.max(this.config_.bufferBehind,this.manifest_.presentationTimeline.getMaxSegmentDuration()),a=this.playerInterface_.mediaSourceEngine.bufferStart(e.type);if(null==a)return void i.v2(n,"buffer behind okay because nothing buffered:","presentationTime="+t,"bufferBehind="+s);const r=t-a,o=r-s;o<=this.config_.evictionGoal?i.v2(n,"buffer behind okay:","presentationTime="+t,"bufferedBehind="+r,"bufferBehind="+s,"evictionGoal="+this.config_.evictionGoal,"underflow="+Math.abs(o)):(i.v1(n,"buffer behind too large:","presentationTime="+t,"bufferedBehind="+r,"bufferBehind="+s,"evictionGoal="+this.config_.evictionGoal,"overflow="+o),await this.playerInterface_.mediaSourceEngine.remove(e.type,a,a+o),this.destroyer_.ensureNotDestroyed(),i.v1(n,"evicted "+o+" seconds"))}static isEmbeddedText_(e){const t=B.CEA608_CLOSED_CAPTION_MIMETYPE,i=B.CEA708_CLOSED_CAPTION_MIMETYPE;return e&&e.type==k.ContentType.TEXT&&(e.stream.mimeType==t||e.stream.mimeType==i)}async fetch_(e,t,i){const n=t.getSegmentData();if(n)return n;let s=null;e.segmentPrefetch&&(s=e.segmentPrefetch.getPrefetchedSegment(t,i)),s||(s=this.dispatchFetch_(t,e.stream,i));let a=0;e.segmentIterator&&(a=e.segmentIterator.currentPosition()),e.operation=s;const r=await s.promise;e.operation=null;let o=r.data;return t.aesKey&&(o=await this.aesDecrypt_(o,t.aesKey,a)),o}dispatchFetch_(e,t,i){return console.assert(this.playerInterface_.netEngine,"Must have net engine"),Le.dispatchFetch(e,t,i||null,this.config_.retryParameters,this.playerInterface_.netEngine)}static dispatchFetch(e,t,n,s,a){const r=O.RequestType.SEGMENT,o=e instanceof ye?e:void 0,l=o?O.AdvancedRequestType.MEDIA_SEGMENT:O.AdvancedRequestType.INIT_SEGMENT,d=Ne.createSegmentRequest(e.getUris(),e.startByte,e.endByte,s,n);return d.contentType=t.type,i.v2("fetching: reference=",e),a.request(r,d,{type:l,stream:t,segment:o})}async clearBuffer_(e,t,n){const s=Le.logPrefix_(e);if(console.assert(!e.performingUpdate&&null==e.updateTimer,s+" unexpected call to clearBuffer_()"),e.waitingToClearBuffer=!1,e.waitingToFlushBuffer=!1,e.clearBufferSafeMargin=0,e.clearingBuffer=!0,e.lastSegmentReference=null,e.lastInitSegmentReference=null,e.segmentIterator=null,i.debug(s,"clearing buffer"),e.segmentPrefetch&&!this.audioPrefetchMap_.has(e.stream)&&e.segmentPrefetch.clearAll(),n){const t=this.playerInterface_.getPresentationTime(),i=this.playerInterface_.mediaSourceEngine.getDuration();await this.playerInterface_.mediaSourceEngine.remove(e.type,t+n,i)}else await this.playerInterface_.mediaSourceEngine.clear(e.type),this.destroyer_.ensureNotDestroyed(),t&&await this.playerInterface_.mediaSourceEngine.flush(e.type);this.destroyer_.ensureNotDestroyed(),i.debug(s,"cleared buffer"),e.clearingBuffer=!1,e.endOfStream=!1,e.performingUpdate||e.updateTimer||this.scheduleUpdate_(e,0)}scheduleUpdate_(e,t){const n=Le.logPrefix_(e),s=e.type;s!=k.ContentType.TEXT||this.mediaStates_.has(s)?(i.v2(n,"updating in "+t+" seconds"),console.assert(null==e.updateTimer,n+" did not expect update to be scheduled"),e.updateTimer=new r((async()=>{try{await this.onUpdate_(e)}catch(e){this.playerInterface_&&this.playerInterface_.onError(e)}})).tickAfter(t)):i.v1(n,"Text stream is unloaded. No update is needed.")}cancelUpdate_(e){null!=e.updateTimer&&(e.updateTimer.stop(),e.updateTimer=null)}async abortOperations_(e){e.operation&&await e.operation.abort()}async handleStreamingError_(e,t){await this.failureCallbackBackoff_.attempt(),this.destroyer_.ensureNotDestroyed();const i=this.getDisabledTime_(t);t.category===v.Category.NETWORK&&i>0&&(t.handled=this.playerInterface_.disableStream(e.stream,i),t.handled&&(t.severity=v.Severity.RECOVERABLE)),this.playerInterface_.onError(t),t.handled||this.config_.failureCallback(t)}getDisabledTime_(e){return 0===this.config_.maxDisabledTime&&e.code==v.Code.SEGMENT_MISSING?1:this.config_.maxDisabledTime}async resetMediaSource(){const e=Date.now()/1e3,t=this.config_.minTimeBetweenRecoveries;if(!this.config_.allowMediaSourceRecoveries||e-this.lastMediaSourceReset_<t)return!1;this.lastMediaSourceReset_=e;const i=k.ContentType,n=this.mediaStates_.get(i.AUDIO);n&&(n.lastInitSegmentReference=null,this.forceClearBuffer_(n),this.abortOperations_(n).catch((()=>{})));const s=this.mediaStates_.get(i.VIDEO);s&&(s.lastInitSegmentReference=null,this.forceClearBuffer_(s),this.abortOperations_(s).catch((()=>{})));const a=new Map;return this.currentVariant_.audio&&a.set(i.AUDIO,this.currentVariant_.audio),this.currentVariant_.video&&a.set(i.VIDEO,this.currentVariant_.video),await this.playerInterface_.mediaSourceEngine.reset(a),!0}static logPrefix_(e){return"("+e.type+":"+e.stream.id+")"}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}Le.PlayerInterface,Le.MediaState_,Le.APPEND_WINDOW_START_FUDGE_=.1,Le.APPEND_WINDOW_END_FUDGE_=.01,Le.MAX_RUN_AHEAD_SEGMENTS_=1;class xe extends a{constructor(e,t,i,n,s){super();const a=s;this.assetUri_=e,this.mimeType_=t,this.networkingEngine_=a.networkingEngine,this.startTime_=n,this.currentAdaptationSetCriteria_=null,this.startTimeOfLoad_=i,this.manifestFilterer_=a.manifestFilterer,this.manifestPlayerInterface_=a.manifestPlayerInterface,this.config_=a.config,this.manifest_=null,this.parserFactory_=null,this.parser_=null,this.parserEntrusted_=!1,this.regionTimeline_=a.regionTimeline,this.regionTimelineEntrusted_=!1,this.abrManagerFactory_=null,this.abrManager_=null,this.abrManagerEntrusted_=!1,this.segmentPrefetchById_=new Map,this.segmentPrefetchEntrusted_=!1,this.qualityObserver_=a.qualityObserver,this.stats_=new ie,this.manifestPromise_=new C,this.chooseInitialVariantPromise_=new C,this.destroyPromise_=new C,this.destroyPromise_.catch((e=>{})),this.eventHandoffTarget_=null,this.destroyed_=!1,this.allowPrefetch_=a.allowPrefetch,this.prefetchedVariant_=null,this.allowMakeAbrManager_=a.allowMakeAbrManager,this.hasBeenAttached_=!1,this.queuedOperations_=[],this.latePhaseQueuedOperations_=[]}addQueuedOperation(e,t){const i=e?this.latePhaseQueuedOperations_:this.queuedOperations_;i?i.push(t):t()}stopQueuingLatePhaseQueuedOperations(){if(this.latePhaseQueuedOperations_)for(const e of this.latePhaseQueuedOperations_)e();this.latePhaseQueuedOperations_=null}setEventHandoffTarget(e){if(this.eventHandoffTarget_=e,this.hasBeenAttached_=!0,this.queuedOperations_)for(const e of this.queuedOperations_)e();this.queuedOperations_=null}getStartTime(){return this.startTime_}getStartTimeOfLoad(){return this.startTimeOfLoad_}getMimeType(){return this.mimeType_}getAssetUri(){return this.assetUri_}getManifest(){return this.manifest_}getParserFactory(){return this.parserFactory_}getCurrentAdaptationSetCriteria(){return this.currentAdaptationSetCriteria_}getAbrManagerFactory(){return this.abrManagerFactory_}receiveAbrManager(){return this.abrManagerEntrusted_=!0,this.abrManager_}getAbrManager(){return this.abrManager_}receiveParser(){return this.parserEntrusted_=!0,this.parser_}getParser(){return this.parser_}receiveRegionTimeline(){return this.regionTimelineEntrusted_=!0,this.regionTimeline_}getRegionTimeline(){return this.regionTimeline_}getQualityObserver(){return this.qualityObserver_}getStats(){return this.stats_}getManifestFilterer(){return this.manifestFilterer_}getPrefetchedVariant(){return this.prefetchedVariant_}receiveSegmentPrefetchesById(){return this.segmentPrefetchEntrusted_=!0,this.segmentPrefetchById_}waitForManifest(){return this.manifestPromise_}waitForChooseInitialVariant(){return this.chooseInitialVariantPromise_}attachAbrManager(e,t){this.abrManager_=e,this.abrManagerFactory_=t}attachAdaptationSetCriteria(e){this.currentAdaptationSetCriteria_=e}attachManifest(e,t,i){this.manifest_=e,this.parser_=t,this.parserFactory_=i}async start(){await Promise.resolve();try{if(await this.parseManifestInner_(),this.isDestroyed())return;if(this.manifestPromise_.resolve(),this.isDestroyed())return;if(await this.chooseInitialVariantInner_(),this.isDestroyed())return;this.chooseInitialVariantPromise_.resolve()}catch(e){throw this.destroyPromise_.reject(e),e}}dispatchEvent(e){return this.eventHandoffTarget_?this.eventHandoffTarget_.dispatchEvent(e):super.dispatchEvent(e)}onError(e){e.severity===v.Severity.CRITICAL&&(this.destroyPromise_.reject(e),this.destroy());const t=s.EventName.Error,i=this.makeEvent_(t,(new Map).set("detail",e));this.dispatchEvent(i),i.defaultPrevented&&(e.handled=!0)}makeStateChangeEvent_(e){this.dispatchEvent(new s(s.EventName.OnStateChange,(new Map).set("state",e)))}makeEvent_(e,t){return new s(e,t)}async parseManifestInner_(){this.makeStateChangeEvent_("manifest-parser"),this.parser_||(this.parserFactory_=ue.getFactory(this.assetUri_,this.mimeType_),console.assert(this.parserFactory_,"Must have manifest parser"),this.parser_=this.parserFactory_(),this.parser_.configure(this.config_.manifest));const e=Date.now()/1e3;this.makeStateChangeEvent_("manifest"),this.manifest_||(this.manifest_=await this.parser_.start(this.assetUri_,this.manifestPlayerInterface_));const t=this.makeEvent_(s.EventName.ManifestParsed);if(this.dispatchEvent(t),0==this.manifest_.variants.length)throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.NO_VARIANTS);xe.filterForAVVariants_(this.manifest_);const i=Date.now()/1e3-e;this.stats_.setManifestTime(i)}reconfigure(e){this.config_=e}configure(e,t){const i=j.convertToConfigObject(e,t);J.mergeConfigObjects(this.config_,i)}getConfiguration(){return b.cloneObject(this.config_)}chooseInitialVariantInner_(){if(console.assert(this.manifest_,"The manifest should already be parsed."),this.currentAdaptationSetCriteria_||(this.currentAdaptationSetCriteria_=new Pe(this.config_.preferredAudioLanguage,this.config_.preferredVariantRole,this.config_.preferredAudioChannelCount,this.config_.preferredVideoHdrLevel,this.config_.preferSpatialAudio,this.config_.preferredVideoLayout,this.config_.preferredAudioLabel,this.config_.preferredVideoLabel,this.config_.mediaSource.codecSwitchingStrategy,this.config_.manifest.dash.enableAudioGroups),z.chooseCodecsAndFilterManifest(this.manifest_,this.config_.preferredVideoCodecs,this.config_.preferredAudioCodecs,this.config_.preferredDecodingAttributes)),this.allowMakeAbrManager_){const e=this.config_.abrFactory;this.abrManagerFactory_=e,this.abrManager_=e(),this.abrManager_.configure(this.config_.abr)}if(this.allowPrefetch_){const e=this.manifest_.presentationTimeline.isLive(),t=z.getPlayableVariants(this.manifest_.variants),i=this.currentAdaptationSetCriteria_.create(t);this.abrManager_.configure(this.config_.abr),this.abrManager_.setVariants(Array.from(i.values()));const n=this.abrManager_.chooseVariant(!0);n&&(this.prefetchedVariant_=n,n.video&&this.makePrefetchForStream_(n.video,e),n.audio&&this.makePrefetchForStream_(n.audio,e))}}async makePrefetchForStream_(e,t){const i=this.config_.streaming.segmentPrefetchLimit||2,n=new Me(i,e,((e,t,i)=>Le.dispatchFetch(e,t,i||null,this.config_.streaming.retryParameters,this.networkingEngine_)));this.segmentPrefetchById_.set(e.id,n),await e.createSegmentIndex();const s=this.startTime_||0,a=e.segmentIndex.getIteratorForTime(s);let r=a?a.current():null;r||(r=e.segmentIndex.get(0)),r&&(t?r.initSegmentReference&&n.prefetchInitSegment(r.initSegmentReference):n.prefetchSegmentsByTime(r.startTime))}waitForFinish(){return Promise.race([this.chooseInitialVariantPromise_,this.destroyPromise_])}async destroy(){if(this.destroyed_=!0,this.parser_&&!this.parserEntrusted_&&await this.parser_.stop(),this.abrManager_&&!this.abrManagerEntrusted_&&await this.abrManager_.stop(),this.regionTimeline_&&!this.regionTimelineEntrusted_&&this.regionTimeline_.release(),this.segmentPrefetchById_.size>0&&!this.segmentPrefetchEntrusted_)for(const e of this.segmentPrefetchById_.values())e.clearAll()}isDestroyed(){return this.destroyed_}hasBeenAttached(){return this.hasBeenAttached_}static filterForAVVariants_(e){const t=e=>e.video&&e.audio||e.video&&e.video.codecs.includes(",");e.variants.some(t)&&(i.debug("Found variant with audio and video content, so filtering out audio-only content."),e.variants=e.variants.filter(t))}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0,void 0]}}class ke{static waitForReadyState(e,t,i,n){if(t==HTMLMediaElement.HAVE_NOTHING||e.readyState>=t)n();else{const s=ke.READY_STATES_TO_EVENT_NAMES_.value().get(t);i.listenOnce(e,s,n)}}}ke.READY_STATES_TO_EVENT_NAMES_=new N((()=>new Map([[HTMLMediaElement.HAVE_METADATA,"loadedmetadata"],[HTMLMediaElement.HAVE_CURRENT_DATA,"loadeddata"],[HTMLMediaElement.HAVE_FUTURE_DATA,"canplay"],[HTMLMediaElement.HAVE_ENOUGH_DATA,"canplaythrough"]])));class Ue{constructor(e,t,i,n){this.video_=e,this.onSeek_=t,this.onStarted_=i,this.startTime_=null,this.getStartTime_=()=>(null==this.startTime_&&(this.startTime_=n()),this.startTime_),this.started_=!1,this.eventManager_=new Z,this.mover_=new Ue.PlayheadMover(e,10),ke.waitForReadyState(this.video_,HTMLMediaElement.HAVE_METADATA,this.eventManager_,(()=>{this.setStartTime_(this.getStartTime_())}))}release(){this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null),null!=this.mover_&&(this.mover_.release(),this.mover_=null),this.onSeek_=()=>{},this.video_=null}getTime(){return this.started_?this.video_.currentTime:this.getStartTime_()}setTime(e){this.video_.readyState>0?this.mover_.moveTo(e):ke.waitForReadyState(this.video_,HTMLMediaElement.HAVE_METADATA,this.eventManager_,(()=>{this.setStartTime_(this.getStartTime_())}))}setStartTime_(e){Math.abs(this.video_.currentTime-e)<.001?this.startListeningToSeeks_():(this.eventManager_.listenOnce(this.video_,"seeking",(()=>{this.startListeningToSeeks_()})),this.mover_.moveTo(this.video_.currentTime&&0!=this.video_.currentTime?this.video_.currentTime:e))}startListeningToSeeks_(){console.assert(this.video_.readyState>0,"The media element should be ready before we listen for seeking."),this.started_=!0,this.eventManager_.listen(this.video_,"seeking",(()=>this.onSeek_())),this.onStarted_(this.video_.currentTime)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0]}}class Be{constructor(e,t){this.mediaElement_=e,this.maxAttempts_=t,this.remainingAttempts_=0,this.originTime_=0,this.targetTime_=0,this.timer_=new o((()=>this.onTick_()))}release(){this.timer_&&(this.timer_.stop(),this.timer_=null),this.mediaElement_=null}moveTo(e){this.originTime_=this.mediaElement_.currentTime,this.targetTime_=e,this.remainingAttempts_=this.maxAttempts_,this.mediaElement_.currentTime=e,this.timer_.tickEvery(.1)}onTick_(){if(this.remainingAttempts_<=0)return i.warning(["Failed to move playhead from",this.originTime_,"to",this.targetTime_].join(" ")),void this.timer_.stop();this.mediaElement_.currentTime==this.originTime_?(this.mediaElement_.currentTime=this.targetTime_,this.remainingAttempts_--):this.timer_.stop()}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}Ue.PlayheadMover=Be;class Fe{constructor(e,t,i,n,s){this.onEvent_=s,this.video_=e,this.timeline_=t,this.config_=i,this.eventManager_=new Z,this.seekingEventReceived_=!1,this.prevReadyState_=e.readyState,this.startTime_=0,this.gapsJumped_=0,this.stallDetector_=n,this.hadSegmentAppended_=!1,this.eventManager_.listen(e,"waiting",(()=>this.onPollGapJump_())),this.gapJumpTimer_=new o((()=>{this.onPollGapJump_()})).tickEvery(this.config_.gapJumpTimerTime)}release(){this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null),null!=this.gapJumpTimer_&&(this.gapJumpTimer_.stop(),this.gapJumpTimer_=null),this.stallDetector_&&(this.stallDetector_.release(),this.stallDetector_=null),this.onEvent_=null,this.timeline_=null,this.video_=null}onSegmentAppended(){this.hadSegmentAppended_=!0,this.onPollGapJump_()}onStarted(e){this.video_.seeking&&!this.seekingEventReceived_&&(this.seekingEventReceived_=!0,this.startTime_=e)}onSeeking(){this.seekingEventReceived_=!0,this.hadSegmentAppended_=!1}getGapsJumped(){return this.gapsJumped_}onPollGapJump_(){if(0==this.video_.readyState)return;if(this.video_.seeking){if(!this.seekingEventReceived_)return}else this.seekingEventReceived_=!1;if(this.video_.paused&&(this.video_.currentTime!=this.startTime_||!this.video_.autoplay&&this.video_.currentTime==this.startTime_))return;if(this.video_.readyState!=this.prevReadyState_&&(this.prevReadyState_=this.video_.readyState),this.stallDetector_&&this.stallDetector_.poll())return;const e=this.video_.currentTime,t=this.video_.buffered,n=this.config_.gapDetectionThreshold,a=me.getGapIndex(t,e,n);if(null==a)return;if(0==a&&!this.hadSegmentAppended_)return;const r=t.start(a);if(r>=this.timeline_.getSeekRangeEnd())return;const o=r-e;o<Fe.BROWSER_GAP_TOLERANCE||(0==a?i.info("Jumping forward",o,"seconds because of gap before start time of",r):i.info("Jumping forward",o,"seconds because of gap starting at",t.end(a-1),"and ending at",r),this.video_.currentTime=r,e==this.startTime_&&(this.startTime_=r),this.gapsJumped_++,this.onEvent_(new s(s.EventName.GapJumped)))}static get[Symbol.for("___CTOR_ARGS___")](){return["HTMLMediaElement","PresentationTimeline",void 0,"StallDetector",void 0]}}Fe.BROWSER_GAP_TOLERANCE=.001;class Ve{constructor(e,t,i){this.onEvent_=i,this.implementation_=e,this.wasMakingProgress_=e.shouldBeMakingProgress(),this.value_=e.getPresentationSeconds(),this.lastUpdateSeconds_=e.getWallSeconds(),this.didJump_=!1,this.stallsDetected_=0,this.stallThresholdSeconds_=t,this.onStall_=()=>{}}release(){this.implementation_=null,this.onEvent_=null,this.onStall_=()=>{}}onStall(e){this.onStall_=e}getStallsDetected(){return this.stallsDetected_}poll(){const e=this.implementation_,t=e.shouldBeMakingProgress(),i=e.getPresentationSeconds(),n=e.getWallSeconds();(this.value_!=i||this.wasMakingProgress_!=t)&&(this.lastUpdateSeconds_=n,this.value_=i,this.wasMakingProgress_=t,this.didJump_=!1);const a=n-this.lastUpdateSeconds_,r=a>=this.stallThresholdSeconds_&&t&&!this.didJump_;return r&&(this.onStall_(this.value_,a),this.didJump_=!0,this.value_=e.getPresentationSeconds(),this.stallsDetected_++,this.onEvent_(new s(s.EventName.StallDetected))),r}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0]}}class Ge{constructor(e){this.mediaElement_=e}shouldBeMakingProgress(){return!this.mediaElement_.paused&&0!=this.mediaElement_.buffered.length&&Ge.hasContentFor_(this.mediaElement_.buffered,this.mediaElement_.currentTime)}getPresentationSeconds(){return this.mediaElement_.currentTime}getWallSeconds(){return Date.now()/1e3}static hasContentFor_(e,t){for(const{start:i,end:n}of me.getBufferedInfo(e))if(!(t<i-.1||t>n-.5))return!0;return!1}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class He{constructor(e){this.mediaElement_=e,this.started_=!1,this.startTime_=null,this.eventManager_=new Z}ready(){console.assert(null!=this.mediaElement_,"Playhead should not be released before calling ready()");const e=()=>{if(null==this.startTime_||0==this.startTime_)this.started_=!0;else{this.eventManager_.listenOnce(this.mediaElement_,"seeking",(()=>{this.started_=!0}));const e=this.mediaElement_.currentTime,t=Math.max(0,e+this.startTime_);this.mediaElement_.currentTime=t}};ke.waitForReadyState(this.mediaElement_,HTMLMediaElement.HAVE_CURRENT_DATA,this.eventManager_,(()=>{e()}))}release(){this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null),this.mediaElement_=null}setStartTime(e){this.startTime_=this.started_?this.startTime_:e}getTime(){return(this.started_?this.mediaElement_.currentTime:this.startTime_)||0}getStallsDetected(){return 0}getGapsJumped(){return 0}notifyOfBufferingChange(){}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class We{constructor(e,t,i,n,s,a){this.minSeekRange_=3,this.mediaElement_=e,this.timeline_=t.presentationTimeline,this.minBufferTime_=t.minBufferTime||0,this.config_=i,this.onSeek_=s,this.lastCorrectiveSeek_=null,this.stallDetector_=this.createStallDetector_(e,i,a),this.gapController_=new Fe(e,t.presentationTimeline,i,this.stallDetector_,a),this.videoWrapper_=new Ue(e,(()=>this.onSeeking_()),(e=>this.onStarted_(e)),(()=>this.getStartTime_(n))),this.checkWindowTimer_=new o((()=>{this.onPollWindow_()}))}ready(){this.checkWindowTimer_.tickEvery(.25)}release(){this.videoWrapper_&&(this.videoWrapper_.release(),this.videoWrapper_=null),this.gapController_&&(this.gapController_.release(),this.gapController_=null),this.checkWindowTimer_&&(this.checkWindowTimer_.stop(),this.checkWindowTimer_=null),this.config_=null,this.timeline_=null,this.videoWrapper_=null,this.mediaElement_=null,this.onSeek_=()=>{}}setStartTime(e){this.videoWrapper_.setTime(e)}getTime(){const e=this.videoWrapper_.getTime();return this.mediaElement_.readyState>0&&!this.mediaElement_.paused?this.clampTime_(e):e}getStallsDetected(){return this.stallDetector_?this.stallDetector_.getStallsDetected():0}getGapsJumped(){return this.gapController_.getGapsJumped()}getStartTime_(e){return null==e?e=this.timeline_.getDuration()<1/0?this.timeline_.getSeekRangeStart():this.timeline_.getSeekRangeEnd():e<0&&(e=this.timeline_.getSeekRangeEnd()+e),this.clampSeekToDuration_(this.clampTime_(e))}notifyOfBufferingChange(){this.gapController_.onSegmentAppended()}onPollWindow_(){if(0==this.mediaElement_.readyState||this.mediaElement_.paused)return;const e=this.videoWrapper_.getTime();let t=this.timeline_.getSeekRangeStart();const n=this.timeline_.getSeekRangeEnd();if(n-t<this.minSeekRange_&&(t=n-this.minSeekRange_),e<t){const t=this.reposition_(e);i.info("Jumping forward "+(t-e)+" seconds to catch up with the seek range."),this.mediaElement_.currentTime=t}}onStarted_(e){this.gapController_.onStarted(e)}onSeeking_(){this.gapController_.onSeeking();const e=this.videoWrapper_.getTime(),t=this.reposition_(e),n=Fe.BROWSER_GAP_TOLERANCE;if(Math.abs(t-e)>n){const e=Date.now()/1e3;if(!this.lastCorrectiveSeek_||this.lastCorrectiveSeek_<e-1)return this.lastCorrectiveSeek_=e,void this.videoWrapper_.setTime(t)}i.v1("Seek to "+e),this.onSeek_()}clampSeekToDuration_(e){const t=this.timeline_.getDuration();return e>=t?(console.assert(this.config_.durationBackoff>=0,"Duration backoff must be non-negative!"),t-this.config_.durationBackoff):e}reposition_(e){console.assert(this.config_,"Cannot reposition playhead when it has beeen destroyed");const t=e=>me.isBuffered(this.mediaElement_.buffered,e),n=Math.max(this.minBufferTime_,this.config_.rebufferingGoal),s=this.config_.safeSeekOffset;let a=this.timeline_.getSeekRangeStart();const r=this.timeline_.getSeekRangeEnd(),o=this.timeline_.getDuration();r-a<this.minSeekRange_&&(a=r-this.minSeekRange_);const l=this.timeline_.getSafeSeekRangeStart(n),d=this.timeline_.getSafeSeekRangeStart(s),c=this.timeline_.getSafeSeekRangeStart(n+s);return e>=o?(i.v1("Playhead past duration."),this.clampSeekToDuration_(e)):e>r?(i.v1("Playhead past end."),r):e<a?t(d)?(i.v1("Playhead before start & start is buffered"),d):(i.v1("Playhead before start & start is unbuffered"),c):e>=l||t(e)?(i.v1("Playhead in safe region or in buffered region."),e):(i.v1("Playhead outside safe region & in unbuffered region."),c)}clampTime_(e){const t=this.timeline_.getSeekRangeStart();if(e<t)return t;const i=this.timeline_.getSeekRangeEnd();return e>i?i:e}createStallDetector_(e,t,n){if(!t.stallEnabled)return null;const s=t.stallThreshold,a=t.stallSkip,r=new Ve(new Ge(e),s,n);return r.onStall(((t,n)=>{i.debug(`Stall detected at ${t} for ${n} seconds.`),a?(i.debug(`Seeking forward ${a} seconds to break stall.`),e.currentTime+=a):(i.debug("Pausing and unpausing to break stall."),e.pause(),e.play())})),r}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0,void 0,void 0,void 0]}}class qe{constructor(e,t){const i=qe.State;this.previousState_=i.SATISFIED,this.thresholds_=(new Map).set(i.SATISFIED,t).set(i.STARVING,e),this.lastRebufferTime_=0}setThresholds(e,t){const i=qe.State;this.thresholds_.set(i.SATISFIED,t).set(i.STARVING,e)}update(e,t){const i=qe.State,n=this.thresholds_.get(this.previousState_),s=this.previousState_,a=t||e>=n?i.SATISFIED:i.STARVING;this.previousState_=a;const r=s!=a;return r&&a===i.SATISFIED&&(this.lastRebufferTime_=Date.now()),r}setState(e){this.previousState_=e}getState(){return this.previousState_}getLastRebufferTime(){return this.lastRebufferTime_}resetLastRebufferTime(){this.lastRebufferTime_=0}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}qe.State={STARVING:0,SATISFIED:1};class Xe{constructor(e){this.harness_=e,this.rate_=this.harness_.getRate(),this.pollRate_=.25,this.timer_=new o((()=>{this.harness_.movePlayhead(this.rate_*this.pollRate_)}))}release(){this.set(this.getDefaultRate()),this.timer_&&(this.timer_.stop(),this.timer_=null),this.harness_=null}set(e){this.rate_!=e&&(this.rate_=e,this.apply_())}getRealRate(){return this.rate_}getDefaultRate(){return this.harness_.getDefaultRate()}apply_(){if(this.timer_.stop(),i.v1("Changing effective playback rate to",this.rate_),this.rate_>=0)try{return void this.applyRate_(this.rate_)}catch(e){}this.timer_.tickEvery(this.pollRate_),this.applyRate_(0)}applyRate_(e){const t=this.harness_.getRate();return t!=e&&this.harness_.setRate(e),t!=e}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}class ze{static createHTMLElement(e){return document.createElement(e)}static createButton(){const e=document.createElement("button");return e.setAttribute("type","button"),e}static asHTMLElement(e){return e}static asHTMLMediaElement(e){return e}static getElementByClassName(e,t){const i=t.getElementsByClassName(e);return console.assert(1==i.length,"Should only be one element with class name "+e),ze.asHTMLElement(i[0])}static removeAllChildren(e){for(;e.firstChild;)e.removeChild(e.firstChild)}}class Ye{constructor(e,t,i){const n=n;this.startTime=e,this.endTime=t,this.payload=i,this.region=new je,this.position=null,this.positionAlign=n.positionAlign.AUTO,this.size=0,this.textAlign=n.textAlign.CENTER,this.direction=n.direction.HORIZONTAL_LEFT_TO_RIGHT,this.writingMode=n.writingMode.HORIZONTAL_TOP_TO_BOTTOM,this.lineInterpretation=n.lineInterpretation.LINE_NUMBER,this.line=null,this.lineHeight="",this.lineAlign=n.lineAlign.START,this.displayAlign=n.displayAlign.AFTER,this.color="",this.backgroundColor="",this.backgroundImage="",this.border="",this.fontSize="",this.fontWeight=n.fontWeight.NORMAL,this.fontStyle=n.fontStyle.NORMAL,this.fontFamily="",this.letterSpacing="",this.linePadding="",this.opacity=1,this.textCombineUpright="",this.textDecoration=[],this.textShadow="",this.textStrokeColor="",this.textStrokeWidth="",this.wrapLine=!0,this.id="",this.nestedCues=[],this.isContainer=!1,this.lineBreak=!1,this.rubyTag=null,this.cellResolution={columns:32,rows:15}}static lineBreak(e,t){const i=new Ye(e,t,"");return i.lineBreak=!0,i}clone(){const e=new Ye(0,0,"");for(const t in this)e[t]=this[t],e[t]&&e[t].constructor==Array&&(e[t]=e[t].slice());return e}static equal(e,t){if(e.startTime!=t.startTime||e.endTime!=t.endTime||e.payload!=t.payload)return!1;for(const i in e)if("startTime"==i||"endTime"==i||"payload"==i);else if("nestedCues"==i){if(!I.equal(e.nestedCues,t.nestedCues,Ye.equal))return!1}else if("region"==i||"cellResolution"==i){for(const n in e[i])if(e[i][n]!=t[i][n])return!1}else if(Array.isArray(e[i])){if(!I.equal(e[i],t[i]))return!1}else if(e[i]!=t[i])return!1;return!0}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0]}}Ye.positionAlign={LEFT:"line-left",RIGHT:"line-right",CENTER:"center",AUTO:"auto"},Ye.textAlign={LEFT:"left",RIGHT:"right",CENTER:"center",START:"start",END:"end"},Ye.displayAlign={BEFORE:"before",CENTER:"center",AFTER:"after"},Ye.direction={HORIZONTAL_LEFT_TO_RIGHT:"ltr",HORIZONTAL_RIGHT_TO_LEFT:"rtl"},Ye.writingMode={HORIZONTAL_TOP_TO_BOTTOM:"horizontal-tb",VERTICAL_LEFT_TO_RIGHT:"vertical-lr",VERTICAL_RIGHT_TO_LEFT:"vertical-rl"},Ye.lineInterpretation={LINE_NUMBER:0,PERCENTAGE:1},Ye.lineAlign={CENTER:"center",START:"start",END:"end"},Ye.defaultTextColor={white:"white",lime:"lime",cyan:"cyan",red:"red",yellow:"yellow",magenta:"magenta",blue:"blue",black:"black"},Ye.defaultTextBackgroundColor={bg_white:"white",bg_lime:"lime",bg_cyan:"cyan",bg_red:"red",bg_yellow:"yellow",bg_magenta:"magenta",bg_blue:"blue",bg_black:"black"},Ye.fontWeight={NORMAL:400,BOLD:700},Ye.fontStyle={NORMAL:"normal",ITALIC:"italic",OBLIQUE:"oblique"},Ye.textDecoration={UNDERLINE:"underline",LINE_THROUGH:"lineThrough",OVERLINE:"overline"};class je{constructor(){this.id="",this.viewportAnchorX=0,this.viewportAnchorY=0,this.regionAnchorX=0,this.regionAnchorY=0,this.width=100,this.height=100,this.heightUnits=je.units.PERCENTAGE,this.widthUnits=je.units.PERCENTAGE,this.viewportAnchorUnits=je.units.PERCENTAGE,this.scroll=je.scrollMode.NONE}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}je.units={PX:0,PERCENTAGE:1,LINES:2},je.scrollMode={NONE:"",UP:"up"};class Ke{static flattenPayload_(e,t){if(e.lineBreak)return"\n";if(e.nestedCues.length)return e.nestedCues.map((t=>Ke.flattenPayload_(t,e))).join("");const i=[],n=e.fontWeight>=Ye.fontWeight.BOLD,s=e.fontStyle==Ye.fontStyle.ITALIC,a=e.textDecoration.includes(Ye.textDecoration.UNDERLINE);n&&i.push(["b"]),s&&i.push(["i"]),a&&i.push(["u"]);let r=e.color;""==r&&t&&(r=t.color);let o="";const l=Ke.getColorName_(r);l&&(o+=`.${l}`);let d=e.backgroundColor;""==d&&t&&(d=t.backgroundColor);const c=Ke.getColorName_(d);return c&&(o+=`.bg_${c}`),o&&i.push(["c",o]),i.reduceRight(((e,[t,i=""])=>`<${t}${i}>${e}</${t}>`),e.payload)}static getColorName_(e){let t=e.toLowerCase();const i=t.replace(/\s/g,"").match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i);switch(i?t="#"+(256|parseInt(i[1],10)).toString(16).slice(1)+(256|parseInt(i[2],10)).toString(16).slice(1)+(256|parseInt(i[3],10)).toString(16).slice(1):t.startsWith("#")&&t.length>7&&(t=t.slice(0,7)),t){case"white":case"#fff":case"#ffffff":return"white";case"lime":case"#0f0":case"#00ff00":return"lime";case"cyan":case"#0ff":case"#00ffff":return"cyan";case"red":case"#f00":case"#ff0000":return"red";case"yellow":case"#ff0":case"#ffff00":return"yellow";case"magenta":case"#f0f":case"#ff00ff":return"magenta";case"blue":case"#00f":case"#0000ff":return"blue";case"black":case"#000":case"#000000":return"black"}return null}static getCuesToFlatten(e,t){const i=[];for(const n of e)if(n.isContainer)i.push(...Ke.getCuesToFlatten(n.nestedCues,n));else{const e=n.clone();e.nestedCues=[],e.payload=Ke.flattenPayload_(n,t),i.push(e)}return i}}class Qe{constructor(e,t){this.textTrack_=null;for(const i of Array.from(e.textTracks))i.mode="disabled",i.label==t&&(this.textTrack_=i);this.textTrack_||(this.textTrack_=e.addTextTrack("subtitles",t)),this.textTrack_.mode="hidden"}remove(e,t){return!!this.textTrack_&&(Qe.removeWhere_(this.textTrack_,(i=>i.startTime<t&&i.endTime>e)),!0)}append(e){const t=Ke.getCuesToFlatten(e),i=[],n=this.textTrack_.cues?Array.from(this.textTrack_.cues):[];for(const e of t)if(!n.some((t=>t.startTime==e.startTime&&t.endTime==e.endTime&&t.text==e.payload))){const t=Qe.convertToTextTrackCue_(e);t&&i.push(t)}const s=i.slice().sort(((e,t)=>e.startTime!=t.startTime?e.startTime-t.startTime:e.endTime!=t.endTime?e.endTime-t.startTime:"line"in VTTCue.prototype?i.indexOf(t)-i.indexOf(e):i.indexOf(e)-i.indexOf(t)));for(const e of s)this.textTrack_.addCue(e)}destroy(){if(this.textTrack_){const e=e=>!0;Qe.removeWhere_(this.textTrack_,e),this.textTrack_.mode="disabled"}return this.textTrack_=null,Promise.resolve()}isTextVisible(){return"showing"==this.textTrack_.mode}setTextVisibility(e){this.textTrack_.mode=e?"showing":"hidden"}static convertToTextTrackCue_(e){if(e.startTime>=e.endTime)return Logger.warning("Invalid cue times: "+e.startTime+" - "+e.endTime),null;const t=t,i=new VTTCue(e.startTime,e.endTime,e.payload);i.lineAlign=e.lineAlign,i.positionAlign=e.positionAlign,e.size&&(i.size=e.size);try{i.align=e.textAlign}catch(e){}return"center"==e.textAlign&&"center"!=i.align&&(i.align="middle"),e.writingMode==t.writingMode.VERTICAL_LEFT_TO_RIGHT?i.vertical="lr":e.writingMode==t.writingMode.VERTICAL_RIGHT_TO_LEFT&&(i.vertical="rl"),e.lineInterpretation==t.lineInterpretation.PERCENTAGE&&(i.snapToLines=!1),null!=e.line&&(i.line=e.line),null!=e.position&&(i.position=e.position),i}static removeWhere_(e,t){const i=e.mode,n="showing"==i?"showing":"hidden";e.mode=n,console.assert(e.cues,'Cues should be accessible when mode is set to "'+n+'".');for(const i of Array.from(e.cues))i&&t(i)&&e.removeCue(i);e.mode=i}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}class $e{remove(e,t){}append(e){}destroy(){}isTextVisible(){return!1}setTextVisibility(e){}}class Je{constructor(e,t){console.assert(t,"videoContainer should be valid."),this.isTextVisible_=!1,this.cues_=[],this.video_=e,this.videoContainer_=t,this.aspectRatio_=null,this.textContainer_=ze.createHTMLElement("div"),this.textContainer_.classList.add("shaka-text-container"),this.textContainer_.style.textAlign="center",this.textContainer_.style.display="flex",this.textContainer_.style.flexDirection="column",this.textContainer_.style.alignItems="center",this.textContainer_.style.justifyContent="flex-end",this.videoContainer_.appendChild(this.textContainer_),this.captionsTimer_=new o((()=>{this.updateCaptions_()})).tickEvery(.25),this.currentCuesMap_=new Map,this.eventManager_=new Z,this.eventManager_.listen(document,"fullscreenchange",(()=>{this.updateCaptions_(!0)})),this.eventManager_.listen(this.video_,"resize",(()=>{const e=this.video_,t=e.videoWidth,i=e.videoHeight;this.aspectRatio_=t&&i?t/i:null})),this.resizeObserver_=null,"ResizeObserver"in window&&(this.resizeObserver_=new ResizeObserver((()=>{this.updateCaptions_(!0)})),this.resizeObserver_.observe(this.textContainer_)),this.regionElements_=new Map}append(e){const t=[...this.cues_];for(const i of e)t.some((e=>Ye.equal(e,i)))||this.cues_.push(i);this.updateCaptions_()}destroy(){return this.textContainer_?(this.videoContainer_.removeChild(this.textContainer_),this.textContainer_=null,this.isTextVisible_=!1,this.cues_=[],this.captionsTimer_&&this.captionsTimer_.stop(),this.currentCuesMap_.clear(),this.eventManager_&&(this.eventManager_.release(),this.eventManager_=null),this.resizeObserver_&&(this.resizeObserver_.disconnect(),this.resizeObserver_=null),Promise.resolve()):Promise.resolve()}remove(e,t){if(!this.textContainer_)return!1;const i=this.cues_.length;this.cues_=this.cues_.filter((i=>i.startTime<e||i.endTime>=t));const n=i>this.cues_.length;return this.updateCaptions_(n),!0}isTextVisible(){return this.isTextVisible_}setTextVisibility(e){this.isTextVisible_=e}isElementUnderTextContainer_(e){for(;null!=e;){if(e==this.textContainer_)return!0;e=e.parentElement}return!1}updateCuesRecursive_(e,t,i,n){let s=!1;const a=[],r=[];for(const t of e){n.push(t);let e=this.currentCuesMap_.get(t);const o=t.startTime<=i&&t.endTime>i;let l=e?e.wrapper:null;e&&(a.push(e.cueElement),e.regionElement&&a.push(e.regionElement),o||(s=!0,this.currentCuesMap_.delete(t),e=null)),o&&(r.push(t),e?this.isElementUnderTextContainer_(l)||(s=!0):(this.createCue_(t,n),e=this.currentCuesMap_.get(t),l=e.wrapper,s=!0)),t.nestedCues.length>0&&l&&this.updateCuesRecursive_(t.nestedCues,l,i,n);const d=n.pop();console.assert(d==t,"Parent cues should be kept in order")}if(s){for(const e of a)e.parentElement&&e.parentElement.removeChild(e);r.sort(((e,t)=>e.startTime!=t.startTime?e.startTime-t.startTime:e.endTime-t.endTime));for(const e of r){const i=this.currentCuesMap_.get(e);console.assert(i,"cueRegistry should exist."),i.regionElement?(t.appendChild(i.regionElement),i.regionElement.appendChild(i.cueElement)):t.appendChild(i.cueElement)}}}updateCaptions_(e=!1){if(!this.textContainer_)return;const t=this.video_.currentTime;if(!this.isTextVisible_||e){for(const e of this.regionElements_.values())ze.removeAllChildren(e);ze.removeAllChildren(this.textContainer_),this.currentCuesMap_.clear(),this.regionElements_.clear()}if(this.isTextVisible_){const e=new Map;for(const t of this.currentCuesMap_.keys())e.set(t,this.currentCuesMap_.get(t));this.updateCuesRecursive_(this.cues_,this.textContainer_,t,[]);for(const t of e.keys())if(!this.currentCuesMap_.has(t)){const i=e.get(t).cueElement;console.assert(!i.parentNode,"Cue was not properly removed!")}}}generateRegionId_(e){const t=je.units.PERCENTAGE,i=e.heightUnits==t?"%":"px",n=e.viewportAnchorUnits==t?"%":"px";return`${e.id}_${e.width}x${e.height}${i}-${e.viewportAnchorX}x${e.viewportAnchorY}${n}`}getRegionElement_(e){const t=e.region,i=this.aspectRatio_===4/3?2.5:1.9,n=this.generateRegionId_(t);if(this.regionElements_.has(n))return this.regionElements_.get(n);const s=ze.createHTMLElement("span"),a=je.units.PERCENTAGE,r=t.heightUnits==a?"%":"px",o=t.widthUnits==a?"%":"px",l=t.viewportAnchorUnits==a?"%":"px";s.id="shaka-text-region---"+n,s.classList.add("shaka-text-region"),s.style.position="absolute";const d=je.units.LINES;if(t.heightUnits===d&&t.widthUnits===d?(s.style.height=5.33*t.height+"%",s.style.width=t.width*i+"%"):(s.style.height=t.height+r,s.style.width=t.width+o),t.viewportAnchorUnits===d){let e=t.viewportAnchorY/75*100;const n=this.aspectRatio_===4/3?160:210;let a=t.viewportAnchorX/n*100;e-=t.regionAnchorY*t.height*5.33/100,a-=t.regionAnchorX*t.width*i/100,s.style.top=e+"%",s.style.left=a+"%"}else s.style.top=t.viewportAnchorY-t.regionAnchorY*t.height/100+l,s.style.left=t.viewportAnchorX-t.regionAnchorX*t.width/100+l;return s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",e.displayAlign==Ye.displayAlign.BEFORE?s.style.justifyContent="flex-start":e.displayAlign==Ye.displayAlign.CENTER?s.style.justifyContent="center":s.style.justifyContent="flex-end",this.regionElements_.set(n,s),s}createCue_(e,t){const i=t.length>1;let n=i?"span":"div";e.lineBreak&&(n="br"),e.rubyTag&&(n=e.rubyTag);const s=!i&&e.nestedCues.length>0,a=ze.createHTMLElement(n);"br"!=n&&this.setCaptionStyles_(a,e,t,s);let r=null;e.region&&e.region.id&&(r=this.getRegionElement_(e));let o=a;s&&(o=ze.createHTMLElement("span"),o.classList.add("shaka-text-wrapper"),o.style.backgroundColor=e.backgroundColor,o.style.lineHeight="normal",a.appendChild(o)),this.currentCuesMap_.set(e,{cueElement:a,wrapper:o,regionElement:r})}computeCuePositionAlignment_(e){const t=t,{direction:i,positionAlign:n,textAlign:s}=e;return n!==t.positionAlign.AUTO?n:s===t.textAlign.LEFT||s===t.textAlign.START&&i===t.direction.HORIZONTAL_LEFT_TO_RIGHT||s===t.textAlign.END&&i===t.direction.HORIZONTAL_RIGHT_TO_LEFT?t.positionAlign.LEFT:s===t.textAlign.RIGHT||s===t.textAlign.START&&i===t.direction.HORIZONTAL_RIGHT_TO_LEFT||s===t.textAlign.END&&i===t.direction.HORIZONTAL_LEFT_TO_RIGHT?t.positionAlign.RIGHT:t.positionAlign.CENTER}setCaptionStyles_(e,t,i,n){const s=s,a=e=>Je.inheritProperty_(i,e),r=e.style,o=0==t.nestedCues.length,l=i.length>1;r.whiteSpace="pre-wrap";const d=t.payload.replace(/\s+$/g,(e=>" ".repeat(e.length)));if(r.webkitTextStrokeColor=t.textStrokeColor,r.webkitTextStrokeWidth=t.textStrokeWidth,r.color=t.color,r.direction=t.direction,r.opacity=t.opacity,r.paddingLeft=Je.convertLengthValue_(t.linePadding,t,this.videoContainer_),r.paddingRight=Je.convertLengthValue_(t.linePadding,t,this.videoContainer_),r.textCombineUpright=t.textCombineUpright,r.textShadow=t.textShadow,t.backgroundImage)r.backgroundImage="url('"+t.backgroundImage+"')",r.backgroundRepeat="no-repeat",r.backgroundSize="contain",r.backgroundPosition="center",r.width="100%",r.height="100%";else{let i;if(t.nestedCues.length?i=e:(i=ze.createHTMLElement("span"),e.appendChild(i)),t.border&&(i.style.border=t.border),!n){const e=a((e=>e.backgroundColor));e?i.style.backgroundColor=e:d&&(i.style.backgroundColor="rgba(0, 0, 0, 0.8)");const t=a((e=>e.fontFamily));t&&(i.style.fontFamily=t)}d&&(i.textContent=d)}l&&!i[i.length-1].isContainer?r.display="inline":(r.display="flex",r.flexDirection="column",r.alignItems="center",t.displayAlign==s.displayAlign.BEFORE?r.justifyContent="flex-start":t.displayAlign==s.displayAlign.CENTER?r.justifyContent="center":r.justifyContent="flex-end"),o||(r.margin="0"),r.fontFamily=t.fontFamily,r.fontWeight=t.fontWeight.toString(),r.fontStyle=t.fontStyle,r.letterSpacing=t.letterSpacing,r.fontSize=Je.convertLengthValue_(t.fontSize,t,this.videoContainer_);let c=t.line;if(null!=c){let e=t.lineInterpretation;if(e==s.lineInterpretation.LINE_NUMBER){e=s.lineInterpretation.PERCENTAGE;let t=16;this.aspectRatio_&&this.aspectRatio_<1&&(t=32),c=c<0?100+c/t*100:c/t*100}e==s.lineInterpretation.PERCENTAGE&&(r.position="absolute",t.writingMode==s.writingMode.HORIZONTAL_TOP_TO_BOTTOM?(r.width="100%",t.lineAlign==s.lineAlign.START?r.top=c+"%":t.lineAlign==s.lineAlign.END&&(r.bottom=100-c+"%")):t.writingMode==s.writingMode.VERTICAL_LEFT_TO_RIGHT?(r.height="100%",t.lineAlign==s.lineAlign.START?r.left=c+"%":t.lineAlign==s.lineAlign.END&&(r.right=100-c+"%")):(r.height="100%",t.lineAlign==s.lineAlign.START?r.right=c+"%":t.lineAlign==s.lineAlign.END&&(r.left=100-c+"%")))}r.lineHeight=t.lineHeight,null!=t.position&&(t.writingMode==s.writingMode.HORIZONTAL_TOP_TO_BOTTOM?r.paddingLeft=t.position:r.paddingTop=t.position);const h=this.computeCuePositionAlignment_(t);h==s.positionAlign.LEFT?r.cssFloat="left":h==s.positionAlign.RIGHT&&(r.cssFloat="right"),r.textAlign=t.textAlign,r.textDecoration=t.textDecoration.join(" "),r.writingMode=t.writingMode,"writingMode"in document.documentElement.style&&r.writingMode==t.writingMode||(r.webkitWritingMode=t.writingMode),t.size&&(t.writingMode==s.writingMode.HORIZONTAL_TOP_TO_BOTTOM?r.width=t.size+"%":r.height=t.size+"%")}static getLengthValueInfo_(e){const t=new RegExp(/(\d*\.?\d+)([a-z]+|%+)/).exec(e);return t?{value:Number(t[1]),unit:t[2]}:null}static convertLengthValue_(e,t,i){const n=Je.getLengthValueInfo_(e);if(!n)return e;const{unit:s,value:a}=n;switch(s){case"%":return Je.getAbsoluteLengthInPixels_(a/100,t,i);case"c":return Je.getAbsoluteLengthInPixels_(a,t,i);default:return e}}static getAbsoluteLengthInPixels_(e,t,i){return i.clientHeight*e/t.cellResolution.rows+"px"}static inheritProperty_(e,t){for(let i=e.length-1;i>=0;i--){const n=t(e[i]);if(n||0===n)return n}return null}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}class Ze{static convert(e,t){const i=e=>{let i=e;for(const n of t)n.end&&n.start<e&&(i+=n.end-n.start);const n=Math.floor(i/3600),s=Math.floor(i/60%60),a=Math.floor(i%60),r=Math.floor(1e3*i%1e3);return(n<10?"0":"")+n+":"+(s<10?"0":"")+s+":"+(a<10?"0":"")+a+"."+(r<100?r<10?"00":"0":"")+r},n=Ke.getCuesToFlatten(e);let s="WEBVTT\n\n";for(const e of n){const t=e=>{const t=[],i=i;switch(e.textAlign){case i.textAlign.LEFT:t.push("align:left");break;case i.textAlign.RIGHT:t.push("align:right");break;case i.textAlign.CENTER:t.push("align:middle");break;case i.textAlign.START:t.push("align:start");break;case i.textAlign.END:t.push("align:end")}switch(e.writingMode){case i.writingMode.VERTICAL_LEFT_TO_RIGHT:t.push("vertical:lr");break;case i.writingMode.VERTICAL_RIGHT_TO_LEFT:t.push("vertical:rl")}return t.length?" "+t.join(" "):""};s+=i(e.startTime)+" --\x3e "+i(e.endTime)+t(e)+"\n",s+=e.payload+"\n\n"}return s}}class et{constructor(){this.acquiredIdentifier=null,this.unlockQueue=[]}async acquire(e){i.v2(e+" has requested mutex"),this.acquiredIdentifier&&await new Promise((e=>this.unlockQueue.push(e))),this.acquiredIdentifier=e,i.v2(e+" has acquired mutex")}release(){i.v2(this.acquiredIdentifier+" has released mutex"),this.unlockQueue.length>0?this.unlockQueue.shift()():this.acquiredIdentifier=null}releaseAll(){for(;this.acquiredIdentifier;)this.release()}static get[Symbol.for("___CTOR_ARGS___")](){return[]}}class tt{static parseXml(e,t){const i=L.fromBytesAutoDetect(e);return tt.parseXmlString(i,t)}static parseXmlString(e,t){const n=tt.parse(e);if(!t&&n.length)return n[0];const s=n.find((e=>this.isNode(e)&&e.tagName===t));return s||(i.error("parseXml root element not found!"),null)}static getKnownNameSpace(e){var t;return tt.knownNameSpaces_.has(e)&&null!==(t=tt.knownNameSpaces_.get(e))&&void 0!==t?t:""}static setKnownNameSpace(e,t){tt.knownNameSpaces_.set(e,t)}static parse(e){let t=0;const i="<".charCodeAt(0),n=">".charCodeAt(0),s="-".charCodeAt(0),a="/".charCodeAt(0),r="!".charCodeAt(0),o="'".charCodeAt(0),l='"'.charCodeAt(0),d="[".charCodeAt(0);function c(o,l=!1){const c=[];for(;e[t];)if(e.charCodeAt(t)==i){if(e.charCodeAt(t+1)===a){const i=t+2;t=e.indexOf(">",t);const n=e.substring(i,t);let s=n.indexOf(o);if(-1==s){const e=o.indexOf(".");if(e>0){const t=o.substring(0,e);s=n.indexOf(t)}}if(-1==s){const i=e.substring(0,t).split("\n");throw new Error("Unexpected close tag\nLine: "+(i.length-1)+"\nColumn: "+(i[i.length-1].length+1)+"\nChar: "+e[t])}return t+1&&(t+=1),c}if(e.charCodeAt(t+1)===r){if(e.charCodeAt(t+2)==s){for(;-1!==t&&(e.charCodeAt(t)!==n||e.charCodeAt(t-1)!=s||e.charCodeAt(t-2)!=s||-1==t);)t=e.indexOf(">",t+1);-1===t&&(t=e.length)}else if(e.charCodeAt(t+2)===d&&e.charCodeAt(t+8)===d&&"cdata"===e.substr(t+3,5).toLowerCase()){const i=e.indexOf("]]>",t);-1==i?(c.push(e.substr(t+9)),t=e.length):(c.push(e.substring(t+9,i)),t=i+3);continue}++t;continue}const i=_(l);if(c.push(i),"string"==typeof i)return c;"?"===i.tagName[0]&&i.children&&(c.push(...i.children),i.children=[])}else{const e=h();l?e.length>0&&c.push(e):(c.length&&1==e.length&&"\n"==e[0]||e.trim().length>0)&&c.push(e),++t}return c}function h(){const i=t;return t=e.indexOf("<",t)-1,-2===t&&(t=e.length),e.slice(i,t+1)}function u(){const i=t;for(;-1==="\r\n\t>/= ".indexOf(e[t])&&e[t];)++t;return e.slice(i,t)}function _(i){t++;const s=u(),r={};let d=[];for(;e.charCodeAt(t)!==n&&e[t];){const a=e.charCodeAt(t);if(a>64&&a<91||a>96&&a<123){const a=u();let c=e.charCodeAt(t);for(;c&&c!==o&&c!==l&&!(c>64&&c<91||c>96&&c<123)&&c!==n;)t++,c=e.charCodeAt(t);let h=m();if(c===o||c===l){if(-1===t){const e={tagName:s,attributes:r,children:d,parent:null};for(let t=0;t<d.length;++t){const i=d[t];"string"!=typeof i&&(i.parent=e)}return e}}else h=null,--t;if(a.startsWith("xmlns:")){const e=a.split(":");tt.setKnownNameSpace(null!=h?h:"",e[1])}"tt"===s&&"xml:space"===a&&"preserve"===h&&(i=!0),r[a]=null!=h?h:""}++t}e.charCodeAt(t-1)!==a?(++t,d=c(s,i)):++t;const h={tagName:s,attributes:r,children:d,parent:null},_=d.length;for(let e=0;e<_;e++){const t=d[e];"string"!=typeof t?t.parent=h:e==_-1&&"\n"==t&&d.pop()}return h}function m(){const i=e[t],n=t+1;return t=e.indexOf(i,n),e.slice(n,t)}return c("")}static isNode(e){return Boolean(e&&e.tagName&&e.tagName)}static isText(e){return"string"==typeof e}static getChildNodes(e){const t=[];if(!e.children)return[];for(const i of e.children)"string"!=typeof i&&t.push(i);return t}static findChildren(e,t){const i=[];if(!e.children)return[];for(const n of e.children)this.isNode(n)&&n.tagName===t&&i.push(n);return i}static getTextContents(e){if("string"==typeof e)return L.htmlUnescape(e);const t=e.children.reduce(((e,t)=>"string"==typeof t?e+t:e),"");return""===t?null:L.htmlUnescape(t)}static getContents(e){if(!Array.from(e.children).every((e=>"string"==typeof e)))return null;let t=tt.getTextContents(e);return t&&(t=t.trim()),t}static getElementsByTagName(e,t,i=[]){if(e.tagName===t&&i.push(e),e.children)for(const n of e.children)this.isNode(n)&&tt.getElementsByTagName(n,t,i);return i}static findChild(e,t){const i=tt.findChildren(e,t);return 1!=i.length?null:i[0]}static findChildNS(e,t,i){const n=tt.findChildrenNS(e,t,i);return 1!=n.length?null:n[0]}static parseAttr(e,t,i,n=null){let s=null;const a=e.attributes[t];return null!=a&&(s=i(a)),null==s?n:s}static parseAttrWithDefaultValue(e,t,i,n){let s=this.parseAttr(e,t,i);return null!=s?s:n}static getAttributeNS(e,t,i){const n=tt.getKnownNameSpace(t);return e.attributes[`${n}:${i}`]||null}static findChildrenNS(e,t,i){const n=tt.getKnownNameSpace(t),s=[];if(e.children)for(const t of e.children)t&&this.isNode(t)&&t.tagName===`${n}:${i}`&&s.push(t);return s}static getAttributeNSList(e,t,i){for(const n of t){const t=tt.getAttributeNS(e,n,i);if(t)return t}return null}static parseDate(e){if(!e)return null;/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(e)&&(e+="Z");const t=Date.parse(e);return isNaN(t)?null:t/1e3}static parseDuration(e){if(!e)return null;const t=new RegExp("^P(?:([0-9]*)Y)?(?:([0-9]*)M)?(?:([0-9]*)D)?(?:T(?:([0-9]*)H)?(?:([0-9]*)M)?(?:([0-9.]*)S)?)?$").exec(e);if(!t)return i.warning("Invalid duration string:",e),null;const n=31536e3*Number(t[1]||null)+2592e3*Number(t[2]||null)+86400*Number(t[3]||null)+3600*Number(t[4]||null)+60*Number(t[5]||null)+Number(t[6]||null);return isFinite(n)?n:null}static parseRange(e){const t=/([0-9]+)-([0-9]+)/.exec(e);if(!t)return null;const i=Number(t[1]);if(!isFinite(i))return null;const n=Number(t[2]);return isFinite(n)?{start:i,end:n}:null}static parseInt(e){const t=Number(e);return t%1==0?t:null}static parsePositiveInt(e){const t=Number(e);return t%1==0&&t>0?t:null}static parseNonNegativeInt(e){const t=Number(e);return t%1==0&&t>=0?t:null}static parseFloat(e){const t=Number(e);return isNaN(t)?null:t}static parseBoolean(e){return!!e&&"true"===e.toLowerCase()}static evalDivision(e){let t,i;return i=(t=e.match(/^(\d+)\/(\d+)$/))?Number(t[1])/Number(t[2]):Number(e),isNaN(i)?null:i}}tt.knownNameSpaces_=new Map([]);class it{static fillUriTemplate(e,t,n,s,a,r){const o={RepresentationID:t,Number:n,SubNumber:s,Bandwidth:a,Time:r};return e.replace(/\$(RepresentationID|Number|SubNumber|Bandwidth|Time)?(?:%0([0-9]+)([diouxX]))?\$/g,((t,n,s,a)=>{if("$$"==t)return"$";let r,l=o[n];if(console.assert(void 0!==l,"Unrecognized identifier"),null==l)return i.warning("URL template does not have an available substitution for ",'identifier "'+n+'":',e),t;switch("RepresentationID"==n&&s&&(i.warning("URL template should not contain a width specifier for identifier",'"RepresentationID":',e),s=void 0),"Time"==n&&"bigint"!=typeof l&&(console.assert("number"==typeof l,"Time value should be a number or bigint!"),"number"==typeof l&&(Math.abs(l-Math.round(l))>=.2&&i.alwaysWarn("Calculated $Time$ values must be close to integers"),l=Math.round(l))),a){case void 0:case"d":case"i":case"u":r=l.toString();break;case"o":r=l.toString(8);break;case"x":r=l.toString(16);break;case"X":r=l.toString(16).toUpperCase();break;default:console.assert(!1,"Unhandled format specifier"),r=l.toString()}const d=window.parseInt(s,10)||1,c=Math.max(0,d-r.length);return new Array(c+1).join("0")+r}))}static createTimeline(e,t,n,s,a){console.assert(t>0&&t<1/0,"timescale must be a positive, finite integer"),console.assert(s>0,"period duration must be a positive integer");const r=tt.findChildren(e,"S"),o=[];let l=-n;for(let e=0;e<r.length;++e){const d=r[e],c=r[e+1];let h=tt.parseAttr(d,"t",tt.parseNonNegativeInt);const u=tt.parseAttr(d,"d",tt.parseNonNegativeInt),_=tt.parseAttr(d,"r",tt.parseInt),m=tt.parseAttr(d,"k",tt.parseInt)||0;if(null!=h&&(h-=n),!u)return i.warning('"S" element must have a duration:','ignoring the remaining "S" elements.',d),o;let g=null!=h?h:l,f=_||0;if(f<0)if(c){const e=tt.parseAttr(c,"t",tt.parseNonNegativeInt);if(null==e)return i.warning('An "S" element cannot have a negative repeat','if the next "S" element does not have a valid start time:','ignoring the remaining "S" elements.',d),o;if(g>=e)return i.warning('An "S" element cannot have a negative repeatif its start ','time exceeds the next "S" element\'s start time:','ignoring the remaining "S" elements.',d),o;f=Math.ceil((e-g)/u)-1}else{if(s==1/0)return i.warning('The last "S" element cannot have a negative repeat',"if the Period has an infinite duration:",'ignoring the last "S" element.',d),o;if(g/t>=s)return i.warning('The last "S" element cannot have a negative repeat',"if its start time exceeds the Period's duration:",'igoring the last "S" element.',d),o;f=Math.ceil((s*t-g)/u)-1}if(o.length>0&&g!=l){const e=g-l;Math.abs(e/t)>=k.GAP_OVERLAP_TOLERANCE_SECONDS&&i.warning("SegmentTimeline contains a large gap/overlap:","the content may have errors in it.",d),o[o.length-1].end=g/t}for(let e=0;e<=f;++e){const e=g+u,i={start:g/t,end:e/t,unscaledStart:g,partialSegments:m,segmentPosition:o.length+a};o.push(i),g=e,l=e}}return o}static parseSegmentInfo(e,t){console.assert(t(e.representation),"There must be at least one element of the given type.");const i=it.inheritAttribute(e,t,"timescale");let n=1;i&&(n=tt.parsePositiveInt(i)||1);const s=it.inheritAttribute(e,t,"duration");let a=tt.parsePositiveInt(s||"");const r=k.ContentType;e.representation.contentType==r.IMAGE&&(a=tt.parseFloat(s||"")),a&&(a/=n);const o=it.inheritAttribute(e,t,"startNumber"),l=Number(it.inheritAttribute(e,t,"presentationTimeOffset"))||0;let d=tt.parseNonNegativeInt(o||"");null!=o&&null!=d||(d=1);const c=it.inheritChild(e,t,"SegmentTimeline");let h=[];return c&&(h=it.createTimeline(c,n,l,e.periodInfo.duration||1/0,d)),{timescale:n,segmentDuration:a,startNumber:d,scaledPresentationTimeOffset:l/n||0,unscaledPresentationTimeOffset:l,timeline:h}}static getNodes(e,t){return console.assert(t(e.representation),"There must be at least one element of the given type"),[t(e.representation),t(e.adaptationSet),t(e.period)].filter(F.isNotNull)}static inheritAttribute(e,t,i){const n=it.getNodes(e,t);let s=null;for(const e of n)if(s=e.attributes[i],s)break;return s}static inheritChild(e,t,i){const n=it.getNodes(e,t);let s=null;for(const e of n)if(s=tt.findChild(e,i),s)break;return s}static handleXlinkInElement_(e,t,i,n,s,a){const r=it.XlinkNamespaceUri_,o=tt.getAttributeNS(e,r,"href"),l=tt.getAttributeNS(e,r,"actuate")||"onRequest";for(const t of Object.keys(e.attributes)){const i=t.split(":"),n=tt.getKnownNameSpace(r);i[0]==n&&delete e.attributes[t]}if(a>=5)return w.failed(new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_XLINK_DEPTH_LIMIT));if("onLoad"!=l)return w.failed(new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_UNSUPPORTED_XLINK_ACTUATE));const d=k.resolveUris([n],[null!=o?o:""]),c=O.RequestType.MANIFEST,h=O.makeRequest(d,t),u=s.request(c,h);return console.assert(u instanceof w,"Unexpected implementation of IAbortableOperation!"),u.chain((n=>{const r=tt.parseXml(n.data,e.tagName);if(!r||!tt.isNode(r))return w.failed(new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_INVALID_XML,o));for(e.children=[];r.children.length;){const t=r.children.shift();t&&(tt.isNode(t)&&(t.parent=e),e.children.push(t))}for(const t of Object.keys(r.attributes))e.attributes[t]=r.attributes[t];return it.processXlinks(e,t,i,d[0],s,a+1)}))}static processXlinks(e,t,i,n,s,a=0){const r=it.XlinkNamespaceUri_;if(tt.getAttributeNS(e,r,"href")){let r=it.handleXlinkInElement_(e,t,i,n,s,a);return i&&(r=r.chain(void 0,(r=>it.processXlinks(e,t,i,n,s,a)))),r}const o=[];for(const l of tt.getChildNodes(e)){const d="urn:mpeg:dash:resolve-to-zero:2013";tt.getAttributeNS(l,r,"href")==d?e.children=e.children.filter((e=>e!==l)):"SegmentTimeline"!=l.tagName&&o.push(it.processXlinks(l,t,i,n,s,a))}return w.all(o).chain((()=>e))}}it.XlinkNamespaceUri_="http://www.w3.org/1999/xlink";let nt=class e{static parse(t,n,s,a,r,o,l){let d;const c=(new oe).fullBox("sidx",(t=>{d=e.parseSIDX_(n,a,r,o,l,s,t)}));if(t&&c.parse(t),d)return d;throw i.error('Invalid box type, expected "sidx".'),new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.MP4_SIDX_WRONG_BOX_TYPE)}static parseSIDX_(e,t,n,s,a,r,o){console.assert(null!=o.version,"SIDX is a full box and should have a valid version.");const l=[];o.reader.skip(4);const d=o.reader.readUint32();if(0==d)throw i.error("Invalid timescale."),new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.MP4_SIDX_INVALID_TIMESCALE);let c,h;0==o.version?(c=o.reader.readUint32(),h=o.reader.readUint32()):(c=o.reader.readUint64(),h=o.reader.readUint64()),o.reader.skip(2);const u=o.reader.readUint16();let _=c,m=e+o.size+h;for(let e=0;e<u;e++){const e=o.reader.readUint32(),c=(2147483648&e)>>>31,h=2147483647&e,u=o.reader.readUint32();if(o.reader.skip(4),1==c)throw i.error("Heirarchical SIDXs are not supported."),new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.MP4_SIDX_TYPE_NOT_SUPPORTED);const g=_/d,f=(_+u)/d;l.push(new ye(g+n,f+n,(()=>r),m,m+h-1,t,n,s,a)),_+=u,m+=h}return o.parser.stop(),l}};class st{constructor(e){this.dataView_=l.toDataView(e),this.reader_=new re(this.dataView_,re.Endianness.BIG_ENDIAN)}hasMoreData(){return this.reader_.hasMoreData()}parseElement(){const e=this.parseId_(),t=this.parseVint_();let i;i=st.isDynamicSizeValue_(t)?this.dataView_.byteLength-this.reader_.getPosition():st.getVintValue_(t);const n=this.reader_.getPosition()+i<=this.dataView_.byteLength?i:this.dataView_.byteLength-this.reader_.getPosition(),s=l.toDataView(this.dataView_,this.reader_.getPosition(),n);return this.reader_.skip(n),new at(e,s)}parseId_(){const e=this.parseVint_();if(e.length>7)throw new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.EBML_OVERFLOW);let t=0;for(const i of e)t=256*t+i;return t}parseVint_(){const e=this.reader_.getPosition(),t=this.reader_.readUint8();if(0==t)throw new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.EBML_OVERFLOW);const i=8-Math.floor(Math.log2(t));return console.assert(i<=8&&i>=1,"Incorrect log2 value"),this.reader_.skip(i-1),l.toUint8(this.dataView_,e,i)}static getVintValue_(e){if(8==e.length&&224&e[1])throw new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.JS_INTEGER_OVERFLOW);let t=0;for(let i=0;i<e.length;i++){const n=e[i];t=0==i?n&(1<<8-e.length)-1:256*t+n}return t}static isDynamicSizeValue_(e){for(const t of st.DYNAMIC_SIZES)if(l.equal(e,new Uint8Array(t)))return!0;return!1}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0]}}st.DYNAMIC_SIZES=[[255],[127,255],[63,255,255],[31,255,255,255],[15,255,255,255,255],[7,255,255,255,255,255],[3,255,255,255,255,255,255],[1,255,255,255,255,255,255,255]];class at{constructor(e,t){this.id=e,this.dataView_=t}getOffset(){return this.dataView_.byteOffset}createParser(){return new st(this.dataView_)}getUint(){if(this.dataView_.byteLength>8)throw new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.EBML_OVERFLOW);if(8==this.dataView_.byteLength&&224&this.dataView_.getUint8(0))throw new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.JS_INTEGER_OVERFLOW);let e=0;for(let t=0;t<this.dataView_.byteLength;t++)e=256*e+this.dataView_.getUint8(t);return e}getFloat(){if(4==this.dataView_.byteLength)return this.dataView_.getFloat32(0);if(8==this.dataView_.byteLength)return this.dataView_.getFloat64(0);throw new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.EBML_BAD_FLOATING_POINT_SIZE)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}let rt=class e{static parse(t,n,s,a,r,o,l){const d=e.parseWebmContainer_(n),c=new st(t).parseElement();if(c.id!=e.CUES_ID)throw i.error("Not a Cues element."),new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.WEBM_CUES_ELEMENT_MISSING);return e.parseCues_(c,d.segmentOffset,d.timecodeScale,d.duration,s,a,r,o,l)}static parseWebmContainer_(t){const n=new st(t);if(n.parseElement().id!=e.EBML_ID)throw i.error("Not an EBML element."),new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.WEBM_EBML_HEADER_ELEMENT_MISSING);const s=n.parseElement();if(s.id!=e.SEGMENT_ID)throw i.error("Not a Segment element."),new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.WEBM_SEGMENT_ELEMENT_MISSING);const a=s.getOffset(),r=e.parseSegment_(s);return{segmentOffset:a,timecodeScale:r.timecodeScale,duration:r.duration}}static parseSegment_(t){const n=t.createParser();let s=null;for(;n.hasMoreData();){const t=n.parseElement();if(t.id==e.INFO_ID){s=t;break}}if(!s)throw i.error("Not an Info element."),new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.WEBM_INFO_ELEMENT_MISSING);return e.parseInfo_(s)}static parseInfo_(t){const i=t.createParser();let n=1e6,s=null;for(;i.hasMoreData();){const t=i.parseElement();t.id==e.TIMECODE_SCALE_ID?n=t.getUint():t.id==e.DURATION_ID&&(s=t.getFloat())}if(null==s)throw new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.WEBM_DURATION_ELEMENT_MISSING);const a=n/1e9;return{timecodeScale:a,duration:s*a}}static parseCues_(t,i,n,s,a,r,o,l,d){const c=[],h=()=>a,u=t.createParser();let _=null,m=null;for(;u.hasMoreData();){const t=u.parseElement();if(t.id!=e.CUE_POINT_ID)continue;const s=e.parseCuePoint_(t);if(!s)continue;const a=n*s.unscaledTime,g=i+s.relativeOffset;null!=_&&(console.assert(null!=m,"last offset cannot be null"),c.push(new ye(_+o,a+o,h,m,g-1,r,o,l,d))),_=a,m=g}return null!=_&&(console.assert(null!=m,"last offset cannot be null"),c.push(new ye(_+o,s+o,h,m,null,r,o,l,d))),c}static parseCuePoint_(t){const n=t.createParser(),s=n.parseElement();if(s.id!=e.CUE_TIME_ID)throw i.warning("Not a CueTime element."),new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.WEBM_CUE_TIME_ELEMENT_MISSING);const a=s.getUint(),r=n.parseElement();if(r.id!=e.CUE_TRACK_POSITIONS_ID)throw i.warning("Not a CueTrackPositions element."),new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING);const o=r.createParser();let l=0;for(;o.hasMoreData();){const t=o.parseElement();if(t.id==e.CUE_CLUSTER_POSITION){l=t.getUint();break}}return{unscaledTime:a,relativeOffset:l}}};rt.EBML_ID=440786851,rt.SEGMENT_ID=408125543,rt.INFO_ID=357149030,rt.TIMECODE_SCALE_ID=2807729,rt.DURATION_ID=17545,rt.CUES_ID=475249515,rt.CUE_POINT_ID=187,rt.CUE_TIME_ID=179,rt.CUE_TRACK_POSITIONS_ID=183,rt.CUE_CLUSTER_POSITION=241;class ot{static createInitSegment(e,t){if(null==e.representation)return null;const i=it.inheritChild(e,t,"Initialization");if(!i)return null;let n=e.representation.getBaseUris();const s=i.attributes.sourceURL;s&&(n=k.resolveUris(n,[L.htmlUnescape(s)]));let a=0,r=null;const o=tt.parseAttr(i,"range",tt.parseRange);o&&(a=o.start,r=o.end);const l=ot.createQualityInfo(e);return new Se((()=>n),a,r,l,null,null)}static createStreamInfo(e,t){if(null==e.representation)return null;console.assert(e.representation.segmentBase,"Should only be called with SegmentBase");const i=Number(it.inheritAttribute(e,ot.fromInheritance_,"presentationTimeOffset"))||0,n=it.inheritAttribute(e,ot.fromInheritance_,"timescale");let s=1;n&&(s=tt.parsePositiveInt(n)||1);const a=i/s||0,r=ot.createInitSegment(e,ot.fromInheritance_);ot.checkSegmentIndexRangeSupport_(e,r);const o=b.shallowCloneObject(e);return{generateSegmentIndex:()=>ot.generateSegmentIndex_(o,t,r,a)}}static async generateSegmentIndexFromUris(e,t,i,n,s,a,r){var o,l,d,c,h,u,_;const m=e.presentationTimeline,g=!e.dynamic||!(null===(o=e.periodInfo)||void 0===o?void 0:o.isLastPeriod),f=null!==(d=null===(l=e.periodInfo)||void 0===l?void 0:l.start)&&void 0!==d?d:0,p=null!==(h=null===(c=e.periodInfo)||void 0===c?void 0:c.duration)&&void 0!==h?h:0,T=null!==(_=null===(u=e.representation)||void 0===u?void 0:u.mimeType.split("/")[1])&&void 0!==_?_:"";let S=t,y=null;const E=[S(n,s,a,!1),"webm"==T&&i?S(i.getUris(),i.startByte,i.endByte,!0):null];S=null;const v=await Promise.all(E),I=v[0],A=v[1]||null;let b;const C=f-r,w=f,M=p?f+p:1/0;return"mp4"==T?b=nt.parse(I,s,n,i,C,w,M):(console.assert(A,"WebM requires init data"),b=rt.parse(I,A,n,i,C,w,M)),m.notifySegments(b),console.assert(!y,"Should not call generateSegmentIndex twice"),y=new Ee(b),g&&y.fit(w,M,!0),y}static fromInheritance_(e){var t;return null!==(t=null==e?void 0:e.segmentBase)&&void 0!==t?t:null}static computeIndexRange_(e){const t=it.inheritChild(e,ot.fromInheritance_,"RepresentationIndex"),i=it.inheritAttribute(e,ot.fromInheritance_,"indexRange");let n=tt.parseRange(i||"");return t&&(n=tt.parseAttr(t,"range",tt.parseRange,n)),n}static computeIndexUris_(e){var t,i;const n=it.inheritChild(e,ot.fromInheritance_,"RepresentationIndex");let s=null!==(i=null===(t=e.representation)||void 0===t?void 0:t.getBaseUris())&&void 0!==i?i:[];if(n){const e=L.htmlUnescape(n.attributes.sourceURL);e&&(s=k.resolveUris(s,[e]))}return s}static checkSegmentIndexRangeSupport_(e,t){if(ot.checkSegmentIndexSupport(e,t),!ot.computeIndexRange_(e))throw i.error("SegmentBase does not contain sufficient segment information:","the SegmentBase does not contain @indexRange","or a RepresentationIndex element.",e.representation),new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_NO_SEGMENT_INFO)}static checkSegmentIndexSupport(e,t){var n,s,a,r;const o=null!==(s=null===(n=e.representation)||void 0===n?void 0:n.contentType)&&void 0!==s?s:f.UNKNOWN,l=null!==(r=null===(a=e.representation)||void 0===a?void 0:a.mimeType.split("/")[1])&&void 0!==r?r:"";if(o!=k.ContentType.TEXT&&"mp4"!=l&&"webm"!=l)throw i.error("SegmentBase specifies an unsupported container type.",e.representation),new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_UNSUPPORTED_CONTAINER);if("webm"==l&&!t)throw i.error("SegmentBase does not contain sufficient segment information:","the SegmentBase uses a WebM container,","but does not contain an Initialization element.",e.representation),new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_WEBM_MISSING_INIT)}static generateSegmentIndex_(e,t,i,n){const s=ot.computeIndexUris_(e),a=ot.computeIndexRange_(e);if(console.assert(a,"Index range should not be null!"),null==a)throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_EMPTY_INDEX_RANGE);return ot.generateSegmentIndexFromUris(e,t,i,s,a.start,a.end,n)}static createQualityInfo(e){var t,i,n,s,a,r,o,l,d;const c=e.representation;return{bandwidth:e.bandwidth,audioSamplingRate:null!==(t=null==c?void 0:c.audioSamplingRate)&&void 0!==t?t:null,codecs:null!==(i=null==c?void 0:c.codecs)&&void 0!==i?i:"",contentType:null!==(n=null==c?void 0:c.contentType)&&void 0!==n?n:f.UNKNOWN,frameRate:null!==(s=null==c?void 0:c.frameRate)&&void 0!==s?s:null,height:null!==(a=null==c?void 0:c.height)&&void 0!==a?a:null,mimeType:null!==(r=null==c?void 0:c.mimeType)&&void 0!==r?r:null,channelsCount:null!==(o=null==c?void 0:c.numChannels)&&void 0!==o?o:null,pixelAspectRatio:null!==(l=null==c?void 0:c.pixelAspectRatio)&&void 0!==l?l:null,width:null!==(d=null==c?void 0:c.width)&&void 0!==d?d:null}}}class lt{static createStreamInfo(e,t){if(null==e.representation||null==e.periodInfo)return null;console.assert(e.representation.segmentList,"Should only be called with SegmentList");const i=ot.createInitSegment(e,lt.fromInheritance_),n=lt.parseSegmentListInfo_(e);lt.checkSegmentListInfo_(e,n);let s=null,a=null;e.period&&e.period.id&&e.representation.id&&(a=t[e.period.id+","+e.representation.id],a&&(s=a.segmentIndex));const r=lt.createSegmentReferences_(e.periodInfo.start,e.periodInfo.duration,n.startNumber,e.representation.getBaseUris,n,i),o=!s;if(s){const t=e.presentationTimeline.getSegmentAvailabilityStart();s.mergeAndEvict(r,t)}else s=new Ee(r);if(e.presentationTimeline.notifySegments(r),!e.dynamic||!e.periodInfo.isLastPeriod){const t=e.periodInfo.start,i=e.periodInfo.duration?e.periodInfo.start+e.periodInfo.duration:1/0;s.fit(t,i,o)}return a&&(a.segmentIndex=s),{generateSegmentIndex:()=>(s&&!s.isEmpty()||s.merge(r),Promise.resolve(s))}}static fromInheritance_(e){var t;return null!==(t=null==e?void 0:e.segmentList)&&void 0!==t?t:null}static parseSegmentListInfo_(e){const t=lt.parseMediaSegments_(e),n=it.parseSegmentInfo(e,lt.fromInheritance_);let s=n.startNumber;0==s&&(i.warning("SegmentList@startNumber must be > 0"),s=1);let a=0;return n.segmentDuration?a=n.segmentDuration*(s-1):n.timeline&&n.timeline.length>0&&(a=n.timeline[0].start),{segmentDuration:n.segmentDuration,startTime:a,startNumber:s,scaledPresentationTimeOffset:n.scaledPresentationTimeOffset,timeline:n.timeline,mediaSegments:t}}static checkSegmentListInfo_(e,t){if(!t.segmentDuration&&!t.timeline&&t.mediaSegments.length>1)throw i.warning("SegmentList does not contain sufficient segment information:","the SegmentList specifies multiple segments,","but does not specify a segment duration or timeline.",e.representation),new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_NO_SEGMENT_INFO);const n=e.periodInfo,s=null==n?void 0:n.duration;if(!t.segmentDuration&&!s&&!t.timeline&&1==t.mediaSegments.length)throw i.warning("SegmentList does not contain sufficient segment information:","the SegmentList specifies one segment,","but does not specify a segment duration, period duration,","or timeline.",e.representation),new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_NO_SEGMENT_INFO);if(t.timeline&&0==t.timeline.length)throw i.warning("SegmentList does not contain sufficient segment information:","the SegmentList has an empty timeline.",e.representation),new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_NO_SEGMENT_INFO)}static createSegmentReferences_(e,t,n,s,a,r){let o=a.mediaSegments.length;a.timeline&&a.timeline.length!=a.mediaSegments.length&&(o=Math.min(a.timeline.length,a.mediaSegments.length),i.warning("The number of items in the segment timeline and the number of ","segment URLs do not match, truncating",a.mediaSegments.length,"to",o));const l=e-a.scaledPresentationTimeOffset,d=e,c=t?e+t:1/0,h=[];let u=a.startTime;for(let i=0;i<o;i++){const n=a.mediaSegments[i],o=u;let _;null!=a.segmentDuration?_=o+a.segmentDuration:a.timeline?_=a.timeline[i].end:(console.assert(1==a.mediaSegments.length&&t,"There should be exactly one segment with a Period duration."),_=o+(null!=t?t:0));let m=null;const g=()=>(null==m&&(m=k.resolveUris(s(),[n.mediaUri])),m);h.push(new ye(e+o,e+_,g,n.start,n.end,r,l,d,c,[],"",null,null,ye.Status.AVAILABLE)),u=_}return h}static parseMediaSegments_(e){var t,n,s;return[null===(t=e.representation)||void 0===t?void 0:t.segmentList,null===(n=e.adaptationSet)||void 0===n?void 0:n.segmentList,null===(s=e.period)||void 0===s?void 0:s.segmentList].filter(F.isNotNull).map((e=>tt.findChildren(e,"SegmentURL"))).reduce(((e,t)=>e.length>0?e:t)).map((t=>{t.attributes.indexRange&&!e.indexRangeWarningGiven&&(e.indexRangeWarningGiven=!0,i.warning("We do not support the SegmentURL@indexRange attribute on SegmentList. We only use the SegmentList@duration attribute or SegmentTimeline, which must be accurate."));const n=L.htmlUnescape(t.attributes.media),s=tt.parseAttrWithDefaultValue(t,"mediaRange",tt.parseRange,{start:0,end:null});return{mediaUri:n,start:s.start,end:s.end}}))}}class dt{static createStreamInfo(e,t,n,s,a,r){var o,l,d;if(!e.representation||!e.periodInfo)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.NOT_CONFIGURED);console.assert(e.representation.segmentTemplate,"Should only be called with SegmentTemplate");const c=dt.createInitSegment_(e),h=dt.parseSegmentTemplateInfo_(e);dt.checkSegmentTemplateInfo_(e,h);const u=b.shallowCloneObject(e);if(h.indexTemplate)return ot.checkSegmentIndexSupport(e,c),{generateSegmentIndex:()=>dt.generateSegmentIndexFromIndexTemplate_(u,t,c,h)};if(h.segmentDuration)return s||"image"===(null===(o=e.adaptationSet)||void 0===o?void 0:o.contentType)||(e.presentationTimeline.notifyMaxSegmentDuration(h.segmentDuration),e.presentationTimeline.notifyMinSegmentStartTime(e.periodInfo.start)),{generateSegmentIndex:()=>dt.generateSegmentIndexFromDuration_(u,h,a,c,r)};{let t=null,s=null,a=null;(null===(l=e.period)||void 0===l?void 0:l.id)&&e.representation.id&&(s=e.period.id+","+e.representation.id,a=n[s],a&&(t=a.segmentIndex));const r=e.periodInfo.start,o=e.periodInfo.duration?r+e.periodInfo.duration:1/0;i.debug(`New manifest ${r} - ${o}`);const u=!(e.dynamic&&e.periodInfo.isLastPeriod);if(t){const i=t;i.appendTemplateInfo(h,r,o,u,c);const n=e.presentationTimeline.getSegmentAvailabilityStart();i.evict(n)}else i.debug(`Creating TSI with end ${o}`),t=new ct(h,e.representation.id,e.bandwidth,e.representation.getBaseUris,r,o,c,u,e.representation.segmentSequenceCadence);if(h.timeline&&"image"!==(null===(d=e.adaptationSet)||void 0===d?void 0:d.contentType)){const t=h.timeline;e.presentationTimeline.notifyTimeRange(t,r)}return a&&e.dynamic&&(a.segmentIndex=t),{generateSegmentIndex:()=>(t instanceof ct&&t.isEmpty()&&t.appendTemplateInfo(h,r,o,u,c),Promise.resolve(t))}}}static fromInheritance_(e){var t;return null!==(t=null==e?void 0:e.segmentTemplate)&&void 0!==t?t:null}static parseSegmentTemplateInfo_(e){const t=it.parseSegmentInfo(e,dt.fromInheritance_),i=it.inheritAttribute(e,dt.fromInheritance_,"media"),n=it.inheritAttribute(e,dt.fromInheritance_,"index");return{segmentDuration:t.segmentDuration,timescale:t.timescale,startNumber:t.startNumber,scaledPresentationTimeOffset:t.scaledPresentationTimeOffset,unscaledPresentationTimeOffset:t.unscaledPresentationTimeOffset,timeline:t.timeline,mediaTemplate:i&&L.htmlUnescape(i),indexTemplate:n}}static checkSegmentTemplateInfo_(e,t){let n=0;if(n+=t.indexTemplate?1:0,n+=t.timeline?1:0,n+=t.segmentDuration?1:0,0==n)throw i.error("SegmentTemplate does not contain any segment information:","the SegmentTemplate must contain either an index URL template","a SegmentTimeline, or a segment duration.",e.representation),new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_NO_SEGMENT_INFO);if(1!=n&&(i.warning("SegmentTemplate containes multiple segment information sources:","the SegmentTemplate should only contain an index URL template,","a SegmentTimeline or a segment duration.",e.representation),t.indexTemplate?(i.info("Using the index URL template by default."),t.timeline=null,t.segmentDuration=null):(console.assert(t.timeline,"There should be a timeline"),i.info("Using the SegmentTimeline by default."),t.segmentDuration=null)),!t.indexTemplate&&!t.mediaTemplate)throw i.error("SegmentTemplate does not contain sufficient segment information:","the SegmentTemplate's media URL template is missing.",e.representation),new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_NO_SEGMENT_INFO)}static generateSegmentIndexFromIndexTemplate_(e,t,i,n){var s;if(console.assert(n.indexTemplate,"must be using index template"),!e.representation)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.NOT_CONFIGURED);const a=it.fillUriTemplate(null!==(s=n.indexTemplate)&&void 0!==s?s:"",e.representation.id,null,null,e.bandwidth||null,null),r=k.resolveUris(e.representation.getBaseUris(),[a]);return ot.generateSegmentIndexFromUris(e,t,i,r,0,null,n.scaledPresentationTimeOffset)}static generateSegmentIndexFromDuration_(e,t,i,n,s){var a,r;if(console.assert(t.mediaTemplate,"There should be a media template with duration"),!e.representation||!e.periodInfo)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.NOT_CONFIGURED);const o=e.presentationTimeline,l=e.periodInfo.start,u=null!==(r=null===(a=e.period)||void 0===a?void 0:a.id)&&void 0!==r?r:null,_=e.periodInfo.duration,m=()=>{const e=null!=u&&s[u]||_;return e?l+e:1/0},g=t.segmentDuration;if(console.assert(null!=g,"Segment duration must not be null!"),null==g)throw new v(d.CRITICAL,c.MANIFEST,h.SEGMENT_DURATION_IS_NULL);const f=t.startNumber,p=t.timescale,T=t.mediaTemplate,S=e.bandwidth||null,y=e.representation.id,E=e.representation.getBaseUris,I=l-t.scaledPresentationTimeOffset,A=()=>{const e=[Math.max(o.getSegmentAvailabilityStart(),l),Math.min(o.getSegmentAvailabilityEnd(),m())];console.assert(e.every(isFinite),"Available presentation times must be finite!"),console.assert(e.every((e=>e>=0)),"Available presentation times must be positive!"),console.assert(null!=g,"Segment duration must not be null!");const t=e.map((e=>e-l));return[Math.ceil(t[0]/g),Math.ceil(t[1]/g)-1].map((e=>e+f))},b=A(),C=e.dynamic?Math.max(b[0],b[1]-i+1):b[0],w=b[1],M=[],R=e=>{console.assert(null!=g,"Segment duration must not be null!");const i=(e-f)*g,s=i+t.scaledPresentationTimeOffset,a=i+l,r=a+g,o=Math.min(r,m());console.assert(a<o,"Generated a segment outside of the period!");const d=new ye(a,o,(()=>{let t=s*p;"BigInt"in window&&t>Number.MAX_SAFE_INTEGER&&(t=BigInt(s)*BigInt(p));const i=it.fillUriTemplate(null!=T?T:"",y,e,null,S,t);return k.resolveUris(E(),[i])}),0,null,n,I,l,m(),[],"",null,null,ye.Status.AVAILABLE);return d.trueEndTime=r,d};for(let e=C;e<=w;++e){const t=R(e);M.push(t)}const O=new Ee(M),D=o.getSegmentAvailabilityEnd()<m(),P=o.isLive();if(D||P){let e=Math.max(C,w+1);O.updateEvery(g,(()=>{const t=o.getSegmentAvailabilityStart();O.evict(t);const[i,n]=A(),s=[];for(;e<=n;){const t=R(e);s.push(t),++e}return t>m()&&!s.length?null:s}))}return Promise.resolve(O)}static createInitSegment_(e){let t=it.inheritAttribute(e,dt.fromInheritance_,"initialization");if(!t)return null;if(t=L.htmlUnescape(t),!e.representation)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.NOT_CONFIGURED);const i=e.representation.id,n=e.bandwidth||null,s=e.representation.getBaseUris,a=ot.createQualityInfo(e);return new Se((()=>{console.assert(t,"Should have returned earler");const e=it.fillUriTemplate(null!=t?t:"",i,null,null,n,null);return k.resolveUris(s(),[e])}),0,null,a,null,null)}}class ct extends Ee{constructor(e,t,i,n,s,a,r,o,l){super([]),this.templateInfo_=e,this.representationId_=t,this.bandwidth_=i,this.getBaseUris_=n,this.periodStart_=s,this.periodEnd_=a,this.initSegmentReference_=r,this.segmentSequenceCadence_=l,o&&this.fitTimeline()}getNumReferences(){var e,t;return this.templateInfo_&&null!==(t=null===(e=this.templateInfo_.timeline)||void 0===e?void 0:e.length)&&void 0!==t?t:0}release(){super.release(),this.templateInfo_=null}evict(e){var t;if(!this.templateInfo_)return;i.debug(`${this.representationId_} Evicting at ${e}`);let n=0;const s=null!==(t=this.templateInfo_.timeline)&&void 0!==t?t:[];for(let t=0;t<s.length;t+=1){const a=s[t],r=a.end+this.periodStart_,o=a.start+this.periodStart_;if(!(r<=e))break;i.debug(`Evicting ${o} - ${r}`),n+=1}n>0&&(this.templateInfo_.timeline=s.slice(n),this.references.length>=n&&(this.references=this.references.slice(n)),this.numEvicted_+=n,0===this.getNumReferences()&&this.release())}appendTemplateInfo(e,t,n,s,a){var r,o;if(this.initSegmentReference_=a,this.templateInfo_){const t=null!==(r=this.templateInfo_.timeline)&&void 0!==r?r:[];this.templateInfo_.mediaTemplate=e.mediaTemplate;const s=t[t.length-1];let a=[];null!=s&&(a=(null!==(o=e.timeline)&&void 0!==o?o:[]).filter((e=>e.start>=s.end))),a.length>0&&(i.debug(`Appending ${a.length} entries`),null==this.templateInfo_.timeline?this.templateInfo_.timeline=a:this.templateInfo_.timeline.push(...a)),this.periodEnd_!==n&&(this.periodEnd_=n)}else this.templateInfo_=e,this.periodStart_=t,this.periodEnd_=n;s&&this.fitTimeline()}isBeforeFirstEntry(e){var t;const i=null===(t=this.templateInfo_)||void 0===t?void 0:t.timeline;return!(!i||!i.length)&&e<i[0].start+this.periodStart_}fitTimeline(){var e,t;if(this.getIsImmutable())return;const i=null!==(t=null===(e=this.templateInfo_)||void 0===e?void 0:e.timeline)&&void 0!==t?t:[];for(;i.length&&i[i.length-1].start>=this.periodEnd_;)i.pop();this.evict(this.periodStart_)}find(e){var t;if(i.debug(`Find ${e}`),this.isBeforeFirstEntry(e))return this.numEvicted_;if(!this.templateInfo_)return null;const n=null!==(t=this.templateInfo_.timeline)&&void 0!==t?t:[];if(e<this.periodStart_||e>=this.periodEnd_)return null;if(n.length>0){const t=n.length-1;for(let i=0;i<n.length;++i){const s=n[i],a=s.start+this.periodStart_;let r;if(r=i<t?n[i+1].start+this.periodStart_:this.periodEnd_===1/0?s.end+this.periodStart_:this.periodEnd_,e>=a&&e<r)return i+this.numEvicted_}}return null}get(e){var t,i;const n=e-this.numEvicted_;if(n<0||n>=this.getNumReferences()||!this.templateInfo_)return null;let s=this.references[n];if(!s){const e=null!==(t=this.templateInfo_.mediaTemplate)&&void 0!==t?t:"",a=(null!==(i=this.templateInfo_.timeline)&&void 0!==i?i:[])[n];if(a){const t=a.segmentPosition,i=this.templateInfo_.unscaledPresentationTimeOffset+a.unscaledStart,r=this.periodStart_-this.templateInfo_.scaledPresentationTimeOffset,o=this.periodStart_+a.end;let l=o;n===this.getNumReferences()-1&&this.periodEnd_!==1/0&&(l=this.periodEnd_);const d=[],c=(a.end-a.start)/a.partialSegments;for(let e=0;e<a.partialSegments;e++){const n=a.start+c*e,s=n+c,o=e+1;let l=null;const h=()=>{var e;return this.templateInfo_?(null==l&&(l=ct.createUris_(null!==(e=this.templateInfo_.mediaTemplate)&&void 0!==e?e:"",this.representationId_,t,this.bandwidth_,i,o,this.getBaseUris_)),l):[]},u=new ye(this.periodStart_+n,this.periodStart_+s,h,0,null,this.initSegmentReference_,r,this.periodStart_,this.periodEnd_,[],"",null,null,ye.Status.AVAILABLE);0==this.segmentSequenceCadence_?e>0&&u.markAsNonIndependent():e%this.segmentSequenceCadence_!=0&&u.markAsNonIndependent(),d.push(u)}const h=()=>a.partialSegments>0?[]:ct.createUris_(e,this.representationId_,t,this.bandwidth_,i,null,this.getBaseUris_);s=new ye(this.periodStart_+a.start,l,h,0,null,this.initSegmentReference_,r,this.periodStart_,this.periodEnd_,d,"",null,null,ye.Status.AVAILABLE,a.partialSegments>0),s.trueEndTime=o,this.references[n]=s}}return s}static createUris_(e,t,i,n,s,a,r){const o=it.fillUriTemplate(e,t,i,a,n||null,s);return k.resolveUris(r(),[o]).map((e=>e.toString()))}static get[Symbol.for("___CTOR_ARGS___")](){return["SegmentTemplateInfo | null","string | null","number","() => Array<string>","number","number","InitSegmentReference | null","boolean","number"]}}class ht{constructor(e,t,i=!0){this.presentationStartTime_=e,this.presentationDelay_=t,this.duration_=1/0,this.segmentAvailabilityDuration_=1/0,this.maxSegmentDuration_=1,this.minSegmentStartTime_=null,this.maxSegmentEndTime_=null,this.clockOffset_=0,this.static_=!0,this.userSeekStart_=0,this.autoCorrectDrift_=i,this.availabilityTimeOffset_=0,this.startTimeLocked_=!1,this.initialProgramDateTime_=null}getDuration(){return this.duration_}getMaxSegmentDuration(){return this.maxSegmentDuration_}setPresentationStartTime(e){console.assert(e>=0,"presentationStartTime must be >= 0"),this.presentationStartTime_=e}setDuration(e){console.assert(e>0,"duration must be > 0"),this.duration_=e}getPresentationStartTime(){return this.presentationStartTime_}setClockOffset(e){this.clockOffset_=e}setStatic(e){this.static_=e}setSegmentAvailabilityDuration(e){console.assert(e>=0,"segmentAvailabilityDuration must be >= 0"),this.segmentAvailabilityDuration_=e}getSegmentAvailabilityDuration(){return this.segmentAvailabilityDuration_}setDelay(e){console.assert(e>=0,"delay must be >= 0"),this.presentationDelay_=e}getDelay(){return this.presentationDelay_}notifyTimeRange(e,t){if(0==e.length)return;const n=e[0].start+t,s=e[e.length-1].end+t;if(this.notifyMinSegmentStartTime(n),this.maxSegmentDuration_=e.reduce(((e,t)=>Math.max(e,t.end-t.start)),this.maxSegmentDuration_),this.maxSegmentEndTime_=Math.max(this.maxSegmentEndTime_,s),null!=this.presentationStartTime_&&this.autoCorrectDrift_&&!this.startTimeLocked_){const e=(Date.now()+this.clockOffset_)/1e3;this.presentationStartTime_=e-this.maxSegmentEndTime_-this.maxSegmentDuration_}i.v1("notifySegments:","maxSegmentDuration="+this.maxSegmentDuration_)}notifySegments(e){if(0==e.length)return;let t=e[0].startTime,n=e[0].endTime;const s=(Date.now()+this.clockOffset_)/1e3;for(const i of e)s<i.startTime||(t=Math.min(t,i.startTime),n=Math.max(n,i.endTime),this.maxSegmentDuration_=Math.max(this.maxSegmentDuration_,i.endTime-i.startTime));this.notifyMinSegmentStartTime(t),this.maxSegmentEndTime_=Math.max(this.maxSegmentEndTime_,n),null!=this.presentationStartTime_&&this.autoCorrectDrift_&&!this.startTimeLocked_&&(this.presentationStartTime_=s-this.maxSegmentEndTime_-this.maxSegmentDuration_),i.v1("notifySegments:","maxSegmentDuration="+this.maxSegmentDuration_)}lockStartTime(){this.startTimeLocked_=!0}isStartTimeLocked(){return this.startTimeLocked_}setInitialProgramDateTime(e){this.initialProgramDateTime_=e}getInitialProgramDateTime(){return this.initialProgramDateTime_}notifyMinSegmentStartTime(e){null==this.minSegmentStartTime_?this.minSegmentStartTime_=e:this.minSegmentStartTime_=Math.min(this.minSegmentStartTime_,e)}notifyMaxSegmentDuration(e){this.maxSegmentDuration_=Math.max(this.maxSegmentDuration_,e),i.v1("notifyNewSegmentDuration:","maxSegmentDuration="+this.maxSegmentDuration_)}offset(e){null!=this.minSegmentStartTime_&&(this.minSegmentStartTime_+=e),null!=this.maxSegmentEndTime_&&(this.maxSegmentEndTime_+=e)}isLive(){return this.duration_==1/0&&!this.static_}isInProgress(){return this.duration_!=1/0&&!this.static_}getSegmentAvailabilityStart(){console.assert(this.segmentAvailabilityDuration_>=0,"The availability duration should be positive");const e=this.getSegmentAvailabilityEnd()-this.segmentAvailabilityDuration_;return Math.max(this.userSeekStart_,e)}setUserSeekStart(e){this.userSeekStart_=e}getSegmentAvailabilityEnd(){return this.isLive()||this.isInProgress()?Math.min(this.getLiveEdge_()+this.availabilityTimeOffset_,this.duration_):this.maxSegmentEndTime_?Math.min(this.maxSegmentEndTime_,this.duration_):this.duration_}getSafeSeekRangeStart(e){const t=Math.max(this.minSegmentStartTime_,this.userSeekStart_);if(this.segmentAvailabilityDuration_==1/0)return Math.ceil(1e3*t)/1e3;const i=this.getSegmentAvailabilityEnd()-this.segmentAvailabilityDuration_,n=Math.min(i+e,this.getSeekRangeEnd());return Math.max(t,n)}getSeekRangeStart(){return this.getSafeSeekRangeStart(0)}getSeekRangeEnd(){const e=this.isLive()||this.isInProgress()?this.presentationDelay_:0;return Math.max(0,this.getSegmentAvailabilityEnd()-e)}usingPresentationStartTime(){return null!=this.presentationStartTime_&&(null==this.maxSegmentEndTime_||!this.autoCorrectDrift_)}getLiveEdge_(){console.assert(null!=this.presentationStartTime_,"Cannot compute timeline live edge without start time");const e=(Date.now()+this.clockOffset_)/1e3;return Math.max(0,e-this.maxSegmentDuration_-this.presentationStartTime_)}setAvailabilityTimeOffset(e){this.availabilityTimeOffset_=e}assertIsValid(){this.isLive()?console.assert(null!=this.presentationStartTime_,"Detected as live stream, but does not match our model of live!"):this.isInProgress()?console.assert(null!=this.presentationStartTime_&&this.segmentAvailabilityDuration_==1/0,"Detected as IPR stream, but does not match our model of IPR!"):console.assert(this.segmentAvailabilityDuration_==1/0&&this.duration_!=1/0&&this.static_,"Detected as VOD stream, but does not match our model of VOD!")}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0,void 0]}}class ut{constructor(){this.variants_=[],this.audioStreams_=[],this.videoStreams_=[],this.textStreams_=[],this.imageStreams_=[],this.multiTypeVariantsAllowed_=!1,this.useStreamOnce_=!1,this.usedPeriodIds_=new Set}release(){const e=this.audioStreams_.concat(this.videoStreams_,this.textStreams_,this.imageStreams_);for(const t of e)t.segmentIndex&&t.segmentIndex.release();this.audioStreams_=[],this.videoStreams_=[],this.textStreams_=[],this.imageStreams_=[],this.variants_=[]}getVariants(){return this.variants_}getTextStreams(){return this.textStreams_.slice()}getImageStreams(){return this.imageStreams_}getStreamsPerPeriod_(e,t){const i=k.ContentType,n=[],s=[],a=[],r=[];for(const o of e){const e=new Map(o.audioStreams.map((e=>[ut.generateAudioKey_(e),e]))),l=new Map(o.videoStreams.map((e=>[ut.generateVideoKey_(e),e]))),d=new Map(o.textStreams.map((e=>[ut.generateTextKey_(e),e]))),c=new Map(o.imageStreams.map((e=>[ut.generateImageKey_(e),e])));if(t){const e=ut.dummyStream_(i.TEXT);d.set(ut.generateTextKey_(e),e);const t=ut.dummyStream_(i.IMAGE);c.set(ut.generateImageKey_(t),t)}n.push(e),s.push(l),a.push(d),r.push(c)}return{audioStreamsPerPeriod:n,videoStreamsPerPeriod:s,textStreamsPerPeriod:a,imageStreamsPerPeriod:r}}async combinePeriods(e,t){const i=k.ContentType;if(t||1!=e.length){let t=-1;for(let i=0;i<e.length;i++){const n=e[i];this.usedPeriodIds_.has(n.id)||(this.usedPeriodIds_.add(n.id),-1==t&&(t=i))}if(-1==t)return;const{audioStreamsPerPeriod:i,videoStreamsPerPeriod:n,textStreamsPerPeriod:s,imageStreamsPerPeriod:a}=this.getStreamsPerPeriod_(e,!0);await Promise.all([this.combine_(this.audioStreams_,i,t,ut.cloneStream_,ut.concatenateStreams_),this.combine_(this.videoStreams_,n,t,ut.cloneStream_,ut.concatenateStreams_),this.combine_(this.textStreams_,s,t,ut.cloneStream_,ut.concatenateStreams_),this.combine_(this.imageStreams_,a,t,ut.cloneStream_,ut.concatenateStreams_)])}else{const{audioStreamsPerPeriod:t,videoStreamsPerPeriod:i,textStreamsPerPeriod:n,imageStreamsPerPeriod:s}=this.getStreamsPerPeriod_(e,!1);this.audioStreams_=Array.from(t[0].values()),this.videoStreams_=Array.from(i[0].values()),this.textStreams_=Array.from(n[0].values()),this.imageStreams_=Array.from(s[0].values())}let n=0;const s=[];if(this.videoStreams_.length&&this.audioStreams_.length)for(const e of this.audioStreams_)for(const t of this.videoStreams_){const i=n++;s.push({id:i,language:e.language,disabledUntilTime:0,primary:e.primary,audio:e,video:t,bandwidth:(e.bandwidth||0)+(t.bandwidth||0),allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]})}else{const e=this.videoStreams_.length?this.videoStreams_:this.audioStreams_;for(const t of e){const e=n++;s.push({id:e,language:t.language,disabledUntilTime:0,primary:t.primary,audio:t.type==i.AUDIO?t:null,video:t.type==i.VIDEO?t:null,bandwidth:t.bandwidth||0,allowedByApplication:!0,allowedByKeySystem:!0,decodingInfos:[]})}}this.variants_=s}async combine_(e,t,n,s,a){const r=[];for(let e=0;e<n;e++)r.push(new Set);for(let e=n;e<t.length;e++)r.push(new Set(t[e].values()));for(const i of e)if(!await this.extendExistingOutputStream_(i,t,n,a,r))throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.PERIOD_FLATTENING_FAILED);for(const i of r)for(const n of i){const i=this.createNewOutputStream_(n,t,s,a,r);i&&e.push(i)}for(const t of r)for(const n of t)if(!ut.isDummy_(n)&&e.some((e=>this.areAVStreamsCompatible_(n,e))))throw i.error("Unused stream in period-flattening!",n,e),new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.PERIOD_FLATTENING_FAILED);return e}async extendExistingOutputStream_(e,t,n,s,a){return this.findMatchesInAllPeriods_(t,e),console.assert(e.createSegmentIndex,"outputStream should be a Stream type!"),e.matchedStreams?(e.segmentIndex&&await ut.extendOutputSegmentIndex_(e,n),ut.extendOutputStream_(e,n,s,a),!0):(i.error("No matches extending output stream!",e,t),!1)}static async extendOutputSegmentIndex_(e,t){var i;const n=[],s=null!==(i=e.matchedStreams)&&void 0!==i?i:[];console.assert(s,"matched streams should be valid");for(const e of s)n.push(e.createSegmentIndex()),e.trickModeVideo&&!e.trickModeVideo.segmentIndex&&n.push(e.trickModeVideo.createSegmentIndex());if(await Promise.all(n),e.segmentIndex instanceof Ie)for(let i=t;i<s.length;++i){const t=s[i];console.assert(t.segmentIndex,"stream should have a segmentIndex."),t.segmentIndex&&(t.segmentIndex.forEachTopLevelReference((e=>{e.codecs=t.codecs,e.mimeType=t.mimeType,e.initSegmentReference&&(e.initSegmentReference.codecs=t.codecs,e.initSegmentReference.mimeType=t.mimeType)})),e.segmentIndex.appendSegmentIndex(t.segmentIndex))}}createNewOutputStream_(e,t,i,n,s){if(ut.isDummy_(e))return null;const a=i(e);return this.findMatchesInAllPeriods_(t,a),a.createSegmentIndex&&(a.createSegmentIndex=async()=>{a.segmentIndex||(a.segmentIndex=new Ie,await ut.extendOutputSegmentIndex_(a,0))}),a.matchedStreams&&a.matchedStreams.length?(ut.extendOutputStream_(a,0,n,s),a):null}static extendOutputStream_(e,t,i,n){const s=e.matchedStreams;if(console.assert(e.matchedStreams,"matchedStreams should be non-null"),null!=s)for(let a=t;a<s.length;a++){const t=s[a];i(e,t);let r=!0;if(e.type==f.AUDIO&&0==G.relatedness(e.language,t.language)&&(r=!1),r){n[a].delete(t);const i=new Set(e.codecs.split(","));for(const e of t.codecs.split(","))e&&i.add(e);e.codecs=ut.filterDuplicateCodecs_(Array.from(i)).join(",")}}}static filterDuplicateCodecs_(e){const t=new Set,n=[];for(const s of e){const e=B.getCodecBase(s);t.has(e)?i.debug("Ignoring duplicate codec"):(n.push(s),t.add(e))}return n}static cloneStream_(e){const t=Object.assign({},e);return t.originalId=null,t.createSegmentIndex=()=>Promise.resolve(),t.closeSegmentIndex=()=>{if(t.segmentIndex&&(t.segmentIndex.release(),t.segmentIndex=null),t.matchedStreams)for(const e of t.matchedStreams)e.segmentIndex&&(e.segmentIndex.release(),e.segmentIndex=null)},t.roles=t.roles.slice(),t.segmentIndex=null,t.emsgSchemeIdUris=[],t.closedCaptions=null,t.trickModeVideo=null,t}static concatenateStreams_(e,t){var i;const n=(e,t)=>{e||(e=[]);for(const i of t)e.includes(i)||e.push(i);return e};if(e.roles=n(e.roles,t.roles),t.emsgSchemeIdUris&&(e.emsgSchemeIdUris=n(null!==(i=e.emsgSchemeIdUris)&&void 0!==i?i:[],t.emsgSchemeIdUris)),null==e.originalId?e.originalId=t.originalId:e.originalId+=","+(t.originalId||""),t.closedCaptions){e.closedCaptions||(e.closedCaptions=new Map);for(const[i,n]of t.closedCaptions)e.closedCaptions.set(i,n)}t.trickModeVideo?(e.trickModeVideo||(e.trickModeVideo=ut.cloneStream_(t.trickModeVideo),e.trickModeVideo.createSegmentIndex=()=>(console.assert(e.segmentIndex instanceof Ie,"The stream should have a MetaSegmentIndex."),e.trickModeVideo&&e.segmentIndex instanceof Ie&&(e.trickModeVideo.segmentIndex=e.segmentIndex.clone()),Promise.resolve())),ut.concatenateStreams_(e.trickModeVideo,t.trickModeVideo)):e.trickModeVideo&&ut.concatenateStreams_(e.trickModeVideo,t)}findMatchesInAllPeriods_(e,t){const i=[];for(const n of e){const e=this.findBestMatchInPeriod_(n,t);if(!e)return;i.push(e)}t.matchedStreams=i}findBestMatchInPeriod_(e,t){if(t.type===f.UNKNOWN||t.type===f.APPLICATION)return null;const i={audio:ut.generateAudioKey_,video:ut.generateVideoKey_,text:ut.generateTextKey_,image:ut.generateImageKey_}[t.type];let n=null;const s=i(t);if(e.has(s))n=e.get(s);else{const i={audio:(e,t)=>this.areAVStreamsCompatible_(e,t),video:(e,t)=>this.areAVStreamsCompatible_(e,t),text:ut.areTextStreamsCompatible_,image:ut.areImageStreamsCompatible_}[t.type],s={audio:ut.isAudioStreamBetterMatch_,video:ut.isVideoStreamBetterMatch_,text:ut.isTextStreamBetterMatch_,image:ut.isImageStreamBetterMatch_}[t.type];for(const a of e.values())i(t,a)&&t.fastSwitching==a.fastSwitching&&(n&&!s(t,n,a)||(n=a))}return n&&this.useStreamOnce_&&!ut.isDummy_(n)&&e.delete(i(n)),null!=n?n:null}static areAVStreamsExactMatch_(e,t){if(e.mimeType!=t.mimeType)return!1;const i=e=>{if(!ut.memoizedCodecs.has(e)){const t=B.getNormalizedCodec(e);ut.memoizedCodecs.set(e,t)}return ut.memoizedCodecs.get(e)};return i(e.codecs)==i(t.codecs)}setAllowMultiTypeVariants(e){this.multiTypeVariantsAllowed_=e}setUseStreamOnce(e){this.useStreamOnce_=e}areAVStreamsCompatible_(e,t){return!(!ut.areAVStreamsExactMatch_(e,t)&&!this.multiTypeVariantsAllowed_)}static areTextStreamsCompatible_(e,t){return!t.language||e.forced===t.forced&&(0!=G.relatedness(e.language,t.language)&&t.kind==e.kind)}static areImageStreamsCompatible_(e,t){return!0}static isAudioStreamBetterMatch_(e,t,i){var n,s,a,r,o,l,d,c;const h=ut.areAVStreamsExactMatch_(e,t),u=ut.areAVStreamsExactMatch_(e,i);if(h&&!u)return!1;if(!h&&u)return!0;const _=G.relatedness(e.language,t.language),m=G.relatedness(e.language,i.language);if(m>_)return!0;if(m<_)return!1;if(t.label!==i.label){if(e.label===t.label)return!1;if(e.label===i.label)return!0}if(e.roles.length){const n=t.roles.filter((t=>e.roles.includes(t))),s=i.roles.filter((t=>e.roles.includes(t)));return s.length>n.length||!(s.length<n.length)&&i.roles.length<t.roles.length}if(!i.roles.length&&t.roles.length)return!0;if(i.roles.length&&!t.roles.length)return!1;if(!t.primary&&i.primary)return!0;if(t.primary&&!i.primary)return!1;const g=ut.compareClosestPreferLower(null!==(n=e.channelsCount)&&void 0!==n?n:0,null!==(s=t.channelsCount)&&void 0!==s?s:0,null!==(a=i.channelsCount)&&void 0!==a?a:0);if(1==g)return!0;if(-1==g)return!1;const f=ut.compareClosestPreferLower(null!==(r=e.audioSamplingRate)&&void 0!==r?r:0,null!==(o=t.audioSamplingRate)&&void 0!==o?o:0,null!==(l=i.audioSamplingRate)&&void 0!==l?l:0);if(1==f)return!0;if(-1==f)return!1;if(e.bandwidth){const n=ut.compareClosestPreferMinimalAbsDiff_(e.bandwidth,null!==(d=t.bandwidth)&&void 0!==d?d:0,null!==(c=i.bandwidth)&&void 0!==c?c:0);if(1==n)return!0;if(-1==n)return!1}return!1}static isVideoStreamBetterMatch_(e,t,i){var n,s,a,r,o,l,d,c,h,u;const _=ut.areAVStreamsExactMatch_(e,t),m=ut.areAVStreamsExactMatch_(e,i);if(_&&!m)return!1;if(!_&&m)return!0;const g=ut.compareClosestPreferLower((null!==(n=e.width)&&void 0!==n?n:0)*(null!==(s=e.height)&&void 0!==s?s:0),(null!==(a=t.width)&&void 0!==a?a:0)*(null!==(r=t.height)&&void 0!==r?r:0),(null!==(o=i.width)&&void 0!==o?o:0)*(null!==(l=i.height)&&void 0!==l?l:0));if(1==g)return!0;if(-1==g)return!1;if(e.frameRate){const n=ut.compareClosestPreferLower(e.frameRate,null!==(d=t.frameRate)&&void 0!==d?d:0,null!==(c=i.frameRate)&&void 0!==c?c:0);if(1==n)return!0;if(-1==n)return!1}if(e.bandwidth){const n=ut.compareClosestPreferMinimalAbsDiff_(e.bandwidth,null!==(h=t.bandwidth)&&void 0!==h?h:0,null!==(u=i.bandwidth)&&void 0!==u?u:0);if(1==n)return!0;if(-1==n)return!1}return!1}static isTextStreamBetterMatch_(e,t,i){const n=G.relatedness(e.language,t.language),s=G.relatedness(e.language,i.language);if(s>n)return!0;if(s<n)return!1;if(!t.primary&&i.primary)return!0;if(t.primary&&!i.primary)return!1;if(t.label!==i.label){if(e.label===t.label)return!1;if(e.label===i.label)return!0}if(e.roles.length){const n=t.roles.filter((t=>e.roles.includes(t))),s=i.roles.filter((t=>e.roles.includes(t)));if(s.length>n.length)return!0;if(s.length<n.length)return!1}else{if(!i.roles.length&&t.roles.length)return!0;if(i.roles.length&&!t.roles.length)return!1}return i.mimeType==e.mimeType&&i.codecs==e.codecs&&(t.mimeType!=e.mimeType||t.codecs!=e.codecs)}static isImageStreamBetterMatch_(e,t,i){if(null==e.width||null==e.height||null==t.width||null==t.height||null==i.width||null==i.height)return!1;return 1==ut.compareClosestPreferLower(e.width*e.height,t.width*t.height,i.width*i.height)}static dummyStream_(e){return{bandwidth:null,closeSegmentIndex:null,frameRate:null,hdr:null,height:null,kind:null,matchedStreams:null,mssPrivateData:null,pixelAspectRatio:null,tilesLayout:null,videoLayout:null,width:null,id:0,originalId:"",groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:new Ee([]),mimeType:"",codecs:"",language:"",originalLanguage:null,label:null,type:e,primary:!1,trickModeVideo:null,emsgSchemeIdUris:[],roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,accessibilityPurpose:null,external:!1,fastSwitching:!1}}static compareClosestPreferLower(e,t,i){if(t==e&&e!=i)return-1;if(i==e&&e!=t)return 1;if(t>e){if(i<=e)return 1;if(i-e<t-e)return 1;if(i-e>t-e)return-1}else{if(i>e)return-1;if(e-i<e-t)return 1;if(e-i>e-t)return-1}return 0}static compareClosestPreferMinimalAbsDiff_(e,t,i){const n=Math.abs(e-t),s=Math.abs(e-i);return s<n?1:n<s?-1:0}static isDummy_(e){const t=k.ContentType;switch(e.type){case t.TEXT:return!e.language;case t.IMAGE:return!e.tilesLayout;default:return!1}}static generateVideoKey_(e){return ut.generateKey_([e.fastSwitching,e.width,e.frameRate,e.codecs,e.mimeType,e.label,e.roles,e.closedCaptions?Array.from(e.closedCaptions.entries()):null,e.bandwidth])}static generateAudioKey_(e){return ut.generateKey_([e.fastSwitching,e.channelsCount,e.language,e.bandwidth,e.label,e.codecs,e.mimeType,e.roles,e.audioSamplingRate,e.primary])}static generateTextKey_(e){return ut.generateKey_([e.language,e.label,e.codecs,e.mimeType,e.bandwidth,e.roles])}static generateImageKey_(e){return ut.generateKey_([e.width,e.codecs,e.mimeType])}static generateKey_(e){return JSON.stringify(e)}}ut.memoizedCodecs=new Map;class _t{constructor(e){this.playerInterface_=e,this.config_=null,this.operationManager_=new A,this.baseUris_=[],this.defaultPathwayId_=null,this.pathwayPriority_=[],this.lastPathwayUsed_=null,this.pathwayClones_=[],this.lastTTL_=300,this.locations_=new Map,this.bannedLocations_=new Map,this.updateTimer_=null,this.manifestType_=g.UNKNOWN}configure(e){this.config_=e}destroy(){return this.config_=null,this.playerInterface_=null,this.baseUris_=[],this.defaultPathwayId_=null,this.pathwayPriority_=[],this.pathwayClones_=[],this.locations_.clear(),null!=this.updateTimer_&&(this.updateTimer_.stop(),this.updateTimer_=null),this.operationManager_.destroy()}setManifestType(e){this.manifestType_=e}setBaseUris(e){this.baseUris_=e}setDefaultPathwayId(e){this.defaultPathwayId_=e}async requestInfo(e){if(null==this.config_||null==this.playerInterface_)throw new v(d.CRITICAL,c.MANIFEST,v.Code.OPERATION_ABORTED);const t=k.resolveUris(this.baseUris_,[this.addQueryParams_(e)]),i=O.RequestType.CONTENT_STEERING,n=O.makeRequest(t,this.config_.retryParameters),s=this.playerInterface_.networkingEngine.request(i,n);this.operationManager_.manage(s);try{const e=await s.promise,t=L.fromUTF8(e.data),i=JSON.parse(t);1==i.VERSION&&this.processManifest_(i,e.uri)}catch(t){if(t&&t.code==v.Code.OPERATION_ABORTED)return;null!=this.updateTimer_&&(this.updateTimer_.stop(),this.updateTimer_=null),this.updateTimer_=new o((()=>{this.requestInfo(e)})),this.updateTimer_.tickAfter(this.lastTTL_)}}addQueryParams_(e){if(!this.pathwayPriority_.length)return e;if(!this.playerInterface_)return e;const t=new URL(e),i=this.lastPathwayUsed_||this.pathwayPriority_[0],n=Math.round(this.playerInterface_.getBandwidthEstimate()),s=t.searchParams;return this.manifestType_==ue.DASH?(s.set("_DASH_pathway",i),s.set("_DASH_throughput",String(n))):this.manifestType_==ue.HLS&&(s.set("_HLS_pathway",i),s.set("_HLS_throughput",String(n))),t.toString()}processManifest_(e,t){null!=this.updateTimer_&&(this.updateTimer_.stop(),this.updateTimer_=null);const i=e["RELOAD-URI"]||t;this.updateTimer_=new o((()=>{this.requestInfo(i)}));const n=e.TTL;n&&(this.lastTTL_=n),this.updateTimer_.tickAfter(this.lastTTL_),this.pathwayPriority_=e["PATHWAY-PRIORITY"]||[],this.pathwayClones_=e["PATHWAY-CLONES"]||[]}clearPreviousLocations(){this.locations_.clear()}addLocation(e,t,i){let n=this.locations_.get(e);n||(n=new Map),n.set(t,i),this.locations_.set(e,n)}banLocation(e){const t=Date.now()+6e4;this.bannedLocations_.set(e,t)}getLocations(e,t=!1){const i=this.locations_.get(e)||new Map;let n=[];for(const e of this.pathwayPriority_){const t=i.get(e);if(t)n.push({pathwayId:e,location:t});else{const t=this.pathwayClones_.find((t=>t.ID==e));if(t){const s=i.get(t["BASE-ID"]);if(s)if(t["URI-REPLACEMENT"].HOST){const i=new URL(s);i.host=t["URI-REPLACEMENT"].HOST,n.push({pathwayId:e,location:i.toString()})}else n.push({pathwayId:e,location:s})}}}const s=Date.now();for(const e of this.bannedLocations_.keys()){const t=this.bannedLocations_.get(e);null!=t&&s>t&&this.bannedLocations_.delete(e)}n=n.filter((e=>{for(const t of this.bannedLocations_.keys())if(t.includes(new URL(e.location).host))return!1;return!0})),n.length&&(this.lastPathwayUsed_=n[0].pathwayId);const a=n.map((e=>e.location));if(!a.length&&this.defaultPathwayId_)for(const e of this.defaultPathwayId_.split(",")){const t=i.get(e);t&&(this.lastPathwayUsed_=this.defaultPathwayId_,a.push(t))}if(!a.length)for(const e of i.values())a.push(e);return t?a:k.resolveUris(this.baseUris_,a)}static get[Symbol.for("___CTOR_ARGS___")](){return["ManifestParserPlayerInterface | null"]}}class mt{constructor(){this.config_=null,this.playerInterface_=null,this.manifestUris_=[],this.manifest_=null,this.globalId_=1,this.streamMap_={},this.periodDurations_={},this.periodCombiner_=new ut,this.updatePeriod_=0,this.averageUpdateDuration_=new K(5),this.updateTimer_=new o((()=>{this.onUpdate_()})),this.operationManager_=new A,this.largestPeriodStartTime_=null,this.lastManifestUpdatePeriodIds_=[],this.minTotalAvailabilityTimeOffset_=1/0,this.lowLatencyMode_=!1,this.contentSteeringManager_=null}configure(e){console.assert(null!=e.dash,"DashManifestConfiguration should not be null!"),this.config_=e,this.contentSteeringManager_&&this.contentSteeringManager_.configure(this.config_),this.periodCombiner_&&(this.periodCombiner_.setAllowMultiTypeVariants(this.config_.dash.multiTypeVariantsAllowed&&V.isChangeTypeSupported()),this.periodCombiner_.setUseStreamOnce(this.config_.dash.useStreamOnceInPeriodFlattening))}async start(e,t){console.assert(this.config_,"Must call configure() before start()!"),this.lowLatencyMode_=t.isLowLatencyMode(),this.manifestUris_=[e],this.playerInterface_=t;const i=await this.requestManifest_();if(this.playerInterface_&&this.setUpdateTimer_(i),!this.playerInterface_)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.OPERATION_ABORTED);if(console.assert(this.manifest_,"Manifest should be non-null!"),!this.manifest_)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.OPERATION_ABORTED);return this.manifest_}stop(){for(const e of Object.values(this.streamMap_))e.segmentIndex&&e.segmentIndex.release();return this.periodCombiner_&&this.periodCombiner_.release(),this.playerInterface_=null,this.config_=null,this.manifestUris_=[],this.manifest_=null,this.streamMap_={},this.periodCombiner_=null,null!=this.updateTimer_&&(this.updateTimer_.stop(),this.updateTimer_=null),this.contentSteeringManager_&&this.contentSteeringManager_.destroy(),this.operationManager_.destroy()}async update(){try{await this.requestManifest_()}catch(e){if(!this.playerInterface_||!e)return;console.assert(e instanceof v,"Bad error type"),this.playerInterface_.onError(e)}}onExpirationUpdated(e,t){}onInitialVariantChosen(e){if(this.manifest_&&this.manifest_.presentationTimeline.isLive()){const t=e.video||e.audio;if(t&&t.segmentIndex){const e=this.manifest_.presentationTimeline.getSegmentAvailabilityEnd(),i=t.segmentIndex.find(e);if(null==i)return;const n=t.segmentIndex.get(i);if(!n)return;this.updatePeriod_=n.endTime-e,this.setUpdateTimer_(0)}}}banLocation(e){this.contentSteeringManager_&&this.contentSteeringManager_.banLocation(e)}async requestManifest_(){const e=O.RequestType.MANIFEST,t=O.AdvancedRequestType.MPD;let i=this.manifestUris_;if(this.manifestUris_.length>1&&this.contentSteeringManager_){const e=this.contentSteeringManager_.getLocations("Location",!0);e.length&&(i=e)}gt(this.config_);const n=O.makeRequest(i,this.config_.retryParameters),s=Date.now(),a=await this.makeNetworkRequest_(n,e,{type:t,stream:void 0,segment:void 0});if(!this.playerInterface_)return 0;a.uri&&a.uri!=a.originalUri&&!this.manifestUris_.includes(a.uri)&&this.manifestUris_.unshift(a.uri),await this.parseManifest_(a.data,a.uri);const r=(Date.now()-s)/1e3;return this.averageUpdateDuration_.sample(1,r),r}async parseManifest_(e,t){const i=tt.parseXml(e,"MPD");if(!i||!tt.isNode(i))throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_INVALID_XML,t);if(gt(this.config_),ft(this.playerInterface_),this.config_.dash.disableXlinkProcessing)return this.processManifest_(i,t);const n=this.config_.dash.xlinkFailGracefully,s=it.processXlinks(i,this.config_.retryParameters,n,t,this.playerInterface_.networkingEngine);this.operationManager_.manage(s);const a=await s.promise;return this.processManifest_(a,t)}async processManifest_(e,t){var n,s,a,r,o,l,d,c,h,u,_,m,g;gt(this.config_),ft(this.playerInterface_);const f=this.config_.dash.manifestPreprocessor;f&&f(e),this.contentSteeringManager_&&this.contentSteeringManager_.clearPreviousLocations();let p=[t];const T=[],S=new Map,y=tt.findChildren(e,"Location");for(const e of y){const t=e.attributes.serviceLocation,i=tt.getContents(e);if(!i)continue;const n=k.resolveUris(p,[i])[0];t&&(this.contentSteeringManager_?this.contentSteeringManager_.addLocation("Location",t,n):S.set(t,n)),T.push(n)}if(this.contentSteeringManager_){const e=this.contentSteeringManager_.getLocations("Location",!0);e.length>0&&(this.manifestUris_=e,p=e)}else T.length&&(this.manifestUris_=T,p=T);let E=Promise.resolve();const v=tt.findChild(e,"ContentSteering");if(v&&this.playerInterface_){const e=v.attributes.defaultServiceLocation;if(this.contentSteeringManager_)this.contentSteeringManager_.setBaseUris(p),this.contentSteeringManager_.setDefaultPathwayId(e);else{this.contentSteeringManager_=new _t(this.playerInterface_),this.contentSteeringManager_.configure(this.config_),this.contentSteeringManager_.setManifestType(ue.DASH),this.contentSteeringManager_.setBaseUris(p),this.contentSteeringManager_.setDefaultPathwayId(e);const t=tt.getContents(v);t&&(tt.parseAttr(v,"queryBeforeStart",tt.parseBoolean,!1)?E=this.contentSteeringManager_.requestInfo(t):this.contentSteeringManager_.requestInfo(t))}for(const e of S.keys()){const t=S.get(e);this.contentSteeringManager_.addLocation("Location",e,null!=t?t:"")}}const I=tt.findChildren(e,"BaseURL");let A,b=!1;if(this.contentSteeringManager_)for(const e of I){const t=e.attributes.serviceLocation,i=tt.getContents(e);t&&i&&(this.contentSteeringManager_.addLocation("BaseURL",t,i),b=!0)}if(!b||!this.contentSteeringManager_){const e=I.map((e=>{var t;return null!==(t=tt.getContents(e))&&void 0!==t?t:""})).filter(Boolean);A=k.resolveUris(p,e)}const C=()=>this.contentSteeringManager_&&b?this.contentSteeringManager_.getLocations("BaseURL"):A||[];let w=0;I&&I.length&&(w=tt.parseAttr(I[0],"availabilityTimeOffset",tt.parseFloat)||0);let M=0;this.config_.dash.ignoreMinBufferTime||(M=tt.parseAttr(e,"minBufferTime",tt.parseDuration)||0),this.updatePeriod_=tt.parseAttrWithDefaultValue(e,"minimumUpdatePeriod",tt.parseDuration,-1);const R=tt.parseAttr(e,"availabilityStartTime",tt.parseDate);let O=tt.parseAttr(e,"timeShiftBufferDepth",tt.parseDuration),D=null;this.config_.dash.ignoreSuggestedPresentationDelay||(D=tt.parseAttr(e,"suggestedPresentationDelay",tt.parseDuration));let P=null;this.config_.dash.ignoreMaxSegmentDuration||(P=tt.parseAttr(e,"maxSegmentDuration",tt.parseDuration));const N=e.attributes.type||"static";let L;if(this.manifest_){L=this.manifest_.presentationTimeline;for(const e of Object.values(this.streamMap_))e.segmentIndex&&e.segmentIndex.evict(L.getSegmentAvailabilityStart())}else{const e=this.config_.defaultPresentationDelay||1.5*M;L=new ht(R,null!=D?D:e,this.config_.dash.autoCorrectDrift)}L.setStatic("static"==N),L.isLive()&&!isNaN(this.config_.availabilityWindowOverride)&&(O=this.config_.availabilityWindowOverride),null==O&&(O=1/0),L.setSegmentAvailabilityDuration(O);const x={dynamic:"static"!=N,presentationTimeline:L,period:null,periodInfo:null,adaptationSet:null,representation:null,bandwidth:0,indexRangeWarningGiven:!1,availabilityTimeOffset:w,profiles:(e.attributes.profiles||"").split(",")},U=this.parsePeriods_(x,C,e),B=U.duration,F=U.periods;if("static"!=N&&U.durationDerivedFromPeriods||L.setDuration(B||1/0),this.minTotalAvailabilityTimeOffset_&&!this.lowLatencyMode_&&this.playerInterface_.isAutoLowLatencyMode()&&(this.playerInterface_.enableLowLatencyMode(),this.lowLatencyMode_=this.playerInterface_.isLowLatencyMode()),this.lowLatencyMode_?L.setAvailabilityTimeOffset(this.minTotalAvailabilityTimeOffset_):this.minTotalAvailabilityTimeOffset_&&i.alwaysWarn("Low-latency DASH live stream detected, but low-latency streaming mode is not enabled in Shaka Player. Set streaming.lowLatencyMode configuration to true, and see https://bit.ly/3clctcj for details."),L.notifyMaxSegmentDuration(P||1),L.assertIsValid(),await(null===(n=this.periodCombiner_)||void 0===n?void 0:n.combinePeriods(F,x.dynamic)),await E,this.lowLatencyMode_&&(M=0),this.manifest_){this.manifest_.variants=null!==(h=null===(c=this.periodCombiner_)||void 0===c?void 0:c.getVariants())&&void 0!==h?h:[];const e=null!==(_=null===(u=this.periodCombiner_)||void 0===u?void 0:u.getTextStreams())&&void 0!==_?_:[];e.length>0&&(this.manifest_.textStreams=e),this.manifest_.imageStreams=null!==(g=null===(m=this.periodCombiner_)||void 0===m?void 0:m.getImageStreams())&&void 0!==g?g:[],this.playerInterface_.filter(this.manifest_)}else{if(this.manifest_={presentationTimeline:L,variants:null!==(a=null===(s=this.periodCombiner_)||void 0===s?void 0:s.getVariants())&&void 0!==a?a:[],textStreams:null!==(o=null===(r=this.periodCombiner_)||void 0===r?void 0:r.getTextStreams())&&void 0!==o?o:[],imageStreams:null!==(d=null===(l=this.periodCombiner_)||void 0===l?void 0:l.getImageStreams())&&void 0!==d?d:[],offlineSessionIds:[],minBufferTime:M||0,sequenceMode:this.config_.dash.sequenceMode,ignoreManifestTimestampsInSegmentsMode:!1,type:ue.DASH,serviceDescription:this.parseServiceDescription_(e)},L.usingPresentationStartTime()){const t=tt.findChildren(e,"UTCTiming"),i=await this.parseUtcTiming_(C,t);if(!this.playerInterface_)return;L.setClockOffset(i)}L.lockStartTime()}this.playerInterface_.makeTextStreamsForClosedCaptions(this.manifest_)}parseServiceDescription_(e){const t=tt.findChild(e,"ServiceDescription");if(!t)return null;const i=tt.findChild(t,"Latency"),n=tt.findChild(t,"PlaybackRate");return i&&i.attributes.max||n?{maxLatency:i&&i.attributes.max?parseInt(i.attributes.max,10)/1e3:null,maxPlaybackRate:n?parseFloat(n.attributes.max):null,minLatency:i&&i.attributes.min?parseInt(i.attributes.min,10)/1e3:null,minPlaybackRate:n?parseFloat(n.attributes.min):null}:null}parsePeriods_(e,t,n){const s=tt.parseAttr(n,"mediaPresentationDuration",tt.parseDuration),a=[];let r=0;const o=tt.findChildren(n,"Period");for(let n=0;n<o.length;++n){const l=o[n],d=o[n+1],c=tt.parseAttrWithDefaultValue(l,"start",tt.parseDuration,null!=r?r:0),h=l.attributes.id,u=tt.parseAttr(l,"duration",tt.parseDuration);let _=null;if(d){const e=tt.parseAttr(d,"start",tt.parseDuration);null!=e&&(_=e-c)}else null!=s&&(_=s-c);const m=k.GAP_OVERLAP_TOLERANCE_SECONDS;if(_&&u&&Math.abs(_-u)>m&&i.warning("There is a gap/overlap between Periods",l),null==_&&(_=u),null!==this.largestPeriodStartTime_&&null!==h&&null!==c&&c<this.largestPeriodStartTime_&&!this.lastManifestUpdatePeriodIds_.includes(h)&&n+1!=o.length){i.debug(`Skipping Period with ID ${h} as its start time is smaller than the largest period start time that has been seen, and ID is unseen before`);continue}null!==c&&(null===this.largestPeriodStartTime_||c>this.largestPeriodStartTime_)&&(this.largestPeriodStartTime_=c);const g={start:c,duration:_,node:l,isLastPeriod:null==_||!d},f=this.parsePeriod_(e,t,g);if(a.push(f),e.period&&e.period.id&&_&&(this.periodDurations_[e.period.id]=_),null==_){d&&i.warning("Skipping Period",n+1,"and any subsequent Periods:","Period",n+1,"does not have a valid start time.",d),r=null;break}r=c+_}return this.lastManifestUpdatePeriodIds_=a.map((e=>e.id)),null!=s?(r!=s&&i.warning("@mediaPresentationDuration does not match the total duration of ","all Periods."),{periods:a,duration:s,durationDerivedFromPeriods:!1}):{periods:a,duration:r,durationDerivedFromPeriods:!0}}parsePeriod_(e,t,n){var s,a,r;gt(this.config_),ft(this.playerInterface_),e.period=this.createFrame_(n.node,null,t),e.periodInfo=n,e.period.availabilityTimeOffset=e.availabilityTimeOffset,e.period.id||(i.info("No Period ID given for Period with start time "+n.start+", Assigning a default"),e.period.id="__shaka_period_"+n.start);const o=tt.findChildren(n.node,"EventStream"),l=e.presentationTimeline.getSegmentAvailabilityStart();for(const e of o)this.parseEventStream_(n.start,n.duration,e,l);const d=tt.findChildren(n.node,"AdaptationSet").map((t=>this.parseAdaptationSet_(e,t))).filter(F.isNotNull);if(e.dynamic){const e=[];for(const t of d)for(const i of t.representationIds)e.push(i);const t=new Set(e);if(e.length!=t.size)throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_DUPLICATE_REPRESENTATION_ID)}const c=d.filter((e=>!e.trickModeFor)),h=d.filter((e=>e.trickModeFor));for(const e of h){const t=null!==(a=null===(s=e.trickModeFor)||void 0===s?void 0:s.split(" "))&&void 0!==a?a:[];for(const i of c)if(t.includes(i.id))for(const t of i.streams)t.trickModeVideo=null!==(r=e.streams.find((e=>B.getNormalizedCodec(t.codecs)==B.getNormalizedCodec(e.codecs))))&&void 0!==r?r:null}const u=this.getStreamsFromSets_(this.config_.disableAudio,c,f.AUDIO),_=this.getStreamsFromSets_(this.config_.disableVideo,c,f.VIDEO),m=this.getStreamsFromSets_(this.config_.disableText,c,f.TEXT),g=this.getStreamsFromSets_(this.config_.disableThumbnails,c,f.IMAGE);if(0===_.length&&0===u.length)throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_EMPTY_PERIOD);return{id:e.period.id,audioStreams:u,videoStreams:_,textStreams:m,imageStreams:g}}getStreamsFromSets_(e,t,i){return e||!t.length?[]:t.reduce(((e,t)=>(t.contentType!=i||e.push(...t.streams),e)),[])}parseAdaptationSet_(e,t){gt(this.config_),ft(this.playerInterface_),e.adaptationSet=this.createFrame_(t,e.period,null);let i=!1;const n=tt.findChildren(t,"Role"),s=n.map((e=>e.attributes.value)).filter(F.isNotNull);let a=null;const r=e.adaptationSet.contentType==f.TEXT;r&&(a=k.TextStreamKind.SUBTITLE);for(const e of n){const t=e.attributes.schemeIdUri;if(null==t||"urn:mpeg:dash:role:2011"==t)switch(e.attributes.value){case"main":i=!0;break;case"caption":case"subtitle":a=k.TextStreamKind.SUBTITLE}}let o;const l="urn:mpeg:mpegB:cicp",d=`${l}:TransferCharacteristics`,c=`${l}:ColourPrimaries`,h=`${l}:MatrixCoefficients`,u=e=>{switch(e){case 1:case 6:case 13:case 14:case 15:return S.SDR;case 16:return S.PQ;case 18:return S.HLG}return null},_=tt.findChildren(t,"EssentialProperty");let m=null,g=!1,p=!1;for(const e of _){const t=e.attributes.schemeIdUri;if("http://dashif.org/guidelines/trickmode"==t)m=e.attributes.value;else if(t==d)o=u(parseInt(e.attributes.value,10));else{if(t==c||t==h)continue;"urn:mpeg:dash:ssr:2023"==t?g=!0:p=!0}}const T=tt.findChildren(t,"SupplementalProperty");for(const e of T)e.attributes.schemeIdUri==d&&(o=u(parseInt(e.attributes.value,10)));const y=tt.findChildren(t,"Accessibility"),E=new Map;let I;for(const e of y){const t=e.attributes.schemeIdUri,i=e.attributes.value;if("urn:scte:dash:cc:cea-608:2015"==t){let e=1;if(null!=i){const t=i.split(";");for(const i of t){let n,s;if(i.includes("=")){const e=i.split("=");n=e[0].startsWith("CC")?e[0]:`CC${e[0]}`,s=e[1]||"und"}else n=`CC${e}`,2==t.length?e+=2:e++,s=i;E.set(n,G.normalize(s))}}else E.set("CC1","und")}else if("urn:scte:dash:cc:cea-708:2015"==t){let e=1;if(null!=i)for(const t of i.split(";")){let i,n;if(t.includes("=")){const e=t.split("=");i=`svc${e[0]}`,n=e[1].split(",")[0].split(":").pop()}else i=`svc${e}`,e++,n=t;E.set(i,G.normalize(n))}else E.set("svc1","und")}else"urn:mpeg:dash:role:2011"==t?null!=i&&(s.push(i),"captions"==i&&(a=k.TextStreamKind.CLOSED_CAPTION)):"urn:tva:metadata:cs:AudioPurposeCS:2007"==t&&("1"==i?I=ue.AccessibilityPurpose.VISUALLY_IMPAIRED:"2"==i&&(I=ue.AccessibilityPurpose.HARD_OF_HEARING))}if(p)return null;const A=G.normalize(e.adaptationSet.language||"und");let b=t.attributes.label;const C=tt.findChildren(t,"Label");if(C&&C.length){const e=C[0],t=tt.getTextContents(e);t&&(b=t)}const w=tt.findChildren(t,"Representation"),M=[];if(w.forEach((t=>{const n=this.parseRepresentation_(e,a,A,b,i,s,E,t,I);n&&(n.hdr=n.hdr||o,n.fastSwitching=g),null!=n&&M.push(n)})),0==M.length){const t=e.adaptationSet.contentType==f.IMAGE;if(this.config_.dash.ignoreEmptyAdaptationSet||r||t)return null;throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_EMPTY_ADAPTATION_SET)}if(!e.adaptationSet.contentType||e.adaptationSet.contentType==f.APPLICATION){const t=M[0];if(t){const i=t.mimeType,n=t.codecs;e.adaptationSet.contentType=mt.guessContentType_(i,n)}for(const t of M)t.type=e.adaptationSet.contentType}const R=e.adaptationSet.id||"__fake__"+this.globalId_++;for(const e of M)this.config_.dash.enableAudioGroups&&(e.groupId=R);const O=w.map((e=>e.attributes.id)).filter(F.isNotNull);return{id:R,contentType:e.adaptationSet.contentType,language:A,main:i,streams:M,trickModeFor:m,representationIds:O}}parseRepresentation_(e,t,n,s,a,r,o,l,d){var c,h,u,_,m,g;if(gt(this.config_),ft(this.playerInterface_),e.representation=this.createFrame_(l,e.adaptationSet,null),this.minTotalAvailabilityTimeOffset_=Math.min(this.minTotalAvailabilityTimeOffset_,e.representation.availabilityTimeOffset),!this.verifyRepresentation_(e.representation))return i.warning("Skipping Representation",e.representation),null;const p=null!==(h=null===(c=e.periodInfo)||void 0===c?void 0:c.start)&&void 0!==h?h:0;let T;e.bandwidth=tt.parseAttr(l,"bandwidth",tt.parsePositiveInt)||0;const y=e.representation.contentType,E=y==f.TEXT||y==f.APPLICATION,I=y==f.IMAGE;try{const t=this.requestSegment_.bind(this);if(e.representation.segmentBase)T=ot.createStreamInfo(e,t);else if(e.representation.segmentList)T=lt.createStreamInfo(e,this.streamMap_);else if(e.representation.segmentTemplate){const i=!!this.manifest_;T=dt.createStreamInfo(e,t,this.streamMap_,i,this.config_.dash.initialSegmentLimit,this.periodDurations_)}else{console.assert(E,"Must have Segment* with non-text streams.");const t=null!==(_=null===(u=e.periodInfo)||void 0===u?void 0:u.duration)&&void 0!==_?_:0,i=e.representation.getBaseUris;T={generateSegmentIndex:()=>Promise.resolve(Ee.forSingleSegment(p,t,i()))}}}catch(e){if((E||I)&&e.code==v.Code.DASH_NO_SEGMENT_INFO)return null;throw e}if(null==T)return null;let A=!1;tt.findChildren(l,"SupplementalProperty").some((e=>"tag:dolby.com,2018:dash:EC3_ExtensionType:2018"==e.attributes.schemeIdUri&&"JOC"==e.attributes.value))&&(A=!0);let b=!1;E&&(b=r.includes("forced_subtitle")||r.includes("forced-subtitle"));let C=null;if(I){const e=tt.findChildren(l,"EssentialProperty").find((e=>["http://dashif.org/thumbnail_tile","http://dashif.org/guidelines/thumbnail_tile"].includes(e.attributes.schemeIdUri)));if(e&&(C=e.attributes.value),!C)return null}let w=null;const M=e.profiles,R=e.representation.codecs;M.includes("http://dashif.org/guidelines/dash-if-uhd#hevc-hdr-pq10")&&(R.includes("hvc1.2.4.L153.B0")||R.includes("hev1.2.4.L153.B0"))&&(w=S.PQ);const O=e.representation.id?(null!==(g=null===(m=e.period)||void 0===m?void 0:m.id)&&void 0!==g?g:"")+","+e.representation.id:"";let D;if(O&&this.streamMap_[O])D=this.streamMap_[O];else{if(!e.adaptationSet)return null;D={id:this.globalId_++,originalId:e.representation.id,groupId:null,createSegmentIndex:()=>Promise.resolve(),closeSegmentIndex:()=>{D.segmentIndex&&(D.segmentIndex.release(),D.segmentIndex=null)},segmentIndex:null,mimeType:e.representation.mimeType,codecs:e.representation.codecs,frameRate:e.representation.frameRate,pixelAspectRatio:e.representation.pixelAspectRatio,bandwidth:e.bandwidth,width:e.representation.width,height:e.representation.height,kind:t,language:n,originalLanguage:e.adaptationSet.language,label:s,type:e.adaptationSet.contentType,primary:a,trickModeVideo:null,emsgSchemeIdUris:e.representation.emsgSchemeIdUris,roles:r,forced:b,channelsCount:e.representation.numChannels,audioSamplingRate:e.representation.audioSamplingRate,spatialAudio:A,closedCaptions:o,hdr:w,videoLayout:null,tilesLayout:C,accessibilityPurpose:d,external:!1,fastSwitching:!1,matchedStreams:[],mssPrivateData:null}}return D.createSegmentIndex=async()=>{D.segmentIndex||(D.segmentIndex=await T.generateSegmentIndex())},O&&e.dynamic&&!this.streamMap_[O]&&(this.streamMap_[O]=D),D}async onUpdate_(){console.assert(this.updatePeriod_>=0,"There should be an update period"),i.info("Updating manifest...");let e=0;try{e=await this.requestManifest_()}catch(e){if(console.assert(e instanceof v,"Should only receive a Shaka error"),this.playerInterface_&&this.config_){if(this.config_.raiseFatalErrorOnManifestUpdateRequestFailure)return void this.playerInterface_.onError(e);e.severity=v.Severity.RECOVERABLE,this.playerInterface_.onError(e)}}this.playerInterface_&&(this.playerInterface_.onManifestUpdated(),this.setUpdateTimer_(e))}setUpdateTimer_(e){var t;if(this.updatePeriod_<0)return;const i=Math.max(this.updatePeriod_-e,this.averageUpdateDuration_.getEstimate());null===(t=this.updateTimer_)||void 0===t||t.tickAfter(i)}createFrame_(e,t,i){console.assert(t||i,"Must provide either parent or getBaseUris"),t=t||{contentType:f.UNKNOWN,mimeType:"",codecs:"",emsgSchemeIdUris:[],frameRate:null,pixelAspectRatio:null,numChannels:null,audioSamplingRate:null,availabilityTimeOffset:0,segmentSequenceCadence:0,segmentBase:null,segmentList:null,segmentTemplate:null,getBaseUris:null!=i?i:()=>[],width:null,height:null,id:null,language:null},i=i||t.getBaseUris;const n=tt.parseNonNegativeInt,s=tt.evalDivision,a=e.attributes.id,r=tt.findChildren(e,"BaseURL");let o=null,l=!1;if(this.contentSteeringManager_)for(const e of r){const t=e.attributes.serviceLocation,i=tt.getContents(e);t&&i&&(this.contentSteeringManager_.addLocation(a,t,i),l=!0)}l&&this.contentSteeringManager_||(o=r.map((e=>{var t;return null!==(t=tt.getContents(e))&&void 0!==t?t:""})).filter(Boolean));const d=()=>r.length?this.contentSteeringManager_&&l?this.contentSteeringManager_.getLocations(a):o||[]:[];let c=f.UNKNOWN;switch(e.attributes.contentType||t.contentType){case f.VIDEO:c=f.VIDEO;break;case f.AUDIO:c=f.AUDIO;break;case f.TEXT:c=f.TEXT;break;case f.IMAGE:c=f.IMAGE;break;case f.APPLICATION:c=f.APPLICATION;break;default:c=f.UNKNOWN}const h=e.attributes.mimeType||t.mimeType,u=e.attributes.codecs||t.codecs,_=tt.parseAttr(e,"frameRate",s)||t.frameRate,m=e.attributes.sar||t.pixelAspectRatio,g=this.emsgSchemeIdUris_(tt.findChildren(e,"InbandEventStream"),t.emsgSchemeIdUris),p=tt.findChildren(e,"AudioChannelConfiguration"),T=this.parseAudioChannels_(p)||t.numChannels,S=tt.parseAttr(e,"audioSamplingRate",n)||t.audioSamplingRate;c===f.UNKNOWN&&(c=mt.guessContentType_(h,u));const y=tt.findChild(e,"SegmentBase"),E=tt.findChild(e,"SegmentTemplate"),v=y&&tt.parseAttr(y,"availabilityTimeOffset",tt.parseFloat)||0,I=E&&tt.parseAttr(E,"availabilityTimeOffset",tt.parseFloat)||0,A=r&&r.length&&tt.parseAttr(r[0],"availabilityTimeOffset",tt.parseFloat)||0,b=t.availabilityTimeOffset+A+v+I;let C=null;const w=tt.findChild(e,"SegmentSequenceProperties");if(w){const e=tt.findChild(w,"SAP");e&&(C=tt.parseAttr(e,"cadence",tt.parseInt))}return{getBaseUris:()=>k.resolveUris(i(),d()),segmentBase:y||t.segmentBase,segmentList:tt.findChild(e,"SegmentList")||t.segmentList,segmentTemplate:E||t.segmentTemplate,width:tt.parseAttr(e,"width",n)||t.width,height:tt.parseAttr(e,"height",n)||t.height,contentType:c,mimeType:h,codecs:u,frameRate:_,pixelAspectRatio:m,emsgSchemeIdUris:g,id:a,language:e.attributes.lang,numChannels:T,audioSamplingRate:S,availabilityTimeOffset:b,segmentSequenceCadence:C||t.segmentSequenceCadence}}emsgSchemeIdUris_(e,t){const i=t.slice();for(const t of e){const e=t.attributes.schemeIdUri;i.includes(e)||i.push(e)}return i}parseAudioChannels_(e){for(const t of e){const e=t.attributes.schemeIdUri;if(!e)continue;const n=t.attributes.value;if(n)switch(e){case"urn:mpeg:dash:outputChannelPositionList:2012":return n.trim().split(/ +/).length;case"urn:mpeg:dash:23003:3:audio_channel_configuration:2011":case"urn:dts:dash:audio_channel_configuration:2012":{const t=parseInt(n,10);if(!t){i.warning("Channel parsing failure! Ignoring scheme and value",e,n);continue}return t}case"tag:dolby.com,2014:dash:audio_channel_configuration:2011":case"urn:dolby:dash:audio_channel_configuration:2011":{let t=parseInt(n,16);if(!t){i.warning("Channel parsing failure! Ignoring scheme and value",e,n);continue}let s=0;for(;t;)1&t&&++s,t>>=1;return s}case"urn:mpeg:mpegB:cicp:ChannelConfiguration":{const t=0,s=[t,1,2,3,4,5,6,8,2,3,4,7,8,24,8,12,10,12,14,12,14],a=parseInt(n,10);if(!a){i.warning("Channel parsing failure! Ignoring scheme and value",e,n);continue}if(a>t&&a<s.length)return s[a];continue}default:i.warning("Unrecognized audio channel scheme:",e,n);continue}}return null}verifyRepresentation_(e){const t=k.ContentType;let n=0;return n+=e.segmentBase?1:0,n+=e.segmentList?1:0,n+=e.segmentTemplate?1:0,0==n?e.contentType==t.TEXT||e.contentType==t.APPLICATION||(i.warning("Representation does not contain a segment information source:","the Representation must contain one of SegmentBase, SegmentList,",'SegmentTemplate, or explicitly indicate that it is "text".',e),!1):(1!=n&&(i.warning("Representation contains multiple segment information sources:","the Representation should only contain one of SegmentBase,","SegmentList, or SegmentTemplate.",e),e.segmentBase?(i.info("Using SegmentBase by default."),e.segmentList=null,e.segmentTemplate=null):(console.assert(e.segmentList,"There should be a SegmentList"),i.info("Using SegmentList by default."),e.segmentTemplate=null)),!0)}async requestForTiming_(e,t,n){gt(this.config_),ft(this.playerInterface_);const s=k.resolveUris(e(),[t]),a=O.makeRequest(s,this.config_.retryParameters);a.method=n;const r=O.RequestType.TIMING,o=this.playerInterface_.networkingEngine.request(r,a);this.operationManager_.manage(o);const l=await o.promise;let d;if("HEAD"==n){if(!l.headers||!l.headers.date)return i.warning("UTC timing response is missing","expected date header"),0;d=l.headers.date}else d=L.fromUTF8(l.data);const c=Date.parse(d);return isNaN(c)?(i.warning("Unable to parse date from UTC timing response"),0):c-Date.now()}async parseUtcTiming_(e,t){gt(this.config_),ft(this.playerInterface_);const n=t.map((e=>({scheme:e.attributes.schemeIdUri,value:e.attributes.value}))),s=this.config_.dash.clockSyncUri;!n.length&&s&&n.push({scheme:"urn:mpeg:dash:utc:http-head:2014",value:s});for(const t of n)try{const n=t.scheme,s=t.value;switch(n){case"urn:mpeg:dash:utc:http-head:2014":case"urn:mpeg:dash:utc:http-head:2012":return await this.requestForTiming_(e,s,"HEAD");case"urn:mpeg:dash:utc:http-xsdate:2014":case"urn:mpeg:dash:utc:http-iso:2014":case"urn:mpeg:dash:utc:http-xsdate:2012":case"urn:mpeg:dash:utc:http-iso:2012":return await this.requestForTiming_(e,s,"GET");case"urn:mpeg:dash:utc:direct:2014":case"urn:mpeg:dash:utc:direct:2012":{const e=Date.parse(s);return isNaN(e)?0:e-Date.now()}case"urn:mpeg:dash:utc:http-ntp:2014":case"urn:mpeg:dash:utc:ntp:2014":case"urn:mpeg:dash:utc:sntp:2014":i.alwaysWarn("NTP UTCTiming scheme is not supported");break;default:i.alwaysWarn("Unrecognized scheme in UTCTiming element",n)}}catch(e){i.warning("Error fetching time from UTCTiming elem",e.message)}return i.alwaysWarn("A UTCTiming element should always be given in live manifests! This content may not play on clients with bad clocks!"),0}parseEventStream_(e,t,i,n){gt(this.config_),ft(this.playerInterface_);const s=tt.parseNonNegativeInt,a=i.attributes.schemeIdUri||"",r=i.attributes.value||"",o=tt.parseAttr(i,"timescale",s)||1;for(const l of tt.findChildren(i,"Event")){let i=(tt.parseAttr(l,"presentationTime",s)||0)/o+e,d=i+(tt.parseAttr(l,"duration",s)||0)/o;if(null!=t&&(i=Math.min(i,e+t),d=Math.min(d,e+t)),d<n)continue;const c={schemeIdUri:a,value:r,startTime:i,endTime:d,id:l.attributes.id||"",eventElement:l};this.playerInterface_.onTimelineRegionAdded(c)}}async requestSegment_(e,t,i,n){gt(this.config_),ft(this.playerInterface_);const s=O.RequestType.SEGMENT,a=n?O.AdvancedRequestType.INIT_SEGMENT:O.AdvancedRequestType.MEDIA_SEGMENT,r=Ne.createSegmentRequest(e,t,i,this.config_.retryParameters);return(await this.makeNetworkRequest_(r,s,{type:a,stream:void 0,segment:void 0})).data}static guessContentType_(e,t){const i=B.getFullType(e,t);if(X.isTypeSupported(i))return k.ContentType.TEXT;switch(e.split("/")[0]){case f.AUDIO:return f.AUDIO;case f.VIDEO:return f.VIDEO}return f.UNKNOWN}makeNetworkRequest_(e,t,i){gt(this.config_),ft(this.playerInterface_);const n=this.playerInterface_.networkingEngine.request(t,e,i);return this.operationManager_.manage(n),n.promise}}function gt(e){if(null==e)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.NOT_CONFIGURED)}function ft(e){if(null==e)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.NOT_CONFIGURED)}ue.registerParserByMime("application/dash+xml",(()=>new mt)),ue.registerParserByMime("video/vnd.mpeg.dash.mpd",(()=>new mt));class pt{constructor(){this.config_=null,this.playerInterface_=null,this.manifestUris_=[],this.manifest_=null,this.globalId_=1,this.streamMap_={},this.periodDurations_={},this.periodCombiner_=new ut,this.updatePeriod_=0,this.averageUpdateDuration_=new K(5),this.updateTimer_=new o((()=>{this.onUpdate_()})),this.operationManager_=new A,this.largestPeriodStartTime_=null,this.lastManifestUpdatePeriodIds_=[],this.minTotalAvailabilityTimeOffset_=1/0,this.lowLatencyMode_=!1}configure(e){console.assert(null!=e.dash,"DashManifestConfiguration should not be null!"),this.config_=e,this.periodCombiner_&&(this.periodCombiner_.setAllowMultiTypeVariants(this.config_.dash.multiTypeVariantsAllowed&&V.isChangeTypeSupported()),this.periodCombiner_.setUseStreamOnce(this.config_.dash.useStreamOnceInPeriodFlattening))}async start(e,t){console.assert(this.config_,"Must call configure() before start()!"),this.lowLatencyMode_=t.isLowLatencyMode(),this.manifestUris_=[e],this.playerInterface_=t;const i=await this.requestManifest_();if(this.playerInterface_&&this.setUpdateTimer_(i),!this.playerInterface_)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.OPERATION_ABORTED);if(console.assert(this.manifest_,"Manifest should be non-null!"),!this.manifest_)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.OPERATION_ABORTED);return this.manifest_}stop(){for(const e of Object.values(this.streamMap_))e.segmentIndex&&e.segmentIndex.release();return this.periodCombiner_&&this.periodCombiner_.release(),this.playerInterface_=null,this.config_=null,this.manifestUris_=[],this.manifest_=null,this.streamMap_={},this.periodCombiner_=null,null!=this.updateTimer_&&(this.updateTimer_.stop(),this.updateTimer_=null),this.operationManager_.destroy()}async update(){try{await this.requestManifest_()}catch(e){if(!this.playerInterface_||!e)return;console.assert(e instanceof v,"Bad error type"),this.playerInterface_.onError(e)}}onExpirationUpdated(e,t){}onInitialVariantChosen(e){if(this.manifest_&&this.manifest_.presentationTimeline.isLive()){const t=e.video||e.audio;if(t&&t.segmentIndex){const e=this.manifest_.presentationTimeline.getSegmentAvailabilityEnd(),i=t.segmentIndex.find(e);if(null==i)return;const n=t.segmentIndex.get(i);if(!n)return;this.updatePeriod_=n.endTime-e,this.setUpdateTimer_(0)}}}banLocation(e){}async requestManifest_(){const e=O.RequestType.MANIFEST,t=O.AdvancedRequestType.MPD;let i=this.manifestUris_;Tt(this.config_);const n=O.makeRequest(i,this.config_.retryParameters),s=Date.now(),a=await this.makeNetworkRequest_(n,e,{type:t,stream:void 0,segment:void 0});if(!this.playerInterface_)return 0;a.uri&&a.uri!=a.originalUri&&!this.manifestUris_.includes(a.uri)&&this.manifestUris_.unshift(a.uri),await this.parseManifest_(a.data,a.uri);const r=(Date.now()-s)/1e3;return this.averageUpdateDuration_.sample(1,r),r}async parseManifest_(e,t){let i="",n=null;try{i=L.fromUTF8(e),n=JSON.parse(i)}catch(e){throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_INVALID_JSON,t,i)}const s=this.convertDashJsonDTOToAdaptiveSets_(n);return this.processManifest_(s,t)}async processManifest_(e,t){var n,s,a,r,o,l,d,c,h,u,_,m,g;Tt(this.config_),St(this.playerInterface_);let f=0;this.config_.dash.ignoreMinBufferTime||(f=e.minBufferTimeMs/1e3),this.updatePeriod_=-1;let p=null,T=null;this.config_.dash.ignoreSuggestedPresentationDelay||(T=null);let S,y=null;if(this.config_.dash.ignoreMaxSegmentDuration||(y=null),this.manifest_){S=this.manifest_.presentationTimeline;for(const e of Object.values(this.streamMap_))e.segmentIndex&&e.segmentIndex.evict(S.getSegmentAvailabilityStart())}else{const e=this.config_.defaultPresentationDelay||1.5*f;S=new ht(null,null!=T?T:e,this.config_.dash.autoCorrectDrift)}S.setStatic(!0),S.isLive()&&!isNaN(this.config_.availabilityWindowOverride)&&(p=this.config_.availabilityWindowOverride),null==p&&(p=1/0),S.setSegmentAvailabilityDuration(p);const E={dynamic:!1,presentationTimeline:S,period:null,periodInfo:null,adaptationSet:null,representation:null,bandwidth:0,indexRangeWarningGiven:!1,availabilityTimeOffset:0,profiles:"urn:mpeg:dash:profile:isoff-on-demand:2011".split(",")},v=this.parsePeriods_(E,e),I=v.duration,A=v.periods;if(S.setDuration(I||1/0),this.minTotalAvailabilityTimeOffset_&&!this.lowLatencyMode_&&this.playerInterface_.isAutoLowLatencyMode()&&(this.playerInterface_.enableLowLatencyMode(),this.lowLatencyMode_=this.playerInterface_.isLowLatencyMode()),this.lowLatencyMode_?S.setAvailabilityTimeOffset(this.minTotalAvailabilityTimeOffset_):this.minTotalAvailabilityTimeOffset_&&i.alwaysWarn("Low-latency DASH live stream detected, but low-latency streaming mode is not enabled in Shaka Player. Set streaming.lowLatencyMode configuration to true, and see https://bit.ly/3clctcj for details."),S.notifyMaxSegmentDuration(y||1),S.assertIsValid(),await(null===(n=this.periodCombiner_)||void 0===n?void 0:n.combinePeriods(A,E.dynamic)),this.lowLatencyMode_&&(f=0),this.manifest_){this.manifest_.variants=null!==(h=null===(c=this.periodCombiner_)||void 0===c?void 0:c.getVariants())&&void 0!==h?h:[];const e=null!==(_=null===(u=this.periodCombiner_)||void 0===u?void 0:u.getTextStreams())&&void 0!==_?_:[];e.length>0&&(this.manifest_.textStreams=e),this.manifest_.imageStreams=null!==(g=null===(m=this.periodCombiner_)||void 0===m?void 0:m.getImageStreams())&&void 0!==g?g:[],this.playerInterface_.filter(this.manifest_)}else{if(this.manifest_={presentationTimeline:S,variants:null!==(a=null===(s=this.periodCombiner_)||void 0===s?void 0:s.getVariants())&&void 0!==a?a:[],textStreams:null!==(o=null===(r=this.periodCombiner_)||void 0===r?void 0:r.getTextStreams())&&void 0!==o?o:[],imageStreams:null!==(d=null===(l=this.periodCombiner_)||void 0===l?void 0:l.getImageStreams())&&void 0!==d?d:[],offlineSessionIds:[],minBufferTime:f||0,sequenceMode:this.config_.dash.sequenceMode,ignoreManifestTimestampsInSegmentsMode:!1,type:ue.DASH,serviceDescription:this.parseServiceDescription_(e)},S.usingPresentationStartTime()){const t=tt.findChildren(e,"UTCTiming"),i=await this.parseUtcTiming_(getBaseUris,t);if(!this.playerInterface_)return;S.setClockOffset(i)}S.lockStartTime()}this.playerInterface_.makeTextStreamsForClosedCaptions(this.manifest_)}convertDashJsonDTOToAdaptiveSets_(e){var t,i;const n=new Map;let s=null!==(t=e.minBufferTimeMs)&&void 0!==t?t:0,a=null!==(i=e.approxDurationMs)&&void 0!==i?i:0,r=0,o=0;for(const t of e.adaptiveFormats){const e=this.getContentTypeEnumFromString_(t.type),i={contentType:e,containerType:this.getContainerTypeFromMimeType_(t.mimeType),lang:t.lang};let s=n.get(i);null==s&&(s=Object.assign(Object.assign({},t),{contentType:e,representations:[],id:r}),n.set(i,s),++r),s.representations.push(Object.assign(Object.assign({},t),{id:o,contentType:e,segmentBase:!0,getBaseUris:()=>[t.url]})),++o}return{minBufferTimeMs:s,approxDurationMs:a,periods:[{id:0,adaptionSets:Array.from(n.values())}]}}getContentTypeEnumFromString_(e){let t=f.UNKNOWN;switch(e){case f.VIDEO:t=f.VIDEO;break;case f.AUDIO:t=f.AUDIO;break;case f.TEXT:t=f.TEXT;break;case f.IMAGE:t=f.IMAGE;break;case f.APPLICATION:t=f.APPLICATION;break;default:t=f.UNKNOWN}return t}getContainerTypeFromMimeType_(e){var t;let i=[];return e&&(i=e.split("/")),i.length>1&&null!==(t=i[1])&&void 0!==t?t:null}parseServiceDescription_(e){const t=tt.findChild(e,"ServiceDescription");if(!t)return null;const i=tt.findChild(t,"Latency"),n=tt.findChild(t,"PlaybackRate");return i&&i.attributes.max||n?{maxLatency:i&&i.attributes.max?parseInt(i.attributes.max,10)/1e3:null,maxPlaybackRate:n?parseFloat(n.attributes.max):null,minLatency:i&&i.attributes.min?parseInt(i.attributes.min,10)/1e3:null,minPlaybackRate:n?parseFloat(n.attributes.min):null}:null}parsePeriods_(e,t){const n=t.approxDurationMs/1e3,s=n-0,a=[this.parsePeriod_(e,{start:0,duration:s,isLastPeriod:!0,node:t.periods[0]})];return this.lastManifestUpdatePeriodIds_=a.map((e=>e.id)),null!=n?(0!=n&&i.warning("@mediaPresentationDuration does not match the total duration of ","all Periods."),{periods:a,duration:n,durationDerivedFromPeriods:!1}):{periods:a,duration:0,durationDerivedFromPeriods:!0}}parsePeriod_(e,t){var n,s,a;Tt(this.config_),St(this.playerInterface_),e.period=t.node,e.periodInfo=t,e.period.availabilityTimeOffset=e.availabilityTimeOffset,e.period.id||(i.info("No Period ID given for Period with start time "+t.start+", Assigning a default"),e.period.id="__shaka_period_"+t.start);const r=t.node.adaptionSets.map((t=>this.parseAdaptationSet_(e,t))).filter(F.isNotNull);if(e.dynamic){const e=[];for(const t of r)for(const i of t.representationIds)e.push(i);const t=new Set(e);if(e.length!=t.size)throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_DUPLICATE_REPRESENTATION_ID)}const o=r.filter((e=>!e.trickModeFor)),l=r.filter((e=>e.trickModeFor));for(const e of l){const t=null!==(s=null===(n=e.trickModeFor)||void 0===n?void 0:n.split(" "))&&void 0!==s?s:[];for(const i of o)if(t.includes(i.id))for(const t of i.streams)t.trickModeVideo=null!==(a=e.streams.find((e=>B.getNormalizedCodec(t.codecs)==B.getNormalizedCodec(e.codecs))))&&void 0!==a?a:null}const d=this.getStreamsFromSets_(this.config_.disableAudio,o,f.AUDIO),c=this.getStreamsFromSets_(this.config_.disableVideo,o,f.VIDEO),h=this.getStreamsFromSets_(this.config_.disableText,o,f.TEXT),u=this.getStreamsFromSets_(this.config_.disableThumbnails,o,f.IMAGE);if(0===c.length&&0===d.length)throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_EMPTY_PERIOD);return{id:e.period.id,audioStreams:d,videoStreams:c,textStreams:h,imageStreams:u}}getStreamsFromSets_(e,t,i){return e||!t.length?[]:t.reduce(((e,t)=>(t.contentType!=i||e.push(...t.streams),e)),[])}parseAdaptationSet_(e,t){Tt(this.config_),St(this.playerInterface_),e.adaptationSet=t;const i=G.normalize(e.adaptationSet.lang||"und"),n=[],s=new Map,a=[];if(t.representations.forEach((r=>{var o;const l=this.parseRepresentation_(e,null,i,null,!1,n,s,r,null);l&&(l.hdr=l.hdr||t.videoRange,l.fastSwitching=null!==(o=t.isFastSwitching)&&void 0!==o&&o),null!=l&&a.push(l)})),0==a.length){const t=e.adaptationSet.contentType==f.IMAGE;if(this.config_.dash.ignoreEmptyAdaptationSet||t)return null;throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_EMPTY_ADAPTATION_SET)}if(!e.adaptationSet.contentType||e.adaptationSet.contentType==f.APPLICATION){const t=a[0];if(t){const i=t.mimeType,n=t.codecs;e.adaptationSet.contentType=pt.guessContentType_(i,n)}for(const t of a)t.type=e.adaptationSet.contentType}const r=String(e.adaptationSet.id||"__fake__"+this.globalId_++);for(const e of a)this.config_.dash.enableAudioGroups&&(e.groupId=r);const o=t.representations.map((e=>String(e.id))).filter(F.isNotNull);return{id:r,contentType:e.adaptationSet.contentType,language:i,main:!1,streams:a,trickModeFor:null,representationIds:o}}parseRepresentation_(e,t,i,n,s,a,r,o,l){var d,c,h,u,_,m,g,p;Tt(this.config_),St(this.playerInterface_),e.representation=o;const T=null!==(c=null===(d=e.periodInfo)||void 0===d?void 0:d.start)&&void 0!==c?c:0;let y;e.bandwidth=o.bandwidth;const E=null!==(u=null===(h=e.adaptationSet)||void 0===h?void 0:h.contentType)&&void 0!==u?u:f.UNKNOWN,I=E==f.TEXT||E==f.APPLICATION,A=E==f.IMAGE;try{const t=this.requestSegment_.bind(this);if(o.initRange&&o.indexRange)y=pt.createStreamInfo(e,o,t);else{console.assert(I,"Must have Segment* with non-text streams.");const t=null!==(m=null===(_=e.periodInfo)||void 0===_?void 0:_.duration)&&void 0!==m?m:0,i=e.representation.getBaseUris;y={generateSegmentIndex:()=>Promise.resolve(Ee.forSingleSegment(T,t,i()))}}}catch(e){if((I||A)&&e.code==v.Code.DASH_NO_SEGMENT_INFO)return null;throw e}if(null==y)return null;let b=!1;I&&(b=a.includes("forced_subtitle")||a.includes("forced-subtitle"));let C=null;const w=e.profiles,M=e.representation.codecs;w.includes("http://dashif.org/guidelines/dash-if-uhd#hevc-hdr-pq10")&&(M.includes("hvc1.2.4.L153.B0")||M.includes("hev1.2.4.L153.B0"))&&(C=S.PQ);const R=e.representation.id?(null!==(p=null===(g=e.period)||void 0===g?void 0:g.id)&&void 0!==p?p:"")+","+e.representation.id:"";let O;if(R&&this.streamMap_[R])O=this.streamMap_[R];else{if(!e.adaptationSet)return null;O={id:this.globalId_++,originalId:String(e.representation.id),groupId:null,createSegmentIndex:()=>Promise.resolve(),closeSegmentIndex:()=>{O.segmentIndex&&(O.segmentIndex.release(),O.segmentIndex=null)},segmentIndex:null,mimeType:e.representation.mimeType,codecs:e.representation.codecs,frameRate:e.representation.frameRate,pixelAspectRatio:e.representation.pixelAspectRatio,bandwidth:e.bandwidth,width:e.representation.width,height:e.representation.height,kind:t,language:i,originalLanguage:e.adaptationSet.language,label:n,type:e.adaptationSet.contentType,primary:s,trickModeVideo:null,emsgSchemeIdUris:e.representation.emsgSchemeIdUris,roles:a,forced:b,channelsCount:e.representation.numChannels,audioSamplingRate:e.representation.audioSamplingRate,spatialAudio:!1,closedCaptions:r,hdr:C,videoLayout:null,tilesLayout:null,accessibilityPurpose:l,external:!1,fastSwitching:!1,matchedStreams:[],mssPrivateData:null}}return O.createSegmentIndex=async()=>{O.segmentIndex||(O.segmentIndex=await y.generateSegmentIndex())},R&&e.dynamic&&!this.streamMap_[R]&&(this.streamMap_[R]=O),O}async onUpdate_(){console.assert(this.updatePeriod_>=0,"There should be an update period"),i.info("Updating manifest...");let e=0;try{e=await this.requestManifest_()}catch(e){if(console.assert(e instanceof v,"Should only receive a Shaka error"),this.playerInterface_&&this.config_){if(this.config_.raiseFatalErrorOnManifestUpdateRequestFailure)return void this.playerInterface_.onError(e);e.severity=v.Severity.RECOVERABLE,this.playerInterface_.onError(e)}}this.playerInterface_&&(this.playerInterface_.onManifestUpdated(),this.setUpdateTimer_(e))}setUpdateTimer_(e){var t;if(this.updatePeriod_<0)return;const i=Math.max(this.updatePeriod_-e,this.averageUpdateDuration_.getEstimate());null===(t=this.updateTimer_)||void 0===t||t.tickAfter(i)}async requestForTiming_(e,t,n){Tt(this.config_),St(this.playerInterface_);const s=k.resolveUris(e(),[t]),a=O.makeRequest(s,this.config_.retryParameters);a.method=n;const r=O.RequestType.TIMING,o=this.playerInterface_.networkingEngine.request(r,a);this.operationManager_.manage(o);const l=await o.promise;let d;if("HEAD"==n){if(!l.headers||!l.headers.date)return i.warning("UTC timing response is missing","expected date header"),0;d=l.headers.date}else d=L.fromUTF8(l.data);const c=Date.parse(d);return isNaN(c)?(i.warning("Unable to parse date from UTC timing response"),0):c-Date.now()}async parseUtcTiming_(e,t){Tt(this.config_),St(this.playerInterface_);const n=t.map((e=>({scheme:e.attributes.schemeIdUri,value:e.attributes.value}))),s=this.config_.dash.clockSyncUri;!n.length&&s&&n.push({scheme:"urn:mpeg:dash:utc:http-head:2014",value:s});for(const t of n)try{const n=t.scheme,s=t.value;switch(n){case"urn:mpeg:dash:utc:http-head:2014":case"urn:mpeg:dash:utc:http-head:2012":return await this.requestForTiming_(e,s,"HEAD");case"urn:mpeg:dash:utc:http-xsdate:2014":case"urn:mpeg:dash:utc:http-iso:2014":case"urn:mpeg:dash:utc:http-xsdate:2012":case"urn:mpeg:dash:utc:http-iso:2012":return await this.requestForTiming_(e,s,"GET");case"urn:mpeg:dash:utc:direct:2014":case"urn:mpeg:dash:utc:direct:2012":{const e=Date.parse(s);return isNaN(e)?0:e-Date.now()}case"urn:mpeg:dash:utc:http-ntp:2014":case"urn:mpeg:dash:utc:ntp:2014":case"urn:mpeg:dash:utc:sntp:2014":i.alwaysWarn("NTP UTCTiming scheme is not supported");break;default:i.alwaysWarn("Unrecognized scheme in UTCTiming element",n)}}catch(e){i.warning("Error fetching time from UTCTiming elem",e.message)}return i.alwaysWarn("A UTCTiming element should always be given in live manifests! This content may not play on clients with bad clocks!"),0}async requestSegment_(e,t,i,n){Tt(this.config_),St(this.playerInterface_);const s=O.RequestType.SEGMENT,a=n?O.AdvancedRequestType.INIT_SEGMENT:O.AdvancedRequestType.MEDIA_SEGMENT,r=Ne.createSegmentRequest(e,t,i,this.config_.retryParameters);return(await this.makeNetworkRequest_(r,s,{type:a,stream:void 0,segment:void 0})).data}static guessContentType_(e,t){const i=B.getFullType(e,t);if(X.isTypeSupported(i))return k.ContentType.TEXT;switch(e.split("/")[0]){case f.AUDIO:return f.AUDIO;case f.VIDEO:return f.VIDEO}return f.UNKNOWN}makeNetworkRequest_(e,t,i){Tt(this.config_),St(this.playerInterface_);const n=this.playerInterface_.networkingEngine.request(t,e,i);return this.operationManager_.manage(n),n.promise}static createInitSegment(e,t){let i=0,n=null;t.initRange&&(i=t.initRange.start,n=t.initRange.end);const s=pt.createQualityInfo(e);return new Se((()=>[t.url]),i,n,s,null,null)}static createQualityInfo(e){var t,i,n,s,a,r,o,l,d;const c=e.representation,h=e.adaptationSet;return{bandwidth:e.bandwidth,audioSamplingRate:null!==(t=null==c?void 0:c.audioSamplingRate)&&void 0!==t?t:null,codecs:null!==(i=null==c?void 0:c.codecs)&&void 0!==i?i:"",contentType:null!==(n=null==c?void 0:c.contentType)&&void 0!==n?n:f.UNKNOWN,frameRate:null!==(s=null==h?void 0:h.fps)&&void 0!==s?s:null,height:null!==(a=null==c?void 0:c.height)&&void 0!==a?a:null,mimeType:null!==(r=null==c?void 0:c.mimeType)&&void 0!==r?r:null,channelsCount:null!==(o=null==c?void 0:c.numChannels)&&void 0!==o?o:null,pixelAspectRatio:null!==(l=null==c?void 0:c.sar)&&void 0!==l?l:null,width:null!==(d=null==c?void 0:c.width)&&void 0!==d?d:null}}static createStreamInfo(e,t,i){if(null==e.representation)return null;console.assert(e.representation.segmentBase,"Should only be called with SegmentBase");const n=(t.presentationTimeOffset||0)/(t.timescale||1)||0,s=pt.createInitSegment(e,t);pt.checkSegmentIndexRangeSupport_(e,s);const a=b.shallowCloneObject(e);return{generateSegmentIndex:()=>pt.generateSegmentIndex_(a,i,s,n)}}static async generateSegmentIndexFromUris(e,t,i,n,s,a,r){var o,l,d,c,h,u,_;const m=e.presentationTimeline,g=!e.dynamic||!(null===(o=e.periodInfo)||void 0===o?void 0:o.isLastPeriod),f=null!==(d=null===(l=e.periodInfo)||void 0===l?void 0:l.start)&&void 0!==d?d:0,p=null!==(h=null===(c=e.periodInfo)||void 0===c?void 0:c.duration)&&void 0!==h?h:0,T=null!==(_=null===(u=e.representation)||void 0===u?void 0:u.mimeType.split("/")[1])&&void 0!==_?_:"";let S=t,y=null;const E=[S(n,s,a,!1),"webm"==T&&i?S(i.getUris(),i.startByte,i.endByte,!0):null];S=null;const v=await Promise.all(E),I=v[0],A=v[1]||null;let b;const C=f-r,w=f,M=p?f+p:1/0;return"mp4"==T?b=Mp4SegmentIndexParser.parse(I,s,n,i,C,w,M):(console.assert(A,"WebM requires init data"),b=WebmSegmentIndexParser.parse(I,A,n,i,C,w,M)),m.notifySegments(b),console.assert(!y,"Should not call generateSegmentIndex twice"),y=new Ee(b),g&&y.fit(w,M,!0),y}static computeIndexRange_(e){var t;const i=e.representation;return null!==(t=null==i?void 0:i.indexRange)&&void 0!==t?t:null}static computeIndexUris_(e){var t,i;return null!==(i=null===(t=e.representation)||void 0===t?void 0:t.getBaseUris())&&void 0!==i?i:[]}static checkSegmentIndexRangeSupport_(e,t){if(pt.checkSegmentIndexSupport(e,t),!pt.computeIndexRange_(e))throw i.error("SegmentBase does not contain sufficient segment information:","the SegmentBase does not contain @indexRange","or a RepresentationIndex element.",e.representation),new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_NO_SEGMENT_INFO)}static checkSegmentIndexSupport(e,t){var n,s;const a=e.representation,r=null!==(n=a.contentType)&&void 0!==n?n:f.UNKNOWN,o=null!==(s=a.mimeType.split("/")[1])&&void 0!==s?s:"";if(r!=k.ContentType.TEXT&&"mp4"!=o&&"webm"!=o)throw i.error("SegmentBase specifies an unsupported container type.",a),new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_UNSUPPORTED_CONTAINER);if("webm"==o&&!t)throw i.error("SegmentBase does not contain sufficient segment information:","the SegmentBase uses a WebM container,","but does not contain an Initialization element.",a),new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_WEBM_MISSING_INIT)}static generateSegmentIndex_(e,t,i,n){const s=pt.computeIndexUris_(e),a=pt.computeIndexRange_(e);if(console.assert(a,"Index range should not be null!"),null==a)throw new v(v.Severity.CRITICAL,v.Category.MANIFEST,v.Code.DASH_EMPTY_INDEX_RANGE);return ot.generateSegmentIndexFromUris(e,t,i,s,a.start,a.end,n)}}function Tt(e){if(null==e)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.NOT_CONFIGURED)}function St(e){if(null==e)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.NOT_CONFIGURED)}ue.registerParserByMime("application/json",(()=>new pt));class yt{static parse(e,t,i,n){try{const t=yt.parseRaw(e),i={uri:e,originalUri:e,data:t.data,headers:{"content-type":t.contentType}};return w.completed(i)}catch(e){return w.failed(e)}}static parseRaw(e){const t=e.split(":");if(t.length<2||"data"!=t[0])throw i.error("Bad data URI, failed to parse scheme"),new v(v.Severity.CRITICAL,v.Category.NETWORK,v.Code.MALFORMED_DATA_URI,e);const n=t.slice(1).join(":").split(",");if(n.length<2)throw i.error("Bad data URI, failed to extract encoding and MIME type"),new v(v.Severity.CRITICAL,v.Category.NETWORK,v.Code.MALFORMED_DATA_URI,e);const s=n[0],a=window.decodeURIComponent(n.slice(1).join(",")),r=s.split(";"),o=r[0];let l,d=!1;return r.length>1&&"base64"==r[r.length-1]&&(d=!0,r.pop()),l=d?x.fromBase64(a):L.toUTF8(a),{data:l,contentType:o}}}O.registerScheme("data",yt.parse);class Et{static asMap(e){const t=new Map;for(const i of Object.keys(e))t.set(i,e[i]);return t}static asObject(e){const t={};return e.forEach(((e,i)=>{t[i]=e})),t}static hasSameElements(e,t){if(!e&&!t)return!0;if(e&&!t)return!1;if(t&&!e)return!1;if(e.size!=t.size)return!1;for(const[i,n]of e){if(!t.has(i))return!1;const e=t.get(i);if(e!=n||null==e)return!1}return!0}}class vt{static makeResponse(e,t,n,s,a,r){if(n>=200&&n<=299&&202!=n)return{uri:a||s,originalUri:s,data:t,status:n,headers:e,fromCache:!!e["x-vod-from-cache"]};{let a=null;try{a=L.fromBytesAutoDetect(t)}catch(e){}i.debug("HTTP error text:",a);const o=401==n||403==n?v.Severity.CRITICAL:v.Severity.RECOVERABLE;throw new v(o,v.Category.NETWORK,v.Code.BAD_HTTP_STATUS,s,n,a,e,r)}}}class It{static parse(e,t,i,n,s){const a=new It.Headers_;Et.asMap(t.headers).forEach(((e,t)=>{a.append(t,e)}));const r=new It.AbortController_,l={body:t.body||void 0,headers:a,method:t.method,signal:r.signal,credentials:t.allowCrossSiteCredentials?"include":void 0},d={canceled:!1,timedOut:!1},c=It.request_(e,i,l,d,n,s,t.streamDataCallback),h=new w(c,(()=>(d.canceled=!0,r.abort(),Promise.resolve()))),u=t.retryParameters.timeout;if(u){const e=new o((()=>{d.timedOut=!0,r.abort()}));e.tickAfter(u/1e3),h.finally((()=>{e.stop()}))}return h}static async request_(e,t,n,s,a,r,o){const l=It.fetch_,d=It.ReadableStream_;let c,h,u=0,_=0,m=Date.now();try{if(c=await l(e,n),r(It.headersToGenericObject_(c.headers)),"HEAD"!=n.method){console.assert(c.body,"non-HEAD responses should have a body");const e=c.clone().body.getReader(),t=c.headers.get("Content-Length"),n=t?parseInt(t,10):0;new d({start:t=>{const s=async()=>{let r;try{r=await e.read()}catch(e){return void i.v1("error reading from stream",e.message)}r.done||(u+=r.value.byteLength,o&&await o(r.value));const l=Date.now();(l-m>100||r.done)&&(a(l-m,u-_,n-u),_=u,m=l),r.done?(console.assert(!r.value,'readObj should be unset when "done" is true.'),t.close()):(t.enqueue(r.value),s())};s()}}),h=await c.arrayBuffer()}}catch(i){throw s.canceled?new v(v.Severity.RECOVERABLE,v.Category.NETWORK,v.Code.OPERATION_ABORTED,e,t):s.timedOut?new v(v.Severity.RECOVERABLE,v.Category.NETWORK,v.Code.TIMEOUT,e,t):new v(v.Severity.RECOVERABLE,v.Category.NETWORK,v.Code.HTTP_ERROR,e,i,t)}const g=It.headersToGenericObject_(c.headers);return vt.makeResponse(g,h,c.status,e,c.url,t)}static headersToGenericObject_(e){const t={};return e.forEach(((e,i)=>{t[i.trim()]=e})),t}static isSupported(){if(!window.ReadableStream)return!1;try{new ReadableStream({})}catch(e){return!1}return!!window.Response&&(!!new Response("").body&&!(!window.fetch||!window.AbortController))}}It.fetch_=window.fetch,It.AbortController_=window.AbortController,It.ReadableStream_=window.ReadableStream,It.Headers_=window.Headers,It.isSupported()&&(O.registerScheme("http",It.parse,O.PluginPriority.PREFERRED,!0),O.registerScheme("https",It.parse,O.PluginPriority.PREFERRED,!0),O.registerScheme("blob",It.parse,O.PluginPriority.PREFERRED,!0));class At{static parse(e,t,i,n,s){const a=new At.Xhr_;let r=Date.now(),o=0;const l=new Promise(((l,d)=>{a.open(t.method,e,!0),a.responseType="arraybuffer",a.timeout=t.retryParameters.timeout,a.withCredentials=t.allowCrossSiteCredentials,a.onabort=()=>{d(new v(v.Severity.RECOVERABLE,v.Category.NETWORK,v.Code.OPERATION_ABORTED,e,i))};let c=!1;a.onreadystatechange=e=>{if(2==a.readyState&&!c){const e=At.headersToGenericObject_(a);s(e),c=!0}},a.onload=t=>{const n=At.headersToGenericObject_(a);console.assert(a.response instanceof ArrayBuffer,"XHR should have a response by now!");const s=a.response;try{const t=vt.makeResponse(n,s,a.status,e,a.responseURL,i);l(t)}catch(e){console.assert(e instanceof v,"Wrong error type!"),d(e)}},a.onerror=t=>{d(new v(v.Severity.RECOVERABLE,v.Category.NETWORK,v.Code.HTTP_ERROR,e,t,i))},a.ontimeout=t=>{d(new v(v.Severity.RECOVERABLE,v.Category.NETWORK,v.Code.TIMEOUT,e,i))},a.onprogress=e=>{const t=Date.now();(t-r>100||e.lengthComputable&&e.loaded==e.total)&&(n(t-r,e.loaded-o,e.total-e.loaded),o=e.loaded,r=t)};for(const e in t.headers){const i=e.toLowerCase();a.setRequestHeader(i,t.headers[e])}a.send(t.body)}));return new w(l,(()=>(a.abort(),Promise.resolve())))}static headersToGenericObject_(e){const t=e.getAllResponseHeaders().trim().split("\r\n"),i={};for(const e of t){const t=e.split(": ");i[t[0].toLowerCase()]=t.slice(1).join(": ")}return i}}At.Xhr_=window.XMLHttpRequest,O.registerScheme("http",At.parse,O.PluginPriority.FALLBACK,!0),O.registerScheme("https",At.parse,O.PluginPriority.FALLBACK,!0),O.registerScheme("blob",At.parse,O.PluginPriority.FALLBACK,!0),O.registerScheme("vod-asset",At.parse,O.PluginPriority.FALLBACK,!0);class bt extends a{constructor(e,t){super(),this.loadMode_=bt.LoadMode.NOT_LOADED,this.video_=null,this.videoContainer_=null,this.isTextVisible_=!1,this.globalEventManager_=new Z,this.attachEventManager_=new Z,this.loadEventManager_=new Z,this.trickPlayEventManager_=new Z,this.networkingEngine_=null,this.mediaSourceEngine_=null,this.playhead_=null,this.operationId_=0,this.mutex_=new et,this.playheadObservers_=null,this.playRateController_=null,this.bufferObserver_=null,this.regionTimeline_=null,this.cmcdManager_=null,this.cmsdManager_=null,this.lcevcCanvas_=null,this.lcevcDec_=null,this.qualityObserver_=null,this.streamingEngine_=null,this.parser_=null,this.parserFactory_=null,this.manifest_=null,this.assetUri_=null,this.mimeType_=null,this.startTime_=null,this.fullyLoaded_=!1,this.abrManager_=null,this.abrManagerFactory_=null,this.nextExternalStreamId_=1e9,this.externalSrcEqualsThumbnailsStreams_=[],this.completionPercent_=NaN,this.config_=this.defaultConfig_(),this.lastTextFactory_,this.maxHwRes_={width:1/0,height:1/0},this.manifestFilterer_=new Te(this.config_,this.maxHwRes_,null),this.stats_=null,this.currentAdaptationSetCriteria_=new Pe(this.config_.preferredAudioLanguage,this.config_.preferredVariantRole,this.config_.preferredAudioChannelCount,this.config_.preferredVideoHdrLevel,this.config_.preferSpatialAudio,this.config_.preferredVideoLayout,this.config_.preferredAudioLabel,this.config_.preferredVideoLabel,this.config_.mediaSource.codecSwitchingStrategy,this.config_.manifest.dash.enableAudioGroups),this.currentTextLanguage_=this.config_.preferredTextLanguage,this.currentTextRole_=this.config_.preferredTextRole,this.currentTextForced_=this.config_.preferForcedSubs,this.cleanupOnUnload_=[],t&&t(this),this.cmcdManager_=this.createCmcd_(),this.cmsdManager_=this.createCmsd_(),this.networkingEngine_=this.createNetworkingEngine(),this.networkingEngine_.setForceHTTPS(this.config_.streaming.forceHTTPS),this.adManager_=null,bt.adManagerFactory_&&(this.adManager_=bt.adManagerFactory_(),this.adManager_.configure(this.config_.ads)),this.globalEventManager_.listen(window,"online",(()=>{this.restoreDisabledVariants_(),this.retryStreaming()})),this.checkVariantsTimer_=new o((()=>this.checkVariants_())),e&&(ae.deprecateFeature(5,"Player w/ mediaElement","Please migrate from initializing Player with a mediaElement; use the attach method instead."),this.attach(e,!0))}createLcevcDec_(e){null==this.lcevcDec_&&(this.lcevcDec_=new pe(this.video_,this.lcevcCanvas_,e),this.mediaSourceEngine_&&this.mediaSourceEngine_.updateLcevcDec(this.lcevcDec_))}closeLcevcDec_(){null!=this.lcevcDec_&&(this.lcevcDec_.hideCanvas(),this.lcevcDec_.release(),this.lcevcDec_=null)}setupLcevc_(e){if(e.lcevc.enabled){const t=this.getVariantTracks();t&&t[0]&&"video/mp2t"==t[0].videoMimeType&&(P.isEdge()||P.isLegacyEdge())&&(e.mediaSource.forceTransmux||i.alwaysWarn("LCEVC Warning: For MPEG-2 TS decoding the config.mediaSource.forceTransmux must be enabled.")),this.closeLcevcDec_(),this.createLcevcDec_(e.lcevc)}else this.closeLcevcDec_()}static makeEvent_(e,t){return new s(e,t)}async destroy(){if(this.loadMode_==bt.LoadMode.DESTROYED)return;this.closeLcevcDec_();const e=this.detach();this.loadMode_=bt.LoadMode.DESTROYED,await e,this.globalEventManager_&&(this.globalEventManager_.release(),this.globalEventManager_=null),this.attachEventManager_&&(this.attachEventManager_.release(),this.attachEventManager_=null),this.loadEventManager_&&(this.loadEventManager_.release(),this.loadEventManager_=null),this.trickPlayEventManager_&&(this.trickPlayEventManager_.release(),this.trickPlayEventManager_=null),this.abrManagerFactory_=null,this.config_=null,this.stats_=null,this.videoContainer_=null,this.cmcdManager_=null,this.cmsdManager_=null,this.networkingEngine_&&(await this.networkingEngine_.destroy(),this.networkingEngine_=null),this.abrManager_&&(this.abrManager_.release(),this.abrManager_=null),super.release()}static registerSupportPlugin(e,t){bt.supportPlugins_[e]=t}static setAdManagerFactory(e){bt.adManagerFactory_=e}static isBrowserSupported(){if(window.Promise||i.alwaysWarn("A Promise implementation or polyfill is required"),!(window.Promise&&window.Uint8Array&&Array.prototype.forEach))return!1;if(P.isIE())return!1;const e=P.safariVersion();return!(e&&e<9)&&(!!P.supportsMediaSource()||P.supportsMediaType("application/x-mpegurl"))}static async probeSupport(e=!0){console.assert(bt.isBrowserSupported(),"Must have basic support");const t={manifest:ue.probeSupport(),media:fe.probeSupport()},i=bt.supportPlugins_;for(const e in i)t[e]=i[e]();return t}makeStateChangeEvent_(e){this.dispatchEvent(bt.makeEvent_(s.EventName.OnStateChange,(new Map).set("state",e)))}async attach(e,t=!0){if(this.loadMode_==bt.LoadMode.DESTROYED)throw this.createAbortLoadError_();const i=this.video_&&this.video_==e;if(this.video_&&this.video_!=e&&await this.detach(),!await this.atomicOperationAcquireMutex_("attach"))try{if(!i){this.makeStateChangeEvent_("attach");const t=e=>this.onVideoError_(e);this.attachEventManager_.listen(e,"error",t),this.video_=e}t&&P.supportsMediaSource()&&!this.mediaSourceEngine_&&await this.initializeMediaSourceEngineInner_()}catch(e){throw await this.detach(),e}finally{this.mutex_.release()}}attachCanvas(e){this.lcevcCanvas_=e}async detach(e=!1){if(this.loadMode_==bt.LoadMode.DESTROYED)throw this.createAbortLoadError_();if(await this.unload(!1,e),!await this.atomicOperationAcquireMutex_("detach"))try{this.video_&&(this.attachEventManager_.removeAll(),this.video_=null),this.makeStateChangeEvent_("detach"),this.adManager_&&!e&&this.adManager_.release()}finally{this.mutex_.release()}}async atomicOperationAcquireMutex_(e){const t=++this.operationId_;return await this.mutex_.acquire(e),t!=this.operationId_&&(this.mutex_.release(),!0)}async unload(e=!0,t=!1){if(this.loadMode_!=bt.LoadMode.DESTROYED&&(this.loadMode_=bt.LoadMode.NOT_LOADED),!await this.atomicOperationAcquireMutex_("unload")){try{this.fullyLoaded_=!1,this.makeStateChangeEvent_("unload"),e&&!P.supportsMediaSource()&&(e=!1),this.closeLcevcDec_();const i=this.cleanupOnUnload_.map((e=>e()));if(this.cleanupOnUnload_=[],await Promise.all(i),this.dispatchEvent(bt.makeEvent_(s.EventName.Unloading)),this.regionTimeline_&&(this.regionTimeline_.release(),this.regionTimeline_=null),this.video_&&(this.loadEventManager_.removeAll(),this.trickPlayEventManager_.removeAll()),this.checkVariantsTimer_.stop(),this.playheadObservers_&&(this.playheadObservers_.release(),this.playheadObservers_=null),this.parser_&&(await this.parser_.stop(),this.parser_=null,this.parserFactory_=null),this.abrManager_&&await this.abrManager_.stop(),this.streamingEngine_&&(await this.streamingEngine_.destroy(),this.streamingEngine_=null),this.playRateController_&&(this.playRateController_.release(),this.playRateController_=null),this.playhead_&&(this.playhead_.release(),this.playhead_=null),this.mediaSourceEngine_&&(await this.mediaSourceEngine_.destroy(),this.mediaSourceEngine_=null),this.adManager_&&!t&&this.adManager_.onAssetUnload(),this.cmsdManager_&&this.cmsdManager_.reset(),this.video_&&ze.removeAllChildren(this.video_),this.video_&&this.video_.src&&(await new Promise((e=>new o(e).tickAfter(.1))),this.video_.removeAttribute("src"),this.video_.load()),this.assetUri_=null,this.mimeType_=null,this.bufferObserver_=null,this.manifest_){for(const e of this.manifest_.variants)for(const t of[e.audio,e.video])t&&t.segmentIndex&&t.segmentIndex.release();for(const e of this.manifest_.textStreams)e.segmentIndex&&e.segmentIndex.release()}this.manifest_=null,this.stats_=new ie,this.lastTextFactory_=null,this.externalSrcEqualsThumbnailsStreams_=[],this.completionPercent_=NaN,this.updateBufferState_()}finally{this.mutex_.release()}e&&P.supportsMediaSource()&&!this.mediaSourceEngine_&&await this.initializeMediaSourceEngineInner_()}}updateStartTime(e){this.startTime_=e}async load(e,t=null,i){if(console.log("load"),this.loadMode_==bt.LoadMode.DESTROYED)throw this.createAbortLoadError_();let n=null,a="";if(e instanceof xe?(n=e,a=n.getAssetUri()||""):a=e||"",await this.mutex_.acquire("load"),this.mutex_.release(),!this.video_)throw new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.NO_VIDEO_ELEMENT);this.assetUri_&&await this.unload(!1);const r=++this.operationId_,o=async()=>{if(this.operationId_!=r)throw n&&await n.destroy(),this.createAbortLoadError_()},l=async(e,t)=>{try{await this.mutex_.acquire(t),await o(),await e(),await o(),n&&this.config_&&n.reconfigure(this.config_)}finally{this.mutex_.release()}};try{null==t&&n&&(t=n.getStartTime()),this.startTime_=t,this.fullyLoaded_=!1,this.dispatchEvent(bt.makeEvent_(s.EventName.Loading)),n?i=n.getMimeType():i||await l((async()=>{i=await this.guessMimeType_(a)}),"guessMimeType_");const e=!!n;n?n.setEventHandoffTarget(this):(n=await this.preloadInner_(a,t,i,!0),n&&(n.setEventHandoffTarget(this),await l((()=>n.start()),"preload")));const r=!n,o=n?n.getStartTimeOfLoad():Date.now()/1e3;if(this.stats_=n?n.getStats():new ie,this.assetUri_=a,this.mimeType_=i||null,r)await l((async()=>{console.assert(i,"We should know the mimeType by now!"),await this.srcEqualsInner_(o,i)}),"srcEqualsInner_");else{this.mediaSourceEngine_||await l((async()=>{await this.initializeMediaSourceEngineInner_()}),"initializeMediaSourceEngineInner_"),await l((()=>n.waitForManifest()),"waitForManifest"),this.config_=n.getConfiguration(),this.manifestFilterer_=n.getManifestFilterer(),this.parserFactory_=n.getParserFactory(),this.parser_=n.receiveParser(),this.regionTimeline_=n.receiveRegionTimeline(),this.qualityObserver_=n.getQualityObserver(),this.manifest_=n.getManifest();const t=n.getCurrentAdaptationSetCriteria();t&&(this.currentAdaptationSetCriteria_=t),e&&this.video_&&"AUDIO"===this.video_.nodeName&&(this.makeManifestAudioOnly_(),this.configure("manifest.disableVideo",!0)),await l((()=>n.waitForChooseInitialVariant()),"waitForChooseInitialVariant");const i=n.getAbrManagerFactory();i&&(this.abrManagerFactory_&&this.abrManagerFactory_==i||(this.abrManager_=n.receiveAbrManager(),this.abrManagerFactory_=n.getAbrManagerFactory(),"function"!=typeof this.abrManager_.setMediaElement&&(ae.deprecateFeature(5,"AbrManager w/o setMediaElement","Please use an AbrManager with setMediaElement function."),this.abrManager_.setMediaElement=()=>{}),"function"!=typeof this.abrManager_.setCmsdManager&&(ae.deprecateFeature(5,"AbrManager w/o setCmsdManager","Please use an AbrManager with setCmsdManager function."),this.abrManager_.setCmsdManager=()=>{}),"function"!=typeof this.abrManager_.trySuggestStreams&&(ae.deprecateFeature(5,"AbrManager w/o trySuggestStreams","Please use an AbrManager with trySuggestStreams function."),this.abrManager_.trySuggestStreams=()=>{})));const s=n.receiveSegmentPrefetchesById(),a=n.getPrefetchedVariant();await l((async()=>{await this.loadInner_(o,a,s)}),"loadInner_"),n.stopQueuingLatePhaseQueuedOperations()}this.dispatchEvent(bt.makeEvent_(s.EventName.Loaded))}catch(e){throw e.code!=v.Code.LOAD_INTERRUPTED&&await this.unload(!1),e}finally{n&&await n.destroy()}}makeManifestAudioOnly_(){for(const e of this.manifest_.variants)e.video&&(e.video.closeSegmentIndex(),e.video=null),e.audio&&e.audio.bandwidth?e.bandwidth=e.audio.bandwidth:e.bandwidth=0;this.manifest_.variants=this.manifest_.variants.filter((e=>e.audio))}async unloadAndSavePreload(e=!0,t=!1){let i=null;if(this.manifest_&&this.parser_&&this.parserFactory_&&this.assetUri_){let e=this.video_.currentTime;this.isLive()&&(e=null);const t=Date.now()/1e3;i=await this.makePreloadManager_(this.assetUri_,e,this.mimeType_,t,!0,!1,!1),i.attachManifest(this.manifest_,this.parser_,this.parserFactory_),i.attachAbrManager(this.abrManager_,this.abrManagerFactory_),i.attachAdaptationSetCriteria(this.currentAdaptationSetCriteria_),i.start(),this.manifest_=null,this.parser_=null,this.parserFactory_=null,this.abrManager_=null,this.abrManagerFactory_=null}return await this.unload(e,t),i}async preload(e,t=null,i){const n=await this.preloadInner_(e,t,i);return n?n.start().catch((e=>{})):this.onError_(new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.SRC_EQUALS_PRELOAD_NOT_SUPPORTED)),n}async preloadInner_(e,t,i,n=!1){console.assert(this.networkingEngine_,"Should have a net engine!"),console.assert(this.config_,"Config must not be null!");const s=Date.now()/1e3;if(i||(i=await this.guessMimeType_(e)),this.shouldUseSrcEquals_(e,i))return null;let a=!1,r=!0;return n&&(this.abrManager_&&this.abrManagerFactory_==this.config_.abrFactory&&(r=!1),this.video_&&"AUDIO"===this.video_.nodeName&&(a=!0)),this.makePreloadManager_(e,t,i||null,s,!n,a,r)}async makePreloadManager_(e,t,i,n,a=!0,r=!1,o=!0){console.assert(this.networkingEngine_,"Must have net engine");let l=null;const d=b.cloneObject(this.config_);r&&(d.manifest.disableVideo=!0);const c=()=>(console.assert(l,"Must have preload manager"),l.hasBeenAttached()&&l.isDestroyed()?null:l),h=()=>c()?c().getConfiguration():this.config_,u=(e,t)=>{c()?l.configure(e,t):this.configure(e,t)};if(this.maxHwRes_.width==1/0&&this.maxHwRes_.height==1/0){const e=await P.detectMaxHardwareResolution();this.maxHwRes_.width=e.width,this.maxHwRes_.height=e.height}const _=new Te(d,this.maxHwRes_,null),m={networkingEngine:this.networkingEngine_,filter:async e=>{if(await _.filterManifest(e)){const e=bt.makeEvent_(s.EventName.TracksChanged);await Promise.resolve(),l.dispatchEvent(e)}},makeTextStreamsForClosedCaptions:e=>this.makeTextStreamsForClosedCaptions_(e),onTimelineRegionAdded:e=>{l.getRegionTimeline().addRegion(e)},onEvent:e=>l.dispatchEvent(e),onError:e=>l.onError(e),isLowLatencyMode:()=>h().streaming.lowLatencyMode,isAutoLowLatencyMode:()=>h().streaming.autoLowLatencyMode,enableLowLatencyMode:()=>{u("streaming.lowLatencyMode",!0)},updateDuration:()=>{this.streamingEngine_&&l.hasBeenAttached()&&this.streamingEngine_.updateDuration()},onManifestUpdated:()=>{const e=s.EventName.ManifestUpdated,t=(new Map).set("isLive",this.isLive());l.dispatchEvent(bt.makeEvent_(e,t)),l.addQueuedOperation(!1,(()=>{this.adManager_&&this.adManager_.onManifestUpdated(this.isLive())}))},getBandwidthEstimate:()=>this.abrManager_.getBandwidthEstimate()},g=new Ae((()=>this.seekRange()));g.addEventListener("regionadd",(e=>{const t=e.region;this.onRegionEvent_(s.EventName.TimelineRegionAdded,t,l),l.addQueuedOperation(!1,(()=>{this.adManager_&&this.adManager_.onDashTimedMetadata(t)}))}));let f=null;d.streaming.observeQualityChanges&&(f=new we((()=>this.getBufferedInfo())),f.addEventListener("qualitychange",(e=>{const t=e.quality,i=e.position;this.onMediaQualityChange_(t,i)})));const p=this.createNetworkingEngine(c);return l=new xe(e,i,n,t,{config:d,manifestPlayerInterface:m,regionTimeline:g,qualityObserver:f,manifestFilterer:_,networkingEngine:p,allowPrefetch:a,allowMakeAbrManager:o}),l}async guessMimeType_(e){console.assert(this.networkingEngine_,"Should have a net engine!");const t=this.config_.manifest.retryParameters;let i=await D.getMimeType(e,this.networkingEngine_,t);return"application/x-mpegurl"==i&&P.isApple()&&(i="application/vnd.apple.mpegurl"),i}shouldUseSrcEquals_(e,t){if(!P.supportsMediaSource())return!0;if(t){const e=""!=(this.video_||P.anyMediaElement()).canPlayType(t);if(!e)return!1;const i=ue.isSupported(t);return!(i&&(console.assert(e&&i,"Both native and MSE playback should be possible!"),!B.isHlsType(t)||!this.config_.streaming.preferNativeHls))}return!1}async initializeMediaSourceEngineInner_(){console.assert(P.supportsMediaSource(),"We should not be initializing media source on a platform that does not support media source."),console.assert(this.video_,"We should have a media element when initializing media source."),console.assert(null==this.mediaSourceEngine_,"We should not have a media source engine yet."),this.makeStateChangeEvent_("media-source");const e=this.config_.textDisplayFactory,t=e();this.lastTextFactory_=e;const i=this.createMediaSourceEngine(this.video_,t,((e,t,i)=>{this.processTimedMetadataMediaSrc_(e,t,i)}),this.lcevcDec_);i.configure(this.config_.mediaSource);const{segmentRelativeVttTiming:n}=this.config_.manifest;i.setSegmentRelativeVttTiming(n),await i.open(),this.mediaSourceEngine_=i}async loadInner_(e,t,n){console.assert(this.video_,"We should have a media element by now."),console.assert(this.manifest_,"The manifest should already be parsed."),console.assert(this.assetUri_,"We should have an asset uri by now."),console.assert(this.abrManager_,"We should have an abr manager by now."),this.makeStateChangeEvent_("load");const a=this.video_;this.playRateController_=new Xe({getRate:()=>a.playbackRate,getDefaultRate:()=>a.defaultPlaybackRate,setRate:e=>{a.playbackRate=e},movePlayhead:e=>{a.currentTime+=e}});const r=()=>this.updateStateHistory_();this.loadEventManager_.listen(a,"playing",r),this.loadEventManager_.listen(a,"pause",r),this.loadEventManager_.listen(a,"ended",r),this.loadEventManager_.listen(a,"ratechange",(()=>this.onRateChange_())),this.setupLcevc_(this.config_),this.currentTextLanguage_=this.config_.preferredTextLanguage,this.currentTextRole_=this.config_.preferredTextRole,this.currentTextForced_=this.config_.preferForcedSubs,bt.applyPlayRange_(this.manifest_.presentationTimeline,this.config_.playRangeStart,this.config_.playRangeEnd),this.abrManager_.init(((e,t,i)=>this.switch_(e,t,i))),this.abrManager_.setMediaElement(a),this.abrManager_.setCmsdManager(this.cmsdManager_),this.streamingEngine_=this.createStreamingEngine(),this.streamingEngine_.configure(this.config_.streaming),this.loadMode_=bt.LoadMode.MEDIA_SOURCE,a.textTracks&&this.loadEventManager_.listen(a.textTracks,"addtrack",(e=>{const t=e;if(t.track){const e=t.track;console.assert(e instanceof TextTrack,"Wrong track type!"),"chapters"===e.kind&&this.activateChaptersTrack_(e)}})),this.dispatchEvent(bt.makeEvent_(s.EventName.Streaming));let o=t;const l=this.streamingEngine_.getCurrentVariant();l||o||(o=this.chooseVariant_(!0),console.assert(o,"Must choose an initial variant!"));const d=[],c=l||o;for(const e of[c.video,c.audio])e&&!e.segmentIndex&&d.push(e.createSegmentIndex());d.length>0&&await Promise.all(d),this.parser_&&this.parser_.onInitialVariantChosen&&this.parser_.onInitialVariantChosen(c),bt.applyPlayRange_(this.manifest_.presentationTimeline,this.config_.playRangeStart,this.config_.playRangeEnd),this.playhead_=this.createPlayhead(this.startTime_),this.playheadObservers_=this.createPlayheadObserversForMSE_(e);const h=Math.max(this.manifest_.minBufferTime,this.config_.streaming.rebufferingGoal);if(this.startBufferManagement_(a,h),l||(console.assert(o,"Must have choosen an initial variant!"),this.switchVariant_(o,!0,!1,0),this.config_.streaming.startAtSegmentBoundary&&this.playhead_.setStartTime(await this.adjustStartTime_(o,this.playhead_.getTime()))),this.playhead_.ready(),!this.getTextTracks().find((e=>e.active))){const e=this.chooseTextStream_();e&&this.addTextStreamToSwitchHistory_(e,!0),o&&this.setInitialTextState_(o,e),e&&this.shouldStreamText_()&&this.streamingEngine_.switchTextStream(e)}await this.streamingEngine_.start(n),this.config_.abr.enabled&&(this.abrManager_.enable(),this.onAbrStatusChanged_()),this.onTracksChanged_(),this.updateAbrManagerVariants_();const u=this.manifest_.variants.some((e=>e.primary));this.config_.preferredAudioLanguage||u||i.warning("No preferred audio language set. We have chosen an arbitrary language initially");const _=this.isLive();if(_&&(this.config_.streaming.liveSync||this.manifest_.serviceDescription||this.config_.streaming.liveSyncPanicMode)||this.config_.streaming.vodDynamicPlaybackRate){const e=()=>this.onTimeUpdate_();this.loadEventManager_.listen(a,"timeupdate",e)}else if(!_){const e=()=>this.onVideoProgress_();this.loadEventManager_.listen(a,"timeupdate",e),this.onVideoProgress_()}this.adManager_&&this.adManager_.onManifestUpdated(_),this.fullyLoaded_=!0,this.loadEventManager_.listenOnce(a,"loadedmetadata",(()=>{const t=Date.now()/1e3-e;this.stats_.setLoadLatency(t)}))}async srcEqualsInner_(e,t){this.makeStateChangeEvent_("src-equals"),console.assert(this.video_,"We should have a media element when loading."),console.assert(this.assetUri_,"We should have a valid uri when loading.");const n=this.video_;this.playhead_=new He(n);let a=!1;this.cleanupOnUnload_.push((()=>{a=!0})),null!=this.startTime_&&this.playhead_.setStartTime(this.startTime_),this.playRateController_=new Xe({getRate:()=>n.playbackRate,getDefaultRate:()=>n.defaultPlaybackRate,setRate:e=>{n.playbackRate=e},movePlayhead:e=>{n.currentTime+=e}});const r=this.config_.streaming.rebufferingGoal;this.startBufferManagement_(n,r);const l=()=>this.updateStateHistory_();this.loadEventManager_.listen(n,"playing",l),this.loadEventManager_.listen(n,"pause",l),this.loadEventManager_.listen(n,"ended",l),this.loadEventManager_.listen(n,"ratechange",(()=>this.onRateChange_())),"none"!=n.preload&&this.loadEventManager_.listenOnce(n,"loadedmetadata",(()=>{const t=Date.now()/1e3-e;this.stats_.setLoadLatency(t)})),n.audioTracks&&(this.loadEventManager_.listen(n.audioTracks,"addtrack",(()=>this.onTracksChanged_())),this.loadEventManager_.listen(n.audioTracks,"removetrack",(()=>this.onTracksChanged_())),this.loadEventManager_.listen(n.audioTracks,"change",(()=>this.onTracksChanged_()))),n.textTracks&&(this.loadEventManager_.listen(n.textTracks,"addtrack",(e=>{const t=e;if(t.track){const e=t.track;switch(console.assert(e instanceof TextTrack,"Wrong track type!"),e.kind){case"metadata":this.processTimedMetadataSrcEqls_(e);break;case"chapters":this.activateChaptersTrack_(e);break;default:this.onTracksChanged_()}}})),this.loadEventManager_.listen(n.textTracks,"removetrack",(()=>this.onTracksChanged_())),this.loadEventManager_.listen(n.textTracks,"change",(()=>this.onTracksChanged_()))),n.src=this.cmcdManager_.appendSrcData(this.assetUri_,t),(P.isTizen()||P.isWebOS())&&n.load(),this.loadMode_=bt.LoadMode.SRC_EQUALS,this.dispatchEvent(bt.makeEvent_(s.EventName.Streaming));const d=new C;ke.waitForReadyState(n,HTMLMediaElement.HAVE_METADATA,this.loadEventManager_,(()=>{this.playhead_.ready(),d.resolve()})),ke.waitForReadyState(n,HTMLMediaElement.HAVE_CURRENT_DATA,this.loadEventManager_,(async()=>{this.setupPreferredAudioOnSrc_();const e=this.getFilteredTextTracks_();e.find((e=>"disabled"!=e.mode))?e.length>0&&(this.isTextVisible_=!0):await new Promise((e=>{this.loadEventManager_.listenOnce(n.textTracks,"change",e),new o(e).tickAfter(1)})),a||this.setupPreferredTextOnSrc_()})),n.error?d.reject(this.videoErrorToShakaError_()):"none"==n.preload&&(i.alwaysWarn('With <video preload="none">, the browser will not load anything until play() is called. We are unable to measure load latency in a meaningful way, and we cannot provide track info yet. Please do not use preload="none" with Shaka Player.'),d.resolve()),this.loadEventManager_.listenOnce(n,"error",(()=>{d.reject(this.videoErrorToShakaError_())})),await d;const c=this.isLive();if(c&&(this.config_.streaming.liveSync||this.config_.streaming.liveSyncPanicMode)||this.config_.streaming.vodDynamicPlaybackRate){const e=()=>this.onTimeUpdate_();this.loadEventManager_.listen(n,"timeupdate",e)}else if(!c){const e=()=>this.onVideoProgress_();this.loadEventManager_.listen(n,"timeupdate",e),this.onVideoProgress_()}if(this.adManager_&&(this.adManager_.onManifestUpdated(c),c)){let e=this.seekRange().end;this.loadEventManager_.listen(n,"progress",(()=>{const t=this.seekRange().end;e!=t&&(this.adManager_.onManifestUpdated(this.isLive()),e=t)}))}this.fullyLoaded_=!0}setupPreferredAudioOnSrc_(){const e=this.config_.preferredAudioLanguage;if(""==e)return;const t=this.config_.preferredVariantRole;this.selectAudioLanguage(e,t)}setupPreferredTextOnSrc_(){const e=this.config_.preferredTextLanguage;if(""==e)return;const t=this.config_.preferForcedSubs,i=this.config_.preferredTextRole;this.selectTextLanguage(e,i,t)}processTimedMetadataSrcEqls_(e){if("metadata"!=e.kind)return;e.mode="hidden",this.loadEventManager_.listen(e,"cuechange",(()=>{if(e.activeCues)for(const t of e.activeCues)this.dispatchMetadataEvent_(t.startTime,t.endTime,t.type,t.value),this.adManager_&&this.adManager_.onCueMetadataChange(t.value)}));const t=new o((()=>{const e=this.getMetadataTracks_();for(const t of e)t.mode="hidden"})).tickNow().tickAfter(.5);this.cleanupOnUnload_.push((()=>{t.stop()}))}processTimedMetadataMediaSrc_(e,t,i){for(const n of e)if(n.data&&n.cueTime&&n.frames){const e=n.cueTime+t;let s=i;s&&e>s&&(s=e);const a="org.id3";for(const t of n.frames){const i=t;this.dispatchMetadataEvent_(e,s,a,i)}this.adManager_&&this.adManager_.onHlsTimedMetadata(n,e)}}dispatchMetadataEvent_(e,t,i,n){console.assert(!t||e<=t,"Metadata start time should be less or equal to the end time!");const a=s.EventName.Metadata,r=(new Map).set("startTime",e).set("endTime",t).set("metadataType",i).set("payload",n);this.dispatchEvent(bt.makeEvent_(a,r))}activateChaptersTrack_(e){if(!e||"chapters"!=e.kind)return;e.mode="hidden";const t=new o((()=>{e.mode="hidden"})).tickNow().tickAfter(.5);this.cleanupOnUnload_.push((()=>{t.stop()}))}releaseAllMutexes(){this.mutex_.releaseAll()}createNetworkingEngine(e){e||(e=()=>null);const t=()=>e()?e().getAbrManager():this.abrManager_,i=()=>e()?e().getParser():this.parser_,n=t=>{e()?e().addQueuedOperation(!0,t):t()},a=t=>{e()?e().dispatchEvent(t):this.dispatchEvent(t)};return new O(((e,i,n,s)=>{const a=t();a&&a.segmentDownloaded(e,i,n,s)}),((e,t,i)=>{const r=s.EventName.DownloadHeadersReceived,o=(new Map).set("headers",e).set("request",t).set("requestType",i);a(bt.makeEvent_(r,o)),n((()=>{this.cmsdManager_&&this.cmsdManager_.processHeaders(e)}))}),((e,t,i,n)=>{const r=s.EventName.DownloadFailed,o=(new Map).set("request",e).set("error",t).set("httpResponseCode",i).set("aborted",n);a(bt.makeEvent_(r,o))}),((e,t,i)=>{n((()=>{this.cmcdManager_.applyData(e,t,i)}))}),((e,t,n,s)=>{const a=i();a&&a.banLocation&&a.banLocation(s)}))}createPlayhead(e){return console.assert(this.manifest_,"Must have manifest"),console.assert(this.video_,"Must have video"),new We(this.video_,this.manifest_,this.config_.streaming,e,(()=>this.onSeek_()),(e=>this.dispatchEvent(e)))}createPlayheadObserversForMSE_(e){console.assert(this.manifest_,"Must have manifest"),console.assert(this.regionTimeline_,"Must have region timeline"),console.assert(this.video_,"Must have video element");const t=this.isLive()||e>0,i=new Ce(this.regionTimeline_,t);i.addEventListener("enter",(e=>{const t=e.region;this.onRegionEvent_(s.EventName.TimelineRegionEnter,t)})),i.addEventListener("exit",(e=>{const t=e.region;this.onRegionEvent_(s.EventName.TimelineRegionExit,t)})),i.addEventListener("skip",(e=>{const t=e.region;e.seeking||(this.onRegionEvent_(s.EventName.TimelineRegionEnter,t),this.onRegionEvent_(s.EventName.TimelineRegionExit,t))}));const n=new be(this.video_);return n.manage(i),this.qualityObserver_&&n.manage(this.qualityObserver_),n}startBufferManagement_(e,t){console.assert(!this.bufferObserver_,"No buffering observer should exist before initialization."),this.bufferObserver_=new qe(1,2),this.bufferObserver_.setState(qe.State.STARVING),this.updateBufferingSettings_(t),this.updateBufferState_(),this.loadEventManager_.listen(e,"waiting",(e=>this.pollBufferState_())),this.loadEventManager_.listen(e,"stalled",(e=>this.pollBufferState_())),this.loadEventManager_.listen(e,"canplaythrough",(e=>this.pollBufferState_())),this.loadEventManager_.listen(e,"progress",(e=>this.pollBufferState_()))}updateBufferingSettings_(e){const t=e,i=Math.min(bt.TYPICAL_BUFFERING_THRESHOLD_,e/2);this.bufferObserver_.setThresholds(t,i)}pollBufferState_(){let e;switch(console.assert(this.video_,"Need a media element to update the buffering observer"),console.assert(this.bufferObserver_,"Need a buffering observer to update"),this.loadMode_){case bt.LoadMode.SRC_EQUALS:e=this.isBufferedToEndSrc_();break;case bt.LoadMode.MEDIA_SOURCE:e=this.isBufferedToEndMS_();break;default:e=!1}const t=me.bufferedAheadOf(this.video_.buffered,this.video_.currentTime);this.bufferObserver_.update(t,e)&&this.updateBufferState_()}createMediaSourceEngine(e,t,i,n){return new fe(e,t,i,n)}createCmcd_(){return new ne({getBandwidthEstimate:()=>this.abrManager_?this.abrManager_.getBandwidthEstimate():NaN,getBufferedInfo:()=>this.getBufferedInfo(),getCurrentTime:()=>this.video_?this.video_.currentTime:0,getPlaybackRate:()=>this.getPlaybackRate(),getNetworkingEngine:()=>this.getNetworkingEngine(),getVariantTracks:()=>this.getVariantTracks(),isLive:()=>this.isLive()},this.config_.cmcd)}createCmsd_(){return new se(this.config_.cmsd)}createStreamingEngine(){console.assert(this.abrManager_&&this.mediaSourceEngine_&&this.manifest_,"Must not be destroyed");const e={getPresentationTime:()=>this.playhead_?this.playhead_.getTime():0,getBandwidthEstimate:()=>this.abrManager_.getBandwidthEstimate(),mediaSourceEngine:this.mediaSourceEngine_,netEngine:this.networkingEngine_,onError:e=>this.onError_(e),onEvent:e=>this.dispatchEvent(e),onManifestUpdate:()=>this.onManifestUpdate_(),onSegmentAppended:(e,t)=>{this.onSegmentAppended_(e.startTime,e.endTime,t.type),this.abrManager_&&t.fastSwitching&&e.isPartial()&&e.isLastPartial()&&this.abrManager_.trySuggestStreams()},onInitSegmentAppended:(e,t)=>{const i=t.getMediaQuality();i&&this.qualityObserver_&&this.qualityObserver_.addMediaQualityChange(i,e)},beforeAppendSegment:(e,t)=>{},onMetadata:(e,t,i)=>{this.processTimedMetadataMediaSrc_(e,t,i)},disableStream:(e,t)=>this.disableStream(e,t)};return new Le(this.manifest_,e)}configure(e,t){console.assert(this.config_,"Config must not be null!"),console.assert("object"==typeof e||2==arguments.length,"String configs should have values!"),2==arguments.length&&"string"==typeof e&&(e=j.convertToConfigObject(e,t)),console.assert("object"==typeof e,"Should be an object!"),e.streaming&&"forceTransmuxTS"in e.streaming&&(ae.deprecateFeature(5,"streaming.forceTransmuxTS configuration","Please Use mediaSource.forceTransmux instead."),e.mediaSource.mediaSource=e.streaming.forceTransmuxTS,delete e.streaming.forceTransmuxTS),e.streaming&&"forceTransmux"in e.streaming&&(ae.deprecateFeature(5,"streaming.forceTransmux configuration","Please Use mediaSource.forceTransmux instead."),e.mediaSource.mediaSource=e.streaming.forceTransmux,delete e.streaming.forceTransmux),e.streaming&&e.streaming.lowLatencyMode&&(null==e.streaming.inaccurateManifestTolerance&&(e.streaming.inaccurateManifestTolerance=0),null==e.streaming.rebufferingGoal&&(e.streaming.rebufferingGoal=.01),null==e.streaming.segmentPrefetchLimit&&(e.streaming.segmentPrefetchLimit=2),null==e.streaming.retryParameters&&(e.streaming.retryParameters={}),null==e.streaming.retryParameters.baseDelay&&(e.streaming.retryParameters.baseDelay=100),null==e.manifest&&(e.manifest={}),null==e.manifest.retryParameters&&(e.manifest.retryParameters={}),null==e.manifest.retryParameters.baseDelay&&(e.manifest.retryParameters.baseDelay=100));const i=J.mergeConfigObjects(this.config_,e,this.defaultConfig_());return this.applyConfig_(),i}applyConfig_(){if(this.manifestFilterer_=new Te(this.config_,this.maxHwRes_),this.parser_){const e=b.cloneObject(this.config_.manifest);this.video_&&"AUDIO"===this.video_.nodeName&&(e.disableVideo=!0),this.parser_.configure(e)}if(this.streamingEngine_){this.streamingEngine_.configure(this.config_.streaming);try{this.loadMode_!=bt.LoadMode.DESTROYED&&this.manifestFilterer_.filterManifestWithRestrictions(this.manifest_)&&this.onTracksChanged_()}catch(e){this.onError_(e)}this.abrManager_&&this.updateAbrManagerVariants_();const e=this.streamingEngine_.getCurrentVariant();e&&(e.allowedByApplication&&e.allowedByKeySystem||(i.debug("Choosing new variant after changing configuration"),this.chooseVariantAndSwitch_()))}if(this.networkingEngine_&&this.networkingEngine_.setForceHTTPS(this.config_.streaming.forceHTTPS),this.mediaSourceEngine_){this.mediaSourceEngine_.configure(this.config_.mediaSource);const{segmentRelativeVttTiming:e}=this.config_.manifest;this.mediaSourceEngine_.setSegmentRelativeVttTiming(e);const t=this.config_.textDisplayFactory;if(this.lastTextFactory_!=t){const e=t();this.mediaSourceEngine_.setTextDisplayer(e),this.lastTextFactory_=t,this.streamingEngine_&&this.streamingEngine_.reloadTextStream()}}if(this.abrManager_&&(this.abrManager_.configure(this.config_.abr),this.config_.abr.enabled?this.abrManager_.enable():this.abrManager_.disable(),this.onAbrStatusChanged_()),this.bufferObserver_){let e=this.config_.streaming.rebufferingGoal;this.manifest_&&(e=Math.max(e,this.manifest_.minBufferTime)),this.updateBufferingSettings_(e)}this.manifest_&&bt.applyPlayRange_(this.manifest_.presentationTimeline,this.config_.playRangeStart,this.config_.playRangeEnd),this.adManager_&&this.adManager_.configure(this.config_.ads),this.cmcdManager_&&this.cmcdManager_.configure(this.config_.cmcd),this.cmsdManager_&&this.cmsdManager_.configure(this.config_.cmsd)}getConfiguration(){console.assert(this.config_,"Config must not be null!");const e=this.defaultConfig_();return J.mergeConfigObjects(e,this.config_,this.defaultConfig_()),e}getSharedConfiguration(){return console.assert(this.config_,"Cannot call getSharedConfiguration after call destroy!"),this.config_}getBufferFullness(){if(this.video_){const e=this.video_.buffered.length,t=e?this.video_.buffered.end(e-1):0,i=this.getConfiguration().streaming.bufferingGoal,n=Math.min(this.video_.currentTime+i,this.seekRange().end);if(t>=n)return 1;if(t<=this.video_.currentTime)return 0;if(t<n)return(t-this.video_.currentTime)/(n-this.video_.currentTime)}return 0}resetConfiguration(){console.assert(this.config_,"Cannot be destroyed");for(const e in this.config_)delete this.config_[e];J.mergeConfigObjects(this.config_,this.defaultConfig_(),this.defaultConfig_()),this.applyConfig_()}getLoadMode(){return this.loadMode_}getManifestType(){return this.manifest_?this.manifest_.type:null}getMediaElement(){return this.video_}getNetworkingEngine(){return this.networkingEngine_}getAssetUri(){return this.assetUri_}getAdManager(){return this.adManager_?this.adManager_:null}isLive(){return this.manifest_?this.manifest_.presentationTimeline.isLive():!(!this.video_||!this.video_.src)&&this.video_.duration==1/0}isInProgress(){return!!this.manifest_&&this.manifest_.presentationTimeline.isInProgress()}isAudioOnly(){if(this.manifest_){const e=this.manifest_.variants;return!!e.length&&!e[0].video}return!(!this.video_||!this.video_.src)&&(this.video_.videoTracks?0==this.video_.videoTracks.length:0==this.video_.videoHeight)}seekRange(){if(this.manifest_){if(!this.fullyLoaded_&&this.manifest_.type==ue.HLS)return{start:0,end:0};const e=this.manifest_.presentationTimeline;return{start:e.getSeekRangeStart(),end:e.getSeekRangeEnd()}}if(this.video_&&this.video_.src){const e=this.video_.seekable;if(e.length)return{start:e.start(0),end:e.end(e.length-1)}}return{start:0,end:0}}goToLive(){this.isLive()?this.video_.currentTime=this.seekRange().end:i.warning("goToLive is for live streams!")}getExpiration(){return 1/0}getActiveSessionsMetadata(){return[]}getKeyStatuses(){return{}}isBuffering(){const e=qe.State;return!!this.bufferObserver_&&this.bufferObserver_.getState()==e.STARVING}getPlaybackRate(){return this.video_?this.playRateController_?this.playRateController_.getRealRate():1:0}trickPlay(e){console.assert(0!=e,"Should never set a trick play rate of 0!"),0!=e?(this.trickPlayEventManager_.removeAll(),this.video_.paused&&this.video_.play(),this.playRateController_.set(e),this.loadMode_==bt.LoadMode.MEDIA_SOURCE&&(this.abrManager_.playbackRateChanged(e),this.streamingEngine_.setTrickPlay(Math.abs(e)>1)),this.isLive()&&this.trickPlayEventManager_.listen(this.video_,"timeupdate",(()=>{const t=this.video_.currentTime,i=this.seekRange(),n=this.config_.streaming.safeSeekOffset;e>0?t>=i.end&&this.cancelTrickPlay():t<=i.start+n&&this.cancelTrickPlay()}))):i.alwaysWarn("A trick play rate of 0 is unsupported!")}cancelTrickPlay(){const e=this.playRateController_.getDefaultRate();this.loadMode_==bt.LoadMode.SRC_EQUALS&&this.playRateController_.set(e),this.loadMode_==bt.LoadMode.MEDIA_SOURCE&&(this.playRateController_.set(e),this.abrManager_.playbackRateChanged(e),this.streamingEngine_.setTrickPlay(!1)),this.trickPlayEventManager_.removeAll()}getVariantTracks(){if(this.manifest_){const e=this.streamingEngine_?this.streamingEngine_.getCurrentVariant():null,t=[];let i=0;for(const n of this.manifest_.variants){if(!z.isPlayable(n))continue;const s=z.variantToTrack(n);s.active=n==e,s.active||1==i||null==e||n.video!=e.video||n.audio!=e.audio||(s.active=!0),s.active&&i++,t.push(s)}return console.assert(i<=1,"It should only have one active track"),t}return this.video_&&this.video_.audioTracks?Array.from(this.video_.audioTracks).map((e=>z.html5AudioTrackToTrack(e))):[]}getTextTracks(){if(this.manifest_){const e=this.streamingEngine_?this.streamingEngine_.getCurrentTextStream():null,t=[];for(const i of this.manifest_.textStreams){const n=z.textStreamToTrack(i);n.active=i==e,t.push(n)}return t}if(this.video_&&this.video_.src&&this.video_.textTracks){const e=this.getFilteredTextTracks_(),t=t;return e.map((e=>t.html5TextTrackToTrack(e)))}return[]}getImageTracks(){const e=e;let t=this.externalSrcEqualsThumbnailsStreams_;return this.manifest_&&(t=this.manifest_.imageStreams),t.map((t=>e.imageStreamToTrack(t)))}async getAllThumbnails(e){if(this.loadMode_!=bt.LoadMode.MEDIA_SOURCE&&this.loadMode_!=bt.LoadMode.SRC_EQUALS)return null;let t=this.externalSrcEqualsThumbnailsStreams_;this.manifest_&&(t=this.manifest_.imageStreams);const i=t.find((t=>t.id==e));if(!i)return null;i.segmentIndex||await i.createSegmentIndex();const n=[];return i.segmentIndex.forEachTopLevelReference((t=>{const s=this.parseTilesLayout_(t.getTilesLayout()||i.tilesLayout);if(s){const i=s.rows*s.columns,a=t.trueEndTime-t.startTime;for(let s=0;s<i;s++){const r=t.startTime+a*s/i;n.push(this.getThumbnails(e,r))}}})),(await Promise.all(n)).filter((e=>e))}parseTilesLayout_(e){if(!e)return null;const t=/(\d+)x(\d+)/.exec(e);return t?{columns:parseInt(t[1],10),rows:parseInt(t[2],10)}:(i.warning("Tiles layout does not contain a valid format (columns x rows)"),null)}async getThumbnails(e,t){if(this.loadMode_!=bt.LoadMode.MEDIA_SOURCE&&this.loadMode_!=bt.LoadMode.SRC_EQUALS)return null;let i=this.externalSrcEqualsThumbnailsStreams_;this.manifest_&&(i=this.manifest_.imageStreams);const n=i.find((t=>t.id==e));if(!n)return null;n.segmentIndex||await n.createSegmentIndex();const s=n.segmentIndex.find(t);if(null==s)return null;const a=n.segmentIndex.get(s),r=this.parseTilesLayout_(a.getTilesLayout()||n.tilesLayout);if(!r)return null;const o=n.width||0,l=n.height||0;let d=o/r.columns,c=l/r.rows;const h=r.columns*r.rows,u=a.trueEndTime-a.startTime,_=a.getTileDuration()||u/h;let m=a.startTime,g=0,f=0;if(h>1){const e=Math.floor((t-a.startTime)/_);m=a.startTime+e*_,g=e%r.columns*d,f=Math.floor(e/r.columns)*c}let p=!1;const T=a.getThumbnailSprite();return T&&(p=!0,c=T.height,g=T.positionX,f=T.positionY,d=T.width),{segment:a,imageHeight:l,imageWidth:o,height:c,positionX:g,positionY:f,startTime:m,duration:_,uris:a.getUris(),width:d,sprite:p}}selectTextTrack(e){if(this.manifest_&&this.streamingEngine_){const t=this.manifest_.textStreams.find((t=>t.id==e.id));if(!t)return void i.error("No stream with id",e.id);if(t==this.streamingEngine_.getCurrentTextStream())return void i.debug("Text track already selected.");this.addTextStreamToSwitchHistory_(t,!1),this.streamingEngine_.switchTextStream(t),this.onTextChanged_(),this.currentTextLanguage_=t.language}else if(this.video_&&this.video_.src&&this.video_.textTracks){const t=this.getFilteredTextTracks_();for(const i of t)z.html5TrackId(i)==e.id?i.mode=this.isTextVisible_?"showing":"hidden":i.mode="disabled";this.onTextChanged_()}}selectVariantTrack(e,t=!1,n=0){if(this.manifest_&&this.streamingEngine_){this.config_.abr.enabled&&i.alwaysWarn("Changing tracks while abr manager is enabled will likely result in the selected track being overriden. Consider disabling abr before calling selectVariantTrack().");const s=this.manifest_.variants.find((t=>t.id==e.id));if(!s)return void i.error("No variant with id",e.id);if(!z.isPlayable(s))return void i.error("Unable to switch to restricted track",e.id);this.switchVariant_(s,!1,t,n),this.currentAdaptationSetCriteria_=new De(s,this.config_.mediaSource.codecSwitchingStrategy,this.config_.manifest.dash.enableAudioGroups),this.updateAbrManagerVariants_()}else if(this.video_&&this.video_.audioTracks){const t=Array.from(this.video_.audioTracks);for(const i of t)if(z.html5TrackId(i)==e.id)return void this.switchHtml5Track_(i)}}getAudioLanguagesAndRoles(){return bt.getLanguageAndRolesFrom_(this.getVariantTracks())}getTextLanguagesAndRoles(){return bt.getLanguageAndRolesFrom_(this.getTextTracks())}getAudioLanguages(){return Array.from(bt.getLanguagesFrom_(this.getVariantTracks()))}getTextLanguages(){return Array.from(bt.getLanguagesFrom_(this.getTextTracks()))}selectAudioLanguage(e,t,i=0,n=0){if(this.manifest_&&this.playhead_){this.currentAdaptationSetCriteria_=new Pe(e,t||"",i,"",!1,"","","",this.config_.mediaSource.codecSwitchingStrategy,this.config_.manifest.dash.enableAudioGroups);const s=(e,t)=>e.video||t.video?e.video&&t.video?Math.abs((e.video.height||0)-(t.video.height||0))+Math.abs((e.video.width||0)-(t.video.width||0)):1/0:0,a=this.streamingEngine_.getCurrentVariant(),r=this.currentAdaptationSetCriteria_.create(this.manifest_.variants);let o=null;for(const e of r.values())(!o||s(o,a)>s(e,a))&&(o=e);if(o){const e=z.variantToTrack(o);return void this.selectVariantTrack(e,!0,n)}this.chooseVariantAndSwitch_()}else if(this.video_&&this.video_.audioTracks){const i=z.filterStreamsByLanguageAndRole(this.getVariantTracks(),e,t||"",!1)[0];i&&this.selectVariantTrack(i)}}selectTextLanguage(e,t,n=!1){if(this.manifest_&&this.playhead_){this.currentTextLanguage_=e,this.currentTextRole_=t||"",this.currentTextForced_=n;const s=this.chooseTextStream_();if(s){if(s==this.streamingEngine_.getCurrentTextStream())return void i.debug("Text track already selected.");this.addTextStreamToSwitchHistory_(s,!1),this.shouldStreamText_()&&(this.streamingEngine_.switchTextStream(s),this.onTextChanged_())}}else{const i=z.filterStreamsByLanguageAndRole(this.getTextTracks(),e,t||"",n)[0];i&&this.selectTextTrack(i)}}selectVariantsByLabel(e,t=!0,n=0){if(this.manifest_&&this.playhead_){let s=null;for(const t of this.manifest_.variants)if(t.audio.label==e){s=t;break}if(null==s)return void i.warning("No variants were found with label: "+e+". Ignoring the request to switch.");this.currentAdaptationSetCriteria_=new Pe(s.language,"",0,"",!1,"",e,"",this.config_.mediaSource.codecSwitchingStrategy,this.config_.manifest.dash.enableAudioGroups),this.chooseVariantAndSwitch_(t,n)}else if(this.video_&&this.video_.audioTracks){const t=Array.from(this.video_.audioTracks);let i=null;for(const n of t)n.label==e&&(i=n);i&&this.switchHtml5Track_(i)}}isTextTrackVisible(){const e=this.isTextVisible_;if(this.mediaSourceEngine_&&this.loadMode_==bt.LoadMode.MEDIA_SOURCE){const t=this.mediaSourceEngine_.getTextDisplayer().isTextVisible();return console.assert(t==e,"text visibility has fallen out of sync"),t}return this.video_&&this.video_.src&&this.video_.textTracks?this.getFilteredTextTracks_().some((e=>"showing"==e.mode)):e}getChaptersTracks(){if(this.video_&&this.video_.src&&this.video_.textTracks){const e=this.getChaptersTracks_(),t=t;return e.map((e=>t.html5TextTrackToTrack(e)))}return[]}getChapters(e){if(!this.video_||!this.video_.src||!this.video_.textTracks)return[];const t=G.normalize(e),i=this.getChaptersTracks_().filter((e=>G.normalize(e.language)==t));if(!i||!i.length)return[];const n=[],s=new Set;for(const e of i)if(e&&e.cues)for(const t of e.cues){let e=t.id;e&&""!=e||(e=t.startTime+"-"+t.endTime+"-"+t.text);const i={id:e,title:t.text,startTime:t.startTime,endTime:t.endTime};s.has(e)||(n.push(i),s.add(e))}return n}getFilteredTextTracks_(){return console.assert(this.video_.textTracks,"TextTracks should be valid."),Array.from(this.video_.textTracks).filter((e=>"metadata"!=e.kind&&"chapters"!=e.kind&&e.label!=bt.TextTrackLabel))}getMetadataTracks_(){return console.assert(this.video_.textTracks,"TextTracks should be valid."),Array.from(this.video_.textTracks).filter((e=>"metadata"==e.kind))}getChaptersTracks_(){return console.assert(this.video_.textTracks,"TextTracks should be valid."),Array.from(this.video_.textTracks).filter((e=>"chapters"==e.kind))}setTextTrackVisibility(e){const t=!!e;if(this.isTextVisible_!=t){if(this.isTextVisible_=t,this.loadMode_==bt.LoadMode.MEDIA_SOURCE){if(this.mediaSourceEngine_.getTextDisplayer().setTextVisibility(t),!this.config_.streaming.alwaysStreamText)if(t)if(this.streamingEngine_.getCurrentTextStream());else{const e=z.filterStreamsByLanguageAndRole(this.manifest_.textStreams,this.currentTextLanguage_,this.currentTextRole_,this.currentTextForced_);e.length>0&&(this.streamingEngine_.switchTextStream(e[0]),this.onTextChanged_())}else this.streamingEngine_.unloadTextStream()}else if(this.video_&&this.video_.src&&this.video_.textTracks){const e=this.getFilteredTextTracks_();for(const i of e)"disabled"!=i.mode&&(i.mode=t?"showing":"hidden")}this.onTextTrackVisibility_()}}getPlayheadTimeAsDate(){if(!this.isLive())return i.warning("getPlayheadTimeAsDate is for live streams!"),null;let e=0;if(this.playhead_)e=this.playhead_.getTime();else{if(null==this.startTime_)return new Date;e=this.startTime_}if(this.manifest_){const t=this.manifest_.presentationTimeline,i=t.getInitialProgramDateTime()||t.getPresentationStartTime();return new Date(1e3*(i+e))}if(this.video_&&this.video_.getStartDate){const t=this.video_.getStartDate();return isNaN(t.getTime())?(i.warning("EXT-X-PROGRAM-DATETIME required to get playhead time as Date!"),null):new Date(t.getTime()+1e3*e)}return i.warning("No way to get playhead time as Date!"),null}getPresentationStartTimeAsDate(){if(!this.isLive())return i.warning("getPresentationStartTimeAsDate is for live streams!"),null;if(this.manifest_){const e=this.manifest_.presentationTimeline.getPresentationStartTime();return console.assert(null!=e,"Presentation start time should not be null!"),new Date(1e3*e)}if(this.video_&&this.video_.getStartDate){const e=this.video_.getStartDate();return isNaN(e.getTime())?(i.warning("EXT-X-PROGRAM-DATETIME required to get presentation start time as Date!"),null):e}return i.warning("No way to get presentation start time as Date!"),null}getSegmentAvailabilityDuration(){return this.isLive()?this.manifest_?this.manifest_.presentationTimeline.getSegmentAvailabilityDuration():(i.warning("No way to get segment segment availability duration!"),null):(i.warning("getSegmentAvailabilityDuration is for live streams!"),null)}getBufferedInfo(){if(this.loadMode_==bt.LoadMode.MEDIA_SOURCE)return this.mediaSourceEngine_.getBufferedInfo();const e={total:[],audio:[],video:[],text:[]};if(this.loadMode_==bt.LoadMode.SRC_EQUALS){const t=t;e.total=t.getBufferedInfo(this.video_.buffered)}return e}getStats(){if(this.loadMode_!=bt.LoadMode.MEDIA_SOURCE&&this.loadMode_!=bt.LoadMode.SRC_EQUALS)return ie.getEmptyBlob();this.updateStateHistory_(),console.assert(this.video_,"If we have stats, we should have video_");const e=this.video_,t=e.currentTime/e.duration;if(isNaN(t)||this.stats_.setCompletionPercent(Math.round(100*t)),this.playhead_&&(this.stats_.setGapsJumped(this.playhead_.getGapsJumped()),this.stats_.setStallsDetected(this.playhead_.getStallsDetected())),e.getVideoPlaybackQuality){const t=e.getVideoPlaybackQuality();this.stats_.setDroppedFrames(Number(t.droppedVideoFrames),Number(t.totalVideoFrames)),this.stats_.setCorruptedFrames(Number(t.corruptedVideoFrames))}if(this.loadMode_==bt.LoadMode.MEDIA_SOURCE){const t=this.streamingEngine_.getCurrentVariant(),i=this.streamingEngine_.getCurrentTextStream();if(t){const e=this.playRateController_?this.playRateController_.getRealRate():1;let n=e*t.bandwidth;i&&i.bandwidth&&(n+=e*i.bandwidth),this.stats_.setCurrentStreamBandwidth(n)}if(t&&t.video&&this.stats_.setResolution(t.video.width||NaN,t.video.height||NaN),this.isLive()){const t=this.getPresentationStartTimeAsDate().valueOf()+1e3*e.currentTime,i=(Date.now()-t)/1e3;this.stats_.setLiveLatency(i)}if(this.manifest_&&this.manifest_.presentationTimeline){const e=this.manifest_.presentationTimeline.getMaxSegmentDuration();this.stats_.setMaxSegmentDuration(e)}const n=this.abrManager_.getBandwidthEstimate();this.stats_.setBandwidthEstimate(n)}return this.loadMode_==bt.LoadMode.SRC_EQUALS&&this.stats_.setResolution(e.videoWidth||NaN,e.videoHeight||NaN),this.stats_.getBlob()}async addTextTrackAsync(e,t,n,s,a,r,o=!1){if(this.loadMode_!=bt.LoadMode.MEDIA_SOURCE&&this.loadMode_!=bt.LoadMode.SRC_EQUALS)throw i.error("Must call load() and wait for it to resolve before adding text tracks."),new v(v.Severity.RECOVERABLE,v.Category.PLAYER,v.Code.CONTENT_NOT_LOADED);"subtitles"!=n&&"captions"!=n&&i.alwaysWarn("Using a kind value different of `subtitles` or `captions` can cause unwanted issues."),s||(s=await this.getTextMimetype_(e));let l=[];if(this.adManager_&&(l=this.adManager_.getCuePoints()),this.loadMode_==bt.LoadMode.SRC_EQUALS){o&&(n="forced"),await this.addSrcTrackElement_(e,t,n,s,r||"",l);const a=a,d=a.normalize(t),c=this.getTextTracks().find((e=>a.normalize(e.language)==d&&e.label==(r||"")&&e.kind==n));if(c)return this.onTracksChanged_(),c;throw i.error("Cannot add this text when loaded with src="),new v(v.Severity.RECOVERABLE,v.Category.TEXT,v.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS)}const d=k.ContentType;let c=this.video_.duration;if(this.manifest_&&(c=this.manifest_.presentationTimeline.getDuration()),c==1/0)throw new v(v.Severity.RECOVERABLE,v.Category.MANIFEST,v.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM);if(l.length){console.assert(this.networkingEngine_,"Need networking engine.");const t=await this.getTextData_(e,this.networkingEngine_,this.config_.streaming.retryParameters),i=this.convertToWebVTT_(t,s,l),n=new Blob([i],{type:"text/vtt"});e=fe.createObjectURL(n),s="text/vtt"}const h={id:this.nextExternalStreamId_++,originalId:null,groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:Ee.forSingleSegment(0,c,[e]),mimeType:s||"",codecs:a||"",kind:n,language:t,originalLanguage:t,label:r||null,type:d.TEXT,primary:!1,trickModeVideo:null,emsgSchemeIdUris:null,roles:[],forced:Boolean(o),channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,accessibilityPurpose:null,external:!0,fastSwitching:!1},u=B.getFullType(h.mimeType,h.codecs);if(!X.isTypeSupported(u))throw new v(v.Severity.CRITICAL,v.Category.TEXT,v.Code.MISSING_TEXT_PLUGIN,s);return this.manifest_.textStreams.push(h),this.onTracksChanged_(),z.textStreamToTrack(h)}async addThumbnailsTrack(e,t){if(this.loadMode_!=bt.LoadMode.MEDIA_SOURCE&&this.loadMode_!=bt.LoadMode.SRC_EQUALS)throw i.error("Must call load() and wait for it to resolve before adding image tracks."),new v(v.Severity.RECOVERABLE,v.Category.PLAYER,v.Code.CONTENT_NOT_LOADED);if(t||(t=await this.getTextMimetype_(e)),"text/vtt"!=t)throw new v(v.Severity.RECOVERABLE,v.Category.TEXT,v.Code.UNSUPPORTED_EXTERNAL_THUMBNAILS_URI,e);const n=k.ContentType;let s=this.video_.duration;if(this.manifest_&&(s=this.manifest_.presentationTimeline.getDuration()),s==1/0)throw new v(v.Severity.RECOVERABLE,v.Category.MANIFEST,v.Code.CANNOT_ADD_EXTERNAL_THUMBNAILS_TO_LIVE_STREAM);console.assert(this.networkingEngine_,"Need networking engine.");const a=await this.getTextData_(e,this.networkingEngine_,this.config_.streaming.retryParameters),r=X.findParser(t);if(!r)throw new v(v.Severity.CRITICAL,v.Category.TEXT,v.Code.MISSING_TEXT_PLUGIN,t);const o=r(),d={periodStart:0,segmentStart:0,segmentEnd:s,vttOffset:0},c=l.toUint8(a),h=o.parseMedia(c,d,e),u=[];for(const t of h){let i=null;const n=()=>(null==i&&(i=k.resolveUris([e],[t.payload])),i||[]),s=new ye(t.startTime,t.endTime,n,0,null,null,0,0,1/0);if(t.payload.includes("#xywh")){const e=t.payload.split("#xywh=")[1].split(",");4===e.length&&s.setThumbnailSprite({height:parseInt(e[3],10),positionX:parseInt(e[0],10),positionY:parseInt(e[1],10),width:parseInt(e[2],10)})}u.push(s)}const _={id:this.nextExternalStreamId_++,originalId:null,groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:new Ee(u),mimeType:t||"",codecs:"",kind:"",language:"und",originalLanguage:null,label:null,type:n.IMAGE,primary:!1,trickModeVideo:null,emsgSchemeIdUris:null,roles:[],forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,tilesLayout:"1x1",accessibilityPurpose:null,external:!0,fastSwitching:!1};return this.loadMode_==bt.LoadMode.SRC_EQUALS?this.externalSrcEqualsThumbnailsStreams_.push(_):this.manifest_.imageStreams.push(_),this.onTracksChanged_(),z.imageStreamToTrack(_)}async addChaptersTrack(e,t,n){if(this.loadMode_!=bt.LoadMode.MEDIA_SOURCE&&this.loadMode_!=bt.LoadMode.SRC_EQUALS)throw i.error("Must call load() and wait for it to resolve before adding chapters tracks."),new v(v.Severity.RECOVERABLE,v.Category.PLAYER,v.Code.CONTENT_NOT_LOADED);n||(n=await this.getTextMimetype_(e));let s=[];this.adManager_&&(s=this.adManager_.getCuePoints());const a=await this.addSrcTrackElement_(e,t,"chapters",n,"",s),r=this.getChaptersTracks().find((e=>e.language==t));if(r)return await new Promise(((e,t)=>{this.loadEventManager_.listenOnce(a,"load",e),this.loadEventManager_.listenOnce(a,"error",(e=>{t(new v(v.Severity.RECOVERABLE,v.Category.TEXT,v.Code.CHAPTERS_TRACK_FAILED))}))})),this.onTracksChanged_(),r;throw i.error("Cannot add this text when loaded with src="),new v(v.Severity.RECOVERABLE,v.Category.TEXT,v.Code.CANNOT_ADD_EXTERNAL_TEXT_TO_SRC_EQUALS)}async getTextMimetype_(e){let t;try{console.assert(this.networkingEngine_,"Need networking engine."),t=await D.getMimeType(e,this.networkingEngine_,this.config_.streaming.retryParameters)}catch(e){}if(t)return t;throw i.error("The mimeType has not been provided and it could not be deduced from its uri."),new v(v.Severity.RECOVERABLE,v.Category.TEXT,v.Code.TEXT_COULD_NOT_GUESS_MIME_TYPE,e)}async addSrcTrackElement_(e,t,i,n,s,a){if("text/vtt"!=n||a.length){console.assert(this.networkingEngine_,"Need networking engine.");const t=await this.getTextData_(e,this.networkingEngine_,this.config_.streaming.retryParameters),i=this.convertToWebVTT_(t,n,a),s=new Blob([i],{type:"text/vtt"});e=fe.createObjectURL(s),n="text/vtt"}const r=document.createElement("track");return r.src=this.cmcdManager_.appendTextTrackData(e),r.label=s,r.kind=i,r.srclang=t,this.video_.getAttribute("crossorigin")||this.video_.setAttribute("crossorigin","anonymous"),this.video_.appendChild(r),r}async getTextData_(e,t,i){const n=O.RequestType.SEGMENT,s=O.makeRequest([e],i);return s.method="GET",this.cmcdManager_.applyTextData(s),(await t.request(n,s).promise).data}convertToWebVTT_(e,t,i){const n=X.findParser(t);if(n){const t=n(),s={periodStart:0,segmentStart:0,segmentEnd:this.video_.duration,vttOffset:0},a=l.toUint8(e),r=t.parseMedia(a,s,null);return Ze.convert(r,i)}throw new v(v.Severity.CRITICAL,v.Category.TEXT,v.Code.MISSING_TEXT_PLUGIN,t)}setMaxHardwareResolution(e,t){this.maxHwRes_.width=e,this.maxHwRes_.height=t}retryStreaming(e=.1){return this.loadMode_==bt.LoadMode.MEDIA_SOURCE&&this.streamingEngine_.retry(e)}getManifest(){return i.alwaysWarn("Shaka Player's internal Manifest structure is NOT covered by semantic versioning compatibility guarantees. It may change at any time! Please consider filing a feature request for whatever you use getManifest() for."),this.manifest_}getManifestParserFactory(){return this.parserFactory_}addVariantToSwitchHistory_(e,t){this.stats_.getSwitchHistory().updateCurrentVariant(e,t)}addTextStreamToSwitchHistory_(e,t){this.stats_.getSwitchHistory().updateCurrentText(e,t)}defaultConfig_(){const e=J.createDefault();return e.streaming.failureCallback=e=>{this.defaultStreamingFailureCallback_(e)},e.textDisplayFactory=()=>this.videoContainer_?new Je(this.video_,this.videoContainer_):HTMLMediaElement.prototype.addTextTrack?new Qe(this.video_,bt.TextTrackLabel):(i.warning("Text tracks are not supported by the browser, disabling."),new $e),e}setVideoContainer(e){this.videoContainer_=e}defaultStreamingFailureCallback_(e){if(!this.isLive())return;let t=null;e.code==v.Code.BAD_HTTP_STATUS||e.code==v.Code.HTTP_ERROR?t=1:e.code==v.Code.TIMEOUT&&(t=.1),null!=t&&(e.severity=v.Severity.RECOVERABLE,i.warning("Live streaming error. Retrying automatically..."),this.retryStreaming(t))}makeTextStreamsForClosedCaptions_(e){const t=k.ContentType,i=k.TextStreamKind,n=B.CEA608_CLOSED_CAPTION_MIMETYPE,s=B.CEA708_CLOSED_CAPTION_MIMETYPE,a=new Set;for(const t of e.textStreams)t.mimeType!=n&&t.mimeType!=s||a.add(t.originalId);for(const r of e.variants){const o=r.video;if(o&&o.closedCaptions)for(const r of o.closedCaptions.keys())if(!a.has(r)){const l=r.startsWith("CC")?n:s,d=new Ie,c=o.closedCaptions.get(r),h={id:this.nextExternalStreamId_++,originalId:r,groupId:null,createSegmentIndex:()=>Promise.resolve(),segmentIndex:d,mimeType:l,codecs:"",kind:i.CLOSED_CAPTION,language:c,originalLanguage:c,label:null,type:t.TEXT,primary:!1,trickModeVideo:null,emsgSchemeIdUris:null,roles:o.roles,forced:!1,channelsCount:null,audioSamplingRate:null,spatialAudio:!1,closedCaptions:null,accessibilityPurpose:null,external:!1,fastSwitching:!1};e.textStreams.push(h),a.add(r)}}}async adjustStartTime_(e,t){const i=e.audio,n=e.video,s=async(e,t)=>{if(!e)return null;await e.createSegmentIndex();const i=e.segmentIndex.getIteratorForTime(t),n=i?i.next().value:null;if(!n)return null;const s=n.startTime;return console.assert(s<=t,"Segment should start before target time!"),s},a=await s(i,t),r=await s(n,t);return null!=r&&null!=a?Math.max(r,a):null!=r?r:null!=a?a:t}updateBufferState_(){const e=this.isBuffering();i.v2("Player changing buffering state to",e),this.stats_&&this.bufferObserver_&&this.playhead_&&(this.cmcdManager_&&this.cmcdManager_.setBuffering(e),this.updateStateHistory_());const t=s.EventName.Buffering,n=(new Map).set("buffering",e);this.dispatchEvent(bt.makeEvent_(t,n))}onRateChange_(){const e=this.video_.playbackRate;if(0==e)return;this.playRateController_&&this.playRateController_.set(e);const t=bt.makeEvent_(s.EventName.RateChange);this.dispatchEvent(t)}updateStateHistory_(){if(!this.stats_)return;if(!this.bufferObserver_)return;const e=qe.State,t=this.stats_.getStateHistory();let i="playing";if(this.bufferObserver_.getState()==e.STARVING?i="buffering":this.video_.paused?i="paused":this.video_.ended&&(i="ended"),t.update(i)){const e=s.EventName.StateChanged,t=(new Map).set("newstate",i);this.dispatchEvent(bt.makeEvent_(e,t))}}onTimeUpdate_(){const e=this.video_.playbackRate,t=this.isLive();if(this.config_.streaming.vodDynamicPlaybackRate&&!t){const t=this.config_.streaming.vodDynamicPlaybackRateLowBufferRate,n=this.getBufferFullness(),s=this.config_.streaming.vodDynamicPlaybackRateBufferRatio;n<=s?e!=t&&(i.debug("Buffer fullness ratio ("+n+") is less than the vodDynamicPlaybackRateBufferRatio ("+s+"). Updating playbackRate to "+t),this.trickPlay(t)):1==n&&e!==this.playRateController_.getDefaultRate()&&(i.debug("Buffer is full. Cancel trick play."),this.cancelTrickPlay())}if(!t)return;const n=this.seekRange();if(!Number.isFinite(n.end))return;if(this.video_.currentTime<n.start)return;let s,a,r,o;this.config_.streaming.liveSync?(s=this.config_.streaming.liveSyncMaxLatency,a=this.config_.streaming.liveSyncPlaybackRate):this.manifest_&&this.manifest_.serviceDescription&&(s=this.manifest_.serviceDescription.maxLatency||this.config_.streaming.liveSyncMaxLatency,a=this.manifest_.serviceDescription.maxPlaybackRate||this.config_.streaming.liveSyncPlaybackRate),this.config_.streaming.liveSync?(r=this.config_.streaming.liveSyncMinLatency,o=this.config_.streaming.liveSyncMinPlaybackRate):this.manifest_&&this.manifest_.serviceDescription&&(r=this.manifest_.serviceDescription.minLatency||this.config_.streaming.liveSyncMinLatency,o=this.manifest_.serviceDescription.minPlaybackRate||this.config_.streaming.liveSyncMinPlaybackRate);const l=n.end-this.video_.currentTime;let d=0;if(this.loadMode_==bt.LoadMode.SRC_EQUALS){const e=this.video_.buffered;if(e.length>0){const t=e.end(e.length-1);d=Math.max(a,t-n.end)}}const c=this.config_.streaming.liveSyncPanicMode,h=1e3*this.config_.streaming.liveSyncPanicThreshold,u=Date.now()-this.bufferObserver_.getLastRebufferTime();c&&!o&&(o=this.config_.streaming.liveSyncMinPlaybackRate),c&&o&&u<=h?e!=o&&(i.debug("Time since last rebuffer ("+u+"s) is less than the liveSyncPanicThreshold ("+h+"s). Updating playbackRate to "+o),this.trickPlay(o)):s&&a&&l-d>s?e!=a&&(i.debug("Latency ("+l+"s) is greater than liveSyncMaxLatency ("+s+"s). Updating playbackRate to "+a),this.trickPlay(a)):r&&o&&l-d<r?e!=o&&(i.debug("Latency ("+l+"s) is smaller than liveSyncMinLatency ("+r+"s). Updating playbackRate to "+o),this.trickPlay(o)):e!==this.playRateController_.getDefaultRate()&&this.cancelTrickPlay()}onVideoProgress_(){if(!this.video_)return;let e=!1;const t=this.video_.currentTime/this.video_.duration;if(!isNaN(t)){const i=Math.round(100*t);if(isNaN(this.completionPercent_))this.completionPercent_=i,e=!0;else{const t=Math.max(this.completionPercent_,i);this.completionPercent_!=t&&(this.completionPercent_=t,e=!0)}}if(e){let e;0==this.completionPercent_?e=bt.makeEvent_(s.EventName.Started):25==this.completionPercent_?e=bt.makeEvent_(s.EventName.FirstQuartile):50==this.completionPercent_?e=bt.makeEvent_(s.EventName.Midpoint):75==this.completionPercent_?e=bt.makeEvent_(s.EventName.ThirdQuartile):100==this.completionPercent_&&(e=bt.makeEvent_(s.EventName.Complete)),e&&this.dispatchEvent(e)}}onSeek_(){this.playheadObservers_&&this.playheadObservers_.notifyOfSeek(),this.streamingEngine_&&this.streamingEngine_.seeked(),this.bufferObserver_&&this.pollBufferState_()}updateAbrManagerVariants_(){try{console.assert(this.manifest_,"Manifest should exist by now!"),this.manifestFilterer_.checkRestrictedVariants(this.manifest_)}catch(e){return this.onError_(e),!1}const e=z.getPlayableVariants(this.manifest_.variants),t=this.currentAdaptationSetCriteria_.create(e);return this.abrManager_.setVariants(Array.from(t.values())),!0}chooseVariant_(e=!1){return this.updateAbrManagerVariants_()?this.abrManager_.chooseVariant(e):null}checkVariants_(){console.assert(this.manifest_,"Should have manifest!");const e=Date.now()/1e3;let t=!1;const n=e=>{let t="";return e.video&&(t+="video:"+e.video.id),e.audio&&(t+=t?"&":"",t+="audio:"+e.audio.id),t};for(const s of this.manifest_.variants)s.disabledUntilTime>0&&s.disabledUntilTime<=e&&(s.disabledUntilTime=0,t=!0,i.v2("Re-enabled variant with "+n(s)));this.manifest_.variants.every((e=>(console.assert(e.disabledUntilTime>=0,"|variant.disableTimeUntilTime| must always be >= 0"),0===e.disabledUntilTime)))&&this.checkVariantsTimer_.stop(),t&&this.chooseVariantAndSwitch_(!0,void 0,!1,!1)}chooseTextStream_(){return z.filterStreamsByLanguageAndRole(this.manifest_.textStreams,this.currentTextLanguage_,this.currentTextRole_,this.currentTextForced_)[0]||null}chooseVariantAndSwitch_(e=!0,t=0,i=!1,n=!0){console.assert(this.config_,"Must not be destroyed");const s=this.chooseVariant_();s&&this.switchVariant_(s,n,e,t,i)}switchVariant_(e,t,n,s,a=!1){const r=this.streamingEngine_.getCurrentVariant();if(e==r)return i.debug("Variant already selected."),void(n&&this.streamingEngine_.switchVariant(e,n,s,!0));this.addVariantToSwitchHistory_(e,t),this.streamingEngine_.switchVariant(e,n,s,a,t);let o=null;r&&(o=z.variantToTrack(r));const l=z.variantToTrack(e);t?this.onAdaptation_(o,l):this.onVariantChanged_(o,l)}switchHtml5Track_(e){console.assert(this.video_&&this.video_.audioTracks,"Video and video.audioTracks should not be null!");const t=Array.from(this.video_.audioTracks).find((e=>e.enabled));e.enabled=!0,e.id!==t.id&&(t.enabled=!1);const i=z.html5AudioTrackToTrack(t),n=z.html5AudioTrackToTrack(e);this.onVariantChanged_(i,n)}setInitialTextState_(e,t){t?(e.audio&&this.shouldInitiallyShowText_(e.audio,t)&&(this.isTextVisible_=!0),this.isTextVisible_&&(this.mediaSourceEngine_.getTextDisplayer().setTextVisibility(!0),console.assert(this.shouldStreamText_(),"Should be streaming text")),this.onTextTrackVisibility_()):this.isTextVisible_=!1}shouldInitiallyShowText_(e,t){if(0==this.config_.autoShowText)return!1;if(1==this.config_.autoShowText)return!0;const n=n,s=n.normalize(this.config_.preferredTextLanguage),a=n.normalize(t.language);if(2==this.config_.autoShowText)return n.areLanguageCompatible(a,s);if(3==this.config_.autoShowText){const t=n.normalize(e.language);return n.areLanguageCompatible(a,s)&&!n.areLanguageCompatible(t,a)}return i.alwaysWarn("Invalid autoShowText setting!"),!1}onManifestUpdate_(){this.parser_&&this.parser_.update&&this.parser_.update()}onSegmentAppended_(e,t,i){if(this.playhead_){this.playhead_.notifyOfBufferingChange();const e=this.mediaSourceEngine_.bufferStart(i);!this.isLive()&&this.video_.paused&&null!=e&&e>0&&this.playhead_.getTime()<e&&this.playhead_.setStartTime(e)}this.pollBufferState_();const n=(new Map).set("start",e).set("end",t).set("contentType",i);this.dispatchEvent(bt.makeEvent_(s.EventName.SegmentAppended,n))}switch_(e,t=!1,n=0){i.debug("switch_"),console.assert(this.config_.abr.enabled,"AbrManager should not call switch while disabled!"),console.assert(this.manifest_,"We need a manifest to switch variants."),this.streamingEngine_&&e!=this.streamingEngine_.getCurrentVariant()&&this.switchVariant_(e,!0,t,n)}onAdaptation_(e,t){const i=(new Map).set("oldTrack",e).set("newTrack",t);this.lcevcDec_&&this.lcevcDec_.updateVariant(t,this.getManifestType());const n=bt.makeEvent_(s.EventName.Adaptation,i);this.delayDispatchEvent_(n)}onTracksChanged_(){const e=bt.makeEvent_(s.EventName.TracksChanged);this.delayDispatchEvent_(e)}onVariantChanged_(e,t){const i=(new Map).set("oldTrack",e).set("newTrack",t);this.lcevcDec_&&this.lcevcDec_.updateVariant(t,this.getManifestType());const n=bt.makeEvent_(s.EventName.VariantChanged,i);this.delayDispatchEvent_(n)}onTextChanged_(){const e=bt.makeEvent_(s.EventName.TextChanged);this.delayDispatchEvent_(e)}onTextTrackVisibility_(){const e=bt.makeEvent_(s.EventName.TextTrackVisibility);this.delayDispatchEvent_(e)}onAbrStatusChanged_(){this.config_.abr.enabled||this.restoreDisabledVariants_();const e=(new Map).set("newStatus",this.config_.abr.enabled);this.delayDispatchEvent_(bt.makeEvent_(s.EventName.AbrStatusChanged,e))}restoreDisabledVariants_(e=!0){if(this.loadMode_==bt.LoadMode.MEDIA_SOURCE){console.assert(this.manifest_,"Should have manifest!"),i.v2("Restoring all disabled streams..."),this.checkVariantsTimer_.stop();for(const e of this.manifest_.variants)e.disabledUntilTime=0;e&&this.updateAbrManagerVariants_()}}disableStream(e,t){if(!this.config_.abr.enabled||this.loadMode_===bt.LoadMode.DESTROYED)return!1;if(!navigator.onLine)return!1;if(this.manifest_.variants.some((t=>{const i=t[e.type];return!(!i||i.id===e.id||z.isAudio(e)&&e.language!==i.language)}))){let n=!1;for(const s of this.manifest_.variants){const a=s[e.type];a&&a.id===e.id&&(s.disabledUntilTime=Date.now()/1e3+t,n=!0,i.v2("Disabled stream "+e.type+":"+e.id+" for "+t+" seconds..."))}console.assert(n,"Must have disabled stream"),this.checkVariantsTimer_.tickEvery(1);const{video:s}=this.getBufferedInfo(),a=s.reduce(((e,{start:t,end:i})=>e+i-t),0);return this.chooseVariantAndSwitch_(!0,a,!0,!1),!0}return i.warning("No alternate stream found for active "+e.type+" stream. Will ignore request to disable stream..."),!1}async onError_(e){if(console.assert(e instanceof v,"Wrong error type!"),this.loadMode_==bt.LoadMode.DESTROYED)return;let t=!0;if(this.fullyLoaded_&&this.manifest_&&this.streamingEngine_&&(e.code==v.Code.VIDEO_ERROR||e.code==v.Code.MEDIA_SOURCE_OPERATION_FAILED||e.code==v.Code.MEDIA_SOURCE_OPERATION_THREW||e.code==v.Code.TRANSMUXING_FAILED))try{t=!await this.streamingEngine_.resetMediaSource()}catch(e){t=!0}if(!t)return;e.severity===v.Severity.CRITICAL&&this.restoreDisabledVariants_(!1);const i=s.EventName.Error,n=bt.makeEvent_(i,(new Map).set("detail",e));this.dispatchEvent(n),n.defaultPrevented&&(e.handled=!0)}onRegionEvent_(e,t,i=this){const n={schemeIdUri:t.schemeIdUri,value:t.value,startTime:t.startTime,endTime:t.endTime,id:t.id,eventElement:t.eventElement},s=(new Map).set("detail",n);i.dispatchEvent(bt.makeEvent_(e,s))}onMediaQualityChange_(e,t){const i={bandwidth:e.bandwidth,audioSamplingRate:e.audioSamplingRate,codecs:e.codecs,contentType:e.contentType,frameRate:e.frameRate,height:e.height,mimeType:e.mimeType,channelsCount:e.channelsCount,pixelAspectRatio:e.pixelAspectRatio,width:e.width},n=(new Map).set("mediaQuality",i).set("position",t);this.dispatchEvent(bt.makeEvent_(s.EventName.MediaQualityChanged,n))}videoErrorToShakaError_(){if(console.assert(this.video_.error,"Video error expected, but missing!"),!this.video_.error)return null;const e=this.video_.error.code;if(1==e)return null;let t=this.video_.error.msExtendedCode;t&&(t<0&&(t+=Math.pow(2,32)),t=t.toString(16));const i=this.video_.error.message;return new v(v.Severity.CRITICAL,v.Category.MEDIA,v.Code.VIDEO_ERROR,e,t,i)}onVideoError_(e){const t=this.videoErrorToShakaError_();t&&this.onError_(t)}onKeyStatus_(e){console.assert(this.streamingEngine_,"Cannot be called in src= mode");const t=bt.makeEvent_(s.EventName.KeyStatusChanged);this.dispatchEvent(t);const n=Object.keys(e);0==n.length&&i.warning("Got a key status event without any key statuses, so we don't know the real key statuses. If we don't have all the keys, you'll need to set restrictions so we don't select those tracks."),1==n.length&&"00"==n[0]&&i.warning("Got a synthetic key status event, so we don't know the real key statuses. If we don't have all the keys, you'll need to set restrictions so we don't select those tracks.");let a=!1;if(n.length)for(const e of this.manifest_.variants){const t=z.getVariantStreams(e);for(const i of t)e.allowedByKeySystem!=e.allowedByKeySystem&&(a=!0)}if(a&&(this.onTracksChanged_(),!this.updateAbrManagerVariants_()))return;const r=this.streamingEngine_.getCurrentVariant();r&&!r.allowedByKeySystem&&(i.debug("Choosing new streams after key status changed"),this.chooseVariantAndSwitch_())}shouldStreamText_(){return this.config_.streaming.alwaysStreamText||this.isTextTrackVisible()}static applyPlayRange_(e,t,n){t>0&&(e.isLive()?i.warning("|playRangeStart| has been configured for live content. Ignoring the setting."):e.setUserSeekStart(t)),n<e.getDuration()&&(e.isLive()?i.warning("|playRangeEnd| has been configured for live content. Ignoring the setting."):e.setDuration(n))}async delayDispatchEvent_(e){await Promise.resolve(),this.loadMode_!=bt.LoadMode.DESTROYED&&this.dispatchEvent(e)}static getLanguagesFrom_(e){const t=new Set;for(const i of e)i.language?t.add(G.normalize(i.language)):t.add("und");return t}static getLanguageAndRolesFrom_(e){const t=new Map,i=new Map;for(const n of e){let e="und",s=[];n.language&&(e=G.normalize(n.language)),s="variant"==n.type?n.audioRoles:n.roles,s&&s.length||(s=[""]),t.has(e)||t.set(e,new Set);for(const a of s)t.get(e).add(a),n.label&&(i.has(e)||i.set(e,new Map),i.get(e).set(a,n.label))}const n=[];return t.forEach(((e,t)=>{for(const s of e){let e=null;i.has(t)&&i.get(t).has(s)&&(e=i.get(t).get(s)),n.push({language:t,role:s,label:e})}})),n}isBufferedToEndMS_(){if(console.assert(this.video_,"We need a video element to get buffering information"),console.assert(this.mediaSourceEngine_,"We need a media source engine to get buffering information"),console.assert(this.manifest_,"We need a manifest to get buffering information"),this.video_.ended)return!0;if(this.mediaSourceEngine_.ended())return!0;if(this.manifest_.presentationTimeline.isLive()){const e=this.manifest_.presentationTimeline.getSegmentAvailabilityEnd(),t=me.bufferEnd(this.video_.buffered);if(null!=t&&t>=e)return!0}return!1}isBufferedToEndSrc_(){if(console.assert(this.video_,"We need a video element to get buffering information"),this.video_.ended)return!0;const e=me.bufferEnd(this.video_.buffered);return null!=e&&e>=this.video_.duration-1}createAbortLoadError_(){return new v(v.Severity.CRITICAL,v.Category.PLAYER,v.Code.LOAD_INTERRUPTED)}static convertJsonToUri(e){const t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"});return URL.createObjectURL(t)}static get[Symbol.for("___CTOR_ARGS___")](){return[void 0,void 0]}}bt.LoadMode={DESTROYED:0,NOT_LOADED:1,MEDIA_SOURCE:2,SRC_EQUALS:3},bt.TYPICAL_BUFFERING_THRESHOLD_=.5,bt.version="v5.0.0-uncompiled",ae.init(bt.version),bt.supportPlugins_={},bt.adManagerFactory_=null,bt.TextTrackLabel="Shaka Player TextTrack";const Ct=new class{constructor(){Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ias-vod-plugin"})}install(e){e.globalProperties.$videoOnDemand=bt}uninstall(){}};return t.default})()));