%PDF- %PDF-
| Direktori : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/node_modules/hls.js/dist/ |
| Current File : //home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/node_modules/hls.js/dist/hls.light.min.mjs |
const t=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},e=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=r},r=Number.MAX_SAFE_INTEGER||9007199254740991;let i=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),s=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",t.UNKNOWN="unknown",t}({}),n=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});function a(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var o,l={exports:{}};var d,h,u,c,f,g=o?l.exports:(o=1,d=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,h=/^(?=([^\/?#]*))\1([^]*)$/,u=/(?:\/|^)\.(?=\/)/g,c=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,l.exports=f={buildAbsoluteURL:function(t,e,r){if(r=r||{},t=t.trim(),!(e=e.trim())){if(!r.alwaysNormalize)return t;var i=f.parseURL(t);if(!i)throw new Error("Error trying to parse base URL.");return i.path=f.normalizePath(i.path),f.buildURLFromParts(i)}var s=f.parseURL(e);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return r.alwaysNormalize?(s.path=f.normalizePath(s.path),f.buildURLFromParts(s)):e;var n=f.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=h.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(o.netLoc=n.netLoc,"/"!==s.path[0]))if(s.path){var l=n.path,d=l.substring(0,l.lastIndexOf("/")+1)+s.path;o.path=f.normalizePath(d)}else o.path=n.path,s.params||(o.params=n.params,s.query||(o.query=n.query));return null===o.path&&(o.path=r.alwaysNormalize?f.normalizePath(s.path):s.path),f.buildURLFromParts(o)},parseURL:function(t){var e=d.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(u,"");t.length!==(t=t.replace(c,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}});class m{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}let p=function(t){return t.MANIFEST="manifest",t.LEVEL="level",t.AUDIO_TRACK="audioTrack",t.SUBTITLE_TRACK="subtitleTrack",t.MEDIA_FRAGMENT="media-fragment",t.KEY="key",t.STEERING_MANIFEST="steering-manifest",t.SERVER_CERTIFICATE="server-certificate",t.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",t}({}),v=function(t){return t.MAIN="main",t.AUDIO="audio",t.SUBTITLE="subtitle",t}({});var E={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class y{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const r=b(t,e);r&&(r.enumerable=!0,Object.defineProperty(t,e,r))}(this,"stats")}setByteRange(t,e){const r=t.split("@",2);let i;i=1===r.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[E.AUDIO]:null,[E.VIDEO]:null,[E.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new m),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.relurl&&(this._url=g.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[E.AUDIO]=null,t[E.VIDEO]=null,t[E.AUDIOVIDEO]=null,this.url=null}}function T(t){return"initSegment"!==t.sn}function S(t,e){return t.sn===(null==e?void 0:e.sn)&&t.level===e.level}function L(t,e){return t.sn===(null==e?void 0:e.sn)&&t.level===e.level&&t.cc===e.cc}class A extends y{constructor(t,e){super(e),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const e=this.byteRange[0],r=this.byteRange[1];if(t(e)&&t(r))return r-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const r=this._decryptdata=e[t[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=t(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e;const t=Object.keys(this.levelkeys),r=t.length;if(r>1||1===r&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){t(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return T(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var r;const i=e[t];!i||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=i.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,r,i,s,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,s)):a[t]={startPTS:e,endPTS:r,startDTS:i,endDTS:s,partial:n}}}class R extends y{constructor(t,e,r,i,s){super(r),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=i;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo||this.fragment.type===v.SUBTITLE&&this.stats.loading.end>0)}}function b(t,e){const r=Object.getPrototypeOf(t);if(r){const t=Object.getOwnPropertyDescriptor(r,e);return t||b(r,e)}}function D(t,e,r){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var i=r.call(t,e);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)({}).hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t},I.apply(null,arguments)}function k(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,i)}return r}function _(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?k(Object(r),!0).forEach((function(e){D(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):k(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function C(t){switch(t.details){case s.FRAG_LOAD_TIMEOUT:case s.KEY_LOAD_TIMEOUT:case s.LEVEL_LOAD_TIMEOUT:case s.MANIFEST_LOAD_TIMEOUT:case s.AUDIO_TRACK_LOAD_TIMEOUT:case s.SUBTITLE_TRACK_LOAD_TIMEOUT:case s.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function P(t){return t.details.startsWith("key")}function x(t){return P(t)&&!!t.frag&&!t.frag.decryptdata}function w(t,e){const r=C(e);return t.default[(r?"timeout":"error")+"Retry"]}function O(t,e){const r="linear"===t.backoff?1:Math.pow(2,e);return Math.min(r*t.retryDelayMs,t.maxRetryDelayMs)}function M(t){return _(_({},t),{errorRetry:null,timeoutRetry:null})}function F(t,e,r,i){if(!t)return!1;const s=null==i?void 0:i.code,n=e<t.maxNumRetry&&(function(t){return N(t)||!!t&&(t<400||t>499)}(s)||!!r);return t.shouldRetry?t.shouldRetry(t,e,r,i,n):n}function N(t){return 0===t&&!1===navigator.onLine}function $(t,e){return e>0&&t.loadError>0&&0!==t.loadErrorTime&&self.performance.now()-t.loadErrorTime>e}class B{constructor(t,e=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=r}sample(t,e){const r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class U{constructor(t,e,r,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new B(t),this.fast_=new B(e),this.defaultTTFB_=i,this.ttfb_=new B(t)}update(t,e){const{slow_:r,fast_:i,ttfb_:s}=this;r.halfLife!==t&&(this.slow_=new B(t,r.getEstimate(),r.getTotalWeight())),i.halfLife!==e&&(this.fast_=new B(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.ttfb_=new B(t,s.getEstimate(),s.getTotalWeight()))}sample(t,e){if(e<=0)return;const r=Math.min(this.minDelayMs_,e/1e5),i=8*e,s=Math.max(t,r)/1e3,n=i/s;this.fast_.sample(s,n),this.slow_.sample(s,n)}sampleTTFB(t){const e=t/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(r,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class G{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const r=`[${t}]:`;this.trace=V,this.debug=e.debug.bind(null,r),this.log=e.log.bind(null,r),this.warn=e.warn.bind(null,r),this.info=e.info.bind(null,r),this.error=e.error.bind(null,r)}}const V=function(){},H={trace:V,debug:V,log:V,warn:V,info:V,error:V};function K(){return I({},H)}function Y(t,e,r){return e[t]?e[t].bind(e):function(t,e){const r=self.console[t];return r?r.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):V}(t,r)}const W=K();const j=W;var q,z;var X=z?q:(z=1,q={}),Q=a(X);function Z(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function J(t){return t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer}const tt="utf-16",et="utf-16be",rt="utf-16le",it="utf-8";function st(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function nt(t,e){let r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3],r}function at(t,e){return st(t,e)&&nt(t,e+6)+10<=t.length-e}function ot(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function lt(t,e){const r=e;let i=0;for(;st(t,e);){i+=10;i+=nt(t,e+6),ot(t,e+10)&&(i+=10),e+=i}if(i>0)return t.subarray(r,r+i)}function dt(t,e=0,r=1/0){return function(t,e,r,i){const s=(n=t,J(n)?n:n.buffer);var n;let a=1;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);const o=(u=t,u&&J(u.buffer)&&void 0!==u.byteLength&&void 0!==u.byteOffset?t.byteOffset:0),l=(o+t.byteLength)/a,d=(o+e)/a,h=Math.floor(Math.max(0,Math.min(d,l)));var u;return new i(s,h,Math.floor(Math.min(h+Math.max(r,0),l))-h)}(t,e,r,Uint8Array)}function ht(t,e=!1){const r=e?t.indexOf(0):t.length,i=function(t,e={}){let r;r=J(t)?new DataView(t):new DataView(t.buffer,t.byteOffset,t.byteLength);let i=0,{encoding:s}=e;if(!s){const t=r.getUint8(0),e=r.getUint8(1);239==t&&187==e&&191==r.getUint8(2)?(s=it,i=3):254==t&&255==e?(s=et,i=2):255==t&&254==e?(s=rt,i=2):s=it}if("undefined"!=typeof TextDecoder)return new TextDecoder(s).decode(r);const{byteLength:n}=r,a=s!==et;let o,l="";for(;i<n;){switch(s){case it:if(o=r.getUint8(i),o<128)i++;else if(o>=194&&o<=223)if(i+1<n){const t=r.getUint8(i+1);t>=128&&t<=191?(o=(31&o)<<6|63&t,i+=2):i++}else i++;else if(o>=224&&o<=239)if(i+2<=n-1){const t=r.getUint8(i+1),e=r.getUint8(i+2);t>=128&&t<=191&&e>=128&&e<=191?(o=(15&o)<<12|(63&t)<<6|63&e,i+=3):i++}else i++;else if(o>=240&&o<=244)if(i+3<=n-1){const t=r.getUint8(i+1),e=r.getUint8(i+2),s=r.getUint8(i+3);t>=128&&t<=191&&e>=128&&e<=191&&s>=128&&s<=191?(o=(7&o)<<18|(63&t)<<12|(63&e)<<6|63&s,i+=4):i++}else i++;else i++;break;case et:case tt:case rt:o=r.getUint16(i,a),i+=2}l+=String.fromCodePoint(o)}return l}(new DataView(t.buffer,t.byteOffset,r),{encoding:it});return e?i:i.replace(/\0/g,"")}function ut(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const r=t.data.subarray(1).indexOf(0);if(-1===r)return;const i=ht(dt(t.data,1,r)),s=t.data[2+r],n=t.data.subarray(3+r).indexOf(0);if(-1===n)return;const a=ht(dt(t.data,3+r,n));let o;var l;return"--\x3e"===i?o=ht(dt(t.data,4+r+n)):o=J(l=t.data.subarray(4+r+n))?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,e.mimeType=i,e.pictureType=s,e.description=a,e.data=o,e}function ct(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=ht(t.data,!0),r=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:r.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const r=ht(t.data.subarray(e),!0);e+=r.length+1;const i=ht(t.data.subarray(e));return{key:t.type,info:r,data:i}}const e=ht(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?ut(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const{data:r}=t,i=ht(r.subarray(e),!0);e+=i.length+1;const s=ht(r.subarray(e));return{key:t.type,info:i,data:s}}const e=ht(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function ft(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),r=nt(t,4);return{type:e,size:r,data:t.subarray(10,10+r)}}const gt=10,mt=10;function pt(t){let e=0;const r=[];for(;st(t,e);){const i=nt(t,e+6);t[e+5]>>6&1&&(e+=gt),e+=gt;const s=e+i;for(;e+mt<s;){const i=ft(t.subarray(e)),s=ct(i);s&&r.push(s),e+=i.size+gt}ot(t,e)&&(e+=gt)}return r}function vt(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function Et(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),r=1&e[3];let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}}function yt(t){const e=pt(t);for(const t of e)if(vt(t))return Et(t)}function Tt(t){let e="";for(let r=0;r<t.length;r++){let i=t[r].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function St(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Lt(t){return String.fromCharCode.apply(null,t)}const At=Math.pow(2,32)-1,Rt={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},bt={video:1,audio:2,id3:3,text:4};function Dt(t,e){const r=t[e]<<8|t[e+1];return r<0?65536+r:r}function It(t,e){const r=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return r<0?4294967296+r:r}function kt(t,e){let r=It(t,e);return r*=Math.pow(2,32),r+=It(t,e+4),r}function _t(t,e){let r="";for(let i=e;i<t.length;i++)if(r+=String.fromCharCode(t[i]),0===t[i])return r;return null}function Ct(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Pt(t,e,r){t[e]=r>>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=255&r}function xt(t,e){const r=[];return e.length?(wt(t,e,0,0,t.byteLength,r),r):r}function wt(t,e,r,i,s,n){const a=e[r];if(4!==(null==a?void 0:a.length))return;const o=a.charCodeAt(0),l=a.charCodeAt(1),d=a.charCodeAt(2),h=a.charCodeAt(3),u=e.length-1;for(let a=i;a<s;){const i=a+8<=s,c=a+4<=s?16777216*t[a]+(t[a+1]<<16|t[a+2]<<8|t[a+3]):It(t,a),f=c>1?a+c:s;if(i&&t[a+4]===o&&t[a+5]===l&&t[a+6]===d&&t[a+7]===h){const i=Math.min(f,s);r===u?n.push(t.subarray(a+8,i)):wt(t,e,r+1,a+8,i,n)}a=f}}function Ot(t){const e=[],r=t[0];let i=8;const s=It(t,i);i+=4;let n=0,a=0;0===r?(n=It(t,i),a=It(t,i+4),i+=8):(n=kt(t,i),a=kt(t,i+8),i+=16),i+=2;let o=t.length+a;const l=Dt(t,i);i+=2;for(let r=0;r<l;r++){let r=i;const n=It(t,r);r+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return j.warn("SIDX has hierarchical references (not supported)"),null;const l=It(t,r);r+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:o,end:o+a-1}}),o+=a,r+=4,i=r}return{earliestPresentationTime:n,timescale:s,version:r,referencesCount:l,references:e}}function Mt(t){const e=[],r=xt(t,["moov","trak"]);for(let t=0;t<r.length;t++){const i=r[t],s=xt(i,["tkhd"])[0];if(s){let t=s[0];const r=It(s,0===t?12:20),n=xt(i,["mdia","mdhd"])[0];if(n){t=n[0];const s=It(n,0===t?12:20),a=xt(i,["mdia","hdlr"])[0];if(a){const t=Lt(a.subarray(8,12)),n={soun:E.AUDIO,vide:E.VIDEO}[t],o=Ft(xt(i,["mdia","minf","stbl","stsd"])[0]);n?(e[r]={timescale:s,type:n,stsd:o},e[n]=_({timescale:s,id:r},o)):e[r]={timescale:s,type:t,stsd:o}}}}}return xt(t,["moov","mvex","trex"]).forEach((t=>{const r=It(t,4),i=e[r];i&&(i.default={duration:It(t,12),sampleSize:It(t,16),flags:It(t,20)})})),e}function Ft(t){const e=t.subarray(8),r=e.subarray(86),i=Lt(e.subarray(4,8));let s,n=i;const a="enca"===i||"encv"===i;if(a){const t=xt(e,[i])[0];xt(t.subarray("enca"===i?28:78),["sinf"]).forEach((t=>{const e=xt(t,["schm"])[0];if(e){const r=Lt(e.subarray(4,8));if("cbcs"===r||"cenc"===r){const e=xt(t,["frma"])[0];e&&(n=Lt(e))}}}))}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=xt(r,["avcC"])[0];t&&t.length>3&&(n+="."+Bt(t[1])+Bt(t[2])+Bt(t[3]),s=Nt("avc1"===o?"dva1":"dvav",r));break}case"mp4a":{const t=xt(e,[i])[0],r=xt(t.subarray(28),["esds"])[0];if(r&&r.length>7){let t=4;if(3!==r[t++])break;t=$t(r,t),t+=2;const e=r[t++];if(128&e&&(t+=2),64&e&&(t+=r[t++]),4!==r[t++])break;t=$t(r,t);const i=r[t++];if(64!==i)break;if(n+="."+Bt(i),t+=12,5!==r[t++])break;t=$t(r,t);const s=r[t++];let a=(248&s)>>3;31===a&&(a+=1+((7&s)<<3)+((224&r[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=xt(r,["hvcC"])[0];if(t&&t.length>12){const e=t[1],r=["","A","B","C"][e>>6],i=31&e,s=It(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+r+i,n+="."+function(t){let e=0;for(let r=0;r<32;r++)e|=(t>>r&1)<<31-r;return e>>>0}(s).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let t=l.length;t--;){const e=l[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}n+=d}s=Nt("hev1"==o?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=Nt(n,r)||n;break;case"vp09":{const t=xt(r,["vpcC"])[0];if(t&&t.length>6){const e=t[4],r=t[5],i=t[6]>>4&15;n+="."+Ut(e)+"."+Ut(r)+"."+Ut(i)}break}case"av01":{const t=xt(r,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,i=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,d=2===e&&o?l?12:10:o?10:8,h=(16&t[2])>>4,u=(8&t[2])>>3,c=(4&t[2])>>2,f=3&t[2],g=1,m=1,p=1,v=0;n+="."+e+"."+Ut(i)+a+"."+Ut(d)+"."+h+"."+u+c+f+"."+Ut(g)+"."+Ut(m)+"."+Ut(p)+"."+v,s=Nt("dav1",r)}break}}return{codec:n,encrypted:a,supplemental:s}}function Nt(t,e){const r=xt(e,["dvvC"]),i=r.length?r[0]:xt(e,["dvcC"])[0];if(i){const e=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return t+"."+Ut(e)+"."+Ut(r)}}function $t(t,e){const r=e+5;for(;128&t[e++]&&e<r;);return e}function Bt(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Ut(t){return(t<10?"0":"")+t}function Gt(t,e){xt(t,["moov","trak"]).forEach((t=>{const r=xt(t,["mdia","minf","stbl","stsd"])[0];if(!r)return;const i=r.subarray(8);let s=xt(i,["enca"]);const n=s.length>0;n||(s=xt(i,["encv"])),s.forEach((t=>{xt(n?t.subarray(28):t.subarray(78),["sinf"]).forEach((t=>{const r=function(t){const e=xt(t,["schm"])[0];if(e){const r=Lt(e.subarray(4,8));if("cbcs"===r||"cenc"===r){const e=xt(t,["schi","tenc"])[0];if(e)return e}}}(t);r&&e(r,n)}))}))}))}let Vt;function Ht(t){if("undefined"==typeof TextDecoder)return ht(t);return(Vt||(Vt=new TextDecoder("utf-8"))).decode(t).replace(/\0/g,"")}function Kt(e,r,i,s,n){const a={};let o=!1;const l=function(t){const e=t.byteLength,r=[];for(let i=0;i<e;){const s=i+8<=e,n=i+4<=e?16777216*t[i]+(t[i+1]<<16|t[i+2]<<8|t[i+3]):It(t,i),a=n>1?i+n:e;if(s&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7]){const s=Math.min(a,e);for(let e=i+8;e<s;){const n=e+8<=s,a=e+4<=s?16777216*t[e]+(t[e+1]<<16|t[e+2]<<8|t[e+3]):It(t,e),o=a>1?e+a:s;if(n&&116===t[e+4]&&114===t[e+5]&&97===t[e+6]&&102===t[e+7]){const n=Math.min(o,s);let a,l;const d=[];for(let r=e+8;r<n;){const e=r+8<=n,i=r+4<=n?16777216*t[r]+(t[r+1]<<16|t[r+2]<<8|t[r+3]):It(t,r),s=i>1?r+i:n;if(e&&116===t[r+4]){const e=Math.min(s,n);102===t[r+5]&&104===t[r+6]&&100===t[r+7]?l||(l=t.subarray(r+8,e)):102===t[r+5]&&100===t[r+6]&&116===t[r+7]?a||(a=t.subarray(r+8,e)):114===t[r+5]&&117===t[r+6]&&110===t[r+7]&&d.push(t.subarray(r+8,e))}r=s}r.push({moofOffset:t.byteOffset+i,tfdt:a,tfhd:l,truns:d})}e=o}}i=a}return r}(e),d=e.byteLength;for(let c=0;c<l.length;c++){const{moofOffset:f,tfdt:g,tfhd:m,truns:p}=l[c],v=It(m,4),y=r[v];if(!y)continue;const T=a[v]||(a[v]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:y.timescale,type:y.type});let S;if(g){const e=g[0];S=It(g,4),1===e&&(S===At?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=At+1,S+=It(g,8))),t(S)&&(!t(T.start)||S<T.start)&&(T.start=S),n&&t(S)&&(n.timeOffset=S/n.timescale)}const L=(null==n?void 0:n.trackId)===v&&y.type===E.VIDEO,A=y.default,R=16777215&It(m,0);let b,D=(null==A?void 0:A.duration)||0,I=(null==A?void 0:A.sampleSize)||0,k=8;1&R&&(k+=8),2&R&&(k+=4),8&R&&(D=It(m,k),b=m.byteOffset-e.byteOffset+k,k+=4),16&R&&(I=It(m,k));let _=0;const C=0!=(1&R),P=!C&&0!=(131072&R);C?(_=It(m,8),_*=Math.pow(2,32),_+=It(m,12)):P&&(_=f);let x=S||0,w=0,O=D;for(let r=0;r<p.length;r++){const i=p[r],a=It(i,4),o=T.sampleCount;T.sampleCount+=a;const l=1&i[3];let c=0;const f=4&i[3],g=1&i[2],m=2&i[2],v=4&i[2],E=8&i[2];let y=8;if(l&&(c=Ct(i,y),y+=4),f){1&i[y+1]||void 0!==T.keyFrameIndex||(T.keyFrameIndex=o),y+=4}let S,A,R,k=_+c;if(s||0!==i[1]||6!==i[2]||1!==i[3]){s&&(S=[],A={sampleOffset:k,samples:S,defaultSampleDurationOffset:b},k<=d&&T.trun.push(A));for(let r=0;r<a;r++){let a,o,l;g?(s&&(a=i.byteOffset-e.byteOffset+y),O=It(i,y),y+=4):O=D,m?(R=It(i,y),y+=4):R=I,v&&(l=1&i[y+1]?1:0,s&&(o={isNonSync:l,dependsOn:1==(3&i[y])?1:2}),y+=4);let h=0;if(E){h=0===i[0]?It(i,y):Ct(i,y),y+=4}if(L){let t=k,r=0;for(;r<R;){const i=It(e,t);t+=4,jt(n.isHEVCFlavor,e[t])&&qt(e.subarray(t,t+i),n.isHEVCFlavor?2:1,n.timeOffset+h/n.timescale,n.samples),t+=i,r+=i+4}n.timeOffset+=O/n.timescale}if(k+=R,k<=d){A&&void 0!==a&&(A.lastSampleDurationOffset=a),0===l&&void 0===T.keyFrameIndex&&(T.keyFrameIndex=r,T.keyFrameStart=x);const e=x+h;(!t(T.ptsMin)||e<T.ptsMin)&&(T.ptsMin=e),(!t(T.ptsMax)||e+O>T.ptsMax)&&(T.ptsMax=e+O),S&&(S[r]={cts:h,duration:O,flags:o,size:R})}x+=O,w+=O}!w&&D&&(w+=D*a)}else{var h,u;const r=x,s=k,o=y;let l=-1,c=0,f=0,g=null!=(h=null==n?void 0:n.timeOffset)?h:0;const m=D/(null!=(u=null==n?void 0:n.timescale)?u:1),p=!0===(null==n?void 0:n.isHEVCFlavor),v=p?2:1;for(let t=0;t<a;t++){const r=0===i[y]?i[y+1]<<16|i[y+2]<<8|i[y+3]:It(i,y),s=-1===l&&void 0===T.keyFrameIndex&&0==(1&i[y+5]);y+=8;const a=k+r;if(L){if(r>0){let t=k;do{const r=0===e[t]?e[t+1]<<16|e[t+2]<<8|e[t+3]:It(e,t);t+=4;const i=e[t],s=p?i>>1&63:31&i;(p?39===s||40===s:6===s)&&qt(e.subarray(t,t+r),v,g,n.samples),t+=r}while(t<a)}g+=m}k=a,s&&(l=t,c=k)}if(k<=d)f=a;else{let t=s,e=o;for(let r=0;r<a;r++){if(t+=0===i[e]?i[e+1]<<16|i[e+2]<<8|i[e+3]:It(i,e),t>d)break;f=r+1,e+=8}}if(L&&(n.timeOffset=g),-1!==l&&c<=d&&void 0===T.keyFrameIndex&&(T.keyFrameIndex=l,T.keyFrameStart=r+l*D),f){(!t(T.ptsMin)||r<T.ptsMin)&&(T.ptsMin=r);const e=r+f*D;(!t(T.ptsMax)||e>T.ptsMax)&&(T.ptsMax=e)}const E=D*a;x=r+E,w+=E}}T.duration+=w,T.duration&&(o=!0)}if(!o){let r=1/0,i=0;const s=xt(e,["sidx"]);for(let t=0;t<s.length;t++){const e=Ot(s[t]);if(null!=e&&e.references){r=Math.min(r,e.earliestPresentationTime/e.timescale);const t=e.references.reduce(((t,e)=>t+e.info.duration||0),0);i=Math.max(i,t+e.earliestPresentationTime/e.timescale)}}i&&t(i)&&Object.keys(a).forEach((t=>{a[t].duration||(a[t].duration=i*a[t].timescale-a[t].start)}))}return a}function Yt(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function Wt(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function jt(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function qt(t,e,r,i){const s=zt(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;l=s[n++],a+=l}while(255===l);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(255===l);const t=s.length-n;let e=n;if(o<t)n+=o;else if(o>t){j.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===s[e++]){const t=Dt(s,e);if(e+=2,49===t){const t=It(s,e);if(e+=4,1195456820===t){const t=s[e++];if(3===t){const n=s[e++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let t=1;t<l;t++)d[t]=s[e++]}i.push({type:t,payloadType:a,pts:r,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let r=0;r<16;r++){const i=s[e++].toString(16);t.push(1==i.length?"0"+i:i),3!==r&&5!==r&&7!==r&&9!==r||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=s[e++];i.push({payloadType:a,pts:r,uuid:t.join(""),userData:Ht(l),userDataBytes:l})}}}function zt(t){const e=t.byteLength;let r,i=t.indexOf(3,3);for(;-1!==i;)0===t[i-1]&&0===t[i-2]&&(r||(r=[])).push(i),i=t.indexOf(3,i+1);if(!r)return t;const s=e-r.length,n=new Uint8Array(s);let a=0,o=0;for(let e=0;e<s;o++,e++)o===r[a]&&(o++,a++),n[e]=t[o];return n}const Xt=te("userAgent");let Qt,Zt,Jt;function te(t){try{return navigator[t]||""}catch(t){}return""}function ee(){if(void 0===Qt){const t=Xt.match(/Chrome\/(\d+)/i);Qt=t?parseInt(t[1]):0}return Qt}te("vendor");const re={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function ie(t,e){const r=re[e];return!!r&&!!r[t.slice(0,4)]}function se(t,e,r=!0){return!t.split(",").some((t=>!ne(t,e,r)))}function ne(t,e,r=!0){var i;const s=Z(r);return null!=(i=null==s?void 0:s.isTypeSupported(ae(t,e)))&&i}function ae(t,e){return`${e}/mp4;codecs=${t}`}function oe(t){if(t){const e=t.substring(0,4);return re.video[e]}return 2}function le(t){const e=/\(Windows.+Firefox\//i.test(Xt);return t.split(",").reduce(((t,r)=>{const i=e&&Wt(r)?9:re.video[r];return i?(2*i+t)/(t?3:2):(re.audio[r]+t)/(t?2:1)}),0)}const de={};const he=/flac|opus|mp4a\.40\.34/i;function ue(t,e=!0){return t.replace(he,(t=>function(t,e=!0){if(de[t])return de[t];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let s=0;s<r.length;s++){var i;if(ne(r[s],"audio",e))return de[t]=r[s],r[s];if("mp3"===r[s]&&null!=(i=Z(e))&&i.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e)))}function ce(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(fe(t,"audio")||fe(t,"video")))return t;if(e){const r=e.split(",");if(r.length>1){if(t)for(let e=r.length;e--;)if(r[e].substring(0,4)===t.substring(0,4))return r[e];return r[0]}}return e||t}function fe(t,e){return ie(t,e)&&ne(t,e)}function ge(t){const e=Z(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1}}function me(t,e,r){const i=encodeURIComponent(e),s=`${i}=${encodeURIComponent(r)}`;let n=!1;const a=[];t.search.substring(1).split("&").forEach((t=>{t===i||t.startsWith(i+"=")?n||(a.push(s),n=!0):t&&a.push(t)})),n||a.push(s),t.search=a.join("&")}const pe=["NONE","TYPE-0","TYPE-1",null];const ve=["SDR","PQ","HLG"];var Ee={No:"",Yes:"YES",v2:"v2"};function ye(t){const{canSkipUntil:e,canSkipDateRanges:r,age:i}=t;return e&&i<e/2?r?Ee.v2:Ee.Yes:Ee.No}class Te{constructor(t,e,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=r}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&me(e,"_HLS_msn",this.msn.toString()),void 0!==this.part&&me(e,"_HLS_part",this.part.toString()),this.skip&&me(e,"_HLS_skip",this.skip),e.href}}class Se{constructor(t){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,"imageCodec"in t&&(this.imageCodec=t.imageCodec),this.codecSet=[t.videoCodec,t.audioCodec].filter((t=>!!t)).map((t=>t.substring(0,4))).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const r=null==(e=t.supplemental)?void 0:e.videoCodec;r&&r!==t.videoCodec&&(this.codecSet+=`,${r.substring(0,4)}`)}"iframes"in t&&t.iframes?this.iframes=!0:(this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return Le(this._audioGroups,t)}hasSubtitleGroup(t){return Le(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function Le(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function Ae(t,e){let r=!1,i=[];if(t&&(r="SDR"!==t,i=[t]),e){i=e.allowedVideoRanges||ve.slice(0);const t="SDR"!==i.join("")&&!e.videoCodec;r=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),r||(i=["SDR"])}return{preferHDR:r,allowedVideoRanges:i}}const Re=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(r,i)=>{if(t&&(i=t(r,i)),"object"==typeof i&&null!==i){if(e.has(i))return;e.add(i)}return i}})(e));function be(t,e){j.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function De(t){return t.reduce(((t,e)=>{let r=t.groups[e.groupId];r||(r=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(e);const i=e.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||e.default,r.hasAutoSelect=r.hasAutoSelect||e.autoselect,r.hasDefault&&(t.hasDefaultAudio=!0),r.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Ie(t,e){var r;return!!t&&t!==(null==(r=e.loadLevelObj)?void 0:r.uri)}class ke extends G{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var r;const{fragCurrent:i,partCurrent:s,hls:a}=this;if(!a)return;const{autoLevelEnabled:o,media:l}=a;if(!i||!l)return;const d=performance.now(),h=s?s.stats:i.stats,u=s?s.duration:i.duration,c=d-h.loading.start,f=a.minAutoLevel,g=i.level,m=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!o)return;const p=m>-1&&m!==g,v=!!e||p;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;const E=a.mainForwardBufferInfo;if(!v&&null===E)return;const y=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(c<=Math.max(y,u/(2*T)*1e3))return;const S=E?E.len/T:0,L=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&L>-1,R=this.getBwEstimate(),b=a.levels,D=b[g],I=Math.max(h.loaded,Math.round(u*(i.bitrate||D.averageBitrate)/8));let k=A?c-L:c;k<1&&A&&(k=Math.min(c,8*h.loaded/R));const _=A?1e3*h.loaded/k:0,C=y/1e3,P=_?(I-h.loaded)/_:8*I/R+C;if(P<=S)return;const x=_?8*_:R,w=!0===(null==(r=(null==e?void 0:e.details)||a.latestLevelDetails)?void 0:r.live),O=a.config.abrBandWidthUpFactor;let M,F=Number.POSITIVE_INFINITY;for(M=g-1;M>f;M--){const t=b[M].maxBitrate,e=!b[M].details||w;if(F=this.getTimeToLoadFrag(C,x,u*t,e),F<Math.min(S,u+C))break}if(F>=P)return;if(F>10*u)return;A?this.bwEstimator.sample(c-Math.min(y,L),h.loaded):this.bwEstimator.sampleTTFB(c);const N=b[M].maxBitrate;this.getBwEstimate()*O>N&&(this.firstAutoFloor=Math.min(M,a.firstLevel),this.resetEstimator(N));const $=this.findBestLevel(N,f,M,0,S,1,1);$>-1&&(M=$),this.warn(`Fragment ${i.sn}${s?" part "+s.index:""} of level ${g} is loading too slowly;\n Fragment duration: ${i.duration.toFixed(3)}\n Time to underbuffer: ${S.toFixed(3)} s\n Estimated load time for current fragment: ${P.toFixed(3)} s\n Estimated load time for down switch fragment: ${F.toFixed(3)} s\n TTFB estimate: ${0|L} ms\n Current BW estimate: ${t(R)?0|R:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${M} @ ${0|N} bps`),a.nextLoadLevel=a.nextAutoLevel=M,this.clearTimer();const B=()=>{this.clearTimer();const t=this.hls;if(this.fragCurrent===i&&t.loadLevel===M&&M>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${M>0?"and switching down":""}\n Fragment duration: ${i.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,M>f){let r=this.findBestLevel(t.levels[f].bitrate,f,M,0,e,1,1);-1===r&&(r=f),t.nextLoadLevel=t.nextAutoLevel=r,this.firstAutoFloor=Math.min(r,t.firstLevel),this.resetEstimator(t.levels[r].bitrate)}}};p||P>2*F?B():this.timer=self.setInterval(B,1e3*F),a.trigger(n.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:s,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){this.hls&&(t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){const t=this.hls.config;return new U(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const t=this.hls;t.on(n.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.FRAG_LOADING,this.onFragLoading,this),t.on(n.FRAG_LOADED,this.onFragLoaded,this),t.on(n.FRAG_BUFFERED,this.onFragBuffered,this),t.on(n.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(n.LEVEL_LOADED,this.onLevelLoaded,this),t.on(n.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(n.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(n.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(n.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.FRAG_LOADING,this.onFragLoading,this),t.off(n.FRAG_LOADED,this.onFragLoaded,this),t.off(n.FRAG_BUFFERED,this.onFragBuffered,this),t.off(n.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(n.LEVEL_LOADED,this.onLevelLoaded,this),t.off(n.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(n.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(n.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const r=e.frag;if(!this.ignoreFragment(r)){var i;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(i=e.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case s.BUFFER_ADD_CODEC_ERROR:case s.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case s.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:r,partCurrent:i}=this;if(t&&L(t,r)){const e=performance.now(),r=i?i.stats:t.stats,s=e-r.loading.start,n=r.loading.first?r.loading.first-r.loading.start:-1;if(r.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(t,n),r.loaded)}else this.bwEstimator.sampleTTFB(s)}break}}}getTimeToLoadFrag(t,e,r,i){return t+r/e+(i?t+this.lastLevelLoadSec:0)}onLevelLoaded(e,r){const i=this.hls.config,{loading:s}=r.stats,n=s.end-s.first;t(n)&&(this.lastLevelLoadSec=n/1e3),r.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(r.levelInfo)}onFragLoaded(t,e){var r;const{frag:i,part:s}=e,a=s?s.stats:i.stats;if(i.type===v.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(r=this.hls)&&r.config.abrMaxWithRealBitrate){const t=s?s.duration:i.duration,e=this.hls.levels[i.level],r=(e.loaded?e.loaded.bytes:0)+a.loaded,n=(e.loaded?e.loaded.duration:0)+t;e.loaded={bytes:r,duration:n},e.realBitrate=Math.round(8*r/n)}if(i.bitrateTest){const t={stats:a,frag:i,part:s,id:i.type};this.onFragBuffered(n.FRAG_BUFFERED,t),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}onFragBuffered(t,e){const{frag:r,part:i}=e,s=null!=i&&i.stats.loaded?i.stats:r.stats;if(s.aborted)return;if(this.ignoreFragment(r))return;const n=((r.bitrate||0)>=1e5?s.parsing.end:s.loading.end)-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=n/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(t){return t.type!==v.MAIN||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:t}=this;if(!t)return 0;const{maxAutoLevel:e,minAutoLevel:r}=t,i=this.getBwEstimate(),s=this.getStarvationDelay(),n=t.config.maxStarvationDelay,a=this.findBestLevel(i,r,e,s/2,n,1,1);if(a>-1)return a;const o=t.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,d=Math.min(Math.max(o,r),e,l);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${d}`),d}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const i=e&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,i)&&e[t].loadError<=e[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:r}=this;if(!r)return-1;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:i,config:s,minAutoLevel:n}=r,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=s.abrBandWidthFactor,h=s.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,i,l,0,d,h);if(t>=0)return this.rebufferNotice=-1,t}let u=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){u=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),d=h=1}}const c=this.findBestLevel(o,n,i,l,u,d,h);if(this.rebufferNotice!==c&&(this.rebufferNotice=c,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${c}`)),c>-1)return c;const f=r.levels[n],g=r.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:r.loadLevel}getStarvationDelay(){const t=this.hls,e=null==t?void 0:t.media;if(!e)return 1/0;const r=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return(i?i.len:0)/r}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,r,i,s,n,a,o){const{hls:l,lastLoadedFragLevel:d,fragCurrent:h,partCurrent:u}=this;if(!l)return-1;const c=s+n,f=-1===d?l.firstLevel:d,{levels:g,allAudioTracks:m,loadLevel:p,latestLevelDetails:v,config:E}=l;if(1===g.length)return 0;const y=g[f],T=!(null==v||!v.live),S=-1===p||-1===d;let L,A="SDR",R=(null==y?void 0:y.frameRate)||0;const{audioPreference:b,videoPreference:D}=E;this.audioTracksByGroup||(this.audioTracksByGroup=De(m));let I=-1;if(S){if(-1!==this.firstSelection)return this.firstSelection;const s=this.codecTiers||(this.codecTiers=function(t,e,r,i){return t.slice(r,i+1).reduce(((t,e,r)=>{if(!e.codecSet)return t;const i=e.audioGroups;let s=t[e.codecSet];s||(t[e.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,e.bitrate);const n=Math.min(e.height,e.width);return s.minHeight=Math.min(s.minHeight,n),s.minFramerate=Math.min(s.minFramerate,e.frameRate),s.minIndex=Math.min(s.minIndex,r),s.maxScore=Math.max(s.maxScore,e.score),s.fragmentError+=e.fragmentError,s.videoRanges[e.videoRange]=(s.videoRanges[e.videoRange]||0)+1,t}),{})}(g,0,r,i)),n=function(e,r,i,s,n){const a=Object.keys(e),o=null==s?void 0:s.channels,l=null==s?void 0:s.audioCodec,d=null==n?void 0:n.videoCodec,h=o&&2===parseInt(o);let u=!1,c=!1,f=1/0,g=1/0,m=1/0,p=1/0,v=0,E=[];const{preferHDR:y,allowedVideoRanges:T}=Ae(r,n);for(let t=a.length;t--;){const r=e[a[t]];u||(u=r.channels[2]>0),f=Math.min(f,r.minHeight),g=Math.min(g,r.minFramerate),m=Math.min(m,r.minBitrate),T.filter((t=>r.videoRanges[t]>0)).length>0&&(c=!0)}f=t(f)?f:0,g=t(g)?g:0;const S=Math.max(1080,f),L=Math.max(30,g);m=t(m)?m:i,i=Math.max(m,i),c||(r=void 0);const A=a.length>1;return{codecSet:a.reduce(((t,r)=>{const s=e[r];if(r===t)return t;if(E=c?T.filter((t=>s.videoRanges[t]>0)):[],A){if(s.minBitrate>i)return be(r,`min bitrate of ${s.minBitrate} > current estimate of ${i}`),t;if(!s.hasDefaultAudio)return be(r,"no renditions with default or auto-select sound found"),t;if(l&&r.indexOf(l.substring(0,4))%5!=0)return be(r,`audio codec preference "${l}" not found`),t;if(o&&!h){if(!s.channels[o])return be(r,`no renditions with ${o} channel sound found (channels options: ${Object.keys(s.channels)})`),t}else if((!l||h)&&u&&0===s.channels[2])return be(r,"no renditions with stereo sound found"),t;if(s.minHeight>S)return be(r,`min resolution of ${s.minHeight} > maximum of ${S}`),t;if(s.minFramerate>L)return be(r,`min framerate of ${s.minFramerate} > maximum of ${L}`),t;if(!E.some((t=>s.videoRanges[t]>0)))return be(r,`no variants with VIDEO-RANGE of ${Re(E)} found`),t;if(d&&r.indexOf(d.substring(0,4))%5!=0)return be(r,`video codec preference "${d}" not found`),t;if(s.maxScore<v)return be(r,`max score of ${s.maxScore} < selected max of ${v}`),t}return t&&(le(r)>=le(t)||s.fragmentError>e[t].fragmentError)?t:(p=s.minIndex,v=s.maxScore,r)}),void 0),videoRanges:E,preferHDR:y,minFramerate:g,minBitrate:m,minIndex:p}}(s,A,e,b,D),{codecSet:a,videoRanges:o,minFramerate:l,minBitrate:d,minIndex:h,preferHDR:u}=n;I=h,L=a,A=u?o[o.length-1]:o[0],R=l,e=Math.max(e,d),this.log(`picked start tier ${Re(n)}`)}else L=null==y?void 0:y.codecSet,A=null==y?void 0:y.videoRange;const k=u?u.duration:h?h.duration:0,_=this.bwEstimator.getEstimateTTFB()/1e3,C=[];for(let l=i;l>=r;l--){var P;const r=g[l],h=l>f;if(!r)continue;if((L&&r.codecSet!==L||A&&r.videoRange!==A||h&&R>r.frameRate||!h&&R>0&&R<r.frameRate||null!=(P=r.supportedResult)&&null!=(P=P.decodingInfoResults)&&P.some((t=>!1===t.smooth)))&&(!S||l!==I)){C.push(l);continue}const m=r.details,v=(u?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||k||1;let y;y=h?o*e:a*e;const b=k&&s>=2*k&&0===n?r.averageBitrate:r.maxBitrate,D=this.getTimeToLoadFrag(_,y,b*v,!m||m.live);if(y>=b&&(l===d||0===r.loadError&&0===r.fragmentError||$(r,E.errorPenaltyExpireMs))&&(D<=_||!t(D)||T&&!this.bitrateTestDelay||D<c)){const t=this.forcedAutoLevel;return l===p||-1!==t&&t===p||(C.length&&this.trace(`Skipped level(s) ${C.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${g[C[0]].codecs}" ${g[C[0]].videoRange}; not compatible with "${L}" ${A}`),this.info(`switch candidate:${f}->${l} adjustedbw(${Math.round(y)})-bitrate=${Math.round(y-b)} ttfb:${_.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${D.toFixed(1)} firstSelection:${S} codecSet:${r.codecSet} videoRange:${r.videoRange} hls.loadLevel:${p}`)),S&&(this.firstSelection=l),l}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){if(!this.hls)return-1;const{maxAutoLevel:e,minAutoLevel:r}=this.hls;return Math.min(Math.max(t,r),e)}}const _e=function(t,e){let r=0,i=t.length-1,s=null,n=null;for(;r<=i;){s=(r+i)/2|0,n=t[s];const a=e(n);if(a>0)r=s+1;else{if(!(a<0))return n;i=s-1}}return null};function Ce(t,e,r=0,i=0,s=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const i=t.endDTS-r;i>0&&i<15e-7&&(r+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===r&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===Pe(r,i,n)||function(t,e,r){if(0===(null==e?void 0:e.start)&&e.level<t.level&&(e.endPTS||0)>0){const i=e.tagList.reduce(((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t)),r);return t.start<=i}return!1}(n,t,Math.min(s,i))))return n;const a=_e(e,Pe.bind(null,r,i));return!a||a===t&&n?n:a}function Pe(t=0,e=0,r){if(r.start<=t&&r.start+r.duration>t)return 0;const i=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=t?1:r.start-i>t&&r.start?-1:0}function xe(t,e,r){const i=1e3*Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>t}var we={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Oe={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16};class Me extends G{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(n.ERROR,this.onError,this),t.on(n.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(n.ERROR,this.onError,this),t.off(n.ERROR,this.onErrorOut,this),t.off(n.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===v.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,r=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===r?e.loadLevel:r}variantHasKey(t,e){if(t){var r;if(null!=(r=t.details)&&r.hasKey(e))return!0;const i=t.audioGroups;if(i){return this.hls.allAudioTracks.filter((t=>i.indexOf(t.groupId)>=0)).some((t=>{var r;return null==(r=t.details)?void 0:r.hasKey(e)}))}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var r;if(e.fatal)return;const n=this.hls,a=e.context;switch(e.details){case s.FRAG_LOAD_ERROR:case s.FRAG_LOAD_TIMEOUT:case s.KEY_LOAD_ERROR:case s.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case s.FRAG_PARSING_ERROR:if(null!=(r=e.frag)&&r.gap)return void(e.errorAction=$e());case s.FRAG_GAP:case s.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=we.SendAlternateToPenaltyBox);case s.PLAYLIST_UNCHANGED_ERROR:case s.LEVEL_EMPTY_ERROR:case s.LEVEL_PARSING_ERROR:{var o;const t=e.parent===v.MAIN?e.level:n.loadLevel;e.details===s.LEVEL_EMPTY_ERROR&&null!=(o=e.context)&&null!=(o=o.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case s.LEVEL_LOAD_ERROR:case s.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==a?void 0:a.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a.level)));case s.AUDIO_TRACK_LOAD_ERROR:case s.AUDIO_TRACK_LOAD_TIMEOUT:case s.SUBTITLE_LOAD_ERROR:case s.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const t=n.loadLevelObj;if(t&&(a.type===p.AUDIO_TRACK&&t.hasAudioGroup(a.groupId)||a.type===p.SUBTITLE_TRACK&&t.hasSubtitleGroup(a.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.loadLevel),e.errorAction.action=we.SendAlternateToPenaltyBox,void(e.errorAction.flags=Oe.MoveAllAlternatesMatchingHost)}return;case s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:we.SendAlternateToPenaltyBox,flags:Oe.MoveAllAlternatesMatchingHDCP});case s.KEY_SYSTEM_SESSION_UPDATE_FAILED:case s.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case s.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:we.SendAlternateToPenaltyBox,flags:Oe.MoveAllAlternatesMatchingKey});case s.BUFFER_ADD_CODEC_ERROR:case s.REMUX_ALLOC_ERROR:case s.BUFFER_APPEND_ERROR:return void(e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)));case s.MEDIA_SOURCE_REQUIRES_RESET:return e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)),void(e.errorAction.flags|=Oe.ResetMediaSource|Oe.SwitchToSDR);case s.INTERNAL_EXCEPTION:case s.BUFFER_APPENDING_ERROR:case s.BUFFER_APPEND_NO_PROGRESS:case s.BUFFER_FULL_ERROR:case s.LEVEL_SWITCH_ERROR:case s.BUFFER_STALLED_ERROR:case s.BUFFER_SEEK_OVER_HOLE:case s.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=$e())}e.type===i.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=$e())}getPlaylistRetryOrSwitchAction(t,e){const r=w(this.hls.config.playlistLoadPolicy,t),i=this.playlistError++;if(F(r,i,C(t),t.response))return{action:we.RetryRequest,flags:Oe.None,retryConfig:r,retryCount:i};const s=this.getLevelSwitchAction(t,e);return r&&(s.retryConfig=r,s.retryCount=i),s}getFragRetryOrSwitchAction(t){const e=this.hls,r=this.getVariantLevelIndex(t.frag),i=e.levels[r],{fragLoadPolicy:n,keyLoadPolicy:a}=e.config,o=w(P(t)?a:n,t),l=e.levels.reduce(((t,e)=>t+e.fragmentError),0);if(i&&(t.details!==s.FRAG_GAP&&i.fragmentError++,!x(t))){if(F(o,l,C(t),t.response))return{action:we.RetryRequest,flags:Oe.None,retryConfig:o,retryCount:l}}const d=this.getLevelSwitchAction(t,r);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(t,e){const r=this.hls;null==e&&(e=r.loadLevel);const i=this.hls.levels[e];if(i){var n,a;const e=t.details;i.loadError++,i.loadErrorTime=self.performance.now(),e===s.BUFFER_APPEND_ERROR&&i.fragmentError++;let d=-1;const{levels:h,loadLevel:u,minAutoLevel:c,maxAutoLevel:f}=r;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);const g=null==(n=t.frag)?void 0:n.type,m=(g===v.AUDIO&&e===s.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&Fe(t))&&h.some((({audioCodec:t})=>i.audioCodec!==t)),E="video"===t.sourceBufferName&&Fe(t)&&h.some((({codecSet:t,audioCodec:e})=>i.codecSet!==t&&i.audioCodec===e)),{type:y,groupId:T}=null!=(a=t.context)?a:{};for(let n=h.length;n--;){const a=(n+u)%h.length;if(a!==u&&a>=c&&a<=f&&(0===h[a].loadError||$(h[a],r.config.errorPenaltyExpireMs))){var o,l;const r=h[a];if(e===s.FRAG_GAP&&g===v.MAIN&&t.frag){const e=h[a].details;if(e){const r=Ce(t.frag,e.fragments,t.frag.start);if(null!=r&&r.gap)continue}}else{if(y===p.AUDIO_TRACK&&r.hasAudioGroup(T)||y===p.SUBTITLE_TRACK&&r.hasSubtitleGroup(T))continue;if(g===v.AUDIO&&null!=(o=i.audioGroups)&&o.some((t=>r.hasAudioGroup(t)))||g===v.SUBTITLE&&null!=(l=i.subtitleGroups)&&l.some((t=>r.hasSubtitleGroup(t)))||m&&i.audioCodec===r.audioCodec||E&&i.codecSet===r.codecSet||!m&&i.audioCodec!==r.audioCodec)continue}d=a;break}}if(d>-1&&r.loadLevel!==d)return t.levelRetry=!0,this.playlistError=0,{action:we.SendAlternateToPenaltyBox,flags:Oe.None,nextAutoLevel:d}}return{action:we.SendAlternateToPenaltyBox,flags:Oe.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var r,i;switch(null==(r=e.errorAction)?void 0:r.action){case we.DoNothing:break;case we.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===s.FRAG_GAP||e.details===s.PLAYLIST_UNCHANGED_ERROR||Ne(e)||(e.fatal=!0)}((null==(i=e.errorAction)?void 0:i.flags)||0)&Oe.ResetMediaSource&&this.hls.recoverMediaError(),e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,r=t.errorAction;if(!r)return;let i=r.nextAutoLevel;if(r.flags===Oe.None)this.switchLevel(t,i);else if(r.flags&Oe.SwitchToSDR){const t=this.hls.levels;for(let e=t.length;e--;)"SDR"!==t[e].videoRange?(t[e].fragmentError++,t[e].loadError++):void 0===i&&(i=e)}else if(r.flags&Oe.MoveAllAlternatesMatchingHDCP){const i=this.getVariantLevelIndex(t.frag),s=e.levels[i],n=null==s?void 0:s.attrs["HDCP-LEVEL"];r.hdcpLevel=n;const a="NONE"===n;n&&!a?(e.maxHdcpLevel=pe[pe.indexOf(n)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)):(a&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),r.flags|=Oe.MoveAllAlternatesMatchingKey)}if(r.flags&Oe.MoveAllAlternatesMatchingKey){const e=t.decryptdata;if(e){const i=this.hls.levels,a=i.length;for(let r=a;r--;){var s,n;if(this.variantHasKey(i[r],e))this.log(`Banned key found in level ${r} (${i[r].bitrate}bps) or audio group "${null==(s=i[r].audioGroups)?void 0:s.join(",")}" (${null==(n=t.frag)?void 0:n.type} fragment) ${Tt(e.keyId||[])}`),i[r].fragmentError++,i[r].loadError++,this.log(`Removing level ${r} with key error (${t.error})`),this.hls.removeLevel(r)}const o=t.frag;if(this.hls.levels.length<a)r.resolved=!0;else if(o&&o.type!==v.MAIN){const t=o.decryptdata;t&&!e.matches(t)&&(r.resolved=!0)}}}r.resolved||this.switchLevel(t,i)}switchLevel(t,e){if(void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===s.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=t.mimeType.replace(/^.+codecs=["']?([^"']+).*$/,"$1"),r=this.hls.levels;for(let i=r.length;i--;)r[i][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${i} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(i))}}}function Fe(t){const e=t.details;return e===s.BUFFER_ADD_CODEC_ERROR||e===s.MEDIA_SOURCE_REQUIRES_RESET||e===s.BUFFER_APPEND_ERROR&&!Ne(t)}function Ne(t){return t.details===s.BUFFER_APPEND_ERROR&&("QuotaExceededError"===t.error.name||"InvalidStateError"===t.error.name)}function $e(t){const e={action:we.DoNothing,flags:Oe.None};return t&&(e.resolved=!0),e}const Be=/^(\d+)x(\d+)$/,Ue=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Ge{constructor(t,e){"string"==typeof t&&(t=Ge.parseAttrList(t,e)),I(this,t)}get clientAttrs(){return Object.keys(this).filter((t=>"X-"===t.substring(0,2)))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const r=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)r[t]=parseInt(e.slice(2*t,2*t+2),16);return r}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const r=this[t];return r?parseFloat(r):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const r=this[t];return(r?r.split(/[ ,]+/):[]).reduce(((t,e)=>(t[e.toLowerCase()]=!0,t)),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=Be.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let r;const i={};for(Ue.lastIndex=0;null!==(r=Ue.exec(t));){const s=r[1].trim();let n=r[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(s){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o));else if(!o&&!a)switch(s){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":j.warn(`${t}: attribute ${s} is missing quotes`)}i[s]=n}return i}}function Ve(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class He{constructor(e,r,i=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==r?void 0:r.tagAnchor)||null,this.tagOrder=null!=(s=null==r?void 0:r.tagOrder)?s:i,r){const t=r.attr;for(const r in t)if(Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==t[r]){j.warn(`DATERANGE tag attribute: "${r}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=r;break}e=I(new Ge({}),t,e)}if(this.attr=e,r?(this._startDate=r._startDate,this._cue=r._cue,this._endDate=r._endDate,this._dateAtEnd=r._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){const i=(null==r?void 0:r.endDate)||new Date(e["END-DATE"]);t(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(j.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(t(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&t(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:t(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}}class Ke{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,r=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!r||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&r>0,this.updated||this.advanced?this.misses=0:this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some((e=>{let r=e.decryptdata;return r||(e.setKeyFormat(t.keyFormat),r=e.decryptdata),!!r&&t.matches(r)}))}get hasProgramDateTime(){return!!this.fragments.length&&t(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let r=t.length;r--;)if(t[r].index>e)return t[r].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&void 0!==this.advancedDateTime&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}get partsExpired(){return!!(this.live&&this.partTarget&&void 0!==this.advancedDateTime&&this.misses<3)&&this.age>1.5*(this.partHoldBack||3*this.partTarget)}}function Ye(t,e){return t.length===e.length&&!t.some(((t,r)=>t!==e[r]))}function We(t,e){return!t&&!e||!(!t||!e)&&Ye(t,e)}var je=0,qe=1;function ze(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function Xe(t){switch(t){case"AES-128":case"AES-256":return je;case"AES-256-CTR":return qe;default:throw new Error(`invalid full segment method ${t}`)}}let Qe={};class Ze{static clearKeyUriToKeyIdMap(){Qe={}}static setKeyIdForUri(t,e){Qe[t]=e}static addKeyIdForUri(t){const e=Object.keys(Qe).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,e),Qe[t]=r,r}constructor(t,e,r,i=[1],s=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=t,this.uri=e,this.keyFormat=r,this.keyFormatVersions=i,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!ze(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(St(n)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&Ye(t.keyFormatVersions,this.keyFormatVersions)&&We(t.iv,this.iv)&&We(t.keyId,this.keyId)}isSupported(){if(this.method){if(ze(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method}return!1}getDecryptData(t,e){if(!this.encrypted||!this.uri)return null;if(ze(this.method)){let e=this.iv;e||("number"!=typeof t&&(j.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),e=function(t){const e=new Uint8Array(16);for(let r=12;r<16;r++)e[r]=t>>8*(15-r)&255;return e}(t));return new Ze(this.method,this.uri,"identity",this.keyFormatVersions,e)}return this}}const Je=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,tr=/#EXT-X-MEDIA:(.*)/g,er=/^#EXT(?:INF|-X-TARGETDURATION):/m,rr=new RegExp([/#EXTINF:\s*(\d+(?:\.\d*)?|\.\d+)?(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ir=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class sr{static findGroup(t,e){for(let r=0;r<t.length;r++){const i=t[r];if(i.id===e)return i}}static resolve(t,e){return g.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return er.test(t)}static parseMasterPlaylist(t,e){const r={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:!1},i=[];if(Je.lastIndex=0,!t.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let s;for(;null!=(s=Je.exec(t));)if(s[1]){const t=nr(new Ge(s[1],r),s[2],e,r,i);t&&r.levels.push(t)}else if(s[3]){const t=s[3],n=s[4];switch(t){case"I-FRAME-STREAM-INF":{const t=new Ge(n,r),s=nr(t,t.URI,e,r,i,!0);s&&r.iframeVariants.push(s)}break;case"SESSION-DATA":{const t=new Ge(n,r),e=t["DATA-ID"];e&&(null===r.sessionData&&(r.sessionData={}),r.sessionData[e]=t);break}case"SESSION-KEY":{const t=lr(n,e,r);t.encrypted&&t.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(t)):j.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${n}"`);break}case"DEFINE":break;case"CONTENT-STEERING":{const t=new Ge(n,r);r.contentSteering={uri:sr.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=dr(n)}}const n=i.length>0&&i.length<r.levels.length;return r.levels=n?i:r.levels,0===r.levels.length&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(t,e,r){let i;const s={},n=r.levels,a={AUDIO:n.map((t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec}))),SUBTITLES:n.map((t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(tr.lastIndex=0;null!==(i=tr.exec(t));){const t=new Ge(i[1],r),n=t.TYPE;if(n){const r=a[n],i=s[n]||[];s[n]=i;const l=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],h=t.CHANNELS,u=t.CHARACTERISTICS,c=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?sr.resolve(t.URI,e):""};if(d&&(f.assocLang=d),h&&(f.channels=h),u&&(f.characteristics=u),c&&(f.instreamId=c),null!=r&&r.length){const t=sr.findGroup(r,f.groupId)||r[0];ur(f,t,"audioCodec"),ur(f,t,"textCodec")}i.push(f)}}return s}static parseLevelPlaylist(e,r,i,s,n,a){var o;const l={url:r},d=new Ke(r),h=d.fragments,u=[];let c,f,g,m,p=null,v=0,E=0,y=0,T=0,S=0,L=null,b=new A(s,l),D=-1,k=!1,_=null;if(rr.lastIndex=0,d.m3u8=e,d.hasVariableRefs=!1,"#EXTM3U"!==(null==(o=rr.exec(e))?void 0:o[0]))return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;null!==(c=rr.exec(e));){k&&(k=!1,b=new A(s,l),b.playlistOffset=y,b.setStart(y),b.sn=v,b.cc=T,S&&(b.bitrate=S),b.level=i,p&&(b.initSegment=p,p.rawProgramDateTime&&(b.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),_&&(b.setByteRange(_),_=null)));const e=c[1];if(e){b.duration=parseFloat(e);const t=(" "+c[2]).slice(1);b.title=t||null,b.tagList.push(t?["INF",e,t]:["INF",e])}else if(c[3]){if(t(b.duration)){var C;b.playlistOffset=y,b.setStart(y),g&&gr(b,g,d),b.sn=v,b.level=i,b.cc=T;const t=(" "+c[3]).slice(1);b.relurl=t,cr(b,L,u),L=b,y+=b.duration,v++,E=0;const e=b.byteRange;if(2===e.length&&(b.bitrate=8*(e[1]-e[0])/b.duration|0),d.iframesOnly&&e[0]&&(null==(C=p)?void 0:C.cc)!==T){const t=new A(s,l);t.relurl=b.relurl,t.setByteRange(`${Math.min(e[0],1316)}@0`),t.level=i,t.sn="initSegment",g&&(t.levelkeys=g,g.identity&&(t._decryptdata=g.identity.getDecryptData(0))),p=t,b.initSegment=p}h.push(b),k=!0}}else{if(c=c[0].match(ir),!c){j.warn("No matches on slow regex match for level playlist!");continue}for(f=1;f<c.length&&void 0===c[f];f++);const e=(" "+c[f]).slice(1),n=(" "+c[f+1]).slice(1),a=c[f+2]?(" "+c[f+2]).slice(1):null;switch(e){case"BYTERANGE":L?b.setByteRange(n,L):b.setByteRange(n);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=n,b.tagList.push(["PROGRAM-DATE-TIME",n]),-1===D&&(D=h.length);break;case"PLAYLIST-TYPE":d.type&&mr(d,e,c),d.type=n.toUpperCase();break;case"MEDIA-SEQUENCE":0!==d.startSN?mr(d,e,c):null!==L&&pr(d,e,c),d.startSN=parseInt(n),v=d.startSN+d.skippedSegments;break;case"SKIP":{d.skippedSegments&&mr(d,e,c);const r=new Ge(n,d),i=r.decimalInteger("SKIPPED-SEGMENTS");if(t(i)){d.skippedSegments+=i;for(let t=i;t--;)h.push(null);v+=i}const s=r.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(s.split("\t")));break}case"TARGETDURATION":0!==d.targetduration&&mr(d,e,c),d.targetduration=Math.max(parseInt(n),1);break;case"VERSION":null!==d.version&&mr(d,e,c),d.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":case"DEFINE":break;case"I-FRAMES-ONLY":d.iframesOnly=!0;break;case"ENDLIST":d.live||mr(d,e,c),d.live=!1;break;case"#":(n||a)&&b.tagList.push(a?[n,a]:[n]);break;case"DISCONTINUITY":T++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([e]);break;case"BITRATE":b.tagList.push([e,n]),S=1e3*parseInt(n),t(S)?b.bitrate=S:S=0;break;case"DATERANGE":{const t=new Ge(n,d),e=new He(t,d.dateRanges[t.ID],d.dateRangeTagCount);d.dateRangeTagCount++,e.isValid||d.skippedSegments?d.dateRanges[e.id]=e:j.log(`Ignoring invalid DATERANGE tag: ${e.invalidReason}: ${n}`),b.tagList.push(["EXT-X-DATERANGE",n]);break}case"DISCONTINUITY-SEQUENCE":0!==d.startCC&&mr(d,e,c),d.startCC=T=parseInt(n),h.forEach((t=>t&&(t.cc=T)));break;case"KEY":{const t=lr(n,r,d);if(t.isSupported()){if("NONE"===t.method){g=void 0;break}g||(g={});const e=g[t.keyFormat];null!=e&&e.matches(t)||(e&&(g=I({},g)),g[t.keyFormat]=t)}else j.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${n}" (light build)`);break}case"START":d.startTimeOffset=dr(n);break;case"MAP":{const t=new Ge(n,d);if(b.duration){const e=new A(s,l);fr(e,t,i,g),p=e,b.initSegment=p,p.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=p.rawProgramDateTime)}else{const e=b.byteRangeEndOffset;if(e){const t=b.byteRangeStartOffset;_=`${e-t}@${t}`}else _=null;fr(b,t,i,g),p=b,k=!0}p.cc=T;break}case"SERVER-CONTROL":m&&mr(d,e,c),m=new Ge(n),d.canBlockReload=m.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=m.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&m.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=m.optionalFloat("PART-HOLD-BACK",0),d.holdBack=m.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{d.partTarget&&mr(d,e,c);const t=new Ge(n);d.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=d.partList;t||(t=d.partList=[]);const e=E>0?t[t.length-1]:void 0,r=E++,i=new Ge(n,d),s=new R(i,b,l,r,e);t.push(s),b.duration+=s.duration;break}case"PRELOAD-HINT":{const t=new Ge(n,d);d.preloadHint=t;break}case"RENDITION-REPORT":{const t=new Ge(n,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(t);break}default:j.warn(`line parsed but not handled: ${c}`)}}}L&&!L.relurl?(h.pop(),y-=L.duration,d.partList&&(d.fragmentHint=L)):d.partList&&(cr(b,L,u),b.cc=T,d.fragmentHint=b,g&&gr(b,g,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const P=h.length,x=h[0],w=h[P-1];if(y+=d.skippedSegments*d.targetduration,y>0&&P&&w){d.averagetargetduration=y/P;const t=w.sn;d.endSN="initSegment"!==t?t:0,d.live||(w.endList=!0),D>0&&(!function(t,e,r){if(r||(r=t[e]),!r)return;for(let i=e;i--;){const e=t[i];if(!e)return;e.programDateTime=r.programDateTime-1e3*e.duration,r=e}}(h,D,D>P-1?b:null),x&&u.unshift(x))}return d.fragmentHint&&(y+=d.fragmentHint.duration),d.totalduration=y,u.length&&d.dateRangeTagCount&&x&&ar(u,d),d.endCC=T,d}}function nr(t,e,r,i,s,n){var a;if(void 0===e)return null;const o=e,l={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:sr.resolve(o,r)},d=t.decimalResolution("RESOLUTION");d&&(l.width=d.width,l.height=d.height),hr(t.CODECS,l);const h=t["SUPPLEMENTAL-CODECS"];return h&&(l.supplemental={},hr(h,l.supplemental)),null!=(a=l.unknownCodecs)&&a.length||s.push(l),n&&(l.iframes=!0),l}function ar(t,e){let r=t.length;if(!r){if(!e.hasProgramDateTime)return;{const i=e.fragments[e.fragments.length-1];t.push(i),r++}}const i=t[r-1],s=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=r;i--;){var a;if((null==(a=t[i])?void 0:a.sn)<e.startSN)break;const r=or(e,d,t,i,s);if(r){l.tagAnchor=r.ref;break}}}}function or(t,e,r,i,s){const n=r[i];if(n){const o=n.programDateTime;if(e>=o||0===i){var a;if(e<=o+1e3*(((null==(a=r[i+1])?void 0:a.start)||s)-n.start)){const s=n.sn-t.startSN,a=t.fragments;if(s>=0&&s<a.length){if(a.length>r.length){const n=r[i+1]||a[a.length-1];for(let r=Math.min(n.sn-t.startSN,a.length-1);r>s;r--){const t=a[r].programDateTime;if(e>=t&&e<t+1e3*a[r].duration)return a[r]}}return a[s]}}}}return null}function lr(t,e,r){var i,s;const n=new Ge(t,r),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,h=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&j.error(`Invalid IV: ${n.IV}`);const u=o?sr.resolve(o,e):"",c=(d||"1").split("/").map(Number).filter(Number.isFinite);return new Ze(a,u,h,c,l,n.KEYID)}function dr(e){const r=new Ge(e).decimalFloatingPoint("TIME-OFFSET");return t(r)?r:null}function hr(t,e){let r=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text","image"].forEach((t=>{const i=r.filter((e=>ie(e,t)));i.length&&(e[`${t}Codec`]=i.map((t=>t.split("/")[0])).join(","),r=r.filter((t=>-1===i.indexOf(t))))})),e.unknownCodecs=r}function ur(t,e,r){const i=e[r];i&&(t[r]=i)}function cr(t,e,r){t.rawProgramDateTime?r.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function fr(t,e,r,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=r,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function gr(t,e,r){t.levelkeys=e;const{encryptedFragments:i}=r;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some((t=>e[t].isCommonEncryption))||i.push(t)}function mr(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${r[0]})`)}function pr(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${r[0]})`)}function vr(e,r){const i=r.startPTS;if(t(i)){let t,s=0;r.sn>e.sn?(s=i-e.start,t=e):(s=e.start-i,t=r),t.duration!==s&&t.setDuration(s)}else if(r.sn>e.sn){e.cc===r.cc&&e.minEndPTS?r.setStart(e.start+(e.minEndPTS-e.start)):r.setStart(e.start+e.duration)}else r.setStart(Math.max(e.start-r.duration,0))}function Er(e,r,i,s,n,a,o,l){s-i<=0&&(l.warn("Fragment should have a positive duration",r),s=i+r.duration,a=n+r.duration);let d=i,h=s;const u=r.startPTS,c=r.endPTS;if(t(u)){const o=Math.abs(u-i);e&&o>e.totalduration?l.warn(`media timestamps and playlist times differ by ${o}s for level ${r.level} ${e.url}`):t(r.deltaPTS)?r.deltaPTS=Math.max(o,r.deltaPTS):r.deltaPTS=o,d=Math.max(i,u),i=Math.min(i,u),n=void 0!==r.startDTS?Math.min(n,r.startDTS):n,h=Math.min(s,c),s=Math.max(s,c),a=void 0!==r.endDTS?Math.max(a,r.endDTS):a}const f=i-r.start;return 0!==r.start&&r.setStart(i),r.setDuration(s-r.start),r.startPTS=i,r.maxStartPTS=d,r.startDTS=n,r.endPTS=s,r.minEndPTS=h,r.endDTS=a,yr(e,r,f)}function yr(t,e,r){var i;const s=e.sn;if(!t||s<t.startSN||s>((null==(i=t.fragmentHint)?void 0:i.sn)||t.endSN))return 0;let n;const a=s-t.startSN,o=t.fragments;for(o[a]=e,n=a;n>0;n--)vr(o[n],o[n-1]);for(n=a;n<o.length-1;n++)vr(o[n],o[n+1]);return t.fragmentHint&&vr(o[o.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,r}function Tr(e,r,i){if(e===r)return;let s=null;const n=e.fragments;for(let t=n.length-1;t>=0;t--){const e=n[t].initSegment;if(e){s=e;break}}let a;e.fragmentHint&&delete e.fragmentHint.endPTS,function(t,e,r){var i;const s=e.skippedSegments,n=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(s?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,o=e.startSN-t.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,d=null!=(i=t.fragmentHint)&&i.duration?t.fragments.concat(t.fragmentHint):t.fragments;for(let i=n;i<=a;i++){const n=d[o+i];let a=l[i];if(s&&!a&&n&&(a=e.fragments[i]=n),n&&a){r(n,a,i,l);const s=n.relurl,o=a.relurl;if(s&&kr(s,o))return void(e.playlistParsingError=Sr(`media sequence mismatch ${a.sn}:`,t,e,n,a));if(n.cc!==a.cc)return void(e.playlistParsingError=Sr(`discontinuity sequence mismatch (${n.cc}!=${a.cc})`,t,e,n,a))}}}(e,r,((e,i,n,o)=>{if(i.cc!==e.cc&&(e.cc>i.cc||r.skippedSegments)){const t=e.cc-i.cc;for(let e=n;e<o.length;e++)o[e].cc+=t;r.endCC=o[o.length-1].cc}t(e.startPTS)&&t(e.endPTS)&&(i.setStart(i.startPTS=e.startPTS),i.startDTS=e.startDTS,i.maxStartPTS=e.maxStartPTS,i.endPTS=e.endPTS,i.endDTS=e.endDTS,i.minEndPTS=e.minEndPTS,i.setDuration(e.endPTS-e.startPTS),i.duration&&(a=i),r.PTSKnown=r.alignedSliding=!0),e.hasStreams&&(i.elementaryStreams=e.elementaryStreams),i.loader=e.loader,i.gap=e.gap||i.gap,e.hasStats&&(i.stats=e.stats),e.initSegment&&(i.initSegment=e.initSegment,s=e.initSegment)}));const o=r.fragments,l=r.fragmentHint?o.concat(r.fragmentHint):o;if(s&&l.forEach((t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=s)?void 0:e.relurl)||(t.initSegment=s)})),r.skippedSegments){if(r.deltaUpdateFailed=o.some((t=>!t)),r.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=r.skippedSegments;t--;)o.shift();r.startSN=o[0].sn}else{r.canSkipDateRanges&&(r.dateRanges=function(t,e,r){const{dateRanges:i,recentlyRemovedDateranges:s}=e,n=I({},t);s&&s.forEach((t=>{delete n[t]}));const a=Object.keys(n).length;if(!a)return i;return Object.keys(i).forEach((t=>{const e=n[t],s=new He(i[t].attr,e);s.isValid?(n[t]=s,e||(s.tagOrder+=a)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Re(i[t].attr)}"`)})),n}(e.dateRanges,r,i));const t=e.fragments.filter((t=>t.rawProgramDateTime));if(e.hasProgramDateTime&&!r.hasProgramDateTime)for(let e=1;e<l.length;e++)null===l[e].programDateTime&&cr(l[e],l[e-1],t);ar(t,r)}r.endCC=o[o.length-1].cc}else if(r.startSN>e.endSN&&o[0].cc<e.endCC){const t=e.endCC-o[0].cc;l.forEach((e=>{e.cc+=t})),r.endCC+=t}if(!r.startCC){var d;const t=Rr(e,r.startSN-1);r.startCC=null!=(d=null==t?void 0:t.cc)?d:o[0].cc}if(function(t,e,r){if(t&&e){let i=0;for(let s=0,n=t.length;s<n;s++){const n=t[s],a=e[s+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?r(n,a):i--}}}(e.partList,r.partList,((t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats,e.gap=t.gap||e.gap})),a){r.iframesOnly&&(a.type,v.MAIN);Er(r,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,0,i)}else Lr(e,r);o.length&&(r.totalduration=r.edge-o[0].start),r.driftStartTime=e.driftStartTime,r.driftStart=e.driftStart;const h=r.advancedDateTime;if(r.advanced&&h){const t=r.edge;r.driftStart||(r.driftStartTime=h,r.driftStart=t),r.driftEndTime=h,r.driftEnd=t}else r.driftEndTime=e.driftEndTime,r.driftEnd=e.driftEnd,r.advancedDateTime=e.advancedDateTime;-1===r.requestScheduled&&(r.requestScheduled=e.requestScheduled)}function Sr(t,e,r,i,s){return new Error(`${t} ${s.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${r.startSN}\n${r.m3u8}`)}function Lr(t,e,r=!0,i){const s=e.startSN+e.skippedSegments-t.startSN,n=t.fragments,a=s>=0;let o=0;if(a&&s<n.length)o=n[s].start,null==i||i.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===t.endSN+1)o=t.fragmentEnd,null==i||i.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&r)o=t.fragmentStart+s*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return o;o=t.fragmentStart,null==i||i.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`)}return function(t,e){if(e){const r=t.fragments;for(let i=t.skippedSegments;i<r.length;i++)r[i].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}(e,o),o}function Ar(t,e=1/0){let r=1e3*t.targetduration;if(t.updated){const i=t.fragments,s=4;if(i.length&&r*s>e){const t=1e3*i[i.length-1].duration;t>0&&t<r&&(r=t)}}else r/=2;return Math.round(r)}function Rr(t,e,r){var i;if(!t)return null;let s=t.fragments[e-t.startSN];return s||(s=t.fragmentHint,(null==(i=s)?void 0:i.sn)===e?s:r&&e<t.startSN&&r.sn===e?r:null)}function br(t,e,r){return t?Dr(t.partList,e,r):null}function Dr(t,e,r){if(t)for(let i=t.length;i--;){const s=t[i];if(s.index===r&&s.fragment.sn===e)return s}return null}function Ir(t){t.forEach(((t,e)=>{var r;null==(r=t.details)||r.fragments.forEach((t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)}))}))}function kr(t,e){return!(t===e||!e)&&_r(t)!==_r(e)}function _r(t){return t.replace(/\?[^?]*$/,"")}class Cr extends G{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.loadingSync=!1,this.hls=t}destroy(){this.clearTimer(),this.hls=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,r){const i=null==e?void 0:e.renditionReports;if(i){let s=-1;for(let r=0;r<i.length;r++){const n=i[r];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){s=r;break}a===t.substring(0,a.length)&&(s=r)}if(-1!==s){const t=i[s],n=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=r&&ye(r);return new Te(n,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,r){const{details:a,stats:o}=e,l=a.fragments,d=self.performance.now(),h=o.loading.first?Math.max(0,Math.floor(d-o.loading.first)):0;a.advancedDateTime=Date.now()-h;const u=this.hls.config.timelineOffset;if(u!==a.appliedTimelineOffset){const t=Math.max(u||0,0);a.appliedTimelineOffset=t,l.forEach((e=>{null==e||e.setStart(e.playlistOffset+t)}))}if(a.live||null!=r&&r.live){var c;const u="levelInfo"in e?e.levelInfo:e.track;a.reloaded(r);const f=null==(c=l[l.length-1])?void 0:c.type;if(a.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const t=new Error(`${f} playlist ${u.id} hit max allowed unchanged reloads.`);this.warn(t);const{networkDetails:r,context:l}=e;return void this.hls.trigger(n.ERROR,{type:i.NETWORK_ERROR,details:s.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:a.url,error:t,reason:t.message,level:e.level,parent:f,context:l,networkDetails:r,stats:o})}if(r){Tr(r,a,this);const t=a.playlistParsingError;if(t){this.warn(t);const r=this.hls;if(!r.config.ignorePlaylistParsingErrors){const{networkDetails:l}=e;return void r.trigger(n.ERROR,{type:i.NETWORK_ERROR,details:s.LEVEL_PARSING_ERROR,fatal:!1,url:a.url,error:t,reason:t.message,level:e.level,parent:f,networkDetails:l,stats:o})}a.playlistParsingError=null}}-1===a.requestScheduled&&(a.requestScheduled=o.loading.start);const g=this.hls.mainForwardBufferInfo,m=g?g.end-g.len:0,p=Ar(a,1e3*(a.edge-m));a.requestScheduled+p<d?a.requestScheduled=d:a.requestScheduled<=d&&(a.requestScheduled+=p);const v=e.deliveryDirectives;if(this.log(`live playlist ${t} ${a.advanced?`REFRESHED ${a.lastPartSn} - ${a.lastPartIndex}`:a.updated?"UPDATED":`MISSED (received ${a.lastPartSn} - ${a.lastPartIndex}${v?` | requested ${v.msn} - ${v.part}`:""})`}`),!this.canLoad||!a.live)return;let E,y,T;if(a.canBlockReload&&a.advanced){const t=this.hls.config.lowLatencyMode,i=a.lastPartSn,s=a.endSN,n=a.lastPartIndex,o=i===s;-1!==n?o?(y=s+1,T=t?0:n):(y=i,T=t?n+1:a.maxPartIndex):y=s+1;const l=a.age,h=l+a.ageHeader;let c=Math.min(h-a.partTarget,1.5*a.targetduration);if(c>0){if(h>3*a.targetduration)this.log(`Playlist last advanced ${l.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,T=void 0;else if(null!=r&&r.tuneInGoal&&h-a.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${c} with playlist age: ${a.age}`),c=0;else{const t=Math.floor(c/a.targetduration);if(y+=t,void 0!==T){T+=Math.round(c%a.targetduration/a.partTarget)}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${l.toFixed(2)}s goal: ${c} skip sn ${t} to part ${T}`)}a.tuneInGoal=c}if(E=this.getDeliveryDirectives(a,e.deliveryDirectives,y,T),t||!o)return a.requestScheduled=d,void this.loadingPlaylist(u,E)}else(a.canBlockReload||a.canSkipUntil)&&(E=this.getDeliveryDirectives(a,e.deliveryDirectives,y,T));E&&void 0!==y&&a.canBlockReload&&(a.requestScheduled=o.loading.first+Math.max(p-2*h,p/2)),this.scheduleLoading(u,E,a)}else this.clearTimer()}scheduleLoading(t,e,r){const i=r||t.details;if(!i)return void this.loadingPlaylist(t,e);const s=self.performance.now(),n=i.requestScheduled;if(s>=n&&!this.loadingSync)return this.loadingSync=!0,this.loadingPlaylist(t,e),void(this.loadingSync=!1);const a=Math.max(n-s,0);this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout((()=>this.loadingPlaylist(t,e)),a)}getDeliveryDirectives(t,e,r,i){let s=ye(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(r=e.msn,i=e.part,s=Ee.No),new Te(r,i,s)}checkRetry(t){const e=t.details,r=C(t),i=t.errorAction,{action:s,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(s===we.RetryRequest||!i.resolved&&s===we.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(r&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{var d;const r=N(null==(d=t.response)?void 0:d.code);if(this.clearTimer(),r)this.log("Waiting for connection (offline)"),t.reason="offline",this.timer=self.setTimeout((()=>this.checkOfflineStatus()),1e3);else{const t=O(a,n);this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`),this.timer=self.setTimeout((()=>this.loadPlaylist()),t)}}t.levelRetry=!0,i.resolved=!0}return o}checkOfflineStatus(){this.clearTimer(),N(0)?this.timer=self.setTimeout((()=>this.checkOfflineStatus()),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}class Pr{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,r){if(null===this.queues||null===this.tracks)return;const i=this.queues[e];i.push(t),1!==i.length||r||this.executeNext(e)}appendBlocker(t){return new Promise((e=>{const r={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,t)}))}prependBlocker(t){return new Promise((e=>{if(this.queues){const r={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(r)}}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((t=>{var e;const r=null==(e=t[0])?void 0:e.label;"async-blocker"===r||"async-blocker-prepend"===r?(t[0].execute(),t.splice(0,1)):"block-audio"===r&&t.splice(0,1)}))}insertNext(t,e){null!==this.queues&&this.queues[e].splice(1,0,...t)}unblockAudio(){var t;null!==this.queues&&"block-audio"===(null==(t=this.current("audio"))?void 0:t.label)&&this.shiftAndExecuteNext("audio")}audioBlocking(){return null!==this.queues&&this.queues.audio.some((t=>"block-audio"===t.label))}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const i=e[0];try{i.execute()}catch(e){var r;if(i.onError(e),null===this.queues||null===this.tracks)return;const s=null==(r=this.tracks[t])?void 0:r.buffer;null!=s&&s.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,r;return null!=(e=this.queues)&&e[t]||null!=(r=this.tracks)&&r[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const r=null==(e=this.tracks)?void 0:e[t],i=null==r?void 0:r.buffer;return i?`SourceBuffer${i.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map((t=>t.label)).join(", "))||""}}const xr={length:0,start:()=>0,end:()=>0};class wr{static isBuffered(t,e){if(t){const r=wr.getBuffered(t);for(let t=r.length;t--;)if(e>=r.start(t)&&e<=r.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=wr.getBuffered(t);return wr.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let r=0;r<t.length;r++)e.push({start:t.start(r),end:t.end(r)});return e}static bufferInfo(t,e,r){if(t){const i=wr.bufferedRanges(t);if(i.length)return wr.bufferedInfo(i,e,r)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,r){e=Math.max(0,e),t.length>1&&t.sort(((t,e)=>t.start-e.start||e.end-t.end));let i=-1,s=[];if(r)for(let n=0;n<t.length;n++){e>=t[n].start&&e<=t[n].end&&(i=n);const a=s.length;if(a){const e=s[a-1].end;t[n].start-e<r?t[n].end>e&&(s[a-1].end=t[n].end):s.push(t[n])}else s.push(t[n])}else s=t;let n,a=0,o=e,l=e;for(let t=0;t<s.length;t++){const d=s[t].start,h=s[t].end;if(-1===i&&e>=d&&e<=h&&(i=t),e+r>=d&&e<h)o=d,l=h,a=l-e;else if(e+r<d){n=d;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:i}}static getBuffered(t){try{return t.buffered||xr}catch(t){return j.log("failed to get media.buffered",t),xr}}}function Or(t,e,r){Mr(t,e,r),t.addEventListener(e,r)}function Mr(t,e,r){t.removeEventListener(e,r)}function Fr(t){let e="";const r=t.length;for(let i=0;i<r;i++)e+=`[${t.start(i).toFixed(3)}-${t.end(i).toFixed(3)}]`;return e}const Nr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,$r="HlsJsTrackRemovedError",Br="HlsJsSourceBufferError";class Ur extends Error{constructor(t){super(t),this.name=$r}}class Gr extends G{constructor(t,e){var r;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.media&&!this.media.seeking&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:r}=this;t&&this.log("Media source opened"),e&&r&&(Mr(r,"sourceopen",this._onMediaSourceOpen),Mr(e,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(n.MEDIA_ATTACHED,{media:e,mediaSource:r}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){if(this.isMediaSourceReplaced()){const{currentSrc:t}=this.media,e=t&&t!==this._objectUrl?t:this.mediaSrc;return this.warn(`MediaSource closed after media element switched to another source (${this._objectUrl} > ${e}) - detaching media`),void this.hls.detachMedia()}const t=this.media.error,{appendError:e,appendErrors:r}=this;let a=!1;if(!e&&t){a=Math.max(++r.audio,++r.video,++r.audiovideo)>=this.hls.config.appendErrorMaxRetry}const o=new Error(`MediaSource closed while media attached${Kr(a,t)}`);this.warn(o),this.hls.trigger(n.ERROR,I({fatal:a},e,{type:i.MEDIA_ERROR,details:s.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this._onMediaError=()=>{const{media:t}=this;var e,r;t&&this.log(`Media error (code: ${null==(e=t.error)?void 0:e.code}): ${null==(r=t.error)?void 0:r.message}`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(r=Z(t.config.preferManagedMediaSource),"undefined"!=typeof self&&r===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}registerListeners(){const{hls:t}=this;t.on(n.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(n.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(n.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.MANIFEST_PARSED,this.onManifestParsed,this),t.on(n.BUFFER_RESET,this.onBufferReset,this),t.on(n.BUFFER_APPENDING,this.onBufferAppending,this),t.on(n.BUFFER_CODECS,this.onBufferCodecs,this),t.on(n.BUFFER_EOS,this.onBufferEos,this),t.on(n.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(n.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(n.FRAG_PARSED,this.onFragParsed,this),t.on(n.FRAG_CHANGED,this.onFragChanged,this),t.on(n.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(n.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(n.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(n.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.MANIFEST_PARSED,this.onManifestParsed,this),t.off(n.BUFFER_RESET,this.onBufferReset,this),t.off(n.BUFFER_APPENDING,this.onBufferAppending,this),t.off(n.BUFFER_CODECS,this.onBufferCodecs,this),t.off(n.BUFFER_EOS,this.onBufferEos,this),t.off(n.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(n.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(n.FRAG_PARSED,this.onFragParsed,this),t.off(n.FRAG_CHANGED,this.onFragChanged,this),t.off(n.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const r={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return i&&!this.sourceBufferCount&&i.mediaSource===e?I(r,i.tracks):this.sourceBuffers.forEach((t=>{const[e]=t;e&&(r[e]=I({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null})),{media:t,mediaSource:e,tracks:r}}initTracks(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(t,e){var r;let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(t,e){const r=this.media=e.media;this.transferData=this.overrides=void 0;const i=Z(this.appendSource);if(i){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const n=this.mediaSource=e.mediaSource||new i;if(this.assignMediaSource(n),t)this._objectUrl=r.src,this.attachTransferred();else{var s;const t=this._objectUrl=self.URL.createObjectURL(n),e=this.hls.config,i=e.emeEnabled&&r.mediaKeys?null==(s=e.emeController)?void 0:s.CDMCleanupPromise:null;i?i.then((()=>{this.hls&&this.setSource(r,n,t)})).catch((()=>{})):this.setSource(r,n,t)}Or(r,"emptied",this._onMediaEmptied),Or(r,"error",this._onMediaError),this.appendSource&&Or(r,"seeking",this._onStartStreaming)}}setSource(t,e,r){if(this.appendSource)try{t.removeAttribute("src");const i=self.ManagedMediaSource;t.disableRemotePlayback=t.disableRemotePlayback||i&&e instanceof i,Vr(t),function(t,e){const r=self.document.createElement("source");r.type="video/mp4",r.src=e,t.appendChild(r)}(t,r),t.load()}catch(e){t.src=r}else t.src=r}assignMediaSource(t){var e,r;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(r=t.constructor)?void 0:r.name}`),Or(t,"sourceopen",this._onMediaSourceOpen),Or(t,"sourceended",this._onMediaSourceEnded),Or(t,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Or(t,"startstreaming",this._onStartStreaming),Or(t,"endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const r=this.tracks,i=e.tracks,s=i?Object.keys(i):null,a=s?s.length:0,o=()=>{Promise.resolve().then((()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()}))};if(i&&s&&a){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${Re(r,((t,e)=>"initSegment"===t?void 0:e))};\ntransfer tracks: ${Re(i,((t,e)=>"initSegment"===t?void 0:e))}}`),!function(t,e){const r=Object.keys(t),i=Object.keys(e),s=r.length,n=i.length;return!s||!n||s===n&&!r.some((t=>-1===i.indexOf(t)))}(i,r)){e.mediaSource=null,e.tracks=void 0;const s=t.currentTime,a=this.details,o=Math.max(s,(null==a?void 0:a.fragments[0].start)||0);return o-s>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${s} -> ${o}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(r)}") start time: ${o} currentTime: ${s}`),this.onMediaDetaching(n.MEDIA_DETACHING,{}),this.onMediaAttaching(n.MEDIA_ATTACHING,e),void(t.currentTime=o))}this.transferData=void 0,s.forEach((t=>{const e=t,r=i[e];if(r){const t=r.buffer;if(t){const i=this.fragmentTracker,s=r.id;if(i.hasFragments(s)||i.hasParts(s)){const r=wr.getBuffered(t);i.detectEvictedFragments(e,r,s,null,null,!0)}const n=Hr(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,r)}}})),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const r=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:s,_objectUrl:n}=this;if(s){if(this.log("media source "+(r?"transferring":"detaching")),r)this.sourceBuffers.forEach((([t])=>{t&&this.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===s.readyState;try{const e=s.sourceBuffers;for(let r=e.length;r--;)t&&e[r].abort(),s.removeSourceBuffer(e[r]);t&&s.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}Mr(s,"sourceopen",this._onMediaSourceOpen),Mr(s,"sourceended",this._onMediaSourceEnded),Mr(s,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Mr(s,"startstreaming",this._onStartStreaming),Mr(s,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(Mr(i,"emptied",this._onMediaEmptied),Mr(i,"error",this._onMediaError),Mr(i,"seeking",this._onStartStreaming),r||(n&&self.URL.revokeObjectURL(n),this.mediaSrc!==n||this.isMediaSourceReplaced(n)?this.warn("media|source.src was changed by a third party - skip cleanup"):(i.removeAttribute("src"),this.appendSource&&Vr(i),i.load())),this.media=null)}onBufferReset(){this.sourceBuffers.forEach((([t])=>{t&&this.resetBuffer(t)})),this.initTracks()}resetBuffer(t){var e;const r=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[Hr(t)]=[null,null];const e=this.tracks[t];e&&(this.clearBufferAppendTimeoutId(e),e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Pr(this.tracks)}onBufferCodecs(t,e){var r;const i=this.tracks,s=Object.keys(e);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(i.audio||i.video)||i.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&s.some((t=>!i[t]));n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${s}" SourceBuffers`):(s.forEach((t=>{var r,s;const n=e[t],{id:a,codec:o,levelCodec:l,container:d,metadata:h,supplemental:u}=n;let c=i[t];const f=null==(r=this.transferData)||null==(r=r.tracks)?void 0:r[t],g=null!=f&&f.buffer?f:c,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;c||(c=i[t]={buffer:void 0,listeners:[],codec:o,supplemental:u,container:d,levelCodec:l,metadata:h,id:a});const v=ce(m,p),E=null==v?void 0:v.replace(Nr,"$1");let y=ce(o,l);const T=null==(s=y)?void 0:s.replace(Nr,"$1");y&&v&&E!==T&&("audio"===t.slice(0,5)&&(y=ue(y,this.appendSource)),this.log(`switching codec ${m} to ${y}`),y!==(c.pendingCodec||c.codec)&&(c.pendingCodec=y),c.container=d,this.appendChangeType(t,d,y))})),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(r=e.audio)?void 0:r.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((t,e)=>{const r=this.tracks[e];return t[e]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t}),{})}appendChangeType(t,e,r){const i=`${e};codecs=${r}`,s={label:`change-type=${i}`,execute:()=>{const s=this.tracks[t];if(s){const n=s.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${i}`),n.changeType(i),s.codec=r,s.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(s,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const r=t.start,i=r+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(r,v.MAIN))?void 0:e.gap))return;const s={label:"block-audio",execute:()=>{var t,e;(this.lastVideoAppendEnd>i||wr.isBuffered(null==(t=this.tracks.video)?void 0:t.buffer,i)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,v.MAIN))?void 0:e.gap))&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.append(s,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,r){const{tracks:a}=this,{data:o,type:l,parent:d,frag:h,part:u,chunkMeta:c,offset:f}=r,g=c.buffering[l],m=T(h)&&!u&&!h.gap&&!c.partial&&!c.iframe;let p=null,v=!1;const{sn:E,cc:y}=h,S=self.performance.now();g.start=S;const L=h.stats.buffering,A=u?u.stats.buffering:null;0===L.start&&(L.start=S),0===(null==A?void 0:A.start)&&(A.start=S);const R=a.audio;let b=!1;"audio"===l&&"audio/mpeg"===(null==R?void 0:R.container)&&(b=!this.lastMpegAudioChunk||1===c.id||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const D=a.video,I=null==D?void 0:D.buffer;if(I&&"initSegment"!==E&&void 0!==f){const t=null==R?void 0:R.buffer,e=u||h;if("audio"===l&&"main"!==d&&!D.ending&&!D.ended&&t&&wr.getBuffered(t).length){const t=e.start+.05*e.duration,r=wr.getBuffered(I),i=this.currentOp("video");r.length||i?!wr.isBuffered(I,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}else if("video"===l){const t=e.end,r=this.lastVideoAppendEnd-t;this.lastVideoAppendEnd=t,r<0||r>e.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const k=(u||h).start,_={label:`append-${l}`,execute:()=>{var e;g.executeStart=self.performance.now();const r=null==(e=this.tracks[l])?void 0:e.buffer;r&&(m&&(p=wr.timeRangesToArray(wr.getBuffered(r)),v=jr(Wr(p,h),h)),b?this.updateTimestampOffset(r,k,.1,l,E,y):void 0!==f&&t(f)&&this.updateTimestampOffset(r,f,1e-6,l,E,y)),this.appendExecutor(o,l)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[l]);const t=self.performance.now();g.executeEnd=g.end=t,0===L.first&&(L.first=t),0===(null==A?void 0:A.first)&&(A.first=t);const e={};if(this.sourceBuffers.forEach((([t,r])=>{t&&(e[t]=wr.getBuffered(r))})),m){const t=this.getFragmentAppendProgress(h),r=e[l];if(r&&p){const e=Wr(wr.timeRangesToArray(r),h);t.progressed||(t.progressed=e-Wr(p,h)>.001);const i=v&&jr(e,h);t.fullyBuffered[l]=(void 0===t.fullyBuffered[l]||t.fullyBuffered[l])&&i}}this.hls.trigger(n.BUFFER_APPENDED,{type:l,frag:h,part:u,chunkMeta:c,parent:d,timeRanges:e})},onError:t=>{var e;this.clearBufferAppendTimeoutId(this.tracks[l]);const r=t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t;if(r&&!this._quotaEvictionPending[l]){const t=this.getBackBufferEvictionTarget(l,o.byteLength,h.type);if(t>0){this._quotaEvictionPending[l]=!0,this.log(`QuotaExceededError on "${l}" append sn: ${E} - evicting back buffer to ${t.toFixed(3)}s and retrying`);const e=this.getFlushOp(l,0,t),r=this.getClearEvictionPendingOp(l);return void this.insertNext([e,_,r],l)}this.warn(`QuotaExceededError on "${l}" sn: ${E} - no back buffer available to evict`)}m&&(this.getFragmentAppendProgress(h).errored=!0);const a={type:i.MEDIA_ERROR,parent:d,details:s.BUFFER_APPEND_ERROR,sourceBufferName:l,frag:h,part:u,chunkMeta:c,error:t,err:t,fatal:!1},f=null==(e=this.media)?void 0:e.error;if(t.name!==$r||0!==this.sourceBufferCount||this.media&&0!==this.pendingTrackCount){var g;r&&(a.details=s.BUFFER_FULL_ERROR);const e=++this.appendErrors[l],i=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${e}/${i+1} times to append segment in "${l}" sourceBuffer with error: ${t.message}`),e>=i&&(a.fatal=!r);const n=null==(g=this.mediaSource)?void 0:g.readyState;"ended"!==n&&"closed"!==n&&!f||this.isMediaSourceReplaced()||(this.warn(`MediaSource readyState "${n}" during SourceBuffer${Kr(a.fatal,f)}`),a.details=s.MEDIA_SOURCE_REQUIRES_RESET)}else a.errorAction=$e(!0);this.appendError=a,this.hls.trigger(n.ERROR,a),r&&this.hls&&this.trimBuffers(h.start,1)}};this.log(`queuing "${l}" append sn: ${E}${u?" p: "+u.index:""} of ${d} playlist ${h.level} cc: ${y} offset: ${f} bytes: ${o.byteLength}`),this.append(_,l,this.isPending(this.tracks[l]))}getClearEvictionPendingOp(t){return{label:"clear",execute:()=>{this._quotaEvictionPending[t]=!1,this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(t,e,r){return this.log(`queuing "${t}" remove ${e}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,r)},onStart:()=>{},onComplete:()=>{var i;const s=null==(i=this.tracks[t])?void 0:i.buffer;this.log(`Remove request ${e}-${r} from ${t} Source Buffer complete > buffer: ${s?Fr(wr.getBuffered(s)):"(detached)"}`),this.hls.trigger(n.BUFFER_FLUSHED,{type:t,start:e,end:r})},onError:i=>{this.warn(`Failed to remove ${e}-${r} from "${t}" SourceBuffer`,i),this.hls.trigger(n.BUFFER_FLUSHED,{type:t,start:0,end:0,error:i})}}}onBufferFlushing(t,e){const{type:r,startOffset:i,endOffset:s}=e;r&&"audio"!==r||this.unblockAudio(),r?this.append(this.getFlushOp(r,i,s),r):this.sourceBuffers.forEach((([t])=>{t&&this.append(this.getFlushOp(t,i,s),t)}))}onFragParsed(t,e){const{frag:r,part:i,chunkMeta:s}=e,a=[],o=i?i.elementaryStreams:r.elementaryStreams;o[E.AUDIOVIDEO]?a.push("audiovideo"):(o[E.AUDIO]&&a.push("audio"),o[E.VIDEO]&&a.push("video"));0===a.length&&this.log(`Fragments must have at least one ElementaryStreamType set. ${r.type} ${r.level} ${i?`part: ${i.index} of `:""}sn: ${r.sn}`),this.blockBuffers((()=>{const t=self.performance.now();r.stats.buffering.end=t,i&&(i.stats.buffering.end=t);const e=i?i.stats:r.stats;this.checkAppendProgress(r,i,s,a),this.hls&&(this.hls.trigger(n.FRAG_BUFFERED,{frag:r,part:i,stats:e,id:r.type,chunkMeta:s}),!i&&r.gap&&e.retry&&this.log(`Nothing buffered for ${r.type} level: ${r.level} sn: ${r.sn} retries ${e.retry}`))}),a).catch((t=>{this.warn(`Fragment buffered callback ${t.message}`),this.stepOperationQueue(this.sourceBufferTypes)}))}onFragChanged(t,e){var r,i;const s=null==(r=this.hls)?void 0:r.config;if(!s)return;const{backBufferLength:n,frontBufferFlushThreshold:a}=s;this.trimBuffers(a,n,e.frag,e.previousFrag);const o=e.frag.elementaryStreams,{appendErrors:l}=this,d=null==(i=this.appendError)?void 0:i.sourceBufferName;Object.keys(o).forEach((t=>{o[t]&&(l[t]=0,t===d&&(this.appendError=void 0),"audio"===t||"video"===t?(l.audiovideo=0,"audiovideo"===d&&(this.appendError=void 0)):(l.audio=0,l.video=0,"audiovideo"!==d&&(this.appendError=void 0)))}))}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some((([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1}))}onBufferEos(t,e){var r;this.sourceBuffers.forEach((([t])=>{if(t){const r=this.tracks[t];e.type&&e.type!==t||(r.ending=!0,r.ended||(r.ended=!0,this.log(`${t} buffer reached EOS`)))}}));const i=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.allTracksEnding?(this.unblockAudio(),i?(this.log("Queueing EOS"),this.blockUntilOpen((()=>{if(this.tracksEnded(),!this.allTracksEnding)return void this.log("EOS cancelled");const{mediaSource:t}=this;"open"===(null==t?void 0:t.readyState)?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(n.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)}))):(this.tracksEnded(),this.hls.trigger(n.BUFFERED_TO_END,void 0))):"video"===e.type&&this.unblockAudio()}get allTracksEnding(){return this.sourceBufferCount>0&&!this.sourceBuffers.some((([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)}))}tracksEnded(){this.sourceBuffers.forEach((([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}}))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen((()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)}))}onError(e,r){if(r.details===s.BUFFER_APPEND_ERROR&&r.frag){var i;const e=null==(i=r.errorAction)?void 0:i.nextAutoLevel;t(e)&&e!==r.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(t,e,r){const{media:i}=this;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,r,e):0}getFragmentAppendProgress(t){var e;const r=Yr(t);let i=this.fragmentAppendProgress[r];return(null==(e=i)?void 0:e.stats)!==t.stats&&(i={stats:t.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[r]=i),i}checkAppendProgress(t,e,r,a){if(e||!T(t)||t.gap||r.iframe||r.partial)return;const o=Yr(t),l=this.fragmentAppendProgress[o];delete this.fragmentAppendProgress[o];const d=t.stats.buffering;if(d.start&&!d.first)return;const h=(null==l?void 0:l.stats)===t.stats?l:void 0;if(null!=h&&h.errored)return;const u=a.length>0&&a.every((t=>!0===(null==h?void 0:h.fullyBuffered[t])));if(null!=h&&h.progressed||u)return void delete this.appendsWithoutProgress[o];if(!h&&0===a.length)return;const c=(this.appendsWithoutProgress[o]||0)+1,f=this.hls;c>=f.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[o]:this.appendsWithoutProgress[o]=c,this.warn(`Fragment ${t.sn} of ${t.type} playlist ${t.level} appended ${c} time${c>1?"s":""} without buffered range growth`),f.trigger(n.ERROR,{type:i.MEDIA_ERROR,details:s.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:t,chunkMeta:r,parent:t.type,appendsWithoutProgress:c,error:new Error(`Fragment append did not increase buffered coverage (${c})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(e,r,i,s){const{hls:n,details:a,media:o}=this;if(!o||null===a)return;if(!this.sourceBufferCount)return;const l=n.config,d=o.currentTime,h=a.levelTargetDuration;r=a.live&&null!==l.liveBackBufferLength?l.liveBackBufferLength:r;let u=-1/0;if(t(r)&&r>=0){const t=Math.max(r,h);u=Math.floor(d/h)*h-t}if(i){const t=this.getLoopBackBufferFlushEnd(i,null!=s?s:null);t>0&&(u=Math.max(u,t))}if(u>0&&this.flushBackBuffer(d,h,u),t(e)&&e>0){const t=Math.max(l.maxBufferLength,e),r=Math.max(t,h),i=Math.floor(d/h)*h+r;this.flushFrontBuffer(d,h,i)}}getLoopBackBufferFlushEnd(t,e){var r;const{media:i}=this;if(!1===(null==(r=this.hls)?void 0:r.config.loopBackBufferFlush)||null==i||!i.loop||!e||t.level<=e.level)return 0;const{video:s,audiovideo:n}=t.elementaryStreams;if(null!=s&&s.partial||null!=n&&n.partial)return 0;const a=this.getEarliestElementaryStreamStart(t)-.25;return a<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${t.level}, range [0-${a.toFixed(3)}]`),a)}getEarliestElementaryStreamStart(t){const{audio:e,video:r,audiovideo:i}=t.elementaryStreams;let s=t.start;return i?s=Math.min(s,i.startDTS):(e&&(s=Math.min(s,e.startDTS)),r&&(s=Math.min(s,r.startDTS))),s}flushBackBuffer(t,e,r){this.sourceBuffers.forEach((([t,e])=>{if(e){const o=wr.getBuffered(e);if(o.length>0&&r>o.start(0)){var i,s,a;this.hls.trigger(n.BACK_BUFFER_REACHED,{bufferEnd:r});const e=this.tracks[t];if(null!=(i=this.details)&&i.live)this.hls.trigger(n.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=e&&e.ended&&(null==(s=this.media)||!s.loop||!1===(null==(a=this.hls)?void 0:a.config.loopBackBufferFlush)))return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(n.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:t})}}}))}flushFrontBuffer(t,e,r){this.sourceBuffers.forEach((([e,i])=>{if(i){const s=wr.getBuffered(i),a=s.length;if(a<2)return;const o=s.start(a-1),l=s.end(a-1);if(r>o||t>=o&&t<=l)return;this.hls.trigger(n.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:e})}}))}getDurationAndRange(){var e;const{details:r,mediaSource:i}=this;if(!r||!this.media||"open"!==(null==i?void 0:i.readyState))return null;const s=r.edge;if(r.live&&this.hls.config.liveDurationInfinity){if(r.fragments.length&&i.setLiveSeekableRange){const t=Math.max(0,r.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,s)}}return{duration:1/0}}const n=null==(e=this.overrides)?void 0:e.duration;if(n)return t(n)?{duration:n}:null;const a=this.media.duration;return s>(t(i.duration)?i.duration:0)&&s>a||!t(a)?{duration:s}:null}updateMediaSource({duration:e,start:r,end:i}){const s=this.mediaSource;s&&this.media&&"open"===s.readyState&&(s.duration!==e&&(t(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),s.duration=e),void 0!==r&&void 0!==i&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${r}-${i}.`),s.setLiveSeekableRange(r,i)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${Re(r)}`),this.tracksReady){var i;const t=null==(i=this.transferData)?void 0:i.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach((([e,r])=>{if(e){const i=this.tracks[e];t[e]={buffer:r,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}})),this.hls.trigger(n.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach((([t])=>{this.executeNext(t)}))}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(n.ERROR,{type:i.MEDIA_ERROR,details:s.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:r}=this;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(const o in t){const l=o,d=t[l];if(this.isPending(d)){const t=this.getTrackCodec(d,l),o=`${d.container};codecs=${t}`;d.codec=t,this.log(`creating sourceBuffer(${o})${this.currentOp(l)?" Queued":""} ${Re(d)}`);try{const t=r.addSourceBuffer(o),i=Hr(l),s=[l,t];e[i]=s,d.buffer=t}catch(t){var a;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(l),null==(a=this.operationQueue)||a.removeBlockers(),delete this.tracks[l],void this.hls.trigger(n.ERROR,{type:i.MEDIA_ERROR,details:s.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:l,mimeType:o,parent:d.id})}this.trackSourceBuffer(l,d)}}this.bufferCreated()}clearBufferAppendTimeoutId(t){t&&(self.clearTimeout(t.bufferAppendTimeoutId),t.bufferAppendTimeoutId=void 0)}getTrackCodec(t,e){const r=t.supplemental;let i=t.codec;r&&("video"===e||"audiovideo"===e)&&se(r,"video")&&(i=function(t,e){const r=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)ie(e[t],"video")||r.push(e[t])}return e&&r.push(e),r.join(",")}(i,r));const s=ce(i,t.levelCodec);return s?"audio"===e.slice(0,5)?ue(s,this.appendSource):s:""}trackSourceBuffer(t,e){const r=e.buffer;if(!r)return;const i=this.getTrackCodec(e,t);this.tracks[t]={buffer:r,codec:i,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",((t,e)=>{const r=e.removedRanges;null!=r&&r.length&&(this.log(`${t} buffer removed ${Fr(r)}`),this.hls.trigger(n.BUFFER_FLUSHED,{type:t,start:r.start(0),end:r.end(r.length-1)}))}))}get mediaSrc(){var t;const e=this.media;if(!e)return;return(e.src?e:(null==(t=e.querySelector)?void 0:t.call(e,"source"))||e).src}isMediaSourceReplaced(t=this._objectUrl){var e;if(!t)return!1;const r=null==(e=this.media)?void 0:e.currentSrc,i=this.mediaSrc;return!!r&&r!==t||!!i&&i!==t}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e,r;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const i=this.currentOp(t);if(!i)return;i.onComplete();if(null==(r=this.tracks[t])||null==(r=r.buffer)?void 0:r.updating)return this.log(`${t} SourceBuffer updating on "updateend"`),void this.blockUntilOpen((()=>{this.shiftAndExecuteNext(t)}));this.shiftAndExecuteNext(t)}onSBUpdateError(t,e){var r;const a=null==(r=this.mediaSource)?void 0:r.readyState,o=new Error(`${t} SourceBuffer error. MediaSource readyState: ${a}`);o.name=Br,this.error(`${o.message}`,e),this.hls.trigger(n.ERROR,{type:i.MEDIA_ERROR,details:s.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:o,fatal:!1});const l=this.currentOp(t);l&&l.onError(o)}updateTimestampOffset(t,e,r,i,s,n){const a=e-t.timestampOffset;Math.abs(a)>=r&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${e} (sn: ${s} cc: ${n})`),t.timestampOffset=e)}removeExecutor(e,r,i){const{media:s,mediaSource:n}=this,a=this.tracks[e],o=null==a?void 0:a.buffer;if(!s||!n||!o)throw new Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);const l=t(s.duration)?s.duration:1/0,d=t(n.duration)?n.duration:1/0,h=Math.max(0,r);var u;if(h>=d)return null==(u=this.currentOp(e))||u.onComplete(),void this.shiftAndExecuteNext(e);const c=Math.min(i,l,d);if(!(c>h)||a.ending&&!a.ended)throw new Error(`Cannot remove ${c<=h?`invalid range (${h} >= ${c}) `:""}from the ${e} SourceBuffer${a.ending?" while track ending":""}`);a.ended=!1,this.log(`Removing [${h},${c}] from the ${e} SourceBuffer`),o.remove(h,c)}appendExecutor(t,e){const r=this.tracks[e],i=null==r?void 0:r.buffer;if(!i)throw new Ur(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);if(r.ending=!1,r.ended=!1,this.hls.config.appendTimeout!==1/0){const t=this.calculateAppendTimeoutTime(i);r.bufferAppendTimeoutId=self.setTimeout((()=>this.appendTimeoutHandler(e,i,t)),t)}i.appendBuffer(t)}appendTimeoutHandler(t,e,r){this.log(`Received timeout after ${r}ms for append on ${t} source buffer. Aborting and triggering error.`);try{e.abort()}catch(e){this.log(`Failed to abort append on ${t} source buffer after timeout.`)}const i=this.currentOp(t);i&&i.onError(new Error(`${t}-append-timeout`))}calculateAppendTimeoutTime(t){let e=10;this.details&&(e=this.details.levelTargetDuration);let r=2*e*1e3;if(null===this.media)return r;const i=wr.bufferInfo(t,this.media.currentTime,0);return i.len?(r=Math.max(1e3*i.len,r),Math.max(this.hls.config.appendTimeout,r)):r}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch((t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)}));else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some((([t,e])=>t&&e.updating))}isQueued(){return this.sourceBuffers.some((([t])=>t&&!!this.currentOp(t)))}isPending(t){return!!t&&!t.buffer}isAudioBlocked(){var t;return"block-audio"===(null==(t=this.currentOp("audio"))?void 0:t.label)}isAudioBlocking(){return!!this.operationQueue&&this.operationQueue.audioBlocking()}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:r}=this,i=2===e.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:e.map((t=>this.appendBlocker(t)));return Promise.all(i).then((e=>{r===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))}))}stepOperationQueue(t){t.forEach((t=>{var e;const r=null==(e=this.tracks[t])?void 0:e.buffer;!r||r.updating||"audio"===t&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)}))}append(t,e,r){this.operationQueue&&this.operationQueue.append(t,e,r)}insertNext(t,e){this.operationQueue&&this.operationQueue.insertNext(t,e)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce(((t,e)=>t+(this.isPending(this.tracks[e])?1:0)),0)}get sourceBufferCount(){return this.sourceBuffers.reduce(((t,[e])=>t+(e?1:0)),0)}get sourceBufferTypes(){return this.sourceBuffers.map((([t])=>t)).filter((t=>!!t))}addBufferListener(t,e,r){const i=this.tracks[t];if(!i)return;const s=i.buffer;if(!s)return;const n=r.bind(this,t);i.listeners.push({event:e,listener:n}),Or(s,e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const r=e.buffer;r&&(e.listeners.forEach((t=>{Mr(r,t.event,t.listener)})),e.listeners.length=0)}}function Vr(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach((e=>{t.removeChild(e)}))}function Hr(t){return"audio"===t?1:0}function Kr(t,e){return`${t?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function Yr(t){return`${t.type}_${t.sn}_${t.level}`}function Wr(t,e){const{start:r,end:i}=e;let s=0;for(let e=0;e<t.length;e++){const n=t[e];if(n.start>=i)break;const a=Math.max(r,n.start),o=Math.min(i,n.end);o>a&&(s+=o-a)}return s}function jr(t,e){return e.duration-t<=.05}var qr="NOT_LOADED",zr="APPENDING",Xr="PARTIAL",Qr="OK";class Zr{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t&&(t.on(n.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.BUFFER_APPENDED,this.onBufferAppended,this),t.on(n.FRAG_BUFFERED,this.onFragBuffered,this),t.on(n.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(n.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.BUFFER_APPENDED,this.onBufferAppended,this),t.off(n.FRAG_BUFFERED,this.onFragBuffered,this),t.off(n.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const r=this.activePartLists[e];if(r)for(let e=r.length;e--;){const i=r[e];if(!i)break;if(i.start<=t&&t<=i.end&&i.loaded)return i}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,r){const{fragments:i}=this,s=Object.keys(i);for(let n=s.length;n--;){const a=i[s[n]];if((null==a?void 0:a.body.type)===e&&(!r||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,r,i,s,a){this.timeRanges&&(this.timeRanges[t]=e);const o=(null==s?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach((s=>{const l=this.fragments[s];if(!l||!this.hls)return;const d=l.body;if(o>=d.sn)return;if(!l.buffered&&(!l.loaded||a))return void(d.type===r&&this.removeFragment(d));const h=l.range[t];if(h)if(0!==h.time.length){if(h.time.some((t=>{const r=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return r&&this.removeFragment(d),r})),i&&i!==d&&ee()){const t=i.endPTS,e=d.startPTS;if(t&&e&&l.range.video){const r=e-t;r<0&&r>-.1&&(this.removeFragment(d),this.hls.trigger(n.BUFFER_FLUSHING,{startOffset:t+.004,endOffset:1/0,type:"video"}))}}}else this.removeFragment(d)}))}detectPartialFragments(t){const e=this.timeRanges,{frag:r,part:i,id:s}=t;if(!e||!T(r))return;const n=ti(r),a=this.fragments[n];if(!a||a.buffered&&r.gap)return;const o=!r.relurl;Object.keys(e).forEach((t=>{const n=r.elementaryStreams[t];if(!n)return;const l=e[t],d=o||!0===n.partial;a.range[t]=this.getBufferedTimes(r,i,d,l),this.detectEvictedFragments(t,l,s,r,i)})),a.loaded=null;const l=Object.keys(a.range);if(l.length){if(this.bufferedEnd(a,r),Jr(a)||this.removeParts(r.sn-1,r.type),!i){const t=Math.min(.004,r.duration);l.some((e=>{var i;const s=null==(i=a.range[e])?void 0:i.time,n=0===s.length||1===s.length&&s[0].endPTS-s[0].startPTS<t;return n&&this.addAsGap(r),n}))}}else this.removeFragment(r)}addAsGap(t){t.gap=!0,this.removeFragment(t),this.fragBuffered(t,!0)}bufferedEnd(t,e){t.buffered=!0;(t.body.endList=e.endList||t.body.endList)&&!e.gap&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const r=this.activePartLists[e];r&&(this.activePartLists[e]=ei(r,(e=>e.fragment.sn>=t)))}fragBuffered(t,e){const r=ti(t);let i=this.fragments[r];return!i&&e&&(i=this.fragments[r]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,t)),i}getBufferedTimes(t,e,r,i){const s={time:[],partial:r},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<i.length;t++){const e=i.start(t)-this.bufferPadding,r=i.end(t)+this.bufferPadding;if(l>=e&&o<=r){s.time.push({startPTS:Math.max(n,i.start(t)),endPTS:Math.min(a,i.end(t))});break}if(n<r&&a>e){const e=Math.max(n,i.start(t)),r=Math.min(a,i.end(t));r>e&&(s.partial=!0,s.time.push({startPTS:e,endPTS:r}))}else if(a<=e)break}return s}getPartialFragment(t){let e,r,i,s=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const d=o[l];d&&Jr(d)&&(r=d.body.start-a,i=d.body.end+a,t>=r&&t<=i&&(e=Math.min(t-r,i-t),n<=e&&(s=d.body,n=e)))})),s}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Jr(e))}getState(t){const e=ti(t),r=this.fragments[e];return r?r.buffered?Jr(r)?Xr:Qr:zr:qr}isTimeBuffered(t,e,r){let i,s;for(let n=0;n<r.length;n++){if(i=r.start(n)-this.bufferPadding,s=r.end(n)+this.bufferPadding,t>=i&&e<=s)return!0;if(e<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if(!T(e.frag)||e.frag.bitrateTest)return;const r=e.frag,i=e.part?null:e,s=ti(r);this.fragments[s]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:r,part:i,timeRanges:s}=e;if(!T(r))return;const n=r.type;if(i){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(i)}this.timeRanges=s}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=ti(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,r=Object.keys(e);if(!t)return r.length>0;for(let i=r.length;i--;){const s=e[r[i]];if((null==s?void 0:s.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}getBackBufferEvictionEnd(t,e,r){const{fragments:i}=this;let s=0,n=0;const a=Object.keys(i);for(let o=0;o<a.length;o++){const l=i[a[o]];if(!l||!l.buffered||l.body.type!==e)continue;const d=l.body;if(d.gap)return 0;const h=d.hasStats&&d.stats.loaded||d.byteLength||d.bitrate&&8*d.bitrate*d.duration;if(d.end<=t&&h&&(s+=h,n=Math.max(n,d.end),s>=r))return n}return n>0?n:0}removeFragmentsInRange(t,e,r,i,s){i&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==r||i&&!o.gap||o.start<e&&o.end>t&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(t){const e=ti(t);t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const e=t.sn;this.activePartLists[t.type]=ei(r,(t=>t.fragment.sn!==e))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}gapFragments(){return this.hasGaps?Object.keys(this.fragments).map((t=>{var e;return null==(e=this.fragments[t])?void 0:e.body})).filter((t=>!(null==t||!t.gap))):[]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach((t=>t.clearElementaryStreamInfo()))}}function Jr(t){var e,r,i,s;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(r=t.range.audio)&&r.partial||null!=(i=t.range.audiovideo)&&i.partial||null!=(s=t.range.subs)&&s.partial)}function ti(t){return`${t.type}_${t.level}_${t.sn}`}function ei(t,e){return t.filter((t=>{const r=e(t);return r||t.clearElementaryStreamInfo(),r}))}class ri{constructor(t,e,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=r}decrypt(t,e){switch(this.aesMode){case je:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case qe:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class ii{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const e=new DataView(t),r=new Uint32Array(4);for(let t=0;t<4;t++)r[t]=e.getUint32(4*t);return r}initTable(){const t=this.sBox,e=this.invSBox,r=this.subMix,i=r[0],s=r[1],n=r[2],a=r[3],o=this.invSubMix,l=o[0],d=o[1],h=o[2],u=o[3],c=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)c[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let r=g^g<<1^g<<2^g<<3^g<<4;r=r>>>8^255&r^99,t[f]=r,e[r]=f;const o=c[f],m=c[o],p=c[m];let v=257*c[r]^16843008*r;i[f]=v<<24|v>>>8,s[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[r]=v<<24|v>>>8,d[r]=v<<16|v>>>16,h[r]=v<<8|v>>>24,u[r]=v,f?(f=o^c[c[c[p^o]]],g^=c[c[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let r=!0,i=0;for(;i<e.length&&r;)r=e[i]===this.key[i],i++;if(r)return;this.key=e;const s=this.keySize=e.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);const n=this.ksRows=4*(s+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),h=this.sBox,u=this.rcon,c=this.invSubMix,f=c[0],g=c[1],m=c[2],p=c[3];let v,E;for(a=0;a<n;a++)a<s?v=l[a]=e[a]:(E=v,a%s==0?(E=E<<8|E>>>24,E=h[E>>>24]<<24|h[E>>>16&255]<<16|h[E>>>8&255]<<8|h[255&E],E^=u[a/s|0]<<24):s>6&&a%s==4&&(E=h[E>>>24]<<24|h[E>>>16&255]<<16|h[E>>>8&255]<<8|h[255&E]),l[a]=v=(l[a-s]^E)>>>0);for(o=0;o<n;o++)a=n-o,E=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?E:f[h[E>>>24]]^g[h[E>>>16&255]]^m[h[E>>>8&255]]^p[h[255&E]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,r){const i=this.keySize+6,s=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],h=a[3],u=this.uint8ArrayToUint32Array_(r);let c=u[0],f=u[1],g=u[2],m=u[3];const p=new Int32Array(t),v=new Int32Array(p.length);let E,y,T,S,L,A,R,b,D,I,k,_,C,P;const x=this.networkToHostOrderSwap;for(;e<p.length;){for(D=x(p[e]),I=x(p[e+1]),k=x(p[e+2]),_=x(p[e+3]),L=D^s[0],A=_^s[1],R=k^s[2],b=I^s[3],C=4,P=1;P<i;P++)E=o[L>>>24]^l[A>>16&255]^d[R>>8&255]^h[255&b]^s[C],y=o[A>>>24]^l[R>>16&255]^d[b>>8&255]^h[255&L]^s[C+1],T=o[R>>>24]^l[b>>16&255]^d[L>>8&255]^h[255&A]^s[C+2],S=o[b>>>24]^l[L>>16&255]^d[A>>8&255]^h[255&R]^s[C+3],L=E,A=y,R=T,b=S,C+=4;E=n[L>>>24]<<24^n[A>>16&255]<<16^n[R>>8&255]<<8^n[255&b]^s[C],y=n[A>>>24]<<24^n[R>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^s[C+1],T=n[R>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&A]^s[C+2],S=n[b>>>24]<<24^n[L>>16&255]<<16^n[A>>8&255]<<8^n[255&R]^s[C+3],v[e]=x(E^c),v[e+1]=x(S^f),v[e+2]=x(T^g),v[e+3]=x(y^m),c=D,f=I,g=k,m=_,e+=4}return v.buffer}}class si{constructor(t,e,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=r}expandKey(){const t=function(t){switch(t){case je:return"AES-CBC";case qe:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class ni{constructor(t,e){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,!0!==e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const r=new Uint8Array(t);this.reset();const i=this.decryptRange;return i?0===i.start&&i.end>=r.length?r:r.slice(i.start,i.end):function(t){const e=t.byteLength,r=e&&new DataView(t.buffer).getUint8(e-1);return r?t.slice(0,e-r):t}(r)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,r,i,s){return this.decryptRange=s,this.useSoftware||s?new Promise(((s,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,r,i);const o=this.flush();o?s(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),e,r,i)}softwareDecrypt(t,e,r,i){const{currentIV:s,currentResult:n,remainderData:a}=this;if(i!==je||16!==e.byteLength)return j.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=Yt(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;s&&(r=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new ii),l.expandKey(e);const d=n;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(t,e,r,i){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,r,i));this.key=e,this.fastAesKey=new si(this.subtle,e,i)}return this.fastAesKey.expandKey().then((e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new ri(this.subtle,new Uint8Array(r),i).decrypt(t.buffer,e)})).catch((s=>(j.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(t,e,r,i))))}onWebCryptoError(t,e,r,i){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,r,i);const s=this.flush();if(s)return s.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const r=t.length-t.length%16;return r!==t.length&&(e=t.slice(0,r),this.remainderData=t.slice(r)),e}logOnce(t){this.logEnabled&&(j.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const ai=Math.pow(2,17);class oi{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e,r,n){const a=t.url;if(!a)return Promise.reject(new ui({type:i.NETWORK_ERROR,details:s.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(a?"part list":"url")),networkDetails:null}));this.abort();const o=this.config,l=o.fLoader,d=o.loader;return new Promise(((h,u)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some((t=>"GAP"===t[0])))return void u(hi(t));t.gap=!1}const c=this.loader=l?new l(o):new d(o),f=li(t,null,e);t.loader=c;const g=M(o.fragLoadPolicy.default),m={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:ai};c.stats.retry=t.stats.retry,t.stats=c.stats;const p={onSuccess:(e,r,i,s)=>{this.resetLoader(t,c);let n=e.data;i.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),h({frag:t,part:null,payload:n,networkDetails:s})},onError:(e,r,n,o)=>{this.resetLoader(t,c),u(new ui({type:i.NETWORK_ERROR,details:s.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:_({url:a,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:n,stats:o}))},onAbort:(e,r,n)=>{this.resetLoader(t,c),u(new ui({type:i.NETWORK_ERROR,details:s.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:n,stats:e}))},onTimeout:(e,r,n)=>{this.resetLoader(t,c),u(new ui({type:i.NETWORK_ERROR,details:s.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:n,stats:e}))}};if(r){const e=this.gateProgress(r,n);p.onProgress=(r,i,s,n)=>e({frag:t,part:null,payload:s,networkDetails:n})}c.load(f,m,p)}))}gateProgress(t,e){let r=t;if(e){const i=[];let s=!1;e.then((()=>{s=!0,i.forEach((e=>t(e))),i.length=0})).catch((()=>{})),r=e=>{s?t(e):i.push(e)}}return r}loadPart(t,e,r){this.abort();const n=this.config,a=n.fLoader,o=n.loader;return new Promise(((l,d)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void d(hi(t,e));const h=this.loader=a?new a(n):new o(n),u=li(t,e);t.loader=h;const c=M(n.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:ai};e.stats=h.stats,h.load(u,f,{onSuccess:(i,s,n,a)=>{this.resetLoader(t,h),this.updateStatsFromPart(t,e);const o={frag:t,part:e,payload:i.data,networkDetails:a};r(o),l(o)},onError:(r,n,a,o)=>{this.resetLoader(t,h),d(new ui({type:i.NETWORK_ERROR,details:s.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:_({url:u.url,data:void 0},r),error:new Error(`HTTP Error ${r.code} ${r.text}`),networkDetails:a,stats:o}))},onAbort:(r,n,a)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,h),d(new ui({type:i.NETWORK_ERROR,details:s.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:a,stats:r}))},onTimeout:(r,n,a)=>{this.resetLoader(t,h),d(new ui({type:i.NETWORK_ERROR,details:s.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:a,stats:r}))}})}))}updateStatsFromPart(t,e){const r=t.stats,i=e.stats,s=i.total;if(r.loaded+=i.loaded,s){const i=Math.round(t.duration/e.duration),n=Math.min(Math.round(r.loaded/s),i),a=(i-n)*Math.round(r.loaded/n);r.total=r.loaded+a}else r.total=Math.max(r.loaded,r.total);const n=r.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,t.url=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function li(t,e=null,r){const i=e||t,s={type:p.MEDIA_FRAGMENT,frag:t,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},n=di(t,e,r);return n.resetIV&&(s.resetIV=!0),n.byteRange&&(s.rangeStart=n.byteRange.start,s.rangeEnd=n.byteRange.end),s}function di(e,r=null,i){const s={},n=r||e,a=n.byteRangeStartOffset,o=n.byteRangeEndOffset;var l,d;if(t(a)&&t(o))if("initSegment"!==e.sn&&!i||"AES-128"!==(d=null==(l=e.decryptdata)?void 0:l.method)&&"AES-256"!==d)s.byteRange={start:a,end:o};else{let t=16*Math.floor(a/16);const e=16*Math.ceil(o/16);s.decryptRange={start:a-t,end:o-t},t>=16&&(s.resetIV=!0,t-=16),s.byteRange={start:t,end:e}}return s}function hi(t,e){const r=new Error(`GAP ${t.gap?"tag":"attribute"} found`),n={type:i.MEDIA_ERROR,details:s.FRAG_GAP,fatal:!1,frag:t,error:r,networkDetails:null};return e&&(n.part=e),(e||t).stats.aborted=!0,new ui(n)}class ui extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class ci extends G{constructor(t,e){super(t,e),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class fi{constructor(t,e,r,i=0,s=-1,n=!1,a,o,l){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=e,this.id=r,this.size=i,this.part=s,this.partial=n,this.duration=a||0,this.decryptRange=l,this.iframe=o||!1}}function gi(t,e){for(let i=0,s=t.length;i<s;i++){var r;if((null==(r=t[i])?void 0:r.cc)===e)return t[i]}return null}function mi(t,e){const r=t.start+e;t.setStart(r)}function pi(t,e){const r=e.fragments;for(let e=0,i=r.length;e<i;e++)mi(r[e],t);e.fragmentHint&&mi(e.fragmentHint,t),e.alignedSliding=!0}function vi(t,e,r){t&&(!function(t,e,r){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const i=Math.min(e.endCC,t.endCC),s=gi(e.fragments,i),n=gi(t.fragments,i);if(!s||!n)return;const a=s.start-n.start;r.log(`Aligning playlists using dicontinuity sequence ${i} (diff: ${a})`),pi(a,t)}(e,t,r),e.alignedSliding||function(t,e,r){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const i=t.fragments,s=e.fragments;if(!i.length||!s.length)return;let n,a;const o=Math.min(e.endCC,t.endCC);e.startCC<o&&t.startCC<o&&(n=gi(s,o),a=gi(i,o));n&&a||(n=s[Math.floor(s.length/2)]||s.filter((t=>!!t))[0],a=gi(i,n.cc)||i[Math.floor(i.length/2)]);const l=n.programDateTime,d=a.programDateTime;if(!l||!d)return;const h=(d-l)/1e3;if(Math.abs(h)>Math.max(60,t.totalduration))return void r.log(`Cannot align playlists using PDT without overlap (${Math.abs(h)} > ${t.totalduration})`);const u=h-(a.start-n.start);r.log(`Aligning playlists using PDT (diff: ${u})`),pi(u,t)}(e,t,r),e.alignedSliding||e.skippedSegments||Lr(t,e,!1,r))}const Ei={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_LEVEL:"WAITING_LEVEL"};class yi extends ci{constructor(t,e,r,i,s){super(i,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Ei.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:e,media:r,mediaBuffer:i,state:s}=this,n=r?r.currentTime:0,a=wr.bufferInfo(i||r,n,t.maxBufferHole),o=a.len;if(this.log(`Media seeking to ${n}, state: ${s}, ${o?"in":"out of"} buffer`),this.state===Ei.ENDED)this.resetLoadingState();else if(e){const r=t.maxFragLookUpTolerance,i=e.start-r,s=e.start+e.duration+r;if(!o||s<a.start||i>a.end){const t=n<i,r=n>s;(t||r)&&(!e.loader||!r&&this.isFragmentNearlyDownloaded(e)?this.fragPrevious=null:(this.log(`Cancelling fragment load for seek (sn: ${e.sn}) - ${t?"backward":"forward"} seek`),e.abortRequests(),this.resetLoadingState()))}}if(r){var l;null!=(l=this.hls)&&l.hasEnoughToStart&&!o&&n!==this.startPosition&&this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const t=Math.max(a.end,n),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${n} with buffer @${t}`),this.loadingParts=e)}}const d=!wr.isBuffered(r,n);this.hls.hasEnoughToStart&&!d||(this.log(`Setting ${d?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,d?this.startPosition=n:this.lastCurrentTime=n),o<1&&this.state===Ei.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.nextLoadPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=t,this.fragmentLoader=new oi(t.config),this.initFragmentLoader=new oi(t.config),this.keyLoader=r,this.fragmentTracker=e,this.config=t.config,this.decrypter=new ni(t.config)}registerListeners(){const{hls:t}=this;t.on(n.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(n.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(n.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(n.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(n.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(n.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(n.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(n.ERROR,this.onError,this)}doTick(){}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&!1===t.seeking&&(this.lastCurrentTime=t.currentTime)}startLoad(t){}stopLoad(){if(this.state===Ei.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Ei.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;if(-1===e&&t){const e=this.getLevelDetails();if(null!=e&&e.live){return(this.hls.liveSyncPosition||e.fragmentStart)+this.timelineOffset}return t}return e}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(t){}get couldBacktrack(){return!1}set couldBacktrack(t){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const r=t.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;const s=t.buffered;this.config.maxBufferHole&&s&&s.length>1&&(t=wr.bufferedInfo(s,t.start,0));const n=t.nextStart;if(n&&n>i&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return wr.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1];return this.fragmentTracker.isEndListAppended(o.type)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const r=this.media=this.mediaBuffer=e.media;Or(r,"seeking",this.onMediaSeeking),Or(r,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===Ei.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(t,e){this.fragPlaying=null;const r=!!e.transferMedia,i=this.media;if(null===i)return;if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Mr(i,"seeking",this.onMediaSeeking),Mr(i,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1;const{fragmentTracker:s}=this,n=s.gapFragments();s.removeAllFragments(),n.forEach((t=>s.addAsGap(t))),this.stopLoad()}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.nextLoadPosition=0,this.startPosition=-1,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Ei.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,r){this.startFragRequested=!0,this._loadFragForPlayback(t,e,r)}_loadFragForPlayback(t,e,r){this._doFragLoad(t,e,r,(t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)} was dropped during download.`),void this.fragmentTracker.removeFragment(e);const r=++e.stats.chunkCount;this.log(`load progress ${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)} chunk: ${r}`),this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;const e=this.state,r=t.frag;this.fragContextChanged(r)?(e===Ei.FRAG_LOADING||!this.fragCurrent&&e===Ei.PARSING)&&(this.fragmentTracker.removeFragment(r),this.state=Ei.IDLE):("payload"in t&&(this.log(`Loaded ${r.type} sn: ${r.sn} of ${this.playlistLabel()} ${r.level} (bytes ${r.stats.loaded})`),this.hls.trigger(n.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((e=>{this.state!==Ei.STOPPED&&this.state!==Ei.ERROR&&(this.log(`Frag error ${t.type} sn:${t.sn} cc:${t.cc}: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var e;const{fragmentTracker:r}=this;if(r.getState(t)===zr){const e=t.type,i=this.getFwdBufferInfo(this.mediaBuffer,e),s=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(s,t.duration))&&r.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?r.removeAllFragments():r.hasParts(t.type)&&(r.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),r.getState(t)===Xr&&r.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=this.fragmentTracker,r=t.fragments[t.fragments.length-1];if(r.endList&&!e.isEndListAppended(this.playlistType)){const t=e.getPartialFragment(r.end);t&&(e.removeFragment(t),e.fragBuffered(r,!0))}e.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&void 0!==e.advancedDateTime&&(e.expired||this.loadingParts&&e.partsExpired||e.misses<3&&e.partEnd<=this.getLoadPosition())}flushMainBuffer(t,e,r=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:r};this.hls.trigger(n.BUFFER_FLUSHING,i)}_loadInitSegment(t){const{hls:e}=this;return this.initFragmentLoader.abort(),e.trigger(n.FRAG_LOADING,{frag:t,targetBufferTime:0}),this.initFragmentLoader.load(t).then((t=>{var e;const r=t.frag;if(!this.levels||!L(r,null==(e=this.fragCurrent)?void 0:e.initSegment))throw new ui({type:i.NETWORK_ERROR,details:s.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:r,networkDetails:null});return t})).then((t=>{const{frag:r,payload:a}=t,o=r.decryptdata;if(a&&a.byteLength>0&&null!=o&&o.key&&o.iv&&ze(o.method)){const l=self.performance.now(),{decryptRange:d}=di(r,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,Xe(o.method),d).catch((t=>{throw e.trigger(n.ERROR,{type:i.MEDIA_ERROR,details:s.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:r}),this.fragmentLoader.abort(),t})).then((i=>{const s=self.performance.now();return e.trigger(n.FRAG_DECRYPTED,{frag:r,part:null,payload:i,stats:{tstart:l,tdecrypt:s}}),t.payload=i,this.completeInitSegmentLoad(t)}))}return this.completeInitSegmentLoad(t)}))}completeInitSegmentLoad(t){const e=t.frag.stats;t.frag.data=new Uint8Array(t.payload),e.parsing.start=e.buffering.start=self.performance.now(),e.parsing.end=e.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(t){const{initSegment:e}=t;if(!this.bitrateTest&&T(t)&&e&&!e.data){var r;return(!e.encrypted||null!=(r=e.decryptdata)&&r.key?this._loadInitSegment(e):this.keyLoader.load(e).then((()=>this._loadInitSegment(e)))).catch((e=>{if(this.state===Ei.STOPPED||this.state===Ei.ERROR)throw e;throw"data"in e&&(this.fragmentLoader.abort(),this.handleFragLoadError(e,t)),this.resetFragmentLoading(t),e}))}}unhandledEncryptionError(t,e){var r,a;const o=t.tracks;if(o&&!e.encrypted&&(null!=(r=o.audio)&&r.encrypted||null!=(a=o.video)&&a.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,r=new Error("EME not supported (light build)");return this.warn(r.message),!t||t.mediaKeys?!1:(this.hls.trigger(n.ERROR,{type:i.KEY_SYSTEM_ERROR,details:s.KEY_SYSTEM_NO_KEYS,fatal:!0,error:r,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!L(t,e)}fragBufferedComplete(t,e){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${r?Fr(wr.getBuffered(r)):"(detached)"})`),T(t)){var i;if(t.type!==v.SUBTITLE){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return void(this.state=Ei.IDLE)}const r=null==(i=this.levels)?void 0:i[t.level];null!=r&&r.fragmentError&&(e||this.fragmentTracker.getState(t)!==Xr)&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0,t.stats.retry=0)}this.state=Ei.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const r=t.frag,{part:i,partsLoaded:s}=t,n=!s||0===s.length||s.some((t=>!t)),{decryptRange:a}=di(r,i),o=new fi(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n,r.duration,this.iframesOnly,a);this.log(`load complete ${r.type} sn: ${r.sn}${i?" part: "+i.index:""} of ${this.fragInfo(r,!1,i)}`),e.flush(o)}_handleFragmentLoadProgress(t){}loadKeyFor(t,e,r){var i;let s=null;return!t.encrypted||null!=(i=t.decryptdata)&&i.key?t.encrypted||(s=this.keyLoader.loadClear(t,e.encryptedFragments,this.startFragRequested),s&&this.log(`[eme] blocking frag sn: ${t.sn} load until media-keys acquired`)):(this.log(`Loading key for ${t.sn} of [${e.startSN}-${e.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=Ei.KEY_LOADING,s=this.keyLoader.load(t,r).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(n.KEY_LOADED,t),this.state===Ei.KEY_LOADING&&(this.state=Ei.IDLE),t})),this.hls.trigger(n.KEY_LOADING,{frag:t})),s}_doFragLoad(e,r,i=null,s){this.fragCurrent=e;const a=r.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);const o=this.fragPrevious;if(!S(e,o)){const t=this.shouldLoadParts(r.details,e.end);t!==this.loadingParts&&(this.log(`LL-Part loading ${t?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=t)}if(i=Math.max(e.start,i||0),this.loadingParts){const t=a.partList;if(t&&s){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const l=this.getNextPart(t,e,i);if(l>-1){const d=t[l];if(!S(e=this.fragCurrent=d.fragment,o)&&!this.shouldLoadParts(r.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,d)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(d,r.details))return Promise.resolve(null);const h=this.loadKeyFor(e,a);if(this.fragContextChanged(e))return Promise.resolve(null);let u;this.log(`Loading ${e.type} sn: ${e.sn} part: ${d.index} (${l}/${t.length-1}) of ${this.fragInfo(e,!1,d)} cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${i}${d.byteRange.length?` range:${d.byteRange.join("-")}`:""}`),this.nextLoadPosition=d.start+d.duration,this.state=Ei.FRAG_LOADING;const c=this.loadInitSegmentIfNeeded(e);if(h||c){const t=!!h;u=Promise.all([h,c]).then((([i])=>!t||i&&!this.fragContextChanged(i.frag)?this.doFragPartsLoad(e,d,r,s):null)).catch((t=>this.handleFragLoadError(t,e)))}else u=this.doFragPartsLoad(e,d,r,s).catch((t=>this.handleFragLoadError(t,e)));return this.hls.trigger(n.FRAG_LOADING,{frag:e,part:d,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):u}if(!e.url||this.loadedEndOfParts(t,i))return Promise.resolve(null)}}var l;if(this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i} Check buffer at sn: ${e.sn} loaded parts: ${null==(l=a.partList)?void 0:l.filter((t=>t.loaded)).map((t=>`[${t.start}-${t.end}]`))}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,r.details))return Promise.resolve(null);const d=this.loadInitSegmentIfNeeded(e),h=this.loadKeyFor(e,a,d);var u;if(this.fragContextChanged(e))return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${null==(u=this.fragCurrent)?void 0:u.relurl}`),null==d||d.catch((()=>null)),null==h||h.catch((()=>null)),Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${i}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),t(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Ei.FRAG_LOADING;const c=this.config.progressive&&e.type!==v.SUBTITLE;let f;return f=c&&h?h.then((t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,s,d))).catch((t=>this.handleFragLoadError(t,e))):Promise.all([this.fragmentLoader.load(e,this.iframesOnly,c?s:void 0,c?d:void 0),h,d]).then((([t])=>(!c&&s&&s(t),t))).catch((t=>this.handleFragLoadError(t,e))),this.hls.trigger(n.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([f,d]).then((([t])=>t))}doFragPartsLoad(t,e,r,i){return new Promise(((s,a)=>{var o;const l=[],d=null==(o=r.details)?void 0:o.partList,h=e=>{this.fragmentLoader.loadPart(t,e,i).then((i=>{l[e.index]=i;const a=i.part;this.hls.trigger(n.FRAG_LOADED,i);const o=br(r.details,t.sn,e.index+1)||Dr(d,t.sn,e.index+1);if(!o)return s({frag:t,part:a,partsLoaded:l});h(o)})).catch(a)};h(e)}))}handleFragLoadError(t,e){if("data"in t){const r=t.data;r.details===s.INTERNAL_ABORTED?this.handleFragLoadAborted(e,r.part):r.type!==i.KEY_SYSTEM_ERROR||r.fatal||(e.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e)),r.frag!==e?(r.frag&&this.warn(`${r.details} error cascading from ${this.fragInfo(r.frag,!1,r.part)} to ${this.fragInfo(e,!1)}`),this.hls.trigger(n.ERROR,_(_({},r),{},{frag:e}))):this.hls.trigger(n.ERROR,r)}else this.hls.trigger(n.ERROR,{type:i.OTHER_ERROR,details:s.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==Ei.PARSING)return void(this.fragCurrent||this.state===Ei.STOPPED||this.state===Ei.ERROR||(this.state=Ei.IDLE));const{frag:r,part:i,level:s}=e,n=self.performance.now();r.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&r.sn>a.endSN||this.shouldLoadParts(a,r.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${r.end}`),this.loadingParts=o),this.updateLevelTiming(r,i,s,t)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList&&!this.iframesOnly){var r;const i=t.partList[0];if(e>=i.end+((null==(r=t.fragmentHint)?void 0:r.duration)||0)){if(this.playhead>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:r}=this,{level:i,sn:s,part:n}=t;if(null==e||!e[i])return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=e[i],o=a.details,l=n>-1?br(o,s,n):null,d=l?l.fragment:Rr(o,s,r);return d?(r&&r!==d&&(d.stats=r.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(t,e,r,i,s){if(this.state!==Ei.PARSING)return;T(e)&&!this.fragContextChanged(e)&&(this.fragPrevious=e);const{data1:a,data2:o}=t;let l=a;if(o&&(l=Yt(a,o)),!l.length)return;const d=this.initPTS[e.cc],h=d?-d.baseTime/d.timescale:void 0,u={type:t.type,frag:e,part:r,chunkMeta:i,offset:h,parent:e.type,data:l};if(this.hls.trigger(n.BUFFER_APPENDING,u),t.dropped&&t.independent&&!r){if(s)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!wr.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const r=e.currentTime,i=wr.bufferInfo(e,r,0),s=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(t.start-n,i.end-n),r+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var r;const i=this.playhead,s=this.lastCurrentTime>i||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,i,e,s)}getFwdBufferInfoAtPos(t,e,r,i){const s=wr.bufferInfo(t,e,i);if(0===s.len&&void 0!==s.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,r);if(n&&(s.nextStart<=n.end||n.gap)){const r=Math.max(Math.min(s.nextStart,n.end)-e,i);return wr.bufferInfo(t,e,r)}}return s}getMaxBufferLength(t){const{config:e}=this;let r;return r=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(r,e.maxMaxBufferLength)}exceedsMaxBuffer(t,e,r){const i=t.nextStart;if(i&&r.start>i){const i=t.buffered;if(i){let s=t.len;const n=t.bufferedIndex;for(let t=i.length-1;t>n;t--)i[t].start<r.start&&(s+=i[t].end-i[t].start);return s>=e}}return!1}reduceMaxBufferLength(t,e){const r=this.config,i=Math.max(Math.min(t-e,r.maxBufferLength),e/2),s=Math.max(t-3*e,r.maxMaxBufferLength/2,i);return s>=i&&(r.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0)}getAppendedFrag(t){const e=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,this.playlistType):null;return e&&"fragment"in e?e.fragment:e}getNextFragment(t,e){const r=e.fragments,i=r.length;if(!i)return null;const{config:s}=this,n=e.fragmentStart,a=s.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const r=s.initialLiveManifestSize;if(i<r)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${r})`),null;if(this.startFragRequested||!a||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var l;o=this.getInitialLiveFragment(e);const r=this.config.startPosition,i=this.hls.startPosition,s=this.hls.liveSyncPosition,a=(null==(l=o)?void 0:l.start)||0;let d,h;if(-1!==i&&i>=n?(d=i,h=i===r?"config":"next load start"):s?(d=s,h="live edge"):(d=t,h="buffer pos"),d<a&&(d=a,h="live frag start"),d<n&&(d=n,h="playlist start"),this.startPosition!=d||this.nextLoadPosition!=d){const l=e.live&&!this.filterReplacedPrimary(o,e)?-1:d;this.log(`Setting startPosition to ${l} next load ${d} ${-1===i?"":`(from ${r}) `}based on ${h}. live edge: ${s} live frag start: ${a} playlist start: ${n} buffer pos: ${t}`),this.startPosition=l,this.nextLoadPosition=d}}}else t<=n&&(o=r[0]);if(!o){const r=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,r,e)}let d=this.filterReplacedPrimary(o,e);var h,u;return!d&&o&&(h=e,d=(u=o.sn)===h.endSN&&h.fragmentHint?h.fragmentHint:h.fragments[1+u-h.startSN]||null,d&&(this.nextLoadPosition=d.start)),d}isLoopLoading(t,e){if(this.nextLoadPosition<=e)return!1;const r=this.fragmentTracker.getState(t);if(r===Qr)return!0;if(r===Xr){if(t.gap)return!0;if(t.stats.retry>1)return!0}return!1}getNextFragmentLoopLoading(t,e,r,i,s){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&r.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==t&&r.len+t.len>=s){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){return this.config,!1}filterReplacedPrimary(t,e){return t?(this.config,t):t}getNextPart(t,e,r){let i=-1,s=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,i>-1&&r<o.start)break;const l=o.loaded||o.gap;l?i=-1:(s||(o.independent||n)&&o.fragment===e)&&(i=a),s=l&&!o.gap}const a=t[i];return a&&a.fragment!==e&&this.log(`Need buffer at ${r} but next unloaded part starts at ${a.start} (sn: ${e.sn} -> ${a.fragment.sn})`),i}loadedEndOfParts(t,e){let r;for(let i=t.length;i--;){if(r=t[i],!r.loaded)return!1;if(e>r.start)return!0}return!1}getInitialLiveFragment(e){const r=e.fragments,i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(s=function(e,r,i){if(null===r||!Array.isArray(e)||!e.length||!t(r))return null;if(r<(e[0].programDateTime||0))return null;if(r>=(e[e.length-1].endProgramDateTime||0))return null;for(let t=0;t<e.length;++t){const s=e[t];if(xe(r,i,s))return s}return null}(r,i.endProgramDateTime,this.config.maxFragLookUpTolerance),s&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)),!s){const t=i.sn+1;if(t>=e.startSN&&t<=e.endSN){const n=r[t-e.startSN];i.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=function(t,e,r){if(t&&t.startCC<=e&&t.endCC>=e){let i=t.fragments;const{fragmentHint:s}=t;let n;return s&&(i=i.concat(s)),_e(i,(t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=r?1:t.start>r?-1:0))),n||null}return null}(e,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(s=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(t,e,r){const{config:i}=this;let{fragPrevious:s}=this,{fragments:n,endSN:a}=r;const{fragmentHint:o}=r,{maxFragLookUpTolerance:l}=i,d=r.partList,h=!!(this.loadingParts&&null!=d&&d.length&&o);let u;if(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),s&&this.fragmentTracker.getState(s)===qr&&(s=null),t<e){var c;u=Ce(s,n,t,t<this.lastCurrentTime||t>e-l||null!=(c=this.media)&&c.paused||this.loadingParts||!this.startFragRequested?0:l)}else u=n[n.length-1];if(u){const t=u.sn,e=t-r.startSN,i=this.fragmentTracker.getState(u);if((i===Qr||i===Xr&&u.gap)&&(s=u),S(u,s)&&(!h||d[0].fragment.sn>t||!r.live||!d.some((e=>e.fragment.sn===t&&!e.loaded&&!e.gap)))){const t=n[e+1];u=u.sn<a&&this.fragmentTracker.getState(t)!==Qr?t:null}}return u}alignPlaylists(e,r,i){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const n=e.fragmentStart,a=!r,o=e.alignedSliding&&t(n);if(a||!o&&!n){vi(i,e,this);const t=e.fragmentStart;return this.log(`Live playlist sliding: ${t} start-sn: ${r?r.startSN:"na"}->${e.startSN} fragments: ${s}`),t}return n}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(e,r){let i=this.startPosition;i<r&&(i=-1);const s=this.timelineOffset;if(-1===i){const n=null!==this.startTimeOffset,a=n?this.startTimeOffset:e.startTimeOffset;if(null!==a&&t(a))i=r+a,a<0&&(i+=e.edge),i=Math.min(Math.max(r,i),r+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=i;else if(e.live){const t=this.hls.liveSyncPosition;i=t||r,this.log(`Setting startPosition to -1 to start at ${t?"live edge":"playlist start"} ${i}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=i=0;this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var t;const{media:e}=this;let r=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e&&!this.iframesOnly?r=e.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}get playhead(){var e;if(null!=(e=this.hls)&&e.hasEnoughToStart){var r;const e=null==(r=this.media)?void 0:r.currentTime;return t(e)?e:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var t;if(this.playlistType!==v.MAIN)return!1;const e=this.getLevelDetails();return e?e.iframesOnly:null==(t=this.levelLastLoaded)?void 0:t.iframes}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&T(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.state!==Ei.STOPPED&&(this.fragCurrent&&(this.fragContextChanged(t)||this.state===Ei.FRAG_LOADING_WAITING_RETRY)||(this.state=Ei.IDLE))}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const{frag:r,part:i}=e;if(!r||!this.levels||r.type!==t)return;var n;if(this.fragContextChanged(r))return void this.warn(`Frag load error must match current frag to retry ${r.relurl} > ${null==(n=this.fragCurrent)?void 0:n.relurl}`);const a=e.details===s.FRAG_GAP;a&&this.fragmentTracker.addAsGap(r);const o=e.errorAction;if(!o)return void(this.state=Ei.ERROR);const{action:l,flags:d,retryCount:h=0,retryConfig:u}=o,c=!!u,f=c&&l===we.RetryRequest,g=c&&!o.resolved&&d&Oe.MoveAllAlternatesMatchingHost,m=this.hls.latestLevelDetails,p=null==m?void 0:m.live;if(!f&&g&&T(r)&&p&&r.sn<m.endSN&&!x(e))this.resetFragmentErrors(t),i?i.gap=!0:this.treatAsGap(r),o.resolved=!0;else if((f||g)&&h<u.maxNumRetry){var v;const i=N(null==(v=e.response)?void 0:v.code),s=O(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+s,this.state=Ei.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,i)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${r.sn} of ${t} ${r.level} errored with ${e.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${s}ms`)}else if(u){if(this.resetFragmentErrors(t),!(h<u.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${h})`);a||l===we.RemoveAlternatePermanently||(o.resolved=!0)}else this.state=l===we.SendAlternateToPenaltyBox?Ei.WAITING_LEVEL:Ei.ERROR;this.tickImmediate()}onSourceBufferError(t,e){var r,i;const{frag:s,part:n,sourceBufferName:a}=e,o=s&&(null==(r=this.levels)||null==(r=r[s.level])?void 0:r.details);if(e.error.name!==Br||(null==s?void 0:s.type)!==t||!T(s)||null==o||!o.live)return;const l=n?0===n.index?n:null:s,d=l&&a?null==(i=l.elementaryStreams[a])?void 0:i.startPTS:void 0;if(this.markSourceBufferErrorGap(Rr(o,s.sn)||s),void 0===d)return;const h=Rr(o,s.sn-1);h&&this.fragmentTracker.getState(h)!==qr&&!wr.isBuffered(this.mediaBuffer||this.media,d-this.config.maxBufferHole)&&this.markSourceBufferErrorGap(h)}markSourceBufferErrorGap(t){this.warn(`Marking fragment ${t.sn} of ${this.playlistLabel()} ${t.level} as a gap after a SourceBuffer error`),this.fragmentTracker.addAsGap(t)}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,r=e===1/0;(!e||t>=e||r&&!N(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Ei.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===Ei.PARSING||this.state===Ei.PARSED){const e=t.frag,r=t.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),s=i&&i.len>.5;s&&this.reduceMaxBufferLength(i.len,(null==e?void 0:e.duration)||10);const n=!s;return n?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${r} buffer`):i.nextStart&&e&&i.nextStart>e.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,r===v.AUDIO?r:void 0),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===v.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Ei.STOPPED&&(this.state=Ei.IDLE)}afterBufferFlushed(t,e){if(!t)return;const r=wr.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,this.playlistType),this.state===Ei.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Ei.STOPPED&&(this.state=Ei.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.getLevelDetails();null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,r,a){const o=r.details;if(!o)return void this.warn("level.details undefined");this.log(`update level timing ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`);if(!Object.keys(t.elementaryStreams).reduce(((i,s)=>{const l=t.elementaryStreams[s];if(l){const d=l.endPTS-l.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${t.sn} ${s} duration reliably (${d})`),i||!1;let h=0;return a.partial?e&&0===a.part&&(h=e.start-l.startPTS,t.startPTS=t.maxStartPTS=l.startPTS,t.startDTS=l.startDTS,0!==t.start&&t.setStart(l.startPTS),yr(o,t,h)):h=Er(o,t,l.startPTS,l.endPTS,l.startDTS,l.endDTS,this.iframesOnly,this),this.hls.trigger(n.LEVEL_PTS_UPDATED,{details:o,level:r,drift:h,type:s,frag:t,part:e,start:l.startPTS,end:l.endPTS}),!0}return i}),!1)){var l,d,h,u;const a=null===(null==(l=this.transmuxer)?void 0:l.error),o=null!=(null==(d=this.transmuxer)?void 0:d.error),c=(null!=(h=null==(u=this.levels)?void 0:u.length)?h:0)>1;if((0===r.fragmentError||a&&(r.fragmentError<2||t.endList)||o&&c)&&this.treatAsGap(t,r),a){const a=new Error(`Found no media in ${this.playlistLabel()} ${t.level} ${e?`part: ${e.index} of `:""}sn: ${t.sn} at playlist time: ${t.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(a.message),this.hls.trigger(n.ERROR,{type:i.MEDIA_ERROR,details:s.FRAG_PARSING_ERROR,fatal:!1,error:a,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Ei.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`),this.hls.trigger(n.FRAG_PARSED,{frag:t,part:e,chunkMeta:a})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(t,e=!0,r){var i,s;return`${t.type} playlist ${t.level} (${r?"part":"frag"}:[${null!=(i=e&&!r?t.startPTS:(r||t).start)?i:NaN}-${null!=(s=e&&!r?t.endPTS:(r||t).end)?s:NaN}]${r&&"main"===t.type?"INDEPENDENT="+(r.independent?"YES":"NO"):""})`}treatAsGap(t,e){e&&e.fragmentError++,this.fragmentTracker.addAsGap(t)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}isFragmentNearlyDownloaded(t){var e;const r=null==(e=t.loader)?void 0:e.stats;if(!r)return!1;if(r.total<=0)return!1;const i=r.loading.first>0,s=8*(r.total-r.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&s<=.15}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}calculateOptimalSwitchPoint(t,e){let r=0;const{hls:i,media:s,config:n,levels:a,playlistType:o}=this,l=this.getLevelDetails();if(s&&!s.paused&&a){var d;const e=o===v.AUDIO?X.estimatedAudioBitrate(t.audioCodec,128e3):t.maxBitrate,s=1+i.ttfbEstimate/1e3,a=i.bandwidthEstimate*n.abrBandWidthUpFactor;r=s+e*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(d=this.fragCurrent)?void 0:d.duration)||6)/a,t.details||(r+=s)}const h=this.playhead;return{fetchdelay:r,okToFlushForwardBuffer:!(null!=l&&l.live)||e.end-h>1.5*r}}scheduleTrackSwitch(t,e,r){const{media:i,playlistType:s}=this;if(!i||!t)return;const n=r?this.getBufferedFrag(this.playhead+e):null;if(n){const t=this.followingBufferedFrag(n);if(t){var a;this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,r=t.duration,i=Math.max(n.end,e+Math.min(Math.max(r-this.config.maxFragLookUpTolerance,r*(this.couldBacktrack?.5:.125)),r*(this.couldBacktrack?.75:.25)));if(((null==(a=this.getLevelDetails())?void 0:a.fragmentStart)||0)>i)return;const o=s===v.MAIN?null:"audio";this.flushMainBuffer(i,Number.POSITIVE_INFINITY,o),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:t,playlistType:e}=this;if(!t)return;const r=this.getAppendedFrag(this.playhead);if(r&&r.start>1){const t=e===v.AUDIO;this.flushMainBuffer(0,r.start-(t?0:1),t?"audio":null)}}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,this.playlistType)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}abortCurrentFrag(){var t;const e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Ei.KEY_LOADING:case Ei.FRAG_LOADING:case Ei.FRAG_LOADING_WAITING_RETRY:case Ei.PARSING:case Ei.PARSED:this.state=Ei.IDLE}this.nextLoadPosition=null!=(t=this.hls)&&t.hasEnoughToStart?this.playhead:this.lastCurrentTime}checkFragPlaying(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const r=t.currentTime;if(wr.isBuffered(t,r)?e=this.getAppendedFrag(r):wr.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e&&(this.backtrackFragment=void 0,!S(e,this.fragPlaying)))return this.fragPlaying=e,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:t,media:e,hls:r,config:i,playlistType:s}=this;if(null!=e&&e.readyState&&t&&r&&i){const e=this.getBufferOutput(),i=this.getFwdBufferInfo(e,s);if(!i)return;const n=t[s===v.AUDIO?r.nextAudioTrack:r.nextLoadLevel],{fetchdelay:a,okToFlushForwardBuffer:o}=this.calculateOptimalSwitchPoint(n,i);this.scheduleTrackSwitch(i,a,o)}this.tickImmediate()}}class Ti{constructor(t){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){const{hls:t}=this;t&&(t.on(n.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(n.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(n.MANIFEST_PARSED,this.onManifestParsed,this),t.on(n.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(n.BUFFER_CODECS,this.onBufferCodecs,this),t.on(n.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:t}=this;t&&(t.off(n.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(n.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(n.MANIFEST_PARSED,this.onManifestParsed,this),t.off(n.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(n.BUFFER_CODECS,this.onBufferCodecs,this),t.off(n.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(t,e){if(!this.hls)return;const r=this.hls.levels[e.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(t,e){const r=e.media;this.clientRect=null,this.hls&&(r instanceof HTMLVideoElement?(this.media=r,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(t,e){this.restrictedLevels=[],e.video&&this.startCapping(),this.onLevelsUpdated()}onLevelsUpdated(){if(this.hls)if((this.timer||this.observer)&&(t(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(void 0===this.observer&&void 0===this.timer){const t=this.hls.levels;t.length>1&&t.some((t=>!!t.videoCodec))&&this.startCapping()}}onBufferCodecs(t,e){e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls)return void(this.clientRect=null);const t=this.hls.levels;if(t.length>1){const e=this.hls,r=this.getMaxLevel(t.length-1);r!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${r}: ${t[r].height}p@${t[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=r,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}else 1===t.length&&this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;const e=this.hls.levels;if(!e.length)return-1;const r=e.filter(((e,r)=>this.isLevelAllowed(e)&&r<=t));return this.observer||(this.clientRect=null),Ti.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}observe(){const t=self.ResizeObserver;t&&(this.observer=new t((t=>{var e;const r=null==(e=t[0])?void 0:e.contentRect;r&&(this.clientRect=r,this.detectPlayerSize())}))),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var t;this.timer||this.observer||null==(t=this.hls)||!t.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const r=t.getBoundingClientRect();e.width=r.width,e.height=r.height,e.width||e.height||(e.width=r.right-r.left||t.width||0,e.height=r.bottom-r.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls)return t;const{ignoreDevicePixelRatio:e,maxDevicePixelRatio:r}=this.hls.config;if(!e)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,r)}isLevelAllowed(t){return!this.restrictedLevels.some((e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height))}static getMaxLevelByMediaSize(t,e,r){if(null==t||!t.length)return-1;let i=t.length-1;const s=Math.max(e,r);for(let e=0;e<t.length;e+=1){const r=t[e];if((r.width>=s||r.height>=s)&&(n=r,!(a=t[e+1])||n.width!==a.width||n.height!==a.height)){i=e;break}}var n,a;return i}}class Si extends G{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(n.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(n.MANIFEST_PARSED,this.onManifestParsed,this),t.on(n.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(n.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(n.MANIFEST_PARSED,this.onManifestParsed,this),t.off(n.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce(((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t)),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter((e=>e!==t)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:r}=e;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:r}=e;if((null==r?void 0:r.action)===we.SendAlternateToPenaltyBox&&r.flags&Oe.MoveAllAlternatesMatchingHost){const t=this.levels;let i=this._pathwayPriority,n=this.pathwayId;if(e.context){const{groupId:r,pathwayId:i,type:s}=e.context;r&&t?n=this.getPathwayForGroupId(r,s,n):i&&(n=i)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!i&&t&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==n,r.resolved||e.details===s.BUFFER_APPEND_ERROR&&!e.fatal||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${n} levels: ${t?t.length:t} priorities: ${Re(i)} penalized: ${Re(this.penalizedPathways)}`))}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const r=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),e=this.getLevelsForPathway(r),this.pathwayId=r}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter((e=>t===e.pathwayId))}updatePathwayPriority(t){let e;this._pathwayPriority=t;const r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach((t=>{i-r[t]>3e5&&delete r[t]}));for(let i=0;i<t.length;i++){const s=t[i];if(s in r)continue;if(s===this.pathwayId)return;const a=this.hls.nextLoadLevel,o=this.hls.levels[a];if(e=this.getLevelsForPathway(s),e.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,Ir(e),this.hls.trigger(n.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[a];o&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(t,e,r){const i=this.getLevelsForPathway(r).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(e===p.AUDIO_TRACK&&i[r].hasAudioGroup(t)||e===p.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(t))return i[r].pathwayId;return r}clonePathways(t){const e=this.levels;if(!e)return;const r={},i={};t.forEach((t=>{const{ID:s,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some((t=>t.pathwayId===s)))return;const o=this.getLevelsForPathway(n).map((t=>{const e=new Ge(t.attrs);e["PATHWAY-ID"]=s;const n=e.AUDIO&&`${e.AUDIO}_clone_${s}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${s}`;n&&(r[e.AUDIO]=n,e.AUDIO=n),o&&(i[e.SUBTITLES]=o,e.SUBTITLES=o);const l=Ai(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new Se({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)d.addGroupId("audio",`${t.audioGroups[e]}_clone_${s}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)d.addGroupId("text",`${t.subtitleGroups[e]}_clone_${s}`);return d}));e.push(...o),Li(this.audioTracks,r,a,s),Li(this.subtitleTracks,i,a,s)}))}loadSteeringManifest(t){const e=this.hls.config,r=e.loader;let i;this.loader&&this.loader.destroy(),this.loader=new r(e);try{i=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==i.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);me(i,"_HLS_pathway",this.pathwayId),me(i,"_HLS_throughput",""+t)}const s={type:p.STEERING_MANIFEST,responseType:"json",url:i.href},a=e.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},d={onSuccess:(t,e,r,s)=>{this.log(`Loaded steering manifest: "${i}"`);const a=t.data;if(1!==(null==a?void 0:a.VERSION))return void this.log(`Steering VERSION ${a.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=a.TTL;const{"RELOAD-URI":o,"PATHWAY-CLONES":l,"PATHWAY-PRIORITY":d}=a;if(o)try{this.uri=new self.URL(o,i).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`)}this.scheduleRefresh(this.uri||r.url),l&&this.clonePathways(l);const h={steeringManifest:a,url:i.toString()};this.hls.trigger(n.STEERING_MANIFEST_LOADED,h),d&&this.updatePathwayPriority(d)},onError:(t,e,r,i)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||e.url,s);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(s=1e3*parseFloat(e))}this.log(`Steering manifest ${e.url} rate limited`)}},onTimeout:(t,e,r)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(s,l,d)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var e;const r=null==(e=this.hls)?void 0:e.media;!r||r.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),e)}}function Li(t,e,r,i){t&&Object.keys(e).forEach((s=>{const n=t.filter((t=>t.groupId===s)).map((t=>{const n=I({},t);return n.details=void 0,n.attrs=new Ge(n.attrs),n.url=n.attrs.URI=Ai(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),n.groupId=n.attrs["GROUP-ID"]=e[s],n.attrs["PATHWAY-ID"]=i,n}));t.push(...n)}))}function Ai(t,e,r,i){if(e){const{[r]:t}=i;if(t){const r=t[e];if(r)return r}}const{HOST:s,PARAMS:n}=i,a=new self.URL(t);return s&&(a.hostname=s),n&&Object.keys(n).sort().forEach((t=>{t&&me(a,t,n[t])})),a.href}class Ri{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(n.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(n.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(n.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(n.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const r=this.hls.config;if(r.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,r){const i=performance.now();if(e){if(this.lastTime){const t=i-this.lastTime,s=r-this.lastDroppedFrames,a=e-this.lastDecodedFrames,o=1e3*s/t,l=this.hls;if(l.trigger(n.FPS_DROP,{currentDropped:s,currentDecoded:a,totalDroppedFrames:r}),o>0&&s>l.config.fpsDroppedMonitoringThreshold*a){let t=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=t)&&(t-=1,l.trigger(n.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:l.currentLevel}),l.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}var bi,Di={exports:{}};var Ii=(bi||(bi=1,function(t){var e=Object.prototype.hasOwnProperty,r="~";function i(){}function s(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function n(t,e,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new s(i,n||t,a),l=r?r+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new i:delete t._events[e]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),o.prototype.eventNames=function(){var t,i,s=[];if(0===this._eventsCount)return s;for(i in t=this._events)e.call(t,i)&&s.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(t)):s},o.prototype.listeners=function(t){var e=r?r+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var s=0,n=i.length,a=new Array(n);s<n;s++)a[s]=i[s].fn;return a},o.prototype.listenerCount=function(t){var e=r?r+t:t,i=this._events[e];return i?i.fn?1:i.length:0},o.prototype.emit=function(t,e,i,s,n,a){var o=r?r+t:t;if(!this._events[o])return!1;var l,d,h=this._events[o],u=arguments.length;if(h.fn){switch(h.once&&this.removeListener(t,h.fn,void 0,!0),u){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,e),!0;case 3:return h.fn.call(h.context,e,i),!0;case 4:return h.fn.call(h.context,e,i,s),!0;case 5:return h.fn.call(h.context,e,i,s,n),!0;case 6:return h.fn.call(h.context,e,i,s,n,a),!0}for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];h.fn.apply(h.context,l)}else{var c,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(t,h[d].fn,void 0,!0),u){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,e);break;case 3:h[d].fn.call(h[d].context,e,i);break;case 4:h[d].fn.call(h[d].context,e,i,s);break;default:if(!l)for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];h[d].fn.apply(h[d].context,l)}}return!0},o.prototype.on=function(t,e,r){return n(this,t,e,r,!1)},o.prototype.once=function(t,e,r){return n(this,t,e,r,!0)},o.prototype.removeListener=function(t,e,i,s){var n=r?r+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||s&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,d=[],h=o.length;l<h;l++)(o[l].fn!==e||s&&!o[l].once||i&&o[l].context!==i)&&d.push(o[l]);d.length?this._events[n]=1===d.length?d[0]:d:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=r?r+t:t,this._events[e]&&a(this,e)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,t.exports=o}(Di)),Di.exports),ki=a(Ii);function _i(t,e){const r=Ci(t.main);if(r&&r.start<=e)return r;const i=Ci(t.audio);return i&&i.start<=e?i:null}function Ci(t){if(!t)return null;switch(t.state){case Ei.IDLE:case Ei.STOPPED:case Ei.ENDED:case Ei.ERROR:return null}return t.frag}function Pi(t,e){return e.getAppendedFrag(t,v.MAIN)||e.getPartialFragment(t)}function xi(t,e,r,i){i.latestLevelDetails,Pi(e,r),i.config}let wi=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function Oi(t,e,r,i){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&t.cues.length>0){const s=function(t,e,r){const i=[],s=function(t,e){if(e<=t[0].startTime)return 0;const r=t.length-1;if(e>t[r].endTime)return-1;let i,s=0,n=r;for(;s<=n;)if(i=Math.floor((n+s)/2),e<t[i].startTime)n=i-1;else{if(!(e>t[i].startTime&&s<r))return i;s=i+1}return t[s].startTime-e<e-t[n].startTime?s:n}(t,e);if(s>-1)for(let n=s,a=t.length;n<a;n++){const s=t[n];if(s.startTime>=e&&s.endTime<=r)i.push(s);else if(s.startTime>r)return i}return i}(t.cues,e,r);for(let e=0;e<s.length;e++)i&&!i(s[e])||t.removeCue(s[e])}"disabled"===s&&(t.mode=s)}function Mi(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Fi(t,e,r,i,s){let n=new t(e,r,"");try{n.value=i,s&&(n.type=s)}catch(a){n=new t(e,r,Re(s?_({type:s},i):i))}return n}const Ni=(()=>{const t=Mi();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();const $i="1.7.4",Bi={};function Ui(t,e){return 255===t[e]&&240==(246&t[e+1])}function Gi(t,e){return 1&t[e+1]?7:9}function Vi(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Hi(t,e){return e+1<t.length&&Ui(t,e)}function Ki(t,e){if(Hi(t,e)){const r=Gi(t,e);if(e+r>=t.length)return!1;const i=Vi(t,e);if(i<=r)return!1;const s=e+i;return s===t.length||Hi(t,s)}return!1}function Yi(t,e,r,a,o){if(!t.samplerate){const l=function(t,e,r,a){const o=e[r+2],l=o>>2&15;if(l>12){const e=new Error(`invalid ADTS sampling index:${l}`);return void t.emit(n.ERROR,n.ERROR,{type:i.MEDIA_ERROR,details:s.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const d=1+(o>>6&3),h=e[r+3]>>6&3|(1&o)<<2,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][l];let c,f=l;5!==d&&29!==d||(f-=3);const g=(14&f)>>1,m=(1&f)<<7|h<<3;let p=0;if(1===d&&l>=6){p=5;const t=l-3;c=[p<<3|g,m|(14&t)>>1,(1&t)<<7|8,0]}else c=[d<<3|g,m];const v="mp4a.40."+(p||d);return j.log(`manifest codec:${a}, parsed codec:${v}, channels:${h}, rate:${u} (ADTS object type:${d} sampling index:${l} esds config:[${c.join(",")}])`),{config:c,samplerate:u,channelCount:h,codec:v,parsedCodec:v,manifestCodec:a}}(e,r,a,o);if(!l)return;I(t,l)}}function Wi(t){return 9216e4/t}function ji(t,e,r,i,s){const n=i+s*Wi(t.samplerate),a=function(t,e){const r=Gi(t,e);if(e+r<=t.length){const i=Vi(t,e)-r;if(i>0)return{headerLength:r,frameLength:i}}}(e,r);let o;if(a){const{frameLength:i,headerLength:s}=a,l=s+i,d=Math.max(0,r+l-e.length);d?(o=new Uint8Array(l-s),o.set(e.subarray(r+s,e.length),0)):o=e.subarray(r+s,r+l);const h={unit:o,pts:n};return d||t.samples.push(h),{sample:h,length:l,missing:d}}const l=e.length-r;o=new Uint8Array(l),o.set(e.subarray(r,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function qi(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class zi{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,r){}demux(e,r){this.cachedData&&(e=Yt(this.cachedData,e),this.cachedData=null);let i,s=lt(e,0),n=s?s.length:0;const a=this._audioTrack,o=this._id3Track,l=s?yt(s):void 0,d=e.length;for((null===this.basePTS||0===this.frameIndex&&t(l))&&(this.basePTS=Xi(l,r,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:wi.audioId3,duration:Number.POSITIVE_INFINITY});n<d;){if(this.canParse(e,n)){const t=this.appendFrame(a,e,n);t?(this.frameIndex++,this.lastPTS=t.sample.pts,n+=t.length,i=n):n=d}else at(e,n)?(s=lt(e,n),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:wi.audioId3,duration:Number.POSITIVE_INFINITY}),n+=s.length,i=n):n++;if(n===d&&i!==d){const t=e.slice(i);this.cachedData?this.cachedData=Yt(this.cachedData,t):this.cachedData=t}}return{audioTrack:a,videoTrack:qi(),id3Track:o,textTrack:qi()}}demuxSampleAes(t,e,r){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:qi(),id3Track:this._id3Track,textTrack:qi()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Xi=(e,r,i)=>{if(t(e))return 90*e;return 9e4*r+(i?9e4*i.baseTime/i.timescale:0)},Qi=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Zi=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Ji=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],ts=[0,1,1,4];function es(t,e,r,i,s){if(r+24>e.length)return;const n=rs(e,r);if(n&&r+n.frameLength<=e.length){const a=i+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(r,r+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function rs(t,e){const r=t[e+1]>>3&3,i=t[e+1]>>1&3,s=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==r&&0!==s&&15!==s&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*Qi[14*(3===r?3-i:3===i?3:4)+s-1],d=Zi[3*(3===r?0:2===r?1:2)+n],h=3===o?1:2,u=Ji[r][i],c=ts[i],f=8*u*c,g=Math.floor(u*l/d+a)*c,m=ee();return!!m&&m<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function is(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function ss(t,e){return e+1<t.length&&is(t,e)}function ns(t,e){if(e+1<t.length&&is(t,e)){const r=4,i=rs(t,e);let s=r;null!=i&&i.frameLength&&(s=i.frameLength);const n=e+s;return n===t.length||ss(t,n)}return!1}class as{constructor(t,e,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new ni(e,!0)}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,je,{start:0,end:t.byteLength})}decryptAacSample(t,e,r){const i=t[e].unit;if(i.length<=16)return;const s=i.subarray(16,i.length-i.length%16),n=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(n).then((s=>{const n=new Uint8Array(s);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,r)})).catch(r)}decryptAacSamples(t,e,r){for(;;e++){if(e>=t.length)return void r();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e);let i=0;for(let e=32;e<t.length-16;e+=160,i+=16)r.set(t.subarray(e,e+16),i);return r}getAvcDecryptedUnit(t,e){const r=new Uint8Array(e);let i=0;for(let e=32;e<t.length-16;e+=160,i+=16)t.set(r.subarray(i,i+16),e);return t}decryptAvcSample(t,e,r,i,s){const n=zt(s.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{s.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,r+1,i)})).catch(i)}decryptAvcSamples(t,e,r,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,r=0){if(e>=t.length)return void i();const s=t[e].units;for(;!(r>=s.length);r++){const n=s[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,r,i,n),this.decrypter.isSync())))return}}}}const os=/\/emsg[-/]ID3/i;function ls(e,r){return t(e.presentationTime)?e.presentationTime/e.timeScale:r+e.presentationTimeDelta/e.timeScale}class ds{constructor(){this.VideoSample=null}createVideoSample(t,e,r){return{key:t,frame:!1,pts:e,dts:r,units:[],length:0}}getLastNalUnit(t){var e;let r,i=this.VideoSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){const t=i.units;r=t[t.length-1]}return r}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const r=e.samples,i=r.length;if(!i)return void e.dropped++;{const e=r[i-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,r){const i=e.byteLength;if(0===i)return[];const s=t.naluState||0,n=-1===s?0:s,a=[];let o=0,l=0,d=-1,h=0;for(-1===s&&(d=0,h=this.getNALuType(e,0),l=1);l<i;){const r=e.indexOf(1,l);if(-1===r)break;l=r+1;let s=r;for(;s>0&&0===e[s-1];)s--;const u=r-s+(0===s?n:0);if(u<2)continue;const c=Math.min(u,3),f=Math.min(r-s,c),g=c-f;if(s=r-f,d>=0)a.push({data:e.subarray(d,s),type:h});else{const r=this.getLastNalUnit(t.samples);r&&(s>0?r.data=Yt(r.data,e.subarray(0,s)):g>0&&(r.data=r.data.subarray(0,r.data.byteLength-g)),r.state=0)}if(!(l<i)){o=-1,d=-1;break}d=l,h=this.getNALuType(e,l)}if(-1!==o){let t=i;for(;t>0&&0===e[t-1];)t--;o=i-t+(0===t?n:0)}if(d>=0)a.push({data:e.subarray(d),type:h,state:o});else if(0===a.length&&-1!==o){const r=this.getLastNalUnit(t.samples);r&&(r.data=Yt(r.data,e),r.state=o)}return t.naluState=o,a}}class hs{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,r=t.byteLength-e,i=new Uint8Array(4),s=Math.min(4,e);if(0===s)throw new Error("no bytes available");i.set(t.subarray(r,r+s)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const r=this.word>>>32-e;if(t>32&&j.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?r<<e|this.readBits(e):r}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(0!=(this.word&2147483648>>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}}class us extends ds{parsePES(t,e,r,i,s){const n=s.iframe,a=this.parseNALu(t,r.data,i);let o,l=this.VideoSample,d=!1;r.data=null,l&&a.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),a.forEach((i=>{var s,a;switch(i.type){case 1:{if(n)break;let e=!1;o=!0;const s=i.data;if(d&&s.length>4){const t=this.readSliceType(s);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=l)&&h.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null);l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.frame=!0,l.key=e;break}case 5:o=!0,null!=(s=l)&&s.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0,l.frame=!0;break;case 6:if(n)break;o=!0,qt(i.data,1,r.pts,e.samples);break;case 7:{var u,c;o=!0,d=!0;const e=i.data,r=this.readSPS(e);if(!t.sps||t.width!==r.width||t.height!==r.height||(null==(u=t.pixelRatio)?void 0:u[0])!==r.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==r.pixelRatio[1]){t.width=r.width,t.height=r.height,t.pixelRatio=r.pixelRatio,t.sps=[e];const i=e.subarray(1,4);let s="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),s+=e}t.codec=s}break}case 8:o=!0,t.pps=[i.data];break;case 9:o=!0,t.audFound=!0,null!=(a=l)&&a.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:o=!0;break;default:o=!1}if(l&&o){l.units.push(i)}})),i&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new hs(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let r,i=8,s=8;for(let n=0;n<t;n++)0!==s&&(r=e.readEG(),s=(i+r+256)%256),i=0===s?i:s}readSPS(t){const e=new hs(t);let r,i,s,n=0,a=0,o=0,l=0;const d=e.readUByte.bind(e),h=e.readBits.bind(e),u=e.readUEG.bind(e),c=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),p=this.skipScalingList.bind(this);d();const v=d();if(h(5),f(3),d(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=u();if(3===t&&f(1),m(),m(),f(1),c())for(i=3!==t?8:12,s=0;s<i;s++)c()&&p(s<6?16:64,e)}m();const E=u();if(0===E)u();else if(1===E)for(f(1),g(),g(),r=u(),s=0;s<r;s++)g();m(),f(1);const y=u(),T=u(),S=h(1);0===S&&f(1),f(1),c()&&(n=u(),a=u(),o=u(),l=u());let L=[1,1];if(c()&&c()){switch(d()){case 1:L=[1,1];break;case 2:L=[12,11];break;case 3:L=[10,11];break;case 4:L=[16,11];break;case 5:L=[40,33];break;case 6:L=[24,11];break;case 7:L=[20,11];break;case 8:L=[32,11];break;case 9:L=[80,33];break;case 10:L=[18,11];break;case 11:L=[15,11];break;case 12:L=[64,33];break;case 13:L=[160,99];break;case 14:L=[4,3];break;case 15:L=[3,2];break;case 16:L=[2,1];break;case 255:L=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(y+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:L}}}const cs=188;class fs{constructor(t,e,r,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=t,this.config=e,this.typeSupported=r,this.logger=i,this.videoParser=null}static probe(t,e){const r=fs.syncOffset(t);return r>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),-1!==r}static syncOffset(t){const e=t.length;let r=Math.min(940,e-cs)+1,i=0;for(;i<r;){let s=!1,n=-1,a=0;for(let o=i;o<e;o+=cs){if(71!==t[o]||e-o!==cs&&71!==t[o+cs]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(r=Math.min(n+18612,t.length-cs)+1)),s||(s=0===gs(t,o)),s&&a>1&&(0===n&&a>2||o+cs>r))return n}i++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:bt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,r,i,s,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=fs.createTrack("video"),this._videoTrack.duration=i,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new Ts(this.logger):null,this._audioTrack=fs.createTrack("audio",i),this._id3Track=fs.createTrack("id3"),this._txtTrack=fs.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=r,t&&this.demux(t,0,n,"SAMPLE-AES"===(null==s?void 0:s.method))}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:r}=this;t&&(t.pesData=null),e&&(e.pesData=null),r&&(r.pesData=null),this.videoParser=null,this.aacOverFlow=null,this.remainderData=null}demux(t,e,r,i=!1,s=!1){let n;i||(this.sampleAes=null);const a=this._videoTrack,o=this.videoIntegrityChecker,l=this._audioTrack,d=this._id3Track,h=this._txtTrack,u=r.iframe;let c=a.pid,f=a.pesData,g=l.pid,m=d.pid,p=this._klvPid,v=l.pesData,E=d.pesData,y=null,T=null,S=this.pmtParsed,L=this._pmtId,A=t.length;if(this.remainderData&&(A=(t=Yt(this.remainderData,t)).length,this.remainderData=null),A<cs&&!s)return this.remainderData=t,{audioTrack:l,videoTrack:a,id3Track:d,textTrack:h};const R=Math.max(0,fs.syncOffset(t));A-=(A-R)%cs,A<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,A,t.buffer.byteLength-A));let b=0;for(let e=R;e<A;e+=cs)if(71===t[e]){const s=!!(64&t[e+1]),A=gs(t,e);let b;if((48&t[e+3])>>4>1){if(b=e+5+t[e+4],b===e+cs)continue}else b=e+4;switch(A){case c:s&&(!f||null!=o&&o.isCorrupted||!(n=ys(f,this.logger))||(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,h,n,!1,r)),f={data:[],size:0},null==o||o.reset(c)),null==o||o.handlePacket(t.subarray(e)),f&&(f.data.push(t.subarray(b,e+cs)),f.size+=e+cs-b);break;case g:if(u)break;if(s){if(v&&(n=ys(v,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,n,r);break;case"mp3":this.parseMPEGPES(l,n)}v={data:[],size:0}}v&&(v.data.push(t.subarray(b,e+cs)),v.size+=e+cs-b);break;case m:if(u)break;s&&(E&&(n=ys(E,this.logger))&&this.parseID3PES(d,n),E={data:[],size:0}),E&&(E.data.push(t.subarray(b,e+cs)),E.size+=e+cs-b);break;case p:if(u)break;s&&(y&&(n=ys(y,this.logger))&&this.parseKlvPES(d,n),y={data:[],size:0}),y&&(y.data.push(t.subarray(b,e+cs)),y.size+=e+cs-b);break;case 0:s&&(b+=t[b]+1),L=this._pmtId=ms(t,b);break;case L:{s&&(b+=t[b]+1);const n=ps(t,b,this.typeSupported,i,this.observer,this.logger,this.config,r);c=n.videoPid,c>0&&(a.pid=c,a.segmentCodec=n.segmentVideoCodec),g=n.audioPid,g>0&&(l.pid=g,l.segmentCodec=n.segmentAudioCodec),m=n.id3Pid,m>0&&(d.pid=m),p=n.klvPid,p>0&&(this._klvPid=p),null===T||S||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${T}'. Backtracking to sync byte @${R} to parse all TS packets.`),T=null,e=R-188),S=this.pmtParsed=!0;break}case 17:case 8191:break;default:T=A}}else b++;b>0&&vs(this.observer,new Error(`Found ${b} TS packet/s that do not start with 0x47`),r,void 0,this.logger),a.pesData=f,l.pesData=v,d.pesData=E;const D={audioTrack:l,videoTrack:a,id3Track:d,textTrack:h};return s&&this.extractRemainingSamples(D,r),D}flush(t,e){const{remainderData:r}=this;let i;return this.remainderData=null,i=r?this.demux(r,0,e,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i,e),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(t,e){const{audioTrack:r,videoTrack:i,id3Track:s,textTrack:n}=t,a=i.pesData,o=r.pesData,l=s.pesData,d=this.videoIntegrityChecker;let h;if(!a||null!=d&&d.isCorrupted||!(h=ys(a,this.logger))?i.pesData=a:(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,n,h,!0,e),i.pesData=null)),o&&(h=ys(o,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,h,e);break;case"mp3":this.parseMPEGPES(r,h)}r.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(h=ys(l,this.logger))?(this.parseID3PES(s,h),s.pesData=null):s.pesData=l}demuxSampleAes(t,e,r,i){const s=this.demux(t,r,i,!0,!this.config.progressive),n=this.sampleAes=new as(this.observer,this.config,e);return this.decrypt(s,n)}readyVideoParser(t){null===this.videoParser&&"avc"===t&&(this.videoParser=new us)}decrypt(t,e){return new Promise((r=>{const{audioTrack:i,videoTrack:s}=t;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,(()=>{s.samples?e.decryptAvcSamples(s.samples,0,0,(()=>{r(t)})):r(t)})):s.samples&&e.decryptAvcSamples(s.samples,0,0,(()=>{r(t)}))}))}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(t,e,r){let i=0;const s=this.aacOverFlow;let n,a,o,l=e.data;if(s){this.aacOverFlow=null;const e=s.missing,r=s.sample.unit.byteLength;if(-1===e)l=Yt(s.sample.unit,l);else{const n=r-e;s.sample.unit.set(l.subarray(0,e),n),t.samples.push(s.sample),i=s.missing}}for(n=i,a=l.length;n<a-1&&!Hi(l,n);n++);if(n!==i){let t;const e=n<a-1;if(t=e?`AAC PES did not start with ADTS header,offset:${n}`:"No ADTS header found in AAC PES",vs(this.observer,new Error(t),r,e,this.logger),!e)return}if(Yi(t,this.observer,l,n,this.audioCodec),void 0!==e.pts)o=e.pts;else{if(!s)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Wi(t.samplerate);o=s.sample.pts+e}}let d,h=0;for(;n<a;){if(d=ji(t,l,n,o,h),n+=d.length,d.missing){this.aacOverFlow=d;break}for(h++;n<a-1&&!Hi(l,n);n++);}}parseMPEGPES(t,e){const r=e.data,i=r.length;let s=0,n=0;const a=e.pts;if(void 0!==a)for(;n<i;)if(ss(r,n)){const e=es(t,r,n,a,s);if(!e)break;n+=e.length,s++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const r=I({},e,{type:this._videoTrack?wi.emsg:wi.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}parseKlvPES(t,e){var r;const i=null!=(r=e.pts)?r:e.dts;if(void 0===i)return void this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");const s=e.data;if(s.length<16)return void this.logger.warn("[tsdemuxer]: KLV PES payload too short");let n=0;for(;n<s.length;){var a;if(n+16>s.length)break;const r=n;if(n+=16,n>=s.length)break;const o=s[n];n+=1;let l=0;if(128&o){const t=127&o;if(0===t||t>4||n+t>s.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let e=0;e<t;e++)l=l<<8|s[n+e];n+=t}else l=o;if(n+l>s.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const d=n+l,h=s.subarray(r,d),u={data:h,len:h.byteLength,pts:i,dts:null!=(a=e.dts)?a:i,type:wi.misbklv,duration:Number.POSITIVE_INFINITY};t.samples.push(u),n=d}}}function gs(t,e){return((31&t[e+1])<<8)+t[e+2]}function ms(t,e){return(31&t[e+10])<<8|t[e+11]}function ps(t,e,r,i,s,n,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},d=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<d;){const d=gs(t,e),h=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!i){Es("ADTS AAC",n);break}case 15:-1===l.audioPid&&(l.audioPid=d);break;case 21:-1===l.id3Pid&&(l.id3Pid=d);break;case 219:if(!i){Es("H.264",n);break}case 27:-1===l.videoPid&&(l.videoPid=d);break;case 3:case 4:r.mpeg||r.mp3?-1===l.audioPid&&(l.audioPid=d,l.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){Es("AC-3",n);break}case 129:n.warn("AC-3 in M2TS support not included in build");break;case 6:if(h>0){let r=e+5,i=h;for(;i>2;){switch(t[r]){case 106:-1===l.audioPid&&n.warn("AC-3 in M2TS support not included in build");break;case 5:-1===l.klvPid&&a.enableEmsgKLVMetadata&&(l.klvPid=d,n.log(`KLV metadata PID found: ${d}`))}const e=t[r+1]+2;r+=e,i-=e}}break;case 194:case 135:return vs(s,new Error("Unsupported EC-3 in M2TS found"),o,void 0,n),l;case 36:return vs(s,new Error("Unsupported HEVC in M2TS found"),o,void 0,n),l}e+=h+5}return l}function vs(t,e,r,a,o){o.warn(`parsing error: ${e.message}`),t.emit(n.ERROR,n.ERROR,{type:i.MEDIA_ERROR,details:s.FRAG_PARSING_ERROR,fatal:!1,levelRetry:a,chunkMeta:r,error:e,reason:e.message})}function Es(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function ys(t,e){let r,i,s,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Yt(l[0],l[1]),l.splice(1,1);r=l[0];if(1===(r[0]<<16)+(r[1]<<8)+r[2]){if(i=(r[4]<<8)+r[5],i&&i>t.size-6)return null;const d=r[7];192&d&&(n=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&d?(a=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2,n-a>54e5&&(e.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),s=r[8];let h=s+9;if(t.size<=h)return null;t.size-=h;const u=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){r=l[t];let e=r.byteLength;if(h){if(h>e){h-=e;continue}r=r.subarray(h),e-=h,h=0}u.set(r,o),o+=e}return i&&(i-=s+3),{data:u,pts:n,dts:a,len:i}}return null}class Ts{constructor(t){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t}get isCorrupted(){return"ok"!==this.integrityState}reset(t){this.pid=t,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(t){if(t.byteLength<4)return;const e=gs(t,0);if(e!==this.pid)return void this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${e}`);const r=(48&t[3])>>4;if(0===r)return;const i=15&t[3],s=this.lastContinuityCounter;this.lastContinuityCounter=i;const n=0!=(1&r);if(0!=(2&r)&&0!=t[4]&&0!=(128&t[5]))return;if(s<0)return;const a=n?s+1&15:s;return i!==a?(this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${e}', CC=${i}, Expected-CC=${a} Last-CC=${s}`),void(this.integrityState="cc-failed")):0!=(128&t[1])?(this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${e}'`),void(this.integrityState="tei-bit")):void 0}}class Ss{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}var Ls;const As={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},Rs=new Uint8Array([0,0,0,0,0,0,0,0]),bs=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Ds=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Is=new Uint8Array([0,0,0,0,0,0,0,0]),ks=new Uint8Array([0,0,0,0,0,0,0,1]),_s=new Uint8Array([105,115,111,109]),Cs=new Uint8Array([97,118,99,49]),Ps=new Uint8Array([0,0,0,1]);class xs{static box(t,...e){let r=8,i=e.length;const s=i;for(;i--;)r+=e[i].byteLength;const n=new Uint8Array(r);for(Pt(n,0,r),Pt(n,4,t),i=0,r=8;i<s;i++)n.set(e[i],r),r+=e[i].byteLength;return n}static hdlr(t){return xs.box(Rt.hdlr,As[t])}static mdat(t){return xs.box(Rt.mdat,t)}static mdhd(t,e){e*=t;const r=Math.floor(e/(At+1)),i=Math.floor(e%(At+1));return xs.box(Rt.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24,r>>16&255,r>>8&255,255&r,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(t){return xs.box(Rt.mdia,xs.mdhd(t.timescale||0,t.duration||0),xs.hdlr(t.type),xs.minf(t))}static mfhd(t){return xs.box(Rt.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?xs.box(Rt.minf,xs.box(Rt.smhd,Is),xs.DINF,xs.stbl(t)):xs.box(Rt.minf,xs.box(Rt.vmhd,Ds),xs.DINF,xs.stbl(t))}static moof(t,e,r){return xs.box(Rt.moof,xs.mfhd(t),xs.traf(r,e))}static moov(t){let e=t.length;const r=[];for(;e--;)r[e]=xs.trak(t[e]);return xs.box.apply(null,[Rt.moov,xs.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(xs.mvex(t)))}static mvex(t){let e=t.length;const r=[];for(;e--;)r[e]=xs.trex(t[e]);return xs.box.apply(null,[Rt.mvex,...r])}static mvhd(t,e){e*=t;const r=Math.floor(e/(At+1)),i=Math.floor(e%(At+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24,r>>16&255,r>>8&255,255&r,i>>24,i>>16&255,i>>8&255,255&i,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return xs.box(Rt.mvhd,s)}static sdtp(t){const e=t.samples||[],r=new Uint8Array(4+e.length);let i,s;for(i=0;i<e.length;i++)s=e[i].flags,r[i+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return xs.box(Rt.sdtp,r)}static stbl(t){return xs.box(Rt.stbl,xs.stsd(t),xs.box(Rt.stts,Rs),xs.box(Rt.stsc,Rs),xs.box(Rt.stsz,bs),xs.box(Rt.stco,Rs))}static avc1(t){let e,r,i,s=[],n=[];for(e=0;e<t.sps.length;e++)r=t.sps[e],i=r.byteLength,s.push(i>>>8&255),s.push(255&i),s=s.concat(Array.prototype.slice.call(r));for(e=0;e<t.pps.length;e++)r=t.pps[e],i=r.byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(r));const a=xs.box(Rt.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return xs.box(Rt.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,xs.box(Rt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),xs.box(Rt.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))}static esds(t){const e=t.config,r=e.length;return new Uint8Array([0,0,0,0,3,23+r,0,1,0,4,15+r,64,21,0,0,0,0,0,0,0,0,0,0,0,5,r,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return xs.box(Rt.mp4a,xs.audioStsd(t),xs.box(Rt.esds,xs.esds(t)))}static mp3(t){return xs.box(Rt[".mp3"],xs.audioStsd(t))}static ac3(t){return xs.box(Rt["ac-3"],xs.audioStsd(t),xs.box(Rt.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return xs.box(Rt.stsd,ks,xs.mp4a(t));if("mp3"===e&&"mp3"===t.codec)return xs.box(Rt.stsd,ks,xs.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return xs.box(Rt.stsd,ks,xs.avc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,r=(t.duration||0)*(t.timescale||0),i=t.width||0,s=t.height||0,n=Math.floor(r/(At+1)),a=Math.floor(r%(At+1));return xs.box(Rt.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,255&i,0,0,s>>8&255,255&s,0,0]))}static traf(t,e){const r=xs.sdtp(t),i=t.id,s=Math.floor(e/(At+1)),n=Math.floor(e%(At+1));return xs.box(Rt.traf,xs.box(Rt.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),xs.box(Rt.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,n>>24,n>>16&255,n>>8&255,255&n])),xs.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,xs.box(Rt.trak,xs.tkhd(t),xs.mdia(t))}static trex(t){const e=t.id;return xs.box(Rt.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const r=t.samples||[],i=r.length,s=12+16*i,n=new Uint8Array(s);let a,o,l,d,h,u;for(e+=8+s,n.set(["video"===t.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<i;a++)o=r[a],l=o.duration,d=o.size,h=o.flags,u=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,61440&h.degradPrio,15&h.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return xs.box(Rt.trun,n)}static initSegment(t){const e=xs.moov(t);return Yt(xs.FTYP,e)}static hvc1(t){return new Uint8Array}}Ls=xs,xs.FTYP=Ls.box(Rt.ftyp,_s,Ps,_s,Cs),xs.DINF=Ls.box(Rt.dinf,Ls.box(Rt.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));function ws(t,e=!1){return function(t,e,r=1,i=!1){const s=t*e*r;return i?Math.round(s):s}(t,1e3,1/9e4,e)}function Os(t){const{baseTime:e,timescale:r,trackId:i}=t;return`${e/r} (${e}/${r}) trackId: ${i}`}const Ms=8589934592;function Fs(t,e,r,i){return{duration:e,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1,paddingValue:0}}}class Ns extends G{constructor(t,e,r,i){super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=r,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?Os(e):e} > ${t?Os(t):t}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const r=t[0].pts,i=t.reduce(((t,i)=>{let s=i.pts,n=s-t;return n<-4294967296&&(e=!0,s=$s(s,r),n=s-t),n>0?t:s}),r);return e&&this.debug("PTS rollover detected"),i}remux(t,e,r,i,s,n,a,o,l){let d,h,u,c,f,g,m=s,p=s;const E=!l.iframe&&t.pid>-1,y=e.pid>-1,T=e.samples.length,S=t.samples.length>0,L=a&&T>0||T>1;if((!E||S)&&(!y||L)||this.ISGenerated||a){if(this.ISGenerated){var A,R,b,D;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(A=e.pixelRatio)?void 0:A[0])!==(null==(R=t.pixelRatio)?void 0:R[0])||(null==(b=e.pixelRatio)?void 0:b[1])!==(null==(D=t.pixelRatio)?void 0:D[1]))||!t&&L||null===this.nextAudioTs&&S)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(t,e,s,n));const r=this.isVideoContiguous;let i,a=-1;if(L&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!r&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,a>0){this.warn(`Dropped ${a} out of ${T} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,p+=(e.samples[0].pts-t)/e.inputTimeScale,i=p}else-1===a&&(this.warn(`No keyframe found out of ${T} video samples`),g=!1);if(this.ISGenerated){if(S&&L&&s){const r=this.getVideoStartPts(e.samples),i=($s(t.samples[0].pts,r)-r)/e.inputTimeScale;m+=Math.max(0,i),p+=Math.max(0,-i)}if(S){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(t,e,s,n)),h=this.remuxAudio(t,m,this.isAudioContiguous,n,y||L||o===v.AUDIO?p:void 0,l),L){const i=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(t,e,s,n)),d=this.remuxVideo(e,p,r,i,l)}}else L&&(d=this.remuxVideo(e,p,r,0,l));d&&(d.firstKeyFrame=a,d.independent=-1!==a,d.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=Bs(r,s,this._initPTS,this._initDTS)),i.samples.length&&(c=Us(i,s,this._initPTS))),{audio:h,video:d,initSegment:u,independent:g,text:c,id3:f}}computeInitPts(t,e,r,i){const s=Math.round(r*e);let n=$s(t,s);if(n<s)for(this.log(`Adjusting PTS for rollover in timeline near ${(s-n)/e} ${i}`);n<s;)n+=Ms;return n-s}generateIS(e,r,i,s){const n=e.samples,a=r.samples,o=this.typeSupported,l={},d=this._initPTS,h=!d||s;let u,c,f,g="audio/mp4",m=-1;if(h&&(u=c=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(g="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}if(l.audio={id:"audio",container:g,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&o.mpeg?new Uint8Array(0):xs.initSegment([e]),metadata:{channelCount:e.channelCount}},h){m=e.id,f=e.inputTimeScale;const t=this.computeInitPts(n[0].pts,f,i,"audio");(!d||f!==d.timescale||0===i&&t<d.baseTime)&&(u=c=t)}}if(r.sps&&r.pps&&a.length){if(r.timescale=r.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:r.codec,initSegment:xs.initSegment([r]),metadata:{width:r.width,height:r.height}},h){m=r.id,f=r.inputTimeScale;const e=this.getVideoStartPts(a),s=$s(a[0].dts,e),n=this.computeInitPts(s,f,i,"video"),o=this.computeInitPts(e,f,i,"video");if(!d||f!==d.timescale||t(u)||0===i&&o<d.baseTime){c=Math.min(c,n);const t=!d&&this.isVideoContiguous?o:n;u=Math.min(u,t)}}this.videoTrackConfig={width:r.width,height:r.height,pixelRatio:r.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h&&t(u)?(d&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${u/f} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${u/f} (${u}/${f}) trackId: ${m}`),this._initPTS={baseTime:u,timescale:f,trackId:m},this._initDTS={baseTime:c,timescale:f,trackId:m}):u=f=void 0,{tracks:l,initPTS:u,timescale:f,trackId:m}}remuxVideo(t,e,r,a,o){const l=t.inputTimeScale,d=t.samples,h=[],u=d.length,c=this._initPTS,f=c.baseTime*l/c.timescale;let g,m,p=this.nextVideoTs,v=8,E=this.videoSampleDuration,y=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,S=!1;if(!r||null===p){const t=f+e*l,i=d[0].pts-$s(d[0].dts,d[0].pts);ee()&&null!==p&&Math.abs(t-i-(p+f))<15e3?r=!0:p=t-i-f}const L=p+f;for(let t=0;t<u;t++){const e=d[t];e.pts=$s(e.pts,L),e.dts=$s(e.dts,L),e.dts<d[t>0?t-1:t].dts&&(S=!0)}S&&d.sort((function(t,e){const r=t.dts-e.dts,i=t.pts-e.pts;return r||i})),g=d[0].dts,m=d[d.length-1].dts;const A=m-g,R=A?Math.round(A/(u-1)):E||t.inputTimeScale/30;if(r){const r=g-L,i=r>R,s=r<-1;if((i||s)&&(i?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${ws(r,!0)} ms (${r}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${ws(-r,!0)} ms (${r}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!s||L>=d[0].pts||ee())){g=L;const t=d[0].pts-r;if(i)d[0].dts=g,d[0].pts=t;else{let e=!0;for(let i=0;i<d.length&&!(d[i].dts>t&&e);i++){const t=d[i].pts;if(d[i].dts-=r,d[i].pts-=r,i<d.length-1){const r=d[i+1].pts;e=r<=d[i].pts==r<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${ws(t,!0)}/${ws(g,!0)}, delta: ${ws(r,!0)} ms`)}}g=Math.max(0,g);let b=0,D=0,k=g;for(let t=0;t<u;t++){const e=d[t],r=e.units,i=r.length;let s=0;for(let t=0;t<i;t++)s+=r[t].data.length;D+=s,b+=i,e.length=s,e.dts<k?(e.dts=k,k+=R/4|0||1):k=e.dts,y=Math.min(e.pts,y),T=Math.max(e.pts,T)}m=d[u-1].dts;const _=D+4*b+8;let C;try{C=new Uint8Array(_)}catch(t){return void this.observer.emit(n.ERROR,n.ERROR,{type:i.MUX_ERROR,details:s.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:o,error:t,bytes:_,reason:`fail allocating video mdat ${_}`})}Pt(C,0,_),Pt(C,4,Rt.mdat);let P=!1,x=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY,O=Number.NEGATIVE_INFINITY,M=Number.NEGATIVE_INFINITY;for(let t=0;t<u;t++){const e=d[t],i=e.units;let s,n=0;for(let t=0,e=i.length;t<e;t++){const e=i[t],r=e.data,s=e.data.byteLength;Pt(C,v,s),v+=4,C.set(r,v),v+=s,n+=4+s}if(t<u-1)E=d[t+1].dts-e.dts,s=d[t+1].pts-e.pts;else{const r=this.config,i=t>0?e.dts-d[t-1].dts:R;if(s=t>0?e.pts-d[t-1].pts:R,r.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(r.maxBufferHole*l),s=(a?y+a*l:this.nextAudioTs+f)-e.pts;s>t?(E=s-i,E<0?E=i:P=!0,this.log(`It is approximately ${s/90} ms to the next segment; using duration ${E/90} ms for the last video frame.`)):E=i}else E=i}let c=Math.round(e.pts-e.dts);if(x=Math.min(x,E),O=Math.max(O,E),w=Math.min(w,s),M=Math.max(M,s),!r&&0===t&&c>E){const t=Math.round(c/R)*R;t-c==1&&(this.log(`pad first CTS ${c} -> ${t} of sn: ${o.sn}`),c=t)}h.push(Fs(e.key,E,n,c))}if(h.length){const t=ee();if(t){if(t<70){const t=h[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(function(){if(void 0===Jt){const t=Xt.match(/Safari\/(\d+)/i);Jt=t?parseInt(t[1]):0}return Jt}()&&M-w<O-x&&R/O<.025&&0===h[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=g;for(let e=0,r=h.length;e<r;e++){const i=t+h[e].duration,s=t+h[e].cts;if(e<r-1){const t=i+h[e+1].cts;h[e].duration=t-s}else h[e].duration=e?h[e-1].duration:R;h[e].cts=0,t=i}}}E=P||!E?R:E;const F=m+E;this.nextVideoTs=p=F-f,this.videoSampleDuration=E,this.isVideoContiguous=!0;const N={data1:xs.moof(o.sn,g,I(t,{samples:h})),data2:C,startPTS:(y-f)/l,endPTS:(T+E-f)/l,startDTS:(g-f)/l,endDTS:p/l,type:"video",hasAudio:!1,hasVideo:!0,nb:h.length,dropped:t.dropped};return t.samples=[],t.dropped=0,N}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,r,a,o,l){const d=t.inputTimeScale,h=d/(t.samplerate?t.samplerate:d),u=this.getSamplesPerFrame(t),c=u*h,f=this._initPTS,g="mp3"===t.segmentCodec&&this.typeSupported.mpeg,m=[],p=void 0!==o;let v=t.samples,E=g?0:8,y=this.nextAudioTs||-1;const T=f.baseTime*d/f.timescale,S=T+e*d;if(this.isAudioContiguous=r=r||v.length&&y>0&&(a&&Math.abs(S-(y+T))<9e3||Math.abs($s(v[0].pts,S)-(y+T))<20*c),v.forEach((function(t){t.pts=$s(t.pts,S)})),!r||y<0){const t=v.length;if(v=v.filter((t=>t.pts>=0)),t!==v.length&&this.warn(`Removed ${v.length-t} of ${t} samples (initPTS ${T} / ${d})`),!v.length)return;y=0===o?0:a&&!p?Math.max(0,S-T):v[0].pts-T}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let r=0,i=y+T;r<v.length;r++){const s=v[r],n=s.pts,a=n-i,o=Math.abs(1e3*a/d);if(a<=-e*c&&p)0===r&&(this.warn(`Audio frame @ ${(n/d).toFixed(3)}s overlaps marker by ${Math.round(1e3*a/d)} ms.`),this.nextAudioTs=y=n-T,i=n);else if(a>=e*c&&o<1e4&&p){let e=Math.round(a/c);for(i=n-e*c;i<T&&e&&c;)e--,i+=c;0===r&&(this.nextAudioTs=y=i-T),this.warn(`Injecting ${e} audio frames @ ${((i-T)/d).toFixed(3)}s due to ${Math.round(1e3*a/d)} ms gap.`);for(let n=0;n<e;n++){let e=Ss.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=s.unit.subarray()),v.splice(r,0,{unit:e,pts:i}),i+=c,r++}}s.pts=i,i+=c}}let L,A=null,R=null,b=0,D=v.length;for(;D--;)b+=v[D].unit.byteLength;for(let e=0,a=v.length;e<a;e++){const a=v[e],o=a.unit;let d=a.pts;if(null!==R){m[e-1].duration=Math.round((d-R)/h)}else{if(r&&"aac"===t.segmentCodec&&(d=y+T),A=d,!(b>0))return;b+=E;try{L=new Uint8Array(b)}catch(t){return void this.observer.emit(n.ERROR,n.ERROR,{type:i.MUX_ERROR,details:s.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:l,error:t,bytes:b,reason:`fail allocating audio mdat ${b}`})}g||(Pt(L,0,b),Pt(L,4,Rt.mdat))}L&&L.set(o,E);const c=o.byteLength;E+=c,m.push(Fs(!0,u,c,0)),R=d}const k=m.length;if(!k)return;const _=m[m.length-1];y=R-T,this.nextAudioTs=y+h*_.duration;const C=g?new Uint8Array(0):xs.moof(t.sequenceNumber++,A/h,I({},t,{samples:m}));t.samples=[];const P=(A-T)/d,x=this.nextAudioTs/d,w={data1:C,data2:L,startPTS:P,endPTS:x,startDTS:P,endDTS:x,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,w}}function $s(t,e){let r;if(null===e)return t;for(r=e<t?-Ms:Ms;Math.abs(t-e)>4294967296;)t+=r;return t}function Bs(t,e,r,i){const s=t.samples.length;if(!s)return;const n=t.inputTimeScale;for(let a=0;a<s;a++){const s=t.samples[a];s.pts=$s(s.pts-r.baseTime*n/r.timescale,e*n)/n,s.dts=$s(s.dts-i.baseTime*n/i.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Us(t,e,r){const i=t.samples.length;if(!i)return;const s=t.inputTimeScale;for(let n=0;n<i;n++){const i=t.samples[n];i.pts=$s(i.pts-r.baseTime*s/r.timescale,e*s)/s}t.samples.sort(((t,e)=>t.pts-e.pts));const n=t.samples;return t.samples=[],{samples:n}}function Gs(t,e,r=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(r?t.duration:0))/t.timescale:e}function Vs(t,e,r){const i=t.codec;if(i&&i.length>4)return i;if(e===E.AUDIO){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return ue(i,!1)}return r.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"}return"mjpg"===i?i:(r.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}let Hs;try{Hs=self.performance.now.bind(self.performance)}catch(t){Hs=Date.now}const Ks=[{demux:class{constructor(t,e,r,i=j){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=e,this.logger=i}resetTimeStamp(){}resetInitSegment(t,e,r,i){const s=this.videoTrack=qi("video",1),n=this.audioTrack=qi("audio",1),a=this.txtTrack=qi("text",1);if(this.id3Track=qi("id3",1),this.initData=void 0,this.timeOffset=0,null==t||!t.byteLength)return;const o=this.initData=Mt(t);if(o.video){const{id:t,timescale:e,codec:r,supplemental:i}=o.video;s.id=t,s.timescale=a.timescale=e,s.codec=r,s.supplemental=i}if(o.audio){const{id:t,timescale:e,codec:r}=o.audio;n.id=t,n.timescale=e,n.codec=r}a.id=bt.text,s.sampleDuration=0,s.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(t){return function(t,e){const r=t.byteLength;for(let i=0;i<r;){const s=It(t,i);if(s>8&&It(t,i+4)===Rt[e])return!0;i=s>1?i+s:r}return!1}(t,"moof")}demux(t,e,r){this.timeOffset=e;let i=t;const s=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Yt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},r=xt(t,["moof"]);if(r.length<2)return e.remainder=t,e;const i=r[r.length-1];return e.valid=t.slice(0,i.byteOffset-8),e.remainder=t.slice(i.byteOffset-8),e}(i);this.remainderData=e.remainder,s.samples=e.valid||new Uint8Array}else s.samples=i;const a=this.extractID3Track(s,e),o=this.parseFragment(s,n,e,r);return{videoTrack:s,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack,initData:this.initData,sampleData:o}}flush(t,e){const r=this.timeOffset,i=this.videoTrack,s=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(i,this.timeOffset),a=this.parseFragment(i,s,r,e);return{videoTrack:i,audioTrack:qi(),id3Track:n,textTrack:qi(),initData:this.initData,sampleData:a}}parseFragment(t,e,r,i){const s=this.initData;if(s&&i){const{samples:i,sampleData:n}=function(t,e,r,i,s=!1){const n=[];return{samples:n,sampleData:{includeSampleDetails:s,tracks:Kt(e.samples,r,i,s,{isHEVCFlavor:Wt(e.codec),samples:n,timeOffset:t,timescale:e.timescale,trackId:e.id})}}}(r,t,s,this.logger,!1);return e.samples=i,n}e.samples=function(t,e){const r=[],i=e.samples,s=e.timescale,n=e.id;let a=!1;return xt(i,["moof"]).map((o=>{const l=o.byteOffset-8;xt(o,["traf"]).map((o=>{const d=xt(o,["tfdt"]).map((t=>{const e=t[0];let r=It(t,4);return 1===e&&(r*=Math.pow(2,32),r+=It(t,8)),r/s}))[0];return void 0!==d&&(t=d),xt(o,["tfhd"]).map((d=>{const h=It(d,4),u=16777215&It(d,0),c=0!=(1&u);let f=0;const g=0!=(2&u),m=0!=(8&u);let p=0;const v=0!=(16&u);let y=0;const T=0!=(32&u),S=!c&&0!=(131072&u);let L=8;h===n&&(c?(f=It(d,L),L+=4,f*=Math.pow(2,32),f+=It(d,L),L+=4):S&&(f=l),g&&(L+=4),m&&(p=It(d,L),L+=4),v&&(y=It(d,L),L+=4),T&&(L+=4),"video"===e.type&&(a=Wt(e.codec)),xt(o,["trun"]).map((n=>{const o=n[0],l=16777215&It(n,0),d=0!=(1&l);let h=0;const u=0!=(4&l),c=0!=(256&l);let g=0;const m=0!=(512&l);let v=0;const T=0!=(1024&l),S=0!=(2048&l);let L=0;const A=It(n,4);let R=8;d&&(h=It(n,R),R+=4),u&&(R+=4);let b=f+h;for(let l=0;l<A;l++){if(c?(g=It(n,R),R+=4):g=p,m?(v=It(n,R),R+=4):v=y,T&&(R+=4),S&&(L=0===o?It(n,R):Ct(n,R),R+=4),e.type===E.VIDEO){let e=0;for(;e<v;){const n=It(i,b);b+=4,jt(a,i[b])&&qt(i.subarray(b,b+n),a?2:1,t+L/s,r),b+=n,e+=n+4}}t+=g/s}})))}))}))})),r}(r,t)}extractID3Track(t,r){const i=this.id3Track;if(t.samples.length){const s=xt(t.samples,["emsg"]);s&&s.forEach((t=>{const s=function(t){const r=t[0];let i,s="",n="",a=0,o=0,l=0,d=0,h=4;if(0===r){const e=_t(t,h),r=null!==e?_t(t,h+e.length):null;null!==e&&null!==r?(s=e,n=r,h+=e.length+r.length,a=It(t,h),h+=4,o=It(t,h),h+=4,l=It(t,h),h+=4,d=It(t,h),h+=4):(j.warn(`Unterminated ${null===e?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),h=t.length)}else if(1===r){a=It(t,h),h+=4;const r=It(t,h);h+=4;const o=It(t,h);h+=4,i=2**32*r+o,e(i)||(i=Number.MAX_SAFE_INTEGER,j.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=It(t,h),h+=4,d=It(t,h),h+=4;const u=_t(t,h),c=null!==u?_t(t,h+u.length):null;null!==u&&(s=u,h+=u.length),null!==c?(n=c,h+=c.length):(j.warn(`Unterminated ${null===u?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${null===u?"strings and payload":"value and payload"}`),h=t.length)}return{schemeIdUri:s,value:n,timeScale:a,presentationTime:i,presentationTimeDelta:o,eventDuration:l,id:d,payload:t.subarray(h,t.byteLength)}}(t);if(os.test(s.schemeIdUri)){const t=ls(s,r);let e=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;e<=.001&&(e=Number.POSITIVE_INFINITY);const n=s.payload;i.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:wi.emsg,duration:e})}else if(this.config.enableEmsgKLVMetadata){const t=this.config.emsgKLVSchemaUri||wi.misbklv;if(s.schemeIdUri.startsWith(t)){const t=ls(s,r);i.samples.push({data:s.payload,len:s.payload.byteLength,dts:t,pts:t,type:wi.misbklv,duration:Number.POSITIVE_INFINITY})}}}))}return i}demuxSampleAes(t,e,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}},remux:class extends G{constructor(t,e,r,i){super("passthrough-remuxer",i),this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=t}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,r,i){this.audioCodec=e,this.videoCodec=r,this.decryptdata=i,this.pendingInitSegment=t,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(t,e,r){this.videoOnlyRemux=!1;let{audioCodec:i,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:n,video:a}=this.initData=r||Mt(t);if(e)!function(t,e){if(!t||!e)return;const r=e.keyId;16===(null==r?void 0:r.byteLength)&&e.isCommonEncryption&&Gt(t,((t,e)=>{const i=t.subarray(8,24);i.some((t=>0!==t))||(j.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${Tt(i)} -> ${Tt(r)}`),t.set(r,8))}))}(t,e);else{const t=n||a;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}n&&(i=Vs(n,E.AUDIO,this)),a&&(s=Vs(a,E.VIDEO,this));const o={};n&&a?o.audiovideo={container:"video/mp4",codec:i+","+s,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:n?o.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:t,id:"audio"}:a?o.video={container:"video/mp4",codec:s,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,r,i,s,n,a,o,l,d,h,u){var c,f;let{initPTS:g,lastEndTime:m}=this;const p={audio:void 0,video:void 0,text:void 0,id3:i,initSegment:void 0};t(m)||(m=this.lastEndTime=n||0);const v=r.samples;if(!v.length)return p;const E=this.pendingInitSegment;E&&(this.pendingInitSegment=void 0,this.generateInitSegment(E,this.decryptdata,h));const y={initPTS:void 0,timescale:void 0,trackId:void 0};let T=this.initData;if(null!=(c=T)&&c.length||(this.generateInitSegment(v),T=this.initData),null==(f=T)||!f.length)return this.warn("Failed to generate initSegment."),p;this.emitInitSegment&&(y.tracks=this.initTracks,p.initSegment=y,this.emitInitSegment=!1);const S=u?u.tracks:function(t,e,r,i,s=!0){return Kt(t,e,i,s)}(v,T,0,this,false),L=T.audio?S[T.audio.id]:null,A=T.video?S[T.video.id]:null,R=!!T.audio,b=!!T.video;let D="";R&&(D+="audio"),b&&(D+="video");const I=Gs(A,1/0),k=Gs(L,1/0),_=Gs(A,0,!0),C=Gs(L,0,!0);let P=n,x=0;A&&L&&T.audio&&(k>_||I>C)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${I}-${_} a: ${k}-${C}}`,A,L);const w=!!L&&(!A||!g&&k<I||!!g&&g.trackId===T.audio.id),O=w?L:A;if(!O)return this.log(`No media samples found in ${l} ${d.level} ${-1===d.part?"":`part: ${d.part} of`} sn: ${d.sn} at playlist time: ${n}`),p;let M=v;x=w?C-k:_-I;const F=O.timescale,N=O.start-n*F,$=w?T.audio.id:T.video.id;P=O.start/F;if(!(!!g&&d.id>1)&&(a||!g)&&(function(t,e,r,i){if(null===t)return!0;const s=Math.max(i,1),n=e-t.baseTime/t.timescale;return Math.abs(n-r)>=s}(g,P,n,x)||F!==g.timescale)){let t=!1;const e=w?"audio":"video";if(g){const r=0!==n?P/n:1+P/1;t=P>=0&&Math.abs(1-r)<.001,this.log(`${e} timestamps in track ${$} at playlist time: ${a?"":"~"}${n} maps to ${P} with initPTS: ${g.baseTime/g.timescale} (${N/F-g.baseTime/g.timescale}s diff) (${D}) drift estimate: ${r} ${t?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}t||(this.log(`Found initPTS in ${e} track ${$} at playlist time: ${n} offset: ${P-n} (${N}/${F})`),g=null,y.initPTS=N,y.timescale=F,y.trackId=$)}g?(y.initPTS=g.baseTime,y.timescale=g.timescale,y.trackId=g.trackId):(y.timescale&&void 0!==y.trackId&&void 0!==y.initPTS||(this.warn("Could not set initPTS"),y.initPTS=P,y.timescale=1,y.trackId=-1),this.initPTS=g={baseTime:y.initPTS,timescale:y.timescale,trackId:y.trackId});const B=P-g.baseTime/g.timescale,U=B+x,G=b&&void 0!==(null==O?void 0:O.ptsMin)?O.ptsMin/O.timescale-g.baseTime/g.timescale:B,V=b&&null!=O&&O.ptsMax?O.ptsMax/O.timescale-g.baseTime/g.timescale:U;x>0?this.lastEndTime=U:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const H={data1:M,data2:undefined,startPTS:G,startDTS:B,endPTS:V,endDTS:U,type:D,hasAudio:R,hasVideo:b,nb:1,dropped:0,encrypted:!!T.audio&&T.audio.encrypted||!!T.video&&T.video.encrypted};p.audio=R&&!b?H:void 0,p.video=b?H:void 0;const K=this.isVideoContiguous,Y=null==A?void 0:A.sampleCount;if(Y){const t=A.keyFrameIndex,e=-1!==t;H.nb=Y,H.dropped=0===t||K?0:e?t:Y,H.independent=e,H.firstKeyFrame=t,e&&A.keyFrameStart&&(H.firstKeyFramePTS=(A.keyFrameStart-g.baseTime)/g.timescale),K||(p.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),H.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${Y} dropped: ${H.dropped} start: ${H.firstKeyFramePTS||"NA"}`)}return p.initSegment=y,p.id3=Bs(i,n,g,g),s.samples.length&&(p.text=Us(s,n,g)),p}}},{demux:fs,remux:Ns},{demux:class extends zi{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=t,this.config=e}resetInitSegment(t,e,r,i){super.resetInitSegment(t,e,r,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const r=lt(t,0);let i=(null==r?void 0:r.length)||0;if(ns(t,i))return!1;for(let r=t.length;i<r;i++)if(Ki(t,i))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&Ui(t,e)&&Vi(t,e)<=t.length-e}(t,e)}appendFrame(t,e,r){Yi(t,this.observer,e,r,t.manifestCodec);const i=ji(t,e,r,this.basePTS,this.frameIndex);if(0===(null==i?void 0:i.missing))return i}demuxSampleAes(t,e,r){const i=this.demux(t,r),s=this.sampleAes=new as(this.observer,this.config,e);return new Promise((t=>{s.decryptAacSamples(i.audioTrack.samples,0,(()=>{t(i)}))}))}},remux:Ns},{demux:class extends zi{resetInitSegment(t,e,r,i){super.resetInitSegment(t,e,r,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=lt(t,0);let r=(null==e?void 0:e.length)||0;if(e&&11===t[r]&&119===t[r+1]&&void 0!==yt(e)&&((t,e)=>{let r=0,i=5;e+=i;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=t[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,r=r?r<<o|s[0]:s[0],e+=1,i-=o}return r})(t,r)<=16)return!1;for(let e=t.length;r<e;r++)if(ns(t,r))return j.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return is(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,r){if(null!==this.basePTS)return es(t,e,r,this.basePTS,this.frameIndex)}},remux:Ns}];class Ys{constructor(t,e,r,i,s,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=r,this.id=s,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,r,a){if(!this.observer)return Ws(r);const o=r.transmuxing;o.executeStart=Hs();const l=new Uint8Array(t),{currentTransmuxState:d,transmuxConfig:h}=this;a&&(this.currentTransmuxState=a);const{contiguous:u,discontinuity:c,trackSwitch:f,accurateTimeOffset:g,timeOffset:m,initSegmentChange:p}=a||d,{audioCodec:v,videoCodec:E,defaultInitPts:y,duration:T,initSegmentData:S}=h,L=function(t,e){let r=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(r=e);return r}(l,e);if(L&&ze(L.method)){const t=this.getDecrypter(),e=Xe(L.method);return this.asyncResult=!0,this.decryptionPromise=t.decrypt(l,L.key.buffer,L.iv.buffer,e,r.decryptRange).then((t=>{const e=this.push(t,null,r);return this.decryptionPromise=null,e})),this.decryptionPromise}const A=this.needsProbing(c,f);if(A){const t=r.iframe&&S&&fs.probe(S,this.logger)?S:l,e=this.configureTransmuxer(t);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(n.ERROR,n.ERROR,{type:i.MEDIA_ERROR,details:s.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),o.executeEnd=Hs(),Ws(r)}(c||f||p||A)&&this.resetInitSegment(S,v,E,T,e,r),(c||p||A)&&this.resetInitialTimestamp(y),u||this.resetContiguity();const R=this.transmux(l,L,m,g,r);this.asyncResult=js(R);const b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,o.executeEnd=Hs(),R}flush(t){const e=t.transmuxing;e.executeStart=Hs();const{decrypter:r,currentTransmuxState:i,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then((()=>this.flush(t)));const n=[],{timeOffset:a}=i;if(r){const e=r.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Hs();const r=[Ws(t)];return this.asyncResult?Promise.resolve(r):r}const d=o.flush(a,t);return js(d)?(this.asyncResult=!0,d.then((e=>(this.flushRemux(n,e,t),n)))):(this.flushRemux(n,d,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,r){if(!this.remuxer)return;const{audioTrack:i,videoTrack:s,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id} playlist ${r.level}`);const d=this.remuxer.remux(i,s,n,a,l,o,!0,this.id,r,e.initData,e.sampleData);t.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=Hs()}resetInitialTimestamp(t){const{demuxer:e,remuxer:r}=this;e&&r&&(e.resetTimeStamp(t),r.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,r,i,s,n){const{demuxer:a,remuxer:o}=this;a&&o&&(a.resetInitSegment(t,e,r,i,s,n),o.resetInitSegment(t,e,r,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(t,e,r,i,s){let n;return n="SAMPLE-AES"===(null==e?void 0:e.method)?this.transmuxSampleAes(t,e,r,i,s):this.transmuxUnencrypted(t,r,i,s),n}transmuxUnencrypted(t,e,r,i){const{demuxer:s,remuxer:n}=this;if(!s||!n)return Ws(i);const a=s.demux(t,e,i,!1,!this.config.progressive),{audioTrack:o,videoTrack:l,id3Track:d,textTrack:h}=a;return{remuxResult:n.remux(o,l,d,h,e,r,!1,this.id,i,a.initData,a.sampleData),chunkMeta:i}}transmuxSampleAes(t,e,r,i,s){return this.demuxer?this.demuxer.demuxSampleAes(t,e,r,s).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,r,i,!1,this.id,s,t.initData,t.sampleData),chunkMeta:s}))):Promise.reject(new Error("no demuxer"))}configureTransmuxer(t){const{config:e,observer:r,typeSupported:i}=this;if(!r)return;let s;try{for(let e=0,r=Ks.length;e<r;e++){var n;if(null!=(n=Ks[e].demux)&&n.probe(t,this.logger)){s=Ks[e];break}}}catch(t){return t}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=s.demux,d=s.remux;a&&a instanceof l||(this.logger.log(`Using ${l.name}`),this.demuxer=new l(r,e,i,this.logger),this.probe=l.probe),o&&o instanceof d||(this.logger.log(`Using ${d.name}`),this.remuxer=new d(r,e,i,this.logger))}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new ni(this.config)),t}}const Ws=t=>({remuxResult:{},chunkMeta:t});function js(t){return"then"in t&&t.then instanceof Function}class qs{constructor(t,e,r,i,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=r,this.duration=i,this.defaultInitPts=s||null}}class zs{constructor(t,e,r,i,s,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=r,this.trackSwitch=i,this.timeOffset=s,this.initSegmentChange=n}}let Xs=0;class Qs{constructor(t,e,r,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Xs++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{const e=t.data,r=this.hls;if(r&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var i;const t=null==(i=this.workerContext)?void 0:i.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":r.logger[e.data.logType]&&r.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,r.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(n.ERROR,{type:i.OTHER_ERROR,details:s.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const o=t.config;this.hls=t,this.id=e,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=r,this.onFlush=a;const l=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===n.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new ki,this.observer.on(n.FRAG_DECRYPTED,l),this.observer.on(n.ERROR,l);const d=ge(o.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const r=this.hls.logger;if(o.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{o.workerPath?(r.log(`loading Web Worker ${o.workerPath} for "${e}"`),this.workerContext=function(t){const e=Bi[t];if(e)return e.clientCount++,e;const r=new self.URL(t,self.location.href).href,i={worker:new self.Worker(r),scriptURL:r,clientCount:1};return Bi[t]=i,i}(o.workerPath)):(r.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=Bi[$i];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),r=self.URL.createObjectURL(e),i={worker:new self.Worker(r),objectURL:r,clientCount:1};return Bi[$i]=i,i}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:d,id:e,config:Re(o)})}catch(i){r.warn(`Error setting up "${e}" Web Worker, fallback to inline`,i),this.terminateWorker(),this.error=null,this.transmuxer=new Ys(this.observer,d,o,"",e,t.logger)}return}}this.transmuxer=new Ys(this.observer,d,o,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=Xs++;const e=this.hls.config,r=ge(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:r,id:this.id,config:Re(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=Bi[t||$i];if(e&&1==e.clientCount--){const{worker:r,objectURL:i}=e;delete Bi[t||$i],i&&self.URL.revokeObjectURL(i),r.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,r,i,s,n,a,o,l,d){var h,u;l.transmuxing.start=self.performance.now();const{instanceNo:c,transmuxer:f}=this,g=n?n.start:s.start,m=s.decryptdata,p=this.frag,v=!p||s.cc!==p.cc,E=!p||l.level!==p.level,y=p?l.sn-p.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===y&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),L=!E&&(1===y||0===y&&(1===T||S&&T<=0)),A=self.performance.now();(E||y||0===s.stats.parsing.start)&&(s.stats.parsing.start=A),!n||!T&&L||(n.stats.parsing.start=A);const R=!(p&&(null==(h=s.initSegment)?void 0:h.url)===(null==(u=p.initSegment)?void 0:u.url)),b=new zs(v,L,o,E,g,R);if(!L||v||R){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id} playlist: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${E}\n contiguous: ${L}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${R}`);const t=new qs(r,i,e,a,d);this.configureTransmuxer(t)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:c,cmd:"demux",data:t,decryptdata:m,chunkMeta:l,state:b},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,m,l,b);js(e)?e.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(r){const e=r.flush(t);js(e)?e.then((e=>{this.handleFlushResult(e,t)})).catch((e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")})):this.handleFlushResult(e,t)}}transmuxerError(t,e,r){this.hls&&(this.error=t,this.hls.trigger(n.ERROR,{type:i.MEDIA_ERROR,details:s.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:r}))}handleFlushResult(t,e){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):r&&r.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}function Zs(){return self.SourceBuffer||self.WebKitSourceBuffer}function Js(){if(!Z())return!1;const t=Zs();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}function tn(){if(!Js())return!1;const t=Z();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((e=>t.isTypeSupported(ae(e,"video"))))||["mp4a.40.2","fLaC"].some((e=>t.isTypeSupported(ae(e,"audio")))))}var en=0,rn=1,sn=2;class nn{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new m}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(t,e,r){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=r,this.loadInternal()}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(F(t,this.stats.retry,!0))this.retry(t);else{var e;j.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(t){const{context:e,stats:r}=this;this.retryDelay=O(t,r.retry),r.retry++,j.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${r.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout((()=>this.loadInternal()),this.retryDelay)}}class an{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let r;return t.length?(r=1===t.length?t[0]:function(t,e){const r=new Uint8Array(e);let i=0;for(let e=0;e<t.length;e++){const s=t[e];r.set(s,i),i+=s.length}return r}(t,e),this.reset(),r):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function on(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}const ln=/(\d+)-(\d+)\/(\d+)/;class dn extends nn{constructor(t){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=t.fetchSetup||hn}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:e,context:r,stats:i}=this;if(!e||!r)return;i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;const s=function(t,e){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(I({},t.headers))};t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return r}(r,this.controller.signal),n="arraybuffer"===r.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.request=this.fetchSetup(r,s),self.clearTimeout(this.requestTimeout),e.timeout=o&&t(o)?o:l,this.requestTimeout=self.setTimeout((()=>{this.loadtimeout()}),e.timeout);(js(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((s=>{var a;this.response=s;const o=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.loadtimeout()}),l-(o-i.loading.start)),!s.ok){const{status:t,statusText:e}=s;throw new un(e||"fetch, bad network response",t,s)}i.loading.first=o,i.total=function(e){const r=e.get("Content-Range");if(r){const e=function(t){const e=ln.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(r);if(t(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(s.headers)||i.total;const d=null==(a=this.callbacks)?void 0:a.onProgress;return d&&t(e.highWaterMark)?this.loadProgressively(s,i,r,e.highWaterMark,d):n?s.arrayBuffer():"json"===r.responseType?s.json():s.text()})).then((s=>{var n,o;const l=this.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const d=s[a];d&&(i.loaded=i.total=d);const h={url:l.url,data:s,code:l.status},u=null==(n=this.callbacks)?void 0:n.onProgress;u&&!t(e.highWaterMark)&&u(i,r,s,l),null==(o=this.callbacks)||o.onSuccess(h,i,r,l)})).catch((t=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const s=t&&t.code||0,n=t?t.message:null,a=e.loadPolicy.errorRetry;var o;F(a,i.retry,!1,{url:r.url,data:void 0,code:s})?this.retry(a):(j.error(`${s} while loading ${r.url}`),null==(o=this.callbacks)||o.onError({code:s,text:n},r,t?t.details:null,i))}))}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,r,i=0,s){const n=new an,a=t.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&s(e,r,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<i||n.dataLength?(n.push(l),n.dataLength>=i&&s(e,r,n.flush().buffer,t)):s(e,r,l.buffer,t),o()})).catch((()=>Promise.reject()));return o()}}function hn(t,e){return new self.Request(t.url,e)}class un extends Error{constructor(t,e,r){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=r}}const cn=/^age:\s*[\d.]+\s*$/im;class fn extends nn{constructor(t){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=t.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(this.loader===r&&!this.stats.aborted)return s.call(this,r,e.url,e)})).catch((t=>{if(this.loader===r&&!this.stats.aborted)return r.open("GET",e.url,!0),s.call(this,r,e.url,e)})).then((()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,e,t)})).catch((t=>{var s;null==(s=this.callbacks)||s.onError({code:r.status,text:t.message},e,r,i)})):this.openAndSendXhr(r,e,t)}openAndSendXhr(e,r,i){e.readyState||e.open("GET",r.url,!0);const s=r.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(const t in s)e.setRequestHeader(t,s[t]);r.rangeEnd&&e.setRequestHeader("Range",`bytes=${r.rangeStart}-${r.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=r.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&t(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:t,loader:e,stats:r}=this;if(!t||!e)return;const i=e.readyState,s=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const i=e.status,l="text"===e.responseType?e.responseText:null;if(i>=200&&i<300){const s=null!=l?l:e.response;if(null!=s){var n,a;r.loading.end=Math.max(self.performance.now(),r.loading.first);const o="arraybuffer"===e.responseType?s.byteLength:s.length;r.loaded=r.total=o,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(r,t,s,e);const d={url:e.responseURL,data:s,code:i};return t.rangeEnd&&o!==t.rangeEnd-t.rangeStart&&j.warn(`Payload length ${o} does not match requested Range: bytes=${t.rangeStart}-${t.rangeEnd-1}`),void(null==(a=this.callbacks)||a.onSuccess(d,r,t,e))}}const d=s.loadPolicy.errorRetry;var o;if(F(d,r.retry,!1,{url:t.url,data:void 0,code:i}))this.retry(d);else j.error(`${i} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:i,text:e.statusText},t,e,r)}}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&cn.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const gn={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},mn=_(_({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:fn,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:null,requireKeySystemAccessOnStart:!1,reuseKeySessions:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!1,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!1,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:gn},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:gn},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:class extends yi{constructor(e,r,i){super(e,r,i,"stream-controller",v.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=en,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,r=e?e.currentTime:null;if(null===r||!t(r))return;if(this.log(`Media seeked to ${r}`),!this.getBufferedFrag(r))return;const i=this.getFwdBufferInfoAtPos(e,r,v.MAIN,0);i&&0!==i.len?this.tick():this.log(`Main buffer empty at ${r} on "seeked" event: ${i?i.len:i}`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(n.MANIFEST_PARSED,this.onManifestParsed,this),t.on(n.LEVEL_LOADING,this.onLevelLoading,this),t.on(n.LEVEL_LOADED,this.onLevelLoaded,this),t.on(n.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(n.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(n.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(n.BUFFER_CREATED,this.onBufferCreated,this),t.on(n.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(n.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(n.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(n.MANIFEST_PARSED,this.onManifestParsed,this),t.off(n.LEVEL_LOADED,this.onLevelLoaded,this),t.off(n.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(n.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(n.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(n.BUFFER_CREATED,this.onBufferCreated,this),t.off(n.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(n.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(n.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:r,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=i.startLevel;-1===t&&(i.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=i.firstAutoLevel),i.nextLoadLevel=t,this.level=i.loadLevel,this._hasEnoughToStart=!!e}r>0&&-1===t&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${r}`),t=r),this.state=Ei.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,e||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=Ei.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Ei.WAITING_LEVEL:{const{levels:t,level:e}=this,r=null==t?void 0:t[e],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=Ei.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=Ei.IDLE;break}break}case Ei.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===Ei.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:r,media:i}=this;if(null===e||!i&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const s=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==r||!r[s])return;const a=r[s],o=this.getMainFwdBufferInfo();if(null===o)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)&&this.altAudio!==rn){const t={type:this.targetBufferType()};return this.hls.trigger(n.BUFFER_EOS,t),void(this.state=Ei.ENDED)}if(!this.buffering)return;t.loadLevel!==s&&-1===t.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=t.nextLoadLevel=s;const d=a.details;if(!d||this.state===Ei.WAITING_LEVEL||this.waitForLive(a))return this.level=s,this.state=Ei.WAITING_LEVEL,void(this.startFragRequested=!1);const h=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);const c=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(c,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&T(f)&&this.fragmentTracker.getState(f)!==Qr){var g;const t=(null!=(g=this.backtrackFragment)?g:f).sn-d.startSN,e=d.fragments[t-1];e&&f.cc===e.cc&&(f=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,c)){if(!f.gap){const t=this.audioOnly&&!this.altAudio?E.AUDIO:E.VIDEO,e=(t===E.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t)}f=this.getNextFragmentLoopLoading(f,d,o,v.MAIN,u)}f&&(this.exceedsMaxBuffer(o,u,f)||this.loadFragment(f,a,c))}loadFragment(t,e,r){const i=this.fragmentTracker.getState(t);i===qr||i===Xr?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):super.loadFragment(t,e,r):this.clearTrackerIfNeeded(t)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==en){var t;((null==(t=this.getLevelDetails())?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===sn?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const e=this.fragPlaying;if(e){const r=e.level;this.hls.trigger(n.FRAG_CHANGED,{frag:e,previousFrag:t}),(null==t?void 0:t.level)!==r&&this.hls.trigger(n.LEVEL_SWITCHED,{level:r})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(t){this._backtrackFragment=t}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(t){this._couldBacktrack=t}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.targetBufferType())}targetBufferType(){return this.altAudio!==sn||this.audioOnly?null:"video"}onMediaAttached(t,e){super.onMediaAttached(t,e);const r=e.media;Or(r,"playing",this.onMediaPlaying),Or(r,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:r}=this;r&&(Mr(r,"playing",this.onMediaPlaying),Mr(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(n.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=en,this.audioOnly=!1}onManifestParsed(t,e){let r=!1,i=!1;for(let t=0;t<e.levels.length;t++){const s=e.levels[t].audioCodec;s&&(r=r||-1!==s.indexOf("mp4a.40.2"),i=i||-1!==s.indexOf("mp4a.40.5"))}this.audioCodecSwitch=r&&i&&!function(){var t;const e=Zs();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:r}=this;if(!r||this.state!==Ei.IDLE)return;const i=e.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=Ei.WAITING_LEVEL)}onLevelLoaded(t,e){var r;const{levels:i,startFragRequested:s}=this,a=e.level,o=e.details,l=o.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${a}`);this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const d=e.levelInfo,h=this.fragCurrent;!h||this.state!==Ei.FRAG_LOADING&&this.state!==Ei.FRAG_LOADING_WAITING_RETRY||h.level!==e.level&&h.loader&&this.abortCurrentFrag();let u=0;if(o.live||null!=(r=d.details)&&r.live){var c;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,d.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(d.details=o,this.levelLastLoaded=d,s||this.setStartPosition(o,u),this.hls.trigger(n.LEVEL_UPDATED,{details:o,level:a}),this.state===Ei.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=Ei.IDLE}s&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some(((t,e)=>{if(e>=o.startCC)return!0;delete this.initPTS[e]})),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:r}=this;if(!r)return;const i=this.hls.liveSyncPosition,s=this.playhead,n=t.fragmentStart,a=t.edge,o=s>=n-e.maxFragLookUpTolerance&&s<=a;if(null!==i&&r.duration>i&&(s<i||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&r.readyState<4||s<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),r.readyState))if(this.warn(`Playback: ${s} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i}`),"buffered"===this.config.liveSyncMode){var l;const t=wr.bufferInfo(r,i,0);if(null==(l=t.buffered)||!l.length)return void(r.currentTime=i);if(t.start<=s)return void(r.currentTime=i);const{nextStart:e}=wr.bufferedInfo(t.buffered,s,0);e&&(r.currentTime=e)}else r.currentTime=i}}_handleFragmentLoadProgress(t){var e;const r=t.frag,{part:i,payload:s}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);const a=n[r.level];if(!a)return void this.warn(`Level ${r.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),void this.fragmentTracker.removeFragment(r);const l=a.videoCodec,d=o.PTSKnown||!o.live,h=null==(e=r.initSegment)?void 0:e.data,u=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Qs(this.hls,v.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,{decryptRange:m,byteRange:p}=di(r,i,this.iframesOnly),E=new fi(r.level,r.sn,r.stats.chunkCount,p?p.end-p.start:s.byteLength,f,g,r.duration,this.iframesOnly,m),y=this.initPTS[r.cc];c.push(s,h,u,l,r,i,o.totalduration,d,E,y)}onAudioTrackSwitching(t,e){const r=this.hls,i=this.altAudio!==en;if(Ie(e.url,r))this.altAudio=rn;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i)return this.altAudio=en,this.fragmentTracker.removeAllFragments(),r.once(n.BUFFER_FLUSHED,(()=>{this.hls&&this.hls.trigger(n.AUDIO_TRACK_SWITCHED,e)})),void r.trigger(n.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(n.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const r=Ie(e.url,this.hls);if(r){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=r?sn:en,this.tick()}onBufferCreated(t,e){const r=e.tracks;let i,s,n=!1;for(const t in r){const e=r[t];if("main"===e.id){if(s=t,i=e,"video"===t){const e=r[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:r,part:i}=e,s=r.type===v.MAIN;if(s){if(this.fragContextChanged(r))return this.warn(`Fragment ${r.sn}${i?" p: "+i.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Ei.PARSED&&(this.state=Ei.IDLE));let t=!1;if(T(r)&&(t=!!r.gap&&!r.tagList.some((t=>"GAP"===t[0]))),this.fragBufferedComplete(r,i),t){var n;r.stats.retry++;const t=null==(n=this.levels)?void 0:n[r.level];t&&t.fragmentError++}}const a=this.media;a&&(!this._hasEnoughToStart&&wr.getBuffered(a).length&&(this.seekToStartPos(),this._hasEnoughToStart=!0),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var r;if(e.fatal)this.state=Ei.ERROR;else switch(e.details){case s.FRAG_GAP:case s.FRAG_PARSING_ERROR:case s.FRAG_DECRYPT_ERROR:case s.FRAG_LOAD_ERROR:case s.FRAG_LOAD_TIMEOUT:case s.KEY_LOAD_ERROR:case s.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(v.MAIN,e);break;case s.LEVEL_LOAD_ERROR:case s.LEVEL_LOAD_TIMEOUT:case s.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ei.WAITING_LEVEL||(null==(r=e.context)?void 0:r.type)!==p.LEVEL||(this.state=Ei.IDLE);break;case s.BUFFER_APPEND_NO_PROGRESS:if("main"!==e.parent)return;e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${e.frag.sn} of level ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag));break;case s.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(v.MAIN,e);break;case s.BUFFER_ADD_CODEC_ERROR:case s.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case s.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case s.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=Ei.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==E.AUDIO||!this.altAudio){const t=(e===E.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let r=this.startPosition;if(r>=0&&e<r){if(t.seeking)return void this.log(`could not seek to ${r}, already seeking at ${e}`);const i=this.timelineOffset;i&&r&&(r+=i);const s=this.getLevelDetails(),n=wr.getBuffered(t),a=n.length?n.start(0):0,o=a-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==s?void 0:s.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),r+=o,this.startPosition=r),e<r&&(this.log(`seek to target start position ${r} from current time ${e} buffer start ${a}`),t.currentTime=r)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then((t=>{const{hls:r}=this,i=null==t?void 0:t.frag;if(!i||this.fragContextChanged(i))return;e.fragmentError=0,this.state=Ei.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const s=i.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),r.trigger(n.FRAG_LOADED,t),i.bitrateTest=!1})).catch((e=>{this.state!==Ei.STOPPED&&this.state!==Ei.ERROR&&(this.warn(e),this.resetFragmentLoading(t))}))}_handleTransmuxComplete(e){const r=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o)return void this.resetWhenMissingContext(a);const{frag:l,part:d,level:h}=o,{video:u,text:c,id3:f,initSegment:g}=s,{details:m}=h,p=this.altAudio?void 0:s.audio;if(this.fragContextChanged(l))this.fragmentTracker.removeFragment(l);else{if(this.state=Ei.PARSING,g){const e=g.tracks;if(e){const t=l.initSegment||l;if(this.unhandledEncryptionError(g,l))return;this._bufferInitSegment(h,e,t,a),i.trigger(n.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:r,tracks:e})}const s=g.initPTS,o=g.timescale,d=this.initPTS[l.cc];if(t(s)&&(!d||d.baseTime!==s||d.timescale!==o)){const t=g.trackId;this.initPTS[l.cc]={baseTime:s,timescale:o,trackId:t};const e=this.initPTS.slice(0);i.trigger(n.INIT_PTS_FOUND,{timestampOffsets:e,frag:l,id:r,initPTS:s,timescale:o,trackId:t})}}if(u&&m){p&&"audiovideo"===u.type&&this.logMuxedErr(l);const t=m.fragments[l.sn-1-m.startSN],e=l.sn===m.startSN,r=!t||l.cc>t.cc;if(!1!==s.independent){const{startPTS:t,endPTS:i,startDTS:s,endDTS:n}=u;if(d)d.elementaryStreams[u.type]={startPTS:t,endPTS:i,startDTS:s,endDTS:n};else if(u.firstKeyFrame&&u.independent&&1===a.id&&!r&&(this.couldBacktrack=!0),u.dropped&&u.independent){const s=this.getMainFwdBufferInfo(),a=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,o=u.firstKeyFramePTS?u.firstKeyFramePTS:t;if(!e&&a<o-this.config.maxBufferHole&&!r)return void this.backtrack(l);r&&(l.gap=!0),l.setElementaryStreamInfo(u.type,l.start,i,l.start,n,!0)}else e&&t-(m.appliedTimelineOffset||0)>2&&(l.gap=!0);l.setElementaryStreamInfo(u.type,t,i,s,n),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(u,l,d,a,e||r)}else{if(!e&&!r)return void this.backtrack(l);l.gap=!0}}if(p){const{startPTS:t,endPTS:e,startDTS:r,endDTS:i}=p;d&&(d.elementaryStreams[E.AUDIO]={startPTS:t,endPTS:e,startDTS:r,endDTS:i}),l.setElementaryStreamInfo(E.AUDIO,t,e,r,i),this.bufferFragmentData(p,l,d,a)}if(m&&null!=f&&f.samples.length){const t={id:r,frag:l,details:m,samples:f.samples};i.trigger(n.FRAG_PARSING_METADATA,t)}if(m&&c){const t={id:r,frag:l,details:m,samples:c.samples};i.trigger(n.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${T(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,r,i){if(this.state!==Ei.PARSING)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(r));const{audio:s,video:a,audiovideo:o}=e;if(s){const r=t.audioCodec;let i=ce(s.codec,r);if("mp4a"===i&&(i="mp4a.40.5"),this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=s.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&!function(){if(void 0===Zt){const t=Xt.match(/Firefox\/(\d+)/i);Zt=t?parseInt(t[1]):0}return Zt}()&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&/Android/.test(Xt)&&"audio/mpeg"!==s.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),r&&r!==i&&this.log(`Swapping manifest audio codec "${r}" for "${i}"`),s.levelCodec=i,s.id=v.MAIN,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${i||""}/${r||""}/${s.codec}]`),delete e.audiovideo}if(a){a.levelCodec=t.videoCodec,a.id=v.MAIN;const r=a.codec;if(4===(null==r?void 0:r.length))switch(r){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e"}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${t.videoCodec||""}/${r}]${a.codec!==r?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete e.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(r),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete e.video,delete e.audio);const l=Object.keys(e);if(l.length){if(this.hls.trigger(n.BUFFER_CODECS,e),!this.hls)return;l.forEach((t=>{const s=e[t].initSegment;null!=s&&s.byteLength&&this.hls.trigger(n.BUFFER_APPENDING,{type:t,data:s,frag:r,part:null,chunkMeta:i,parent:r.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.getBufferOutput();return this.getFwdBufferInfo(t,v.MAIN)}get maxBufferLength(){const{levels:t,level:e}=this,r=null==t?void 0:t[e];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=Ei.IDLE}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const r=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return t(r)?this.getAppendedFrag(r):null}get currentProgramDateTime(){var e;const r=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(t(r)){const t=this.getLevelDetails(),e=this.currentFrag||(t?Ce(null,t.fragments,r):null);if(e){const t=e.programDateTime;if(null!==t){const i=t+1e3*(r-e.start);return new Date(i)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}},abrController:ke,bufferController:Gr,capLevelController:Ti,errorController:Me,fpsController:Ri,id3TrackController:class{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(n.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(n.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(n.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(n.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(n.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(n.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(n.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(n.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(n.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(n.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(n.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(n.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(n.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(n.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(n.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){this.media=e.media}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){return function(t,e,r,i="",s="disabled"){const n=t.ownerDocument.createElement("track");return n.kind=e,n.label=r,i&&(n.srclang=i),n.src="data:,WEBVTT",n.track.mode=s,t.appendChild(n),n}(t,"metadata","id3","","hidden")}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:r,enableID3MetadataCues:i}=this.hls.config;if(!r&&!i)return;const{samples:s}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Mi();if(n)for(let t=0;t<s.length;t++){const e=s[t].type;if(e===wi.emsg&&!r||!i)continue;const a=pt(s[t].data),o=s[t].pts;let l=o+s[t].duration;l>Ni&&(l=Ni);l-o<=0&&(l=o+.25);for(let t=0;t<a.length;t++){const r=a[t];if(!vt(r)){this.updateId3CueEnds(o,e);const t=Fi(n,o,l,r,e);t&&this.id3Track.track.addCue(t)}}}}updateId3CueEnds(t,e){var r;const i=null==(r=this.id3Track)?void 0:r.track.cues;if(i)for(let r=i.length;r--;){const s=i[r];s.type===e&&s.startTime<t&&s.endTime===Ni&&(s.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:r,type:i}){const{id3Track:s,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(s&&(a||o)){let t;t="audio"===i?t=>t.type===wi.audioId3&&o:"video"===i?t=>t.type===wi.emsg&&a:t=>t.type===wi.audioId3&&o||t.type===wi.emsg&&a,Oi(s.track,e,r,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(e,r){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=Mi();if(!e.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:d}=e,h=Object.keys(d);let u=this.dateRangeCuesAppended;var c;if(l&&r)if(null!=(c=l.track.cues)&&c.length){const t=Object.keys(u).filter((t=>-1===h.indexOf(t)));for(let e=t.length;e--;){var f;const r=t[e],i=null==(f=u[r])?void 0:f.cues;delete u[r],i&&Object.keys(i).forEach((t=>{const e=i[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(e)}catch(t){}}}))}}else u=this.dateRangeCuesAppended={};const g=e.fragments[e.fragments.length-1];if(0!==h.length&&t(null==g?void 0:g.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<h.length;t++){const e=h[t],r=d[e],i=r.startTime,s=u[e],n=(null==s?void 0:s.cues)||{};let a=(null==s?void 0:s.durationKnown)||!1,l=Ni;const{duration:c,endDate:f}=r;if(f&&null!==c)l=i+c,a=!0;else if(r.endOnNext&&!a){const t=h.reduce(((t,e)=>{if(e!==r.id){const i=d[e];if(i.class===r.class&&i.startDate>r.startDate&&(!t||r.startDate<t.startDate))return i}return t}),null);t&&(l=t.startTime,a=!0)}const g=Object.keys(r.attr);for(let t=0;t<g.length;t++){const d=g[t];if("ID"===(m=d)||"CLASS"===m||"CUE"===m||"START-DATE"===m||"DURATION"===m||"END-DATE"===m||"END-ON-NEXT"===m)continue;const h=n[d];if(h)!a||null!=s&&s.durationKnown?Math.abs(h.startTime-i)>.01&&(h.startTime=i,h.endTime=l):h.endTime=l;else if(o){let t=r.attr[d];Ve(d)&&(t=St(t));const s=Fi(o,i,l,{key:d,data:t},wi.dateRange);s&&(s.id=e,this.id3Track.track.addCue(s),n[d]=s)}}u[e]={cues:n,dateRange:r,durationKnown:a}}var m}}},gapController:class extends ci{constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(n.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(n.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(n.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(n.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(n.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(n.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(n.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const r=this.media=e.media;Or(r,"playing",this.onMediaPlaying),Or(r,"waiting",this.onMediaWaiting),Or(r,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:r}=this;r&&(Mr(r,"playing",this.onMediaPlaying),Mr(r,"waiting",this.onMediaWaiting),Mr(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var t;const e=(null==(t=this.hls)?void 0:t.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,e):e}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.getCurrentTime();this.media.currentTime<e||(this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e)}poll(t,e){var r,i;const s=null==(r=this.hls)?void 0:r.config;if(!s)return;const a=this.media;if(!a)return;const{seeking:o}=a,l=this.seeking&&!o,d=!this.seeking&&o,h=a.paused&&!o||a.ended||0===a.playbackRate;if(this.seeking=o,t!==e)return e&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,s.nudgeOnVideoHole&&!h&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(d||l)return void(l&&this.stallResolved(t));if(h)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&a.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(n.MEDIA_ENDED,{stalled:!1})));if(!wr.getBuffered(a).length)return void(this.skipRetry=this.nudgeRetry=0);const u=wr.bufferInfo(a,t,0),c=this.fragmentTracker;c&&this.hls&&xi(u,t,c,this.hls);const f=u.nextStart||0;if(o&&c&&this.hls){const e=_i(this.hls.inFlightFragments,t),r=u.len>2,i=!f||e||f-t>2&&!c.getPartialFragment(t);if(r||i)return;this.moved=!1}const g=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&c){if(!(u.len>0)&&!f)return;const e=Math.max(f,u.start||0)-t,r=!(null==g||!g.live)?2*g.targetduration:2,i=Pi(t,c);if(e>0&&(e<=r||i))return void(a.paused||this._trySkipBufferHole(i))}const m=s.detectStallWithCurrentTimeMs,p=self.performance.now(),v=this.waiting;let E=this.stalled;if(null===E){if(!(v>0&&p-v<m))return void(this.stalled=p);E=this.stalled=v}const y=p-E;if(!o&&(y>=m||v&&this.moved)&&this.hls){var T;if("ended"===(null==(T=this.mediaSource)?void 0:T.readyState)&&(null==g||!g.live)&&Math.abs(t-((null==g?void 0:g.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(n.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(u),!this.media||!this.hls)return;if(a.currentTime!==t){const e=t;return t=a.currentTime,this.moved=!0,void this.log(`currentTime changed ${e} > ${t}`)}}const S=wr.bufferInfo(a,t,s.maxBufferHole);this._tryFixBufferStall(S,y,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(n.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var r;const a=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&a&&a.length>1&&t>a.end(0)){const r=wr.bufferedInfo(wr.timeRangesToArray(this.buffered.audio),t,0);if(r.len>1&&e>=r.start){const r=wr.timeRangesToArray(a),o=wr.bufferedInfo(r,e,0).bufferedIndex;if(o>-1&&o<r.length-1){const e=wr.bufferedInfo(r,t,0).bufferedIndex,a=r[o].end,l=r[o+1].start;if((-1===e||e>o)&&l-a<1&&t-a<2){const r=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${a} -> ${l} buffered index: ${e}`);this.warn(r.message),this.media.currentTime+=1e-6;let o=Pi(t,this.fragmentTracker);o&&"fragment"in o?o=o.fragment:o||(o=void 0);const d=wr.bufferInfo(this.media,t,0);this.hls.trigger(n.ERROR,{type:i.MEDIA_ERROR,details:s.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:r,reason:r.message,frag:o,buffer:d.len,bufferInfo:d})}}}}}_tryFixBufferStall(t,e,r){var i,s;const{fragmentTracker:n,media:a}=this,o=null==(i=this.hls)?void 0:i.config;if(!a||!n||!o)return;const l=null==(s=this.hls)?void 0:s.latestLevelDetails,d=Pi(r,n);if(d||null!=l&&l.live&&r<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const h=t.buffered,u=this.adjacentTraversal(t,r);(h&&h.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-r<o.maxBufferHole||u))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const r=this.fragmentTracker,i=t.nextStart;if(r&&i){const t=r.getFragAtPos(e,v.MAIN),s=r.getFragAtPos(i,v.MAIN);if(t&&s)return s.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:r,stallReported:a,stalled:o}=this;if(!a&&null!==o&&r&&e){this.stallReported=!0;const a=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${Re(t)})`);this.warn(a.message),e.trigger(n.ERROR,{type:i.MEDIA_ERROR,details:s.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:t.len,bufferInfo:t,stalled:{start:o}})}}_trySkipBufferHole(t){const{fragmentTracker:e,media:r,hls:a}=this,o=null==a?void 0:a.config;if(!r||!e||!o)return 0;const l=r.currentTime,d=wr.bufferInfo(r,l,0);xi(d,l,e,a);const h=l<d.start?d.start:d.nextStart;if(h){const c=d.len<=o.maxBufferHole,f=d.len>0&&d.len<1&&r.readyState<3,g=h-l;if(g>0&&(c||f)){if(g>o.maxBufferHole){let r=!1;if(0===l){const t=e.getAppendedFrag(0,v.MAIN);t&&h<t.end&&(r=!0)}if(!r&&t){var u;if(null==(u=a.loadLevelObj)||!u.details)return 0;if(_i(a.inFlightFragments,h))return 0;let r=!1,i=t.end;for(;i<h;){const t=Pi(i,e),s=t?t.duration:0;if(!(s>0)){r=!0;break}i+=s}if(r)return 0}}const{nudgeMaxRetry:c,skipBufferHolePadding:f}=o,m=++this.skipRetry>c,p=Math.max(h,l)+f;if(m||(this.warn(`skipping hole, adjusting currentTime from ${l} to ${p}`),this.moved=!0,r.currentTime=p),null==t||!t.gap||m){const e=new Error(m?`Playhead still not moving after seeking over buffer hole from ${l} to ${p} after ${o.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${l} to ${p}`),r={type:i.MEDIA_ERROR,details:s.BUFFER_SEEK_OVER_HOLE,fatal:m,error:e,reason:e.message,buffer:d.len,bufferInfo:d};t&&("fragment"in t?r.part=t:r.frag=t),a.trigger(n.ERROR,r)}return p}}return 0}_tryNudgeBuffer(t){const{hls:e,media:r,nudgeRetry:a}=this,o=null==e?void 0:e.config;if(!r||!o)return 0;const l=r.currentTime;if(this.nudgeRetry++,a<o.nudgeMaxRetry){const d=l+(a+1)*o.nudgeOffset,h=new Error(`Nudging 'currentTime' from ${l} to ${d}`);this.warn(h.message),r.currentTime=d,e.trigger(n.ERROR,{type:i.MEDIA_ERROR,details:s.BUFFER_NUDGE_ON_STALL,error:h,fatal:!1,buffer:t.len,bufferInfo:t})}else{const r=new Error(`Playhead still not moving while enough data buffered @${l} after ${o.nudgeMaxRetry} nudges`);this.error(r.message),e.trigger(n.ERROR,{type:i.MEDIA_ERROR,details:s.BUFFER_STALLED_ERROR,error:r,fatal:!0,buffer:t.len,bufferInfo:t})}}},latencyController:class{constructor(t){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,e=this.levelDetails;if(!t||!e||!this.hls)return;this.currentTime=t.currentTime;const r=this.hls.config,i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:n}=r;if(!s||1===n||!e.live)return;const a=this.targetLatency;if(null===a)return;const o=i-a;if(o<Math.min(this.maxLatency,a+e.targetduration)&&o>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,n)),r=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20,i=Math.min(e,Math.max(1,r));this.changeMediaPlaybackRate(t,i)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var t;const e=null==(t=this.hls)?void 0:t.config;if(!e)return 0;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const r=this.levelDetails;return r?e.liveMaxLatencyDurationCount*r.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||!this.hls)return null;const e=this.hls.config,{holdBack:r,partHoldBack:i,targetduration:s}=t,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=e,l=this.hls.userConfig;let d=o&&i||r;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===d)&&(d=void 0!==n?n:a*s);const h=s;return d+Math.min(this.stallCount*e.liveSyncOnStallIncrease,h)}set targetLatency(t){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=t,this._targetLatencyUpdated=!0)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e||!this.hls)return null;const r=this.levelDetails;if(null===r)return null;const i=r.edge,s=t-e-this.edgeStalled,n=i-r.totalduration,a=i-(this.hls.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(n,s),a)}get drift(){const t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t||!this.hls)return 0;const e=3*(this.hls.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;const r=t.buffered.length;return(r?t.buffered.end(r-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(n.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(n.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(n.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(n.ERROR,this.onError,this),t.on(n.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(n.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(n.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(n.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(n.ERROR,this.onError,this),t.off(n.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(t,e){var r;const i=this.hls,s=this.media||e.event.appendInPlace&&(null==i||null==(r=i.interstitialsManager)?void 0:r.playerQueue.reduce(((t,e)=>t||e.media),null));i&&s&&s.playbackRate>1&&s.playbackRate<=i.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(s,1)}onError(t,e){var r;e.details===s.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var r,i;t.playbackRate!==e&&(null==(r=this.hls)||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}},{cueHandler:Q,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0,cmcdController:void 0,contentSteeringController:Si,iframeController:void 0,interstitialsController:void 0});function pn(t,e,r){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(void 0!==e.liveMaxUnchangedPlaylistRefresh){const t=e.liveMaxUnchangedPlaylistRefresh,a=(i=t,s=2,n=1/0,Math.max(s,Math.min(i,n)));a!==t&&r.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${t} to ${a}.`),e.liveMaxUnchangedPlaylistRefresh=a}var i,s,n;const a=vn(t),o=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const i=`${"level"===t?"playlist":t}LoadPolicy`,s=void 0===e[i],n=[];o.forEach((r=>{const o=`${t}Loading${r}`,l=e[o];if(void 0!==l&&s){n.push(o);const t=a[i].default;switch(e[i]={default:t},r){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}})),n.length&&r.warn(`hls.js config: "${n.join('", "')}" setting(s) are deprecated, use "${i}": ${Re(e[i])}`)})),_(_({},a),e)}function vn(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(vn):Object.keys(t).reduce(((e,r)=>(e[r]=vn(t[r]),e)),{}):t}class En extends Cr{constructor(t,e){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(n.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(n.LEVEL_LOADED,this.onLevelLoaded,this),t.on(n.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(n.FRAG_BUFFERED,this.onFragBuffered,this),t.on(n.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(n.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(n.LEVEL_LOADED,this.onLevelLoaded,this),t.off(n.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(n.FRAG_BUFFERED,this.onFragBuffered,this),t.off(n.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((t=>{t.loadError=0,t.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const r=this.hls.config.preferManagedMediaSource,i=[],s={},n={};let a=!1,o=!1,l=!1,d=!1;e.levels.forEach((t=>{const e=t.attrs,h=Sn(t,r),{audioCodec:u,videoCodec:c,imageCodec:f,width:g,height:m}=t;if(!h)return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);a||(a=!(!g||!m)),o||(o=!!c),l||(l=!!u),d||(d=!!f);const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":E,"PATHWAY-ID":y,RESOLUTION:T,"VIDEO-RANGE":S}=e,L=`${`${y||"."}-`}${t.bitrate}-${T}-${v}-${p}-${S}-${E}`;if(s[L])if(s[L].uri===t.url||t.attrs["PATHWAY-ID"])t.iframes||(s[L].addGroupId("audio",e.AUDIO),s[L].addGroupId("text",e.SUBTITLES));else{const e=n[L]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const r=this.createLevel(t);s[L]=r,i.push(r)}else{const e=this.createLevel(t);s[L]=e,n[L]=1,i.push(e)}})),this.filterAndSortMediaOptions(i,e,a,o,l,d)}createLevel(t){const e=new Se(t),r=t.supplemental;if(null!=r&&r.videoCodec&&!Tn(r.videoCodec,this.hls.config.preferManagedMediaSource)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(t.message),e.supportedResult=X.getUnsupportedResult(t,[])}return e}filterAndSortMediaOptions(t,e,r,a,o,l){var d;let h=[],u=[],c=t;const f=(null==(d=e.stats)?void 0:d.parsing)||{},g=this.hls.config.preferManagedMediaSource;if((r||a)&&o&&(c=c.filter((({videoCodec:t,videoRange:e,width:r,height:i})=>{return(!!t||!(!r||!i))&&(!!(s=e)&&ve.indexOf(s)>-1);var s}))),a&&l&&(c=c.filter((t=>!t.imageCodec))),0===c.length)return Promise.resolve().then((()=>{if(this.hls){let t="no level with compatible codecs found in manifest",r=t;e.levels.length&&(r=`one or more CODECS in variant not supported: ${Re(e.levels.map((t=>t.attrs.CODECS)).filter(((t,e,r)=>r.indexOf(t)===e)))}`,this.warn(r),t+=` (${r})`);const a=new Error(t);this.hls.trigger(n.ERROR,{type:i.MEDIA_ERROR,details:s.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:a,reason:r})}})),void(f.end=performance.now());e.audioTracks&&(h=e.audioTracks.filter((t=>!t.audioCodec||yn(t.audioCodec,g))),Ln(h)),e.subtitles&&(u=e.subtitles,Ln(u));const m=c.slice(0);c.sort(((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return ve.indexOf(t.videoRange)-ve.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const r=oe(t.videoCodec),i=oe(e.videoCodec);if(r!==i)return i-r}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const r=le(t.codecSet),i=le(e.codecSet);if(r!==i)return i-r}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));let p=m[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==m.length))for(let t=0;t<m.length;t++)if(m[t].pathwayId===c[0].pathwayId){p=m[t];break}this._levels=c;for(let t=0;t<c.length;t++)if(c[t]===p){var v;this._firstLevel=t;const e=p.bitrate,r=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${e}`),void 0===(null==(v=this.hls.userConfig)?void 0:v.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>r&&r===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const E=e.iframeVariants.filter((t=>Sn(t,g)));this._iframeVariants=E;const y=o&&!a,T=this.hls.config,S=!(!T.audioStreamController||!T.audioTrackController),L={levels:c,audioTracks:h,subtitleTracks:u,iframeVariants:E,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:o,video:a,altAudio:S&&!y&&h.some((t=>!!t.url))};f.end=performance.now(),this.hls.trigger(n.MANIFEST_PARSED,L)}get iframeVariants(){return 0===this._iframeVariants.length?null:this._iframeVariants}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const r=new Error("invalid level idx"),a=t<0;if(this.hls.trigger(n.ERROR,{type:i.OTHER_ERROR,details:s.LEVEL_SWITCH_ERROR,level:t,fatal:a,error:r,reason:r.message}),a)return;t=Math.min(t,e.length-1)}const r=this.currentLevelIndex,a=this.currentLevel,o=a?a.attrs["PATHWAY-ID"]:void 0,l=e[t],d=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,r===t&&a&&o===d)return;this.log(`Switching to level ${t} (${l.height?l.height+"p ":""}${l.videoRange?l.videoRange+" ":""}${l.codecSet?l.codecSet+" ":""}@${l.bitrate})${d?" with Pathway "+d:""} from level ${r}${o?" with Pathway "+o:""}`);const h={level:t,attrs:l.attrs,details:l.details,bitrate:l.bitrate,averageBitrate:l.averageBitrate,maxBitrate:l.maxBitrate,realBitrate:l.realBitrate,width:l.width,height:l.height,codecSet:l.codecSet,audioCodec:l.audioCodec,videoCodec:l.videoCodec,audioGroups:l.audioGroups,subtitleGroups:l.subtitleGroups,loaded:l.loaded,loadError:l.loadError,fragmentError:l.fragmentError,name:l.name,id:l.id,uri:l.uri,url:l.url,urlId:0,audioGroupIds:l.audioGroupIds,textGroupIds:l.textGroupIds};this.hls.trigger(n.LEVEL_SWITCHING,h);const u=l.details;if(!u||u.live){const t=this.switchParams(l.uri,null==a?void 0:a.details,u);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),r=t.filter((t=>-1!==e.indexOf(t)));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=r}}onError(t,e){!e.fatal&&e.context&&e.context.type===p.LEVEL&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(e.type===v.MAIN){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return;const r=this._levels[e.level];null!=r&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(t,e){var r;const{level:i,details:s}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(i,e,t)}else null!=(r=e.deliveryDirectives)&&r.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const r=this.getUrlWithDirectives(t.uri,e),i=this.currentLevelIndex,s=t.attrs["PATHWAY-ID"],a=t.details,o=null==a?void 0:a.age;this.log(`Loading level index ${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${s?" Pathway "+s:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(n.LEVEL_LOADING,{url:r,level:i,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){const e=this.currentLevelIndex;if(-1===this.manualLevelIndex&&t!==e&&-1!==t){const r=this.hls.config.abrSwitchInterval;if(r>0){const i=performance.now(),s=i-this.lastABRSwitchTime,n=1e3*r;if(this.lastABRSwitchTime>-1&&s<n)return void this.warn(`Preventing ABR level switch: ${e} -> ${t} (${Math.round(s)}ms < ${n}ms / ${r}s)`);this.lastABRSwitchTime=i,this.log(`Allowing ABR level switch: ${e} -> ${t} (${Math.round(s)}ms >= ${n}ms / ${r}s)`)}}this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const r=this._levels.filter(((e,r)=>r!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach((t=>t.level=-1))),!1)));Ir(r),this._levels=r,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=r.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(n.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(n.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function yn(t,e){return se(t,"audio",e)}function Tn(t,e){return se(t,"video",e)}function Sn(t,e){let{audioCodec:r,videoCodec:i}=t;r&&(t.audioCodec=r=ue(r,e)||void 0),i&&(i=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const r=e[t].split(".");r.length>2&&"avc1"===r[0]&&(e[t]=`avc1.${parseInt(r[1]).toString(16)}${("000"+parseInt(r[2]).toString(16)).slice(-4)}`)}return e.join(",")}(i));const{unknownCodecs:s}=t;return!((null==s?void 0:s.length)||0||r&&!yn(r,e)||i&&!Tn(i,e))}function Ln(t){const e={};t.forEach((t=>{const r=t.groupId||"";t.id=e[r]=e[r]||0,e[r]++}))}class An extends G{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=t}abort(t){for(const r in this.keyLoaderInfo){const i=this.keyLoaderInfo[r].loader;if(i){var e;if(t&&t!==(null==(e=i.context)?void 0:e.frag.type))return;i.abort()}}}destroy(){for(const t in this.keyLoaderInfo){const e=this.keyLoaderInfo[t].loader;e&&e.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(t,e,r){return this.emeController?this.emeController.loadClear(t,e,r):null}load(t,e){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then((r=>this.loadInternal(t,e,r))):this.loadInternal(t,e)}loadInternal(t,e,r){const i=t.decryptdata;if(!i){const e=new Error(r?`Expected frag.decryptdata to be defined after setting format ${r}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Rn(t,s.KEY_LOAD_ERROR,e))}const n=t;switch(i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===i.keyFormat?this.loadKeyHTTP(n):e?e.then((()=>this.loadKeyEME(n))):this.loadKeyEME(n);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(n);default:return Promise.reject(Rn(t,s.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t){if(this.emeController&&this.config.emeEnabled){var e;if(!t.decryptdata.keyId&&null!=(e=t.initSegment)&&e.data){const e=function(t){const e=[];return Gt(t,(t=>e.push(t.subarray(8,24)))),e}(t.initSegment.data);if(e.length){let r=e[0];const i=t.decryptdata.uri;if(r.some((t=>0!==t)))this.log(`Using keyId found in init segment ${Tt(r)} keyUri: ${i}`),Ze.setKeyIdForUri(i,r);else{const t=Ze.addKeyIdForUri(i);this.log(`Patching empty keyId with ${Tt(t)} keyUri: ${i}`),r=t}t.decryptdata.keyId=r}}return this.emeController.loadKey(t).then((()=>({frag:t,keyInfo:{decryptdata:t.decryptdata}})))}return Promise.reject(Rn(t,s.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(t){const e=t.decryptdata,r=e.uri;if(!r)return Promise.reject(Rn(t,s.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${r}"`)));const i=this.keyLoaderInfo[r];if(i){if(i.decryptdata.key)return e.key=i.decryptdata.key,i.keyLoadPromise=null,Promise.resolve({frag:t,keyInfo:i});if(i.keyLoadPromise)return i.keyLoadPromise.then((r=>(e.key=i.decryptdata.key,_(_({},r),{},{frag:t}))))}this.log(`Loading${e.keyId?" keyId: "+Tt(e.keyId):""} URI: ${e.uri} from ${t.type} ${t.level}`);const n=this.config,a=new(0,n.loader)(n);t.keyLoader=a;const o=this.keyLoaderInfo[r]={decryptdata:e,keyLoadPromise:null,loader:a};return o.keyLoadPromise=new Promise(((e,i)=>{const l={type:p.KEY,keyInfo:o,frag:t,responseType:"arraybuffer",url:r},d=n.keyLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(t,r,n,a)=>{const{frag:o,keyInfo:l,url:d}=n;if(!o.decryptdata||l!==this.keyLoaderInfo[d])return this.resetLoader(n),i(Rn(o,s.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),a));l.decryptdata.key=o.decryptdata.key=new Uint8Array(t.data),o.keyLoader=l.loader=l.keyLoadPromise=null,e({frag:o,keyInfo:l})},onError:(e,n,a,o)=>{this.resetLoader(n),i(Rn(t,s.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),a,_({url:r,data:void 0},e)))},onTimeout:(e,r,n)=>{this.resetLoader(r),i(Rn(t,s.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:(e,r,n)=>{this.resetLoader(r),i(Rn(t,s.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};a.load(l,h,u)}))}resetLoader(t){const{frag:e,keyInfo:r,url:i}=t,s=r.loader;e.keyLoader===s&&(e.keyLoader=r.loader=r.keyLoadPromise=null),delete this.keyLoaderInfo[i],s&&s.destroy()}}function Rn(t,e=s.KEY_LOAD_ERROR,r,n,a){return new ui({type:i.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:a,error:r,networkDetails:n||null})}function bn(t){const{type:e}=t;switch(e){case p.AUDIO_TRACK:return v.AUDIO;case p.SUBTITLE_TRACK:return v.SUBTITLE;default:return v.MAIN}}function Dn(t,e){let r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r}class In{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(n.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.LEVEL_LOADING,this.onLevelLoading,this),t.on(n.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(n.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(n.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(n.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.LEVEL_LOADING,this.onLevelLoading,this),t.off(n.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(n.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(n.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,r=e.pLoader,i=e.loader,s=new(r||i)(e);return this.loaders[t.type]=s,s}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:r}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:p.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:r,level:i,pathwayId:s,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:r,level:i,pathwayId:s,responseType:"text",type:p.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:r,groupId:i,url:s,deliveryDirectives:n,track:a}=e;this.load({id:r,groupId:i,level:null,responseType:"text",type:p.AUDIO_TRACK,url:s,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:r,groupId:i,url:s,deliveryDirectives:n,track:a}=e;this.load({id:r,groupId:i,level:null,responseType:"text",type:p.SUBTITLE_TRACK,url:s,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const r=this.loaders[p.LEVEL];if(r){const t=r.context;t&&!e.levels.some((e=>e===t.levelOrTrack))&&(r.abort(),delete this.loaders[p.LEVEL])}}load(e){var r;const i=this.hls.config;let s,n=this.getInternalLoader(e);if(n){const t=this.hls.logger,r=n.context;if((null==r?void 0:r.levelOrTrack)===e.levelOrTrack&&(r.url===e.url||r.deliveryDirectives&&!e.deliveryDirectives))return void(r.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${r.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}if(s=e.type===p.MANIFEST?i.manifestLoadPolicy.default:I({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),t(null==(r=e.deliveryDirectives)?void 0:r.part)){let t;if(e.type===p.LEVEL&&null!==e.level?t=this.hls.levels[e.level].details:e.type===p.AUDIO_TRACK&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===p.SUBTITLE_TRACK&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,r=t.targetduration;if(e&&r){const t=1e3*Math.max(3*e,.8*r);s=I({},s,{maxTimeToFirstByteMs:Math.min(t,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,s.maxTimeToFirstByteMs)})}}}const a=s.errorRetry||s.timeoutRetry||{},o={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,r,i)=>{const s=this.getInternalLoader(r);this.resetInternalLoader(r.type);const n=t.data;e.parsing.start=performance.now(),sr.isMediaPlaylist(n)||r.type!==p.MANIFEST?this.handleTrackOrLevelPlaylist(t,e,r,i||null,s):this.handleMasterPlaylist(t,e,r,i)},onError:(t,e,r,i)=>{this.handleNetworkError(e,r,!1,t,i)},onTimeout:(t,e,r)=>{this.handleNetworkError(e,r,!0,void 0,t)}};n.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:r}=this.hls;(t||r)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,r,i){const s=this.hls,a=t.data,o=Dn(t,r),l=sr.parseMasterPlaylist(a,o);if(l.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,r,l.playlistParsingError,i,e);const{contentSteering:d,levels:h,iframeVariants:u,sessionData:c,sessionKeys:f,startTimeOffset:g,variableList:m}=l;this.variableList=m,h.forEach((t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:r}=this.hls.config;let{audioCodec:i,videoCodec:s}=t;for(let n=e.length;n--;){const a=e[n];se(a,"audio",r)?(t.audioCodec=i=i?`${i},${a}`:a,re.audio[i.substring(0,4)]=2,e.splice(n,1)):se(a,"video",r)&&(t.videoCodec=s=s?`${s},${a}`:a,re.video[s.substring(0,4)]=2,e.splice(n,1))}}}));const{AUDIO:p=[],SUBTITLES:v,"CLOSED-CAPTIONS":E}=sr.parseMasterPlaylistMedia(a,o,l);if(p.length){p.some((t=>!t.url))||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ge({}),bitrate:0,url:""}))}s.trigger(n.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:v,iframeVariants:u,captions:E,contentSteering:d,url:o,stats:e,networkDetails:i,sessionData:c,sessionKeys:f,startTimeOffset:g,variableList:m})}handleTrackOrLevelPlaylist(e,r,i,s,a){const o=this.hls,{id:l,level:d,type:h}=i,u=Dn(e,i),c=t(d)?d:t(l)?l:0,f=bn(i),g=sr.parseLevelPlaylist(e.data,u,c,f,0,this.variableList);if(h===p.MANIFEST){const t={attrs:new Ge({}),bitrate:0,details:g,name:"",url:u};g.requestScheduled=r.loading.start+Ar(g,0),o.trigger(n.MANIFEST_LOADED,{levels:[t],audioTracks:[],iframeVariants:[],url:u,stats:r,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}r.parsing.end=performance.now(),i.levelDetails=g,this.handlePlaylistLoaded(g,e,r,i,s,a)}handleManifestParsingError(t,e,r,a,o){this.hls.trigger(n.ERROR,{type:i.NETWORK_ERROR,details:s.MANIFEST_PARSING_ERROR,fatal:e.type===p.MANIFEST,url:t.url,err:r,error:r,reason:r.message,response:t,context:e,networkDetails:a,stats:o})}handleNetworkError(t,e,r=!1,a,o){let l=`A network ${r?"timeout":"error"+(a?" (status "+a.code+")":"")} occurred while loading ${t.type}`;t.type===p.LEVEL?l+=`: ${t.level} id: ${t.id}`:t.type!==p.AUDIO_TRACK&&t.type!==p.SUBTITLE_TRACK||(l+=` id: ${t.id} group-id: "${t.groupId}"`);const d=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let h=s.UNKNOWN,u=!1;const c=this.getInternalLoader(t);switch(t.type){case p.MANIFEST:h=r?s.MANIFEST_LOAD_TIMEOUT:s.MANIFEST_LOAD_ERROR,u=!0;break;case p.LEVEL:h=r?s.LEVEL_LOAD_TIMEOUT:s.LEVEL_LOAD_ERROR,u=!1;break;case p.AUDIO_TRACK:h=r?s.AUDIO_TRACK_LOAD_TIMEOUT:s.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case p.SUBTITLE_TRACK:h=r?s.SUBTITLE_TRACK_LOAD_TIMEOUT:s.SUBTITLE_LOAD_ERROR,u=!1}c&&this.resetInternalLoader(t.type);const f={type:i.NETWORK_ERROR,details:h,fatal:u,url:t.url,loader:c,context:t,error:d,networkDetails:e,stats:o};if(a){let r=t.url;e&&"url"in e&&(r=e.url),f.response=_({url:r,data:void 0},a)}this.hls.trigger(n.ERROR,f)}handlePlaylistLoaded(t,e,r,a,o,l){const d=this.hls,{type:h,level:u,levelOrTrack:c,id:f,groupId:g,deliveryDirectives:m}=a,E=Dn(e,a),y=bn(a);let T="number"==typeof a.level&&y===v.MAIN?u:void 0;const S=t.playlistParsingError;if(S){if(this.hls.logger.warn(`${S} ${t.url}`),!d.config.ignorePlaylistParsingErrors)return void d.trigger(n.ERROR,{type:i.NETWORK_ERROR,details:s.LEVEL_PARSING_ERROR,fatal:!1,url:E,error:S,reason:S.message,response:e,context:a,level:T,parent:y,networkDetails:o,stats:r});t.playlistParsingError=null}if(t.fragments.length)switch(t.live&&l&&(l.getCacheAge&&(t.ageHeader=l.getCacheAge()||0),l.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),h){case p.MANIFEST:case p.LEVEL:if(T)if(c){if(c!==d.levels[T]){const t=d.levels.indexOf(c);t>-1&&(T=t)}}else T=0;d.trigger(n.LEVEL_LOADED,{details:t,levelInfo:c||d.levels[0],level:T||0,id:f||0,stats:r,networkDetails:o,deliveryDirectives:m,withoutMultiVariant:h===p.MANIFEST,context:a});break;case p.AUDIO_TRACK:d.trigger(n.AUDIO_TRACK_LOADED,{details:t,track:c,id:f||0,groupId:g||"",stats:r,networkDetails:o,deliveryDirectives:m,context:a});break;case p.SUBTITLE_TRACK:d.trigger(n.SUBTITLE_TRACK_LOADED,{details:t,track:c,id:f||0,groupId:g||"",stats:r,networkDetails:o,deliveryDirectives:m,context:a})}else{const l=t.playlistParsingError=new Error("No Segments found in Playlist");d.trigger(n.ERROR,{type:i.NETWORK_ERROR,details:s.LEVEL_EMPTY_ERROR,fatal:!1,url:E,error:l,reason:l.message,response:e,context:a,level:T,parent:y,networkDetails:o,stats:r})}}}class kn{static get version(){return $i}static isMSESupported(){return Js()}static isSupported(){return tn()}static getMediaSource(){return Z()}static get Events(){return n}static get MetadataSchema(){return wi}static get ErrorTypes(){return i}static get ErrorDetails(){return s}static get DefaultConfig(){return kn.defaultConfig?kn.defaultConfig:mn}static set DefaultConfig(t){kn.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ki,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const e=this.logger=function(t,e,r){const i=K();if("object"==typeof console&&!0===t||"object"==typeof t){const s=["debug","log","info","warn","error"];s.forEach((e=>{i[e]=Y(e,t,r)}));try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.7.4`)}catch(t){return K()}s.forEach((e=>{W[e]=Y(e,t)}))}else I(W,i);return i}(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),r=this.config=pn(kn.DefaultConfig,t,e);this.userConfig=t,r.progressive&&function(t,e){const r=t.loader;r!==dn&&r!==fn?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):on()&&(t.loader=dn,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}(r,e);const{streamController:i,abrController:s,bufferController:a,capLevelController:o,errorController:l,fpsController:d,id3TrackController:h,iframeController:u,gapController:c}=r,f=new l(this),g=this.abrController=new s(this),m=new Zr(this),p=r.interstitialsController,v=p?this.interstitialsController=new p(this,kn):null,E=a?this.bufferController=new a(this,m):null,y=o?this.capLevelController=new o(this):null,T=d?new d(this):null,S=r.cmcdController,L=S?this.cmcdController=new S(this):null,A=new In(this),R=r.contentSteeringController,b=R?new R(this):null,D=this.levelController=new En(this,b),k=h?new h(this):void 0,_=new An(this.config,this.logger),C=this.streamController=new i(this,m,_),P=this.gapController=c?new c(this,m):void 0;y&&y.setStreamController(C);const x=[A,D,C];v&&x.splice(1,0,v),b&&x.splice(1,0,b),this.networkControllers=x;const w=[g];E&&w.push(E),P&&w.push(P),y&&w.push(y),T&&(T.setStreamController(C),w.push(T)),k&&w.push(k),w.push(m),this.audioTrackController=this.createController(r.audioTrackController,x);const O=r.audioStreamController;O&&x.push(this.audioStreamController=new O(this,m,_)),this.subtitleTrackController=this.createController(r.subtitleTrackController,x);const M=r.subtitleStreamController;M&&x.push(this.subtititleStreamController=new M(this,m,_)),this.createController(r.timelineController,w),_.emeController=this.emeController=this.createController(r.emeController,w),L&&w.push(L),this.latencyController=this.createController(r.latencyController,w),this.coreComponents=w,this.iframeController=u?new u(this,kn):void 0,x.push(f);const F=f.onErrorOut;"function"==typeof F&&this.on(n.ERROR,F,f),this.on(n.MANIFEST_LOADED,A.onManifestLoaded,A)}createController(t,e){if(t){const r=new t(this);return e&&e.push(r),r}return null}on(t,e,r=this){this._emitter.on(t,e,r)}once(t,e,r=this){this._emitter.once(t,e,r)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,r=this,i){this._emitter.off(t,e,r,i)}listeners(t){return this._emitter.listeners(t)}emit(t,e,r){return this._emitter.emit(t,e,r)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const r=t===n.ERROR;this.trigger(n.ERROR,{type:i.OTHER_ERROR,details:s.INTERNAL_EXCEPTION,fatal:r,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(n.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((t=>t.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((t=>t.destroy())),this.coreComponents.length=0,this.iframeController=void 0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(n.ERROR,{type:i.OTHER_ERROR,details:s.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,r=e?t.media:t,a=e?t:{media:r};this._media=r,this.trigger(n.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia");const t={};this.trigger(n.MEDIA_DETACHING,t),this._media=null,this.trigger(n.MEDIA_DETACHED,t)}transferMedia(){var t;this._media=null;const e=(null==(t=this.bufferController)?void 0:t.transferMedia())||null,r={transferMedia:e};return this.trigger(n.MEDIA_DETACHING,r),this.trigger(n.MEDIA_DETACHED,r),e}loadSource(t){var e;this.stopLoad();const r=this.media,i=this._url,s=this._url=g.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),r&&i&&(i!==s||null!=(e=this.bufferController)&&e.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(n.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(t,e),this.started&&this.networkControllers);r++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started&&this.streamController.state!==Ei.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((t=>{t.resumeBuffering&&t.resumeBuffering()})))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((t=>{t.pauseBuffering&&t.pauseBuffering()})))}get inFlightFragments(){const t={[v.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[v.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[v.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=this.started,r=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&(r?this.startLoad(r):this.config.autoStartLoad||this.startLoad()))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?r:3&r|8).toString(16)}))}}}()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=this.capLevelController,r=!!t;e&&r!==this.config.capLevelToPlayerSize&&(r?e.startCapping():(e.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return pe.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const r=t.length;for(let i=0;i<r;i++)if(t[i].maxBitrate>=e)return i;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:r}=this;let i;if(i=-1===e&&null!=t&&t.length?t.length-1:e,r)for(let e=i;e--;){const i=t[e].attrs["HDCP-LEVEL"];if(i&&i<=r)return e}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var t;return(null==(t=this.audioStreamController)?void 0:t.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get nextAudioTrack(){var t,e;return null!=(t=null==(e=this.audioStreamController)?void 0:e.nextAudioTrack)?t:-1}set nextAudioTrack(t){const{audioTrackController:e}=this;e&&(e.nextAudioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){var t,e;return null!=(t=null==(e=this.latencyController)?void 0:e.liveSyncPosition)?t:null}get latency(){var t;return(null==(t=this.latencyController)?void 0:t.latency)||0}get maxLatency(){var t;return(null==(t=this.latencyController)?void 0:t.maxLatency)||0}get targetLatency(){var t;return(null==(t=this.latencyController)?void 0:t.targetLatency)||null}set targetLatency(t){this.latencyController&&(this.latencyController.targetLatency=t)}get drift(){var t;return(null==(t=this.latencyController)?void 0:t.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){return null}get iframeVariants(){const t=this.levelController.iframeVariants;return t||[]}createIFramePlayer(t){return null}createImageIFramePlayer(t){return null}getMediaDecodingInfo(t,e=this.allAudioTracks){const r=De(e);return X.getMediaDecodingInfoPromise(t,r,navigator.mediaCapabilities)}}kn.defaultConfig=void 0;var _n=X.KeySystemFormats,Cn=X.KeySystems,Pn=X.SubtitleStreamController,xn=X.TimelineController,wn=X.requestMediaKeySystemAccess;export{ke as AbrController,Ge as AttrList,Q as AudioStreamController,Q as AudioTrackController,nn as BaseLoader,Cr as BasePlaylistController,y as BaseSegment,yi as BaseStreamController,Gr as BufferController,Q as CMCDController,Ti as CapLevelController,fi as ChunkMetadata,Si as ContentSteeringController,Q as Cues,He as DateRange,Q as EMEController,Oe as ErrorActionFlags,Me as ErrorController,s as ErrorDetails,i as ErrorTypes,n as Events,Ri as FPSController,dn as FetchLoader,A as Fragment,kn as Hls,Ee as HlsSkip,Te as HlsUrlParameters,_n as KeySystemFormats,Cn as KeySystems,Se as Level,Ke as LevelDetails,Ze as LevelKey,m as LoadStats,p as LoaderContextType,sr as M3U8Parser,wi as MetadataSchema,we as NetworkErrorAction,R as Part,v as PlaylistLevelType,Pn as SubtitleStreamController,Q as SubtitleTrackController,xn as TimelineController,fn as XhrLoader,kn as default,on as fetchSupported,Z as getMediaSource,Js as isMSESupported,tn as isSupported,wn as requestMediaKeySystemAccess};
//# sourceMappingURL=hls.light.min.mjs.map