@hopeplayer/core 1.0.18 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/HopePlayerElement.d.ts +2 -0
- package/dist/HopePlayerElement.d.ts.map +1 -1
- package/dist/chunks/{ads-MCG5a6eK.js → ads-BZYADoen.js} +2 -2
- package/dist/chunks/{ads-MCG5a6eK.js.map → ads-BZYADoen.js.map} +1 -1
- package/dist/chunks/{cast-bMrkGGuD.js → cast-BGgfNj37.js} +2 -2
- package/dist/chunks/{cast-bMrkGGuD.js.map → cast-BGgfNj37.js.map} +1 -1
- package/dist/chunks/hls-DAtZkTUi.js +45 -0
- package/dist/chunks/{hls-BOHE_fg_.js.map → hls-DAtZkTUi.js.map} +1 -1
- package/dist/chunks/hlsLight-CCe_8eOw.js +28 -0
- package/dist/chunks/hlsLight-CCe_8eOw.js.map +1 -0
- package/dist/chunks/{markers-BhMJLPqj.js → markers-u2bpLu30.js} +2 -2
- package/dist/chunks/{markers-BhMJLPqj.js.map → markers-u2bpLu30.js.map} +1 -1
- package/dist/chunks/{player-DW5iWvPs.js → player-B_e_Nnvb.js} +474 -430
- package/dist/chunks/player-B_e_Nnvb.js.map +1 -0
- package/dist/chunks/{playlist-DYGbJ5wz.js → playlist-ClnEXcRy.js} +2 -2
- package/dist/chunks/{playlist-DYGbJ5wz.js.map → playlist-ClnEXcRy.js.map} +1 -1
- package/dist/chunks/{redirectScreen-CSjrS8Kg.js → redirectScreen-DZwpVYWk.js} +2 -2
- package/dist/chunks/{redirectScreen-CSjrS8Kg.js.map → redirectScreen-DZwpVYWk.js.map} +1 -1
- package/dist/chunks/{rewardedUnlock-DZ_qPcDG.js → rewardedUnlock-DoRVfTlV.js} +2 -2
- package/dist/chunks/{rewardedUnlock-DZ_qPcDG.js.map → rewardedUnlock-DoRVfTlV.js.map} +1 -1
- package/dist/chunks/{segments-LsZPlbYi.js → segments-DERcwNUG.js} +2 -2
- package/dist/chunks/{segments-LsZPlbYi.js.map → segments-DERcwNUG.js.map} +1 -1
- package/dist/chunks/skipSegments-XjblXCGo.js +122 -0
- package/dist/chunks/skipSegments-XjblXCGo.js.map +1 -0
- package/dist/chunks/{spriteThumbnails-BQkEBRu-.js → spriteThumbnails-y_JaE9LE.js} +2 -2
- package/dist/chunks/{spriteThumbnails-BQkEBRu-.js.map → spriteThumbnails-y_JaE9LE.js.map} +1 -1
- package/dist/chunks/{story-H6f7gSoX.js → story-UpOGg7Ch.js} +2 -2
- package/dist/chunks/{story-H6f7gSoX.js.map → story-UpOGg7Ch.js.map} +1 -1
- package/dist/controls/SettingsMenu.d.ts +16 -0
- package/dist/controls/SettingsMenu.d.ts.map +1 -1
- package/dist/hls/SourceManager.d.ts +2 -0
- package/dist/hls/SourceManager.d.ts.map +1 -1
- package/dist/hope-player.js +1 -1
- package/dist/i18n/locales/en.d.ts.map +1 -1
- package/dist/i18n/locales/tr.d.ts.map +1 -1
- package/dist/i18n/types.d.ts +5 -0
- package/dist/i18n/types.d.ts.map +1 -1
- package/dist/plugins/skip-segments/SkipSegments.d.ts +40 -0
- package/dist/plugins/skip-segments/SkipSegments.d.ts.map +1 -0
- package/dist/plugins/skip-segments/index.d.ts +6 -0
- package/dist/plugins/skip-segments/index.d.ts.map +1 -0
- package/dist/types/index.d.ts +58 -0
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/hls-BOHE_fg_.js +0 -24791
- package/dist/chunks/player-DW5iWvPs.js.map +0 -1
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const G=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},Aa=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=Ra},Ra=Number.MAX_SAFE_INTEGER||9007199254740991;let Y=(function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a})({}),D=(function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",a.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",a.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ERROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.ASSET_LIST_LOAD_ERROR="assetListLoadError",a.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",a.ASSET_LIST_PARSING_ERROR="assetListParsingError",a.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.ATTACH_MEDIA_ERROR="attachMediaError",a.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",a.UNKNOWN="unknown",a})({}),y=(function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.MEDIA_ENDED="hlsMediaEnded",a.STALL_RESOLVED="hlsStallResolved",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFERED_TO_END="hlsBufferedToEnd",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",a.ASSET_LIST_LOADING="hlsAssetListLoading",a.ASSET_LIST_LOADED="hlsAssetListLoaded",a.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",a.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",a.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",a.INTERSTITIAL_STARTED="hlsInterstitialStarted",a.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",a.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",a.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",a.INTERSTITIAL_ENDED="hlsInterstitialEnded",a.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",a.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",a.EVENT_CUE_ENTER="hlsEventCueEnter",a})({});function es(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var rs={exports:{}},ss;function ba(){return ss||(ss=1,(function(a,t){(function(e){var r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,h,d){if(d=d||{},l=l.trim(),h=h.trim(),!h){if(!d.alwaysNormalize)return l;var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var c=o.parseURL(h);if(!c)throw new Error("Error trying to parse relative URL.");if(c.scheme)return d.alwaysNormalize?(c.path=o.normalizePath(c.path),o.buildURLFromParts(c)):h;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=s.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:c.netLoc,path:null,params:c.params,query:c.query,fragment:c.fragment};if(!c.netLoc&&(p.netLoc=f.netLoc,c.path[0]!=="/"))if(!c.path)p.path=f.path,c.params||(p.params=f.params,c.query||(p.query=f.query));else{var m=f.path,T=m.substring(0,m.lastIndexOf("/")+1)+c.path;p.path=o.normalizePath(T)}return p.path===null&&(p.path=d.alwaysNormalize?o.normalizePath(c.path):c.path),o.buildURLFromParts(p)},parseURL:function(l){var h=r.exec(l);return h?{scheme:h[1]||"",netLoc:h[2]||"",path:h[3]||"",params:h[4]||"",query:h[5]||"",fragment:h[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(i,"");l.length!==(l=l.replace(n,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};a.exports=o})()})(rs)),rs.exports}var sr=ba();class ir{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 Q=(function(a){return a.MANIFEST="manifest",a.LEVEL="level",a.AUDIO_TRACK="audioTrack",a.SUBTITLE_TRACK="subtitleTrack",a.MEDIA_FRAGMENT="media-fragment",a.KEY="key",a.STEERING_MANIFEST="steering-manifest",a.SERVER_CERTIFICATE="server-certificate",a.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",a})({}),j=(function(a){return a.MAIN="main",a.AUDIO="audio",a.SUBTITLE="subtitle",a})({});var st={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class ar{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof t=="string"&&(t={url:t}),this.base=t,Da(this,"stats")}setByteRange(t,e){const r=t.split("@",2);let s;r.length===1?s=e?.byteRangeEndOffset||0:s=parseInt(r[1]),this._byteRange=[s,parseInt(r[0])+s]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[st.AUDIO]:null,[st.VIDEO]:null,[st.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new ir),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.relurl&&(this._url=sr.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[st.AUDIO]=null,t[st.VIDEO]=null,t[st.AUDIOVIDEO]=null,this.url=null}}function Et(a){return a.sn!=="initSegment"}function be(a,t){return a.sn===t?.sn&&a.level===t.level}function nr(a,t){return a.sn===t?.sn&&a.level===t.level&&a.cc===t.cc}class he extends ar{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 t=this.byteRange[0],e=this.byteRange[1];if(G(t)&&G(e))return e-t}return null}get bitrate(){return this.byteLength?this.byteLength*8/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(!((t=this._decryptdata)!=null&&t.keyId)){const r=Object.keys(e);if(r.length===1){const s=this._decryptdata=e[r[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const t=G(this.duration)?this.duration:0;return this.programDateTime+t*1e3}get encrypted(){var t;if((t=this._decryptdata)!=null&&t.encrypted)return!0;if(this.levelkeys){var e;const r=Object.keys(this.levelkeys),s=r.length;if(s>1||s===1&&(e=this.levelkeys[r[0]])!=null&&e.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){if(!G(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return Et(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 s=e[t];s&&!((r=this._decryptdata)!=null&&r.keyId)&&(this._decryptdata=s.getDecryptData(this.sn,e))}}abortRequests(){var t,e;(t=this.loader)==null||t.abort(),(e=this.keyLoader)==null||e.abort()}setElementaryStreamInfo(t,e,r,s,i,n=!1){const{elementaryStreams:o}=this,l=o[t];if(!l){o[t]={startPTS:e,endPTS:r,startDTS:s,endDTS:i,partial:n};return}l.startPTS=Math.min(l.startPTS,e),l.endPTS=Math.max(l.endPTS,r),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,i)}}class is extends ar{constructor(t,e,r,s,i){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=s;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,i),i&&(this.fragOffset=i.fragOffset+i.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===j.SUBTITLE&&this.stats.loading.end>0)}}function as(a,t){const e=Object.getPrototypeOf(a);if(e)return Object.getOwnPropertyDescriptor(e,t)||as(e,t)}function Da(a,t){const e=as(a,t);e&&(e.enumerable=!0,Object.defineProperty(a,t,e))}function Ia(a,t,e){return(t=_a(t))in a?Object.defineProperty(a,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):a[t]=e,a}function lt(){return lt=Object.assign?Object.assign.bind():function(a){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var r in e)({}).hasOwnProperty.call(e,r)&&(a[r]=e[r])}return a},lt.apply(null,arguments)}function ns(a,t){var e=Object.keys(a);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(a);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(a,s).enumerable})),e.push.apply(e,r)}return e}function gt(a){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?ns(Object(e),!0).forEach(function(r){Ia(a,r,e[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(e)):ns(Object(e)).forEach(function(r){Object.defineProperty(a,r,Object.getOwnPropertyDescriptor(e,r))})}return a}function ka(a,t){if(typeof a!="object"||!a)return a;var e=a[Symbol.toPrimitive];if(e!==void 0){var r=e.call(a,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(a)}function _a(a){var t=ka(a,"string");return typeof t=="symbol"?t:t+""}function De(a){switch(a.details){case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_TIMEOUT:case D.LEVEL_LOAD_TIMEOUT:case D.MANIFEST_LOAD_TIMEOUT:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.SUBTITLE_TRACK_LOAD_TIMEOUT:case D.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function os(a){return a.details.startsWith("key")}function ls(a){return os(a)&&!!a.frag&&!a.frag.decryptdata}function hs(a,t){const e=De(t);return a.default[`${e?"timeout":"error"}Retry`]}function or(a,t){const e=a.backoff==="linear"?1:Math.pow(2,t);return Math.min(e*a.retryDelayMs,a.maxRetryDelayMs)}function ds(a){return gt(gt({},a),{errorRetry:null,timeoutRetry:null})}function de(a,t,e,r){if(!a)return!1;const s=r?.code,i=t<a.maxNumRetry&&(Ca(s)||!!e);return a.shouldRetry?a.shouldRetry(a,t,e,r,i):i}function Ca(a){return ue(a)||!!a&&(a<400||a>499)}function ue(a){return a===0&&navigator.onLine===!1}function us(a,t){return t>0&&a.loadError>0&&a.loadErrorTime!==0&&self.performance.now()-a.loadErrorTime>t}class te{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 Pa{constructor(t,e,r,s=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 te(t),this.fast_=new te(e),this.defaultTTFB_=s,this.ttfb_=new te(t)}update(t,e){const{slow_:r,fast_:s,ttfb_:i}=this;r.halfLife!==t&&(this.slow_=new te(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.fast_=new te(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new te(t,i.getEstimate(),i.getTotalWeight()))}sample(t,e){if(e<=0)return;const r=Math.min(this.minDelayMs_,e/1e5),s=8*e,i=Math.max(t,r)/1e3,n=s/i;this.fast_.sample(i,n),this.slow_.sample(i,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 $t{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=Ht,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 Ht=function(){},xa={trace:Ht,debug:Ht,log:Ht,warn:Ht,info:Ht,error:Ht};function lr(){return lt({},xa)}function wa(a,t){const e=self.console[a];return e?e.bind(self.console,`${t?"["+t+"] ":""}[${a}] >`):Ht}function cs(a,t,e){return t[a]?t[a].bind(t):wa(a,e)}const hr=lr();function Oa(a,t,e){const r=lr();if(typeof console=="object"&&a===!0||typeof a=="object"){const s=["debug","log","info","warn","error"];s.forEach(i=>{r[i]=cs(i,a,e)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.7.4`)}catch{return lr()}s.forEach(i=>{hr[i]=cs(i,a)})}else lt(hr,r);return r}const et=hr;var fs,gs;function Ma(){return gs||(gs=1,fs={}),fs}var Bt=Ma(),Xt=es(Bt);function Ut(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Fa(a){return typeof self<"u"&&a===self.ManagedMediaSource}function Na(a,t){const e=Object.keys(a),r=Object.keys(t),s=e.length,i=r.length;return!s||!i||s===i&&!e.some(n=>r.indexOf(n)===-1)}function Ie(a){return a instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&a instanceof SharedArrayBuffer}const $a="utf-16",dr="utf-16be",ms="utf-16le",ke="utf-8";function Ba(a,t={}){let e;Ie(a)?e=new DataView(a):e=new DataView(a.buffer,a.byteOffset,a.byteLength);let r=0,{encoding:s}=t;if(!s){const h=e.getUint8(0),d=e.getUint8(1);h==239&&d==187&&e.getUint8(2)==191?(s=ke,r=3):h==254&&d==255?(s=dr,r=2):h==255&&d==254?(s=ms,r=2):s=ke}if(typeof TextDecoder<"u")return new TextDecoder(s).decode(e);const{byteLength:i}=e,n=s!==dr;let o="",l;for(;r<i;){switch(s){case ke:if(l=e.getUint8(r),l<128)r++;else if(l>=194&&l<=223)if(r+1<i){const h=e.getUint8(r+1);h>=128&&h<=191?(l=(l&31)<<6|h&63,r+=2):r++}else r++;else if(l>=224&&l<=239)if(r+2<=i-1){const h=e.getUint8(r+1),d=e.getUint8(r+2);h>=128&&h<=191&&d>=128&&d<=191?(l=(l&15)<<12|(h&63)<<6|d&63,r+=3):r++}else r++;else if(l>=240&&l<=244)if(r+3<=i-1){const h=e.getUint8(r+1),d=e.getUint8(r+2),u=e.getUint8(r+3);h>=128&&h<=191&&d>=128&&d<=191&&u>=128&&u<=191?(l=(l&7)<<18|(h&63)<<12|(d&63)<<6|u&63,r+=4):r++}else r++;else r++;break;case dr:case $a:case ms:l=e.getUint16(r,n),r+=2;break}o+=String.fromCodePoint(l)}return o}function Ua(){try{return crypto.randomUUID()}catch{try{const a=URL.createObjectURL(new Blob),t=a.toString();return URL.revokeObjectURL(a),t.slice(t.lastIndexOf("/")+1)}catch{let a=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=(a+Math.random()*16)%16|0;return a=Math.floor(a/16),(t=="x"?e:e&3|8).toString(16)})}}}function ur(a,t){return t+10<=a.length&&a[t]===73&&a[t+1]===68&&a[t+2]===51&&a[t+3]<255&&a[t+4]<255&&a[t+6]<128&&a[t+7]<128&&a[t+8]<128&&a[t+9]<128}function _e(a,t){let e=0;return e=(a[t]&127)<<21,e|=(a[t+1]&127)<<14,e|=(a[t+2]&127)<<7,e|=a[t+3]&127,e}function Ga(a,t){return ur(a,t)&&_e(a,t+6)+10<=a.length-t}function ps(a,t){return t+10<=a.length&&a[t]===51&&a[t+1]===68&&a[t+2]===73&&a[t+3]<255&&a[t+4]<255&&a[t+6]<128&&a[t+7]<128&&a[t+8]<128&&a[t+9]<128}function Ce(a,t){const e=t;let r=0;for(;ur(a,t);){r+=10;const s=_e(a,t+6);r+=s,ps(a,t+10)&&(r+=10),t+=r}if(r>0)return a.subarray(e,e+r)}function Va(a){return Ie(a)?a:a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer}function cr(a,t=0,e=1/0){return Ha(a,t,e,Uint8Array)}function Ha(a,t,e,r){const s=Ka(a);let i=1;"BYTES_PER_ELEMENT"in r&&(i=r.BYTES_PER_ELEMENT);const n=Wa(a)?a.byteOffset:0,o=(n+a.byteLength)/i,l=(n+t)/i,h=Math.floor(Math.max(0,Math.min(l,o)));return new r(s,h,Math.floor(Math.min(h+Math.max(e,0),o))-h)}function Ka(a){return Ie(a)?a:a.buffer}function Wa(a){return a&&Ie(a.buffer)&&a.byteLength!==void 0&&a.byteOffset!==void 0}function Rt(a,t=!1){const e=t?a.indexOf(0):a.length,r=Ba(new DataView(a.buffer,a.byteOffset,e),{encoding:ke});return t?r:r.replace(/\0/g,"")}function Ya(a){const t={key:a.type,description:"",data:"",mimeType:null,pictureType:null},e=3;if(a.size<2)return;if(a.data[0]!==e){console.log("Ignore frame with unrecognized character encoding");return}const r=a.data.subarray(1).indexOf(0);if(r===-1)return;const s=Rt(cr(a.data,1,r)),i=a.data[2+r],n=a.data.subarray(3+r).indexOf(0);if(n===-1)return;const o=Rt(cr(a.data,3+r,n));let l;return s==="-->"?l=Rt(cr(a.data,4+r+n)):l=Va(a.data.subarray(4+r+n)),t.mimeType=s,t.pictureType=i,t.description=o,t.data=l,t}function ja(a){if(a.size<2)return;const t=Rt(a.data,!0),e=new Uint8Array(a.data.subarray(t.length+1));return{key:a.type,info:t,data:e.buffer}}function qa(a){if(a.size<2)return;if(a.type==="TXXX"){let e=1;const{data:r}=a,s=Rt(r.subarray(e),!0);e+=s.length+1;const i=Rt(r.subarray(e));return{key:a.type,info:s,data:i}}const t=Rt(a.data.subarray(1));return{key:a.type,info:"",data:t}}function za(a){if(a.type==="WXXX"){if(a.size<2)return;let e=1;const r=Rt(a.data.subarray(e),!0);e+=r.length+1;const s=Rt(a.data.subarray(e));return{key:a.type,info:r,data:s}}const t=Rt(a.data);return{key:a.type,info:"",data:t}}function Xa(a){return a.type==="PRIV"?ja(a):a.type[0]==="W"?za(a):a.type==="APIC"?Ya(a):qa(a)}function Qa(a){const t=String.fromCharCode(a[0],a[1],a[2],a[3]),e=_e(a,4),r=10;return{type:t,size:e,data:a.subarray(r,r+e)}}const Pe=10,Za=10;function vs(a){let t=0;const e=[];for(;ur(a,t);){const r=_e(a,t+6);a[t+5]>>6&1&&(t+=Pe),t+=Pe;const s=t+r;for(;t+Za<s;){const i=Qa(a.subarray(t)),n=Xa(i);n&&e.push(n),t+=i.size+Pe}ps(a,t)&&(t+=Pe)}return e}function Es(a){return a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp"}function Ja(a){if(a.data.byteLength===8){const t=new Uint8Array(a.data),e=t[3]&1;let r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,e&&(r+=4772185884e-2),Math.round(r)}}function ys(a){const t=vs(a);for(const e of t)if(Es(e))return Ja(e)}function ee(a){let t="";for(let e=0;e<a.length;e++){let r=a[e].toString(16);r.length<2&&(r="0"+r),t+=r}return t}function Ts(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function ce(a){return String.fromCharCode.apply(null,a)}const _t=Math.pow(2,32)-1,X={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},Ss={video:1,audio:2,id3:3,text:4};function Ls(a,t){const e=a[t]<<8|a[t+1];return e<0?65536+e:e}function V(a,t){const e=a[t]<<24|a[t+1]<<16|a[t+2]<<8|a[t+3];return e<0?4294967296+e:e}function As(a,t){let e=V(a,t);return e*=Math.pow(2,32),e+=V(a,t+4),e}function xe(a,t){let e="";for(let r=t;r<a.length;r++)if(e+=String.fromCharCode(a[r]),a[r]===0)return e;return null}function fr(a,t){return a[t]<<24|a[t+1]<<16|a[t+2]<<8|a[t+3]}function Qt(a,t,e){a[t]=e>>24,a[t+1]=e>>16&255,a[t+2]=e>>8&255,a[t+3]=e&255}function tn(a,t){const e=a.byteLength;for(let r=0;r<e;){const s=V(a,r);if(s>8&&V(a,r+4)===X[t])return!0;r=s>1?r+s:e}return!1}function tt(a,t){const e=[];return t.length&&Rs(a,t,0,0,a.byteLength,e),e}function Rs(a,t,e,r,s,i){const n=t[e];if(n?.length!==4)return;const o=n.charCodeAt(0),l=n.charCodeAt(1),h=n.charCodeAt(2),d=n.charCodeAt(3),u=t.length-1;for(let c=r;c<s;){const f=c+8<=s,g=c+4<=s?a[c]*16777216+(a[c+1]<<16|a[c+2]<<8|a[c+3]):V(a,c),p=g>1?c+g:s;if(f&&a[c+4]===o&&a[c+5]===l&&a[c+6]===h&&a[c+7]===d){const m=Math.min(p,s);e===u?i.push(a.subarray(c+8,m)):Rs(a,t,e+1,c+8,m,i)}c=p}}function en(a){const t=[],e=a[0];let r=8;const s=V(a,r);r+=4;let i=0,n=0;e===0?(i=V(a,r),n=V(a,r+4),r+=8):(i=As(a,r),n=As(a,r+8),r+=16),r+=2;let o=a.length+n;const l=Ls(a,r);r+=2;for(let h=0;h<l;h++){let d=r;const u=V(a,d);d+=4;const c=u&2147483647;if((u&2147483648)>>>31===1)return et.warn("SIDX has hierarchical references (not supported)"),null;const f=V(a,d);d+=4,t.push({referenceSize:c,subsegmentDuration:f,info:{duration:f/s,start:o,end:o+c-1}}),o+=c,d+=4,r=d}return{earliestPresentationTime:i,timescale:s,version:e,referencesCount:l,references:t}}function bs(a){const t=[],e=tt(a,["moov","trak"]);for(let r=0;r<e.length;r++){const s=e[r],i=tt(s,["tkhd"])[0];if(i){let n=i[0];const o=V(i,n===0?12:20),l=tt(s,["mdia","mdhd"])[0];if(l){n=l[0];const h=V(l,n===0?12:20),d=tt(s,["mdia","hdlr"])[0];if(d){const u=ce(d.subarray(8,12)),c={soun:st.AUDIO,vide:st.VIDEO}[u],f=tt(s,["mdia","minf","stbl","stsd"])[0],g=rn(f);c?(t[o]={timescale:h,type:c,stsd:g},t[c]=gt({timescale:h,id:o},g)):t[o]={timescale:h,type:u,stsd:g}}}}}return tt(a,["moov","mvex","trex"]).forEach(r=>{const s=V(r,4),i=t[s];i&&(i.default={duration:V(r,12),sampleSize:V(r,16),flags:V(r,20)})}),t}function rn(a){const t=a.subarray(8),e=t.subarray(86),r=ce(t.subarray(4,8));let s=r,i;const n=r==="enca"||r==="encv";if(n){const l=tt(t,[r])[0].subarray(r==="enca"?28:78);tt(l,["sinf"]).forEach(h=>{const d=tt(h,["schm"])[0];if(d){const u=ce(d.subarray(4,8));if(u==="cbcs"||u==="cenc"){const c=tt(h,["frma"])[0];c&&(s=ce(c))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const l=tt(e,["avcC"])[0];l&&l.length>3&&(s+="."+Oe(l[1])+Oe(l[2])+Oe(l[3]),i=we(o==="avc1"?"dva1":"dvav",e));break}case"mp4a":{const l=tt(t,[r])[0],h=tt(l.subarray(28),["esds"])[0];if(h&&h.length>7){let d=4;if(h[d++]!==3)break;d=gr(h,d),d+=2;const u=h[d++];if(u&128&&(d+=2),u&64&&(d+=h[d++]),h[d++]!==4)break;d=gr(h,d);const c=h[d++];if(c===64)s+="."+Oe(c);else break;if(d+=12,h[d++]!==5)break;d=gr(h,d);const f=h[d++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((h[d]&224)>>5)),s+="."+g}break}case"hvc1":case"hev1":{const l=tt(e,["hvcC"])[0];if(l&&l.length>12){const h=l[1],d=["","A","B","C"][h>>6],u=h&31,c=V(l,2),f=(h&32)>>5?"H":"L",g=l[12],p=l.subarray(6,12);s+="."+d+u,s+="."+sn(c).toString(16).toUpperCase(),s+="."+f+g;let m="";for(let T=p.length;T--;){const E=p[T];(E||m)&&(m="."+E.toString(16).toUpperCase()+m)}s+=m}i=we(o=="hev1"?"dvhe":"dvh1",e);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{s=we(s,e)||s;break}case"vp09":{const l=tt(e,["vpcC"])[0];if(l&&l.length>6){const h=l[4],d=l[5],u=l[6]>>4&15;s+="."+Ct(h)+"."+Ct(d)+"."+Ct(u)}break}case"av01":{const l=tt(e,["av1C"])[0];if(l&&l.length>2){const h=l[1]>>>5,d=l[1]&31,u=l[2]>>>7?"H":"M",c=(l[2]&64)>>6,f=(l[2]&32)>>5,g=h===2&&c?f?12:10:c?10:8,p=(l[2]&16)>>4,m=(l[2]&8)>>3,T=(l[2]&4)>>2,E=l[2]&3;s+="."+h+"."+Ct(d)+u+"."+Ct(g)+"."+p+"."+m+T+E+"."+Ct(1)+"."+Ct(1)+"."+Ct(1)+".0",i=we("dav1",e)}break}}return{codec:s,encrypted:n,supplemental:i}}function we(a,t){const e=tt(t,["dvvC"]),r=e.length?e[0]:tt(t,["dvcC"])[0];if(r){const s=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return a+"."+Ct(s)+"."+Ct(i)}}function sn(a){let t=0;for(let e=0;e<32;e++)t|=(a>>e&1)<<31-e;return t>>>0}function gr(a,t){const e=t+5;for(;a[t++]&128&&t<e;);return t}function Oe(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function Ct(a){return(a<10?"0":"")+a}function an(a,t){if(!a||!t)return;const e=t.keyId;e?.byteLength===16&&t.isCommonEncryption&&Ds(a,(r,s)=>{const i=r.subarray(8,24);i.some(n=>n!==0)||(et.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${ee(i)} -> ${ee(e)}`),r.set(e,8))})}function nn(a){const t=[];return Ds(a,e=>t.push(e.subarray(8,24))),t}function Ds(a,t){tt(a,["moov","trak"]).forEach(e=>{const r=tt(e,["mdia","minf","stbl","stsd"])[0];if(!r)return;const s=r.subarray(8);let i=tt(s,["enca"]);const n=i.length>0;n||(i=tt(s,["encv"])),i.forEach(o=>{const l=n?o.subarray(28):o.subarray(78);tt(l,["sinf"]).forEach(h=>{const d=on(h);d&&t(d,n)})})})}function on(a){const t=tt(a,["schm"])[0];if(t){const e=ce(t.subarray(4,8));if(e==="cbcs"||e==="cenc"){const r=tt(a,["schi","tenc"])[0];if(r)return r}}}let Is;function ln(a){return typeof TextDecoder>"u"?Rt(a):(Is||(Is=new TextDecoder("utf-8"))).decode(a).replace(/\0/g,"")}function hn(a){const t=a.byteLength,e=[];for(let r=0;r<t;){const s=r+8<=t,i=r+4<=t?a[r]*16777216+(a[r+1]<<16|a[r+2]<<8|a[r+3]):V(a,r),n=i>1?r+i:t;if(s&&a[r+4]===109&&a[r+5]===111&&a[r+6]===111&&a[r+7]===102){const o=Math.min(n,t);for(let l=r+8;l<o;){const h=l+8<=o,d=l+4<=o?a[l]*16777216+(a[l+1]<<16|a[l+2]<<8|a[l+3]):V(a,l),u=d>1?l+d:o;if(h&&a[l+4]===116&&a[l+5]===114&&a[l+6]===97&&a[l+7]===102){const c=Math.min(u,o);let f,g;const p=[];for(let m=l+8;m<c;){const T=m+8<=c,E=m+4<=c?a[m]*16777216+(a[m+1]<<16|a[m+2]<<8|a[m+3]):V(a,m),v=E>1?m+E:c;if(T&&a[m+4]===116){const S=Math.min(v,c);a[m+5]===102&&a[m+6]===104&&a[m+7]===100?g||(g=a.subarray(m+8,S)):a[m+5]===102&&a[m+6]===100&&a[m+7]===116?f||(f=a.subarray(m+8,S)):a[m+5]===114&&a[m+6]===117&&a[m+7]===110&&p.push(a.subarray(m+8,S))}m=v}e.push({moofOffset:a.byteOffset+r,tfdt:f,tfhd:g,truns:p})}l=u}}r=n}return e}function dn(a,t,e,r,s=!0){return ks(a,t,r,s)}function un(a,t,e,r,s=!1){const i=[],n=t.samples,o=ks(n,e,r,s,{isHEVCFlavor:mr(t.codec),samples:i,timeOffset:a,timescale:t.timescale,trackId:t.id});return{samples:i,sampleData:{includeSampleDetails:s,tracks:o}}}function ks(a,t,e,r,s){const i={};let n=!1;const o=hn(a),l=a.byteLength;for(let u=0;u<o.length;u++){const{moofOffset:c,tfdt:f,tfhd:g,truns:p}=o[u],m=V(g,4),T=t[m];if(!T)continue;const E=i[m]||(i[m]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:T.timescale,type:T.type});let v;if(f){const w=f[0];v=V(f,4),w===1&&(v===_t?e.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(v*=_t+1,v+=V(f,8))),G(v)&&(!G(E.start)||v<E.start)&&(E.start=v),s&&G(v)&&(s.timeOffset=v/s.timescale)}const S=s?.trackId===m&&T.type===st.VIDEO,L=T.default,R=V(g,0)&16777215;let A=L?.duration||0,b,k=L?.sampleSize||0,P=8;R&1&&(P+=8),R&2&&(P+=4),R&8&&(A=V(g,P),b=g.byteOffset-a.byteOffset+P,P+=4),R&16&&(k=V(g,P));let M=0;const x=(R&1)!==0,N=!x&&(R&131072)!==0;x?(M=V(g,8),M*=Math.pow(2,32),M+=V(g,12)):N&&(M=c);let U=v||0,$=0,_=A;for(let w=0;w<p.length;w++){const O=p[w],I=V(O,4),C=E.sampleCount;E.sampleCount+=I;const K=O[3]&1;let H=0;const z=O[3]&4,W=O[2]&1,Z=O[2]&2,rt=O[2]&4,St=O[2]&8;let J=8;K&&(H=fr(O,J),J+=4),z&&(!(O[J+1]&1)&&E.keyFrameIndex===void 0&&(E.keyFrameIndex=C),J+=4);let ot=M+H;if(!r&&O[1]===0&&O[2]===6&&O[3]===1){var h,d;const at=U,Tt=ot,qt=J;let Mt=-1,zt=0,ft=0,Jt=(h=s?.timeOffset)!=null?h:0;const oe=A/((d=s?.timescale)!=null?d:1),er=s?.isHEVCFlavor===!0,La=er?2:1;for(let Ft=0;Ft<I;Ft++){const Nt=O[J]===0?O[J+1]<<16|O[J+2]<<8|O[J+3]:V(O,J),le=Mt===-1&&E.keyFrameIndex===void 0&&(O[J+5]&1)===0;J+=8;const Re=ot+Nt;if(S){if(Nt>0){let At=ot;do{const Jr=a[At]===0?a[At+1]<<16|a[At+2]<<8|a[At+3]:V(a,At);At+=4;const ts=a[At],rr=er?ts>>1&63:ts&31;(er?rr===39||rr===40:rr===6)&&Me(a.subarray(At,At+Jr),La,Jt,s.samples),At+=Jr}while(At<Re)}Jt+=oe}ot=Re,le&&(Mt=Ft,zt=ot)}if(ot<=l)ft=I;else{let Ft=Tt,Nt=qt;for(let le=0;le<I;le++){const Re=O[Nt]===0?O[Nt+1]<<16|O[Nt+2]<<8|O[Nt+3]:V(O,Nt);if(Ft+=Re,Ft>l)break;ft=le+1,Nt+=8}}if(S&&(s.timeOffset=Jt),Mt!==-1&&zt<=l&&E.keyFrameIndex===void 0&&(E.keyFrameIndex=Mt,E.keyFrameStart=at+Mt*A),ft){(!G(E.ptsMin)||at<E.ptsMin)&&(E.ptsMin=at);const Ft=at+ft*A;(!G(E.ptsMax)||Ft>E.ptsMax)&&(E.ptsMax=Ft)}const Zr=A*I;U=at+Zr,$+=Zr;continue}let vt,jt;r&&(vt=[],jt={sampleOffset:ot,samples:vt,defaultSampleDurationOffset:b},ot<=l&&E.trun.push(jt));let kt;for(let at=0;at<I;at++){let Tt;W?(r&&(Tt=O.byteOffset-a.byteOffset+J),_=V(O,J),J+=4):_=A,Z?(kt=V(O,J),J+=4):kt=k;let qt,Mt;rt&&(Mt=O[J+1]&1?1:0,r&&(qt={isNonSync:Mt,dependsOn:(O[J]&3)===1?1:2}),J+=4);let zt=0;if(St&&(zt=O[0]===0?V(O,J):fr(O,J),J+=4),S){let ft=ot,Jt=0;for(;Jt<kt;){const oe=V(a,ft);ft+=4,_s(s.isHEVCFlavor,a[ft])&&Me(a.subarray(ft,ft+oe),s.isHEVCFlavor?2:1,s.timeOffset+zt/s.timescale,s.samples),ft+=oe,Jt+=oe+4}s.timeOffset+=_/s.timescale}if(ot+=kt,ot<=l){jt&&Tt!==void 0&&(jt.lastSampleDurationOffset=Tt),Mt===0&&E.keyFrameIndex===void 0&&(E.keyFrameIndex=at,E.keyFrameStart=U);const ft=U+zt;(!G(E.ptsMin)||ft<E.ptsMin)&&(E.ptsMin=ft),(!G(E.ptsMax)||ft+_>E.ptsMax)&&(E.ptsMax=ft+_),vt&&(vt[at]={cts:zt,duration:_,flags:qt,size:kt})}U+=_,$+=_}!$&&A&&($+=A*I)}E.duration+=$,E.duration&&(n=!0)}if(!n){let u=1/0,c=0;const f=tt(a,["sidx"]);for(let g=0;g<f.length;g++){const p=en(f[g]);if(p!=null&&p.references){u=Math.min(u,p.earliestPresentationTime/p.timescale);const m=p.references.reduce((T,E)=>T+E.info.duration||0,0);c=Math.max(c,m+p.earliestPresentationTime/p.timescale)}}c&&G(c)&&Object.keys(i).forEach(g=>{i[g].duration||(i[g].duration=c*i[g].timescale-i[g].start)})}return i}function cn(a){const t={valid:null,remainder:null},e=tt(a,["moof"]);if(e.length<2)return t.remainder=a,t;const r=e[e.length-1];return t.valid=a.slice(0,r.byteOffset-8),t.remainder=a.slice(r.byteOffset-8),t}function bt(a,t){const e=new Uint8Array(a.length+t.length);return e.set(a),e.set(t,a.length),e}function fn(a,t){const e=[],r=t.samples,s=t.timescale,i=t.id;let n=!1;return tt(r,["moof"]).map(o=>{const l=o.byteOffset-8;tt(o,["traf"]).map(h=>{const d=tt(h,["tfdt"]).map(u=>{const c=u[0];let f=V(u,4);return c===1&&(f*=Math.pow(2,32),f+=V(u,8)),f/s})[0];return d!==void 0&&(a=d),tt(h,["tfhd"]).map(u=>{const c=V(u,4),f=V(u,0)&16777215,g=(f&1)!==0;let p=0;const m=(f&2)!==0,T=(f&8)!==0;let E=0;const v=(f&16)!==0;let S=0;const L=(f&32)!==0,R=!g&&(f&131072)!==0;let A=8;c===i&&(g?(p=V(u,A),A+=4,p*=Math.pow(2,32),p+=V(u,A),A+=4):R&&(p=l),m&&(A+=4),T&&(E=V(u,A),A+=4),v&&(S=V(u,A),A+=4),L&&(A+=4),t.type==="video"&&(n=mr(t.codec)),tt(h,["trun"]).map(b=>{const k=b[0],P=V(b,0)&16777215,M=(P&1)!==0;let x=0;const N=(P&4)!==0,U=(P&256)!==0;let $=0;const _=(P&512)!==0;let w=0;const O=(P&1024)!==0,I=(P&2048)!==0;let C=0;const K=V(b,4);let H=8;M&&(x=V(b,H),H+=4),N&&(H+=4);let z=p+x;for(let W=0;W<K;W++){if(U?($=V(b,H),H+=4):$=E,_?(w=V(b,H),H+=4):w=S,O&&(H+=4),I&&(k===0?C=V(b,H):C=fr(b,H),H+=4),t.type===st.VIDEO){let Z=0;for(;Z<w;){const rt=V(r,z);if(z+=4,_s(n,r[z])){const St=r.subarray(z,z+rt);Me(St,n?2:1,a+C/s,e)}z+=rt,Z+=rt+4}}a+=$/s}}))})})}),e}function mr(a){if(!a)return!1;const t=a.substring(0,4);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function _s(a,t){if(a){const e=t>>1&63;return e===39||e===40}else return(t&31)===6}function Me(a,t,e,r){const s=Cs(a);let i=0;i+=t;let n=0,o=0,l=0;for(;i<s.length;){n=0;do{if(i>=s.length)break;l=s[i++],n+=l}while(l===255);o=0;do{if(i>=s.length)break;l=s[i++],o+=l}while(l===255);const h=s.length-i;let d=i;if(o<h)i+=o;else if(o>h){et.error(`Malformed SEI payload. ${o} is too small, only ${h} bytes left to parse.`);break}if(n===4){if(s[d++]===181){const u=Ls(s,d);if(d+=2,u===49){const c=V(s,d);if(d+=4,c===1195456820){const f=s[d++];if(f===3){const g=s[d++],p=31&g,m=64&g,T=m?2+p*3:0,E=new Uint8Array(T);if(m){E[0]=g;for(let v=1;v<T;v++)E[v]=s[d++]}r.push({type:f,payloadType:n,pts:e,bytes:E})}}}}}else if(n===5&&o>16){const u=[];for(let g=0;g<16;g++){const p=s[d++].toString(16);u.push(p.length==1?"0"+p:p),(g===3||g===5||g===7||g===9)&&u.push("-")}const c=o-16,f=new Uint8Array(c);for(let g=0;g<c;g++)f[g]=s[d++];r.push({payloadType:n,pts:e,uuid:u.join(""),userData:ln(f),userDataBytes:f})}}}function Cs(a){const t=a.byteLength;let e,r=a.indexOf(3,3);for(;r!==-1;)a[r-1]===0&&a[r-2]===0&&(e||(e=[])).push(r),r=a.indexOf(3,r+1);if(!e)return a;const s=t-e.length,i=new Uint8Array(s);let n=0,o=0;for(let l=0;l<s;o++,l++)o===e[n]&&(o++,n++),i[l]=a[o];return i}function gn(a){const t=a[0];let e="",r="",s=0,i=0,n,o=0,l=0,h=4;if(t===0){const u=xe(a,h),c=u!==null?xe(a,h+u.length):null;u!==null&&c!==null?(e=u,r=c,h+=u.length+c.length,s=V(a,h),h+=4,i=V(a,h),h+=4,o=V(a,h),h+=4,l=V(a,h),h+=4):(et.warn(`Unterminated ${u===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),h=a.length)}else if(t===1){s=V(a,h),h+=4;const u=V(a,h);h+=4;const c=V(a,h);h+=4,n=2**32*u+c,Aa(n)||(n=Number.MAX_SAFE_INTEGER,et.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=V(a,h),h+=4,l=V(a,h),h+=4;const f=xe(a,h),g=f!==null?xe(a,h+f.length):null;f!==null&&(e=f,h+=f.length),g!==null?(r=g,h+=g.length):(et.warn(`Unterminated ${f===null?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${f===null?"strings and payload":"value and payload"}`),h=a.length)}const d=a.subarray(h,a.byteLength);return{schemeIdUri:e,value:r,timeScale:s,presentationTime:n,presentationTimeDelta:i,eventDuration:o,id:l,payload:d}}const fe=Ps("userAgent");Ps("vendor");let pr,vr,Er;function Ps(a){try{return navigator[a]||""}catch{}return""}function mn(){if(Er===void 0){const a=fe.match(/Safari\/(\d+)/i);Er=a?parseInt(a[1]):0}return Er}function ge(){if(pr===void 0){const a=fe.match(/Chrome\/(\d+)/i);pr=a?parseInt(a[1]):0}return pr}function pn(){if(vr===void 0){const a=fe.match(/Firefox\/(\d+)/i);vr=a?parseInt(a[1]):0}return vr}function vn(){return/\(Windows.+Firefox\//i.test(fe)}function En(){return/Android/.test(fe)}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 yr(a,t){const e=re[t];return!!e&&!!e[a.slice(0,4)]}function me(a,t,e=!0){return!a.split(",").some(r=>!Tr(r,t,e))}function Tr(a,t,e=!0){var r;const s=Ut(e);return(r=s?.isTypeSupported(Sr(a,t)))!=null?r:!1}function Sr(a,t){return`${t}/mp4;codecs=${a}`}function xs(a){if(a){const t=a.substring(0,4);return re.video[t]}return 2}function Fe(a){const t=vn();return a.split(",").reduce((e,r)=>{const s=t&&mr(r)?9:re.video[r];return s?(s*2+e)/(e?3:2):(re.audio[r]+e)/(e?2:1)},0)}const Lr={};function yn(a,t=!0){if(Lr[a])return Lr[a];const e={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[a];for(let s=0;s<e.length;s++){var r;if(Tr(e[s],"audio",t))return Lr[a]=e[s],e[s];if(e[s]==="mp3"&&(r=Ut(t))!=null&&r.isTypeSupported("audio/mpeg"))return""}return a}const Tn=/flac|opus|mp4a\.40\.34/i;function Ne(a,t=!0){return a.replace(Tn,e=>yn(e.toLowerCase(),t))}function Sn(a,t){const e=[];if(a){const r=a.split(",");for(let s=0;s<r.length;s++)yr(r[s],"video")||e.push(r[s])}return t&&e.push(t),e.join(",")}function $e(a,t){if(a&&(a.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(a)!==-1)&&(ws(a,"audio")||ws(a,"video")))return a;if(t){const e=t.split(",");if(e.length>1){if(a){for(let r=e.length;r--;)if(e[r].substring(0,4)===a.substring(0,4))return e[r]}return e[0]}}return t||a}function ws(a,t){return yr(a,t)&&Tr(a,t)}function Ln(a){const t=a.split(",");for(let e=0;e<t.length;e++){const r=t[e].split(".");r.length>2&&r[0]==="avc1"&&(t[e]=`avc1.${parseInt(r[1]).toString(16)}${("000"+parseInt(r[2]).toString(16)).slice(-4)}`)}return t.join(",")}function Os(a){const t=Ut(a)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1}}function An(a){return a.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}function se(a,t,e){const r=encodeURIComponent(t),s=`${r}=${encodeURIComponent(e)}`;let i=!1;const n=[];a.search.substring(1).split("&").forEach(o=>{o===r||o.startsWith(r+"=")?i||(n.push(s),i=!0):o&&n.push(o)}),i||n.push(s),a.search=n.join("&")}const Ar=["NONE","TYPE-0","TYPE-1",null];function Rn(a){return Ar.indexOf(a)>-1}const Be=["SDR","PQ","HLG"];function bn(a){return!!a&&Be.indexOf(a)>-1}var pe={No:"",Yes:"YES",v2:"v2"};function Ms(a){const{canSkipUntil:t,canSkipDateRanges:e,age:r}=a,s=r<t/2;return t&&s?e?pe.v2:pe.Yes:pe.No}class Rr{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 this.msn!==void 0&&se(e,"_HLS_msn",this.msn.toString()),this.part!==void 0&&se(e,"_HLS_part",this.part.toString()),this.skip&&se(e,"_HLS_skip",this.skip),e.href}}class br{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(r=>!!r).map(r=>r.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const r=(e=t.supplemental)==null?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 Fs(this._audioGroups,t)}hasSubtitleGroup(t){return Fs(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e){if(t==="audio"){let r=this._audioGroups;r||(r=this._audioGroups=[]),r.indexOf(e)===-1&&r.push(e)}else if(t==="text"){let r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),r.indexOf(e)===-1&&r.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(t=this.audioGroups)==null?void 0:t[0]}get textGroupId(){var t;return(t=this.subtitleGroups)==null?void 0:t[0]}addFallback(){}}function Fs(a,t){return!t||!a?!1:a.indexOf(t)!==-1}function Dn(){if(typeof matchMedia=="function"){const a=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(a.media!==t.media)return a.matches===!0}return!1}function In(a,t){let e=!1,r=[];if(a&&(e=a!=="SDR",r=[a]),t){r=t.allowedVideoRanges||Be.slice(0);const s=r.join("")!=="SDR"&&!t.videoCodec;e=t.preferHDR!==void 0?t.preferHDR:s&&Dn(),e||(r=["SDR"])}return{preferHDR:e,allowedVideoRanges:r}}const kn=a=>{const t=new WeakSet;return(e,r)=>{if(a&&(r=a(e,r)),typeof r=="object"&&r!==null){if(t.has(r))return;t.add(r)}return r}},yt=(a,t)=>JSON.stringify(a,kn(t));function _n(a,t,e,r,s){const i=Object.keys(a),n=r?.channels,o=r?.audioCodec,l=s?.videoCodec,h=n&&parseInt(n)===2;let d=!1,u=!1,c=1/0,f=1/0,g=1/0,p=1/0,m=0,T=[];const{preferHDR:E,allowedVideoRanges:v}=In(t,s);for(let A=i.length;A--;){const b=a[i[A]];d||(d=b.channels[2]>0),c=Math.min(c,b.minHeight),f=Math.min(f,b.minFramerate),g=Math.min(g,b.minBitrate),v.filter(k=>b.videoRanges[k]>0).length>0&&(u=!0)}c=G(c)?c:0,f=G(f)?f:0;const S=Math.max(1080,c),L=Math.max(30,f);g=G(g)?g:e,e=Math.max(g,e),u||(t=void 0);const R=i.length>1;return{codecSet:i.reduce((A,b)=>{const k=a[b];if(b===A)return A;if(T=u?v.filter(P=>k.videoRanges[P]>0):[],R){if(k.minBitrate>e)return Pt(b,`min bitrate of ${k.minBitrate} > current estimate of ${e}`),A;if(!k.hasDefaultAudio)return Pt(b,"no renditions with default or auto-select sound found"),A;if(o&&b.indexOf(o.substring(0,4))%5!==0)return Pt(b,`audio codec preference "${o}" not found`),A;if(n&&!h){if(!k.channels[n])return Pt(b,`no renditions with ${n} channel sound found (channels options: ${Object.keys(k.channels)})`),A}else if((!o||h)&&d&&k.channels[2]===0)return Pt(b,"no renditions with stereo sound found"),A;if(k.minHeight>S)return Pt(b,`min resolution of ${k.minHeight} > maximum of ${S}`),A;if(k.minFramerate>L)return Pt(b,`min framerate of ${k.minFramerate} > maximum of ${L}`),A;if(!T.some(P=>k.videoRanges[P]>0))return Pt(b,`no variants with VIDEO-RANGE of ${yt(T)} found`),A;if(l&&b.indexOf(l.substring(0,4))%5!==0)return Pt(b,`video codec preference "${l}" not found`),A;if(k.maxScore<m)return Pt(b,`max score of ${k.maxScore} < selected max of ${m}`),A}return A&&(Fe(b)>=Fe(A)||k.fragmentError>a[A].fragmentError)?A:(p=k.minIndex,m=k.maxScore,b)},void 0),videoRanges:T,preferHDR:E,minFramerate:f,minBitrate:g,minIndex:p}}function Pt(a,t){et.log(`[abr] start candidates with "${a}" ignored because ${t}`)}function Ns(a){return a.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 s=e.channels||"2";return r.channels[s]=(r.channels[s]||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 Cn(a,t,e,r){return a.slice(e,r+1).reduce((s,i,n)=>{if(!i.codecSet)return s;const o=i.audioGroups;let l=s[i.codecSet];l||(s[i.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,i.bitrate);const h=Math.min(i.height,i.width);return l.minHeight=Math.min(l.minHeight,h),l.minFramerate=Math.min(l.minFramerate,i.frameRate),l.minIndex=Math.min(l.minIndex,n),l.maxScore=Math.max(l.maxScore,i.score),l.fragmentError+=i.fragmentError,l.videoRanges[i.videoRange]=(l.videoRanges[i.videoRange]||0)+1,s},{})}function $s(a,t){var e;return!!a&&a!==((e=t.loadLevelObj)==null?void 0:e.uri)}class Bs extends $t{constructor(t){super("abr",t.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:s,partCurrent:i,hls:n}=this;if(!n)return;const{autoLevelEnabled:o,media:l}=n;if(!s||!l)return;const h=performance.now(),d=i?i.stats:s.stats,u=i?i.duration:s.duration,c=h-d.loading.start,f=n.minAutoLevel,g=s.level,p=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const m=p>-1&&p!==g,T=!!e||m;if(!T&&(l.paused||!l.playbackRate||!l.readyState))return;const E=n.mainForwardBufferInfo;if(!T&&E===null)return;const v=this.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(c<=Math.max(v,1e3*(u/(S*2))))return;const L=E?E.len/S:0,R=d.loading.first?d.loading.first-d.loading.start:-1,A=d.loaded&&R>-1,b=this.getBwEstimate(),k=n.levels,P=k[g],M=Math.max(d.loaded,Math.round(u*(s.bitrate||P.averageBitrate)/8));let x=A?c-R:c;x<1&&A&&(x=Math.min(c,d.loaded*8/b));const N=A?d.loaded*1e3/x:0,U=v/1e3,$=N?(M-d.loaded)/N:M*8/b+U;if($<=L)return;const _=N?N*8:b,w=((r=e?.details||n.latestLevelDetails)==null?void 0:r.live)===!0,O=n.config.abrBandWidthUpFactor;let I=Number.POSITIVE_INFINITY,C;for(C=g-1;C>f;C--){const W=k[C].maxBitrate,Z=!k[C].details||w;if(I=this.getTimeToLoadFrag(U,_,u*W,Z),I<Math.min(L,u+U))break}if(I>=$||I>u*10)return;A?this.bwEstimator.sample(c-Math.min(v,R),d.loaded):this.bwEstimator.sampleTTFB(c);const K=k[C].maxBitrate;this.getBwEstimate()*O>K&&(this.firstAutoFloor=Math.min(C,n.firstLevel),this.resetEstimator(K));const H=this.findBestLevel(K,f,C,0,L,1,1);H>-1&&(C=H),this.warn(`Fragment ${s.sn}${i?" part "+i.index:""} of level ${g} is loading too slowly;
|
|
2
|
+
Fragment duration: ${s.duration.toFixed(3)}
|
|
3
|
+
Time to underbuffer: ${L.toFixed(3)} s
|
|
4
|
+
Estimated load time for current fragment: ${$.toFixed(3)} s
|
|
5
|
+
Estimated load time for down switch fragment: ${I.toFixed(3)} s
|
|
6
|
+
TTFB estimate: ${R|0} ms
|
|
7
|
+
Current BW estimate: ${G(b)?b|0:"Unknown"} bps
|
|
8
|
+
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
9
|
+
Switching to level ${C} @ ${K|0} bps`),n.nextLoadLevel=n.nextAutoLevel=C,this.clearTimer();const z=()=>{this.clearTimer();const W=this.hls;if(this.fragCurrent===s&&W.loadLevel===C&&C>0){const Z=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${C>0?"and switching down":""}
|
|
10
|
+
Fragment duration: ${s.duration.toFixed(3)} s
|
|
11
|
+
Time to underbuffer: ${Z.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,C>f){let rt=this.findBestLevel(W.levels[f].bitrate,f,C,0,Z,1,1);rt===-1&&(rt=f),W.nextLoadLevel=W.nextAutoLevel=rt,this.firstAutoFloor=Math.min(rt,W.firstLevel),this.resetEstimator(W.levels[rt].bitrate)}}};m||$>I*2?z():this.timer=self.setInterval(z,I*1e3),n.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:i,stats:d})},this.hls=t,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 Pa(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const t=this.hls;t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.FRAG_LOADING,this.onFragLoading,this),t.on(y.FRAG_LOADED,this.onFragLoaded,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this),t.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(y.LEVEL_LOADED,this.onLevelLoaded,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.FRAG_LOADING,this.onFragLoading,this),t.off(y.FRAG_LOADED,this.onFragLoaded,this),t.off(y.FRAG_BUFFERED,this.onFragBuffered,this),t.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(y.LEVEL_LOADED,this.onLevelLoaded,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(y.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(y.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)){if(!r.bitrateTest){var s;this.fragCurrent=r,this.partCurrent=(s=e.part)!=null?s: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 D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case D.FRAG_LOAD_TIMEOUT:{const r=e.frag,{fragCurrent:s,partCurrent:i}=this;if(r&&nr(r,s)){const n=performance.now(),o=i?i.stats:r.stats,l=n-o.loading.start,h=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&h>-1){const d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(d,h),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(t,e,r,s){const i=t+r/e,n=s?t+this.lastLevelLoadSec:0;return i+n}onLevelLoaded(t,e){const r=this.hls.config,{loading:s}=e.stats,i=s.end-s.first;G(i)&&(this.lastLevelLoadSec=i/1e3),e.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,e){var r;const{frag:s,part:i}=e,n=i?i.stats:s.stats;if(s.type===j.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(s)){if(this.clearTimer(),s.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,(r=this.hls)!=null&&r.config.abrMaxWithRealBitrate){const o=i?i.duration:s.duration,l=this.hls.levels[s.level],h=(l.loaded?l.loaded.bytes:0)+n.loaded,d=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:h,duration:d},l.realBitrate=Math.round(8*h/d)}if(s.bitrateTest){const o={stats:n,frag:s,part:i,id:s.type};this.onFragBuffered(y.FRAG_BUFFERED,o),s.bitrateTest=!1}else this.lastLoadedFragLevel=s.level}}onFragBuffered(t,e){const{frag:r,part:s}=e,i=s!=null&&s.stats.loaded?s.stats:r.stats;if(i.aborted||this.ignoreFragment(r))return;const n=((r.bitrate||0)>=1e5?i.parsing.end:i.loading.end)-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,i.loaded),i.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!==j.MAIN||t.sn==="initSegment"}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,s=this.getBwEstimate(),i=this.getStarvationDelay(),n=t.config.maxStarvationDelay,o=this.findBestLevel(s,r,e,i/2,n,1,1);if(o>-1)return o;const l=t.firstLevel,h=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,d=Math.min(Math.max(l,r),e,h);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} 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(t!==-1&&(!e||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const s=e&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const i=this.hls.levels;if(i.length>Math.max(t,s)&&i[t].loadError<=i[s].loadError)return t}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}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:s,config:i,minAutoLevel:n}=r,o=e?e.duration:t?t.duration:0,l=this.getBwEstimate(),h=this.getStarvationDelay();let d=i.abrBandWidthFactor,u=i.abrBandWidthUpFactor;if(h){const m=this.findBestLevel(l,n,s,h,0,d,u);if(m>=0)return this.rebufferNotice=-1,m}let c=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!h){const m=this.bitrateTestDelay;m&&(c=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-m,this.info(`bitrate test took ${Math.round(1e3*m)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),d=u=1)}const f=this.findBestLevel(l,n,s,h,c,d,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${h?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=r.levels[n],p=r.loadLevelObj;return p&&g?.bitrate<p.bitrate?n:r.loadLevel}getStarvationDelay(){const t=this.hls,e=t?.media;if(!e)return 1/0;const r=e&&e.playbackRate!==0?Math.abs(e.playbackRate):1,s=t.mainForwardBufferInfo;return(s?s.len:0)/r}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(t,e,r,s,i,n,o){const{hls:l,lastLoadedFragLevel:h,fragCurrent:d,partCurrent:u}=this;if(!l)return-1;const c=s+i,f=h===-1?l.firstLevel:h,{levels:g,allAudioTracks:p,loadLevel:m,latestLevelDetails:T,config:E}=l;if(g.length===1)return 0;const v=g[f],S=!!(T!=null&&T.live),L=m===-1||h===-1;let R,A="SDR",b=v?.frameRate||0;const{audioPreference:k,videoPreference:P}=E,M=this.audioTracksByGroup||(this.audioTracksByGroup=Ns(p));let x=-1;if(L){if(this.firstSelection!==-1)return this.firstSelection;const w=this.codecTiers||(this.codecTiers=Cn(g,M,e,r)),O=_n(w,A,t,k,P),{codecSet:I,videoRanges:C,minFramerate:K,minBitrate:H,minIndex:z,preferHDR:W}=O;x=z,R=I,A=W?C[C.length-1]:C[0],b=K,t=Math.max(t,H),this.log(`picked start tier ${yt(O)}`)}else R=v?.codecSet,A=v?.videoRange;const N=u?u.duration:d?d.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,$=[];for(let w=r;w>=e;w--){var _;const O=g[w],I=w>f;if(!O)continue;if((R&&O.codecSet!==R||A&&O.videoRange!==A||I&&b>O.frameRate||!I&&b>0&&b<O.frameRate||(_=O.supportedResult)!=null&&(_=_.decodingInfoResults)!=null&&_.some(Z=>Z.smooth===!1))&&(!L||w!==x)){$.push(w);continue}const C=O.details,K=(u?C?.partTarget:C?.averagetargetduration)||N||1;let H;I?H=o*t:H=n*t;const z=N&&s>=N*2&&i===0?O.averageBitrate:O.maxBitrate,W=this.getTimeToLoadFrag(U,H,z*K,!C||C.live);if(H>=z&&(w===h||O.loadError===0&&O.fragmentError===0||us(O,E.errorPenaltyExpireMs))&&(W<=U||!G(W)||S&&!this.bitrateTestDelay||W<c)){const Z=this.forcedAutoLevel;return w!==m&&(Z===-1||Z!==m)&&($.length&&this.trace(`Skipped level(s) ${$.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${g[$[0]].codecs}" ${g[$[0]].videoRange}; not compatible with "${R}" ${A}`),this.info(`switch candidate:${f}->${w} adjustedbw(${Math.round(H)})-bitrate=${Math.round(H-z)} ttfb:${U.toFixed(1)} avgDuration:${K.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${W.toFixed(1)} firstSelection:${L} codecSet:${O.codecSet} videoRange:${O.videoRange} hls.loadLevel:${m}`)),L&&(this.firstSelection=w),w}}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 Us={search:function(a,t){let e=0,r=a.length-1,s=null,i=null;for(;e<=r;){s=(e+r)/2|0,i=a[s];const n=t(i);if(n>0)e=s+1;else if(n<0)r=s-1;else return i}return null}};function Pn(a,t,e){if(t===null||!Array.isArray(a)||!a.length||!G(t))return null;const r=a[0].programDateTime;if(t<(r||0))return null;const s=a[a.length-1].endProgramDateTime;if(t>=(s||0))return null;for(let i=0;i<a.length;++i){const n=a[i];if(wn(t,e,n))return n}return null}function Dr(a,t,e=0,r=0,s=.005){let i=null;if(a){i=t[1+a.sn-t[0].sn]||null;const o=a.endDTS-e;o>0&&o<15e-7&&(e+=15e-7),i&&a.level!==i.level&&i.end<=a.end&&(i=t[2+a.sn-t[0].sn]||null)}else e===0&&t[0].start===0&&(i=t[0]);if(i&&((!a||a.level===i.level)&&Gs(e,r,i)===0||xn(i,a,Math.min(s,r))))return i;const n=Us.search(t,Gs.bind(null,e,r));return n&&(n!==a||!i)?n:i}function xn(a,t,e){if(t?.start===0&&t.level<a.level&&(t.endPTS||0)>0){const r=t.tagList.reduce((s,i)=>(i[0]==="INF"&&(s+=parseFloat(i[1])),s),e);return a.start<=r}return!1}function Gs(a=0,t=0,e){if(e.start<=a&&e.start+e.duration>a)return 0;const r=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0));return e.start+e.duration-r<=a?1:e.start-r>a&&e.start?-1:0}function wn(a,t,e){const r=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0))*1e3;return(e.endProgramDateTime||0)-r>a}function On(a,t,e){if(a&&a.startCC<=t&&a.endCC>=t){let r=a.fragments;const{fragmentHint:s}=a;s&&(r=r.concat(s));let i;return Us.search(r,n=>n.cc<t?1:n.cc>t?-1:(i=n,n.end<=e?1:n.start>e?-1:0)),i||null}return null}function Mn(a,t){return t===a.endSN&&a.fragmentHint?a.fragmentHint:a.fragments[1+t-a.startSN]||null}var ut={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},ht={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16};class Vs extends $t{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(y.ERROR,this.onError,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(y.ERROR,this.onError,this),t.off(y.ERROR,this.onErrorOut,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return t?.type===j.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,r=e.currentLevel;return(t=e.loadLevelObj)!=null&&t.details||r===-1?e.loadLevel:r}variantHasKey(t,e){if(t){var r;if((r=t.details)!=null&&r.hasKey(e))return!0;const s=t.audioGroups;if(s)return this.hls.allAudioTracks.filter(i=>s.indexOf(i.groupId)>=0).some(i=>{var n;return(n=i.details)==null?void 0:n.hasKey(e)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var r;if(e.fatal)return;const s=this.hls,i=e.context;switch(e.details){case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:e.errorAction=this.getFragRetryOrSwitchAction(e);return;case D.FRAG_PARSING_ERROR:if((r=e.frag)!=null&&r.gap){e.errorAction=Ue();return}case D.FRAG_GAP:case D.FRAG_DECRYPT_ERROR:{e.errorAction=this.getFragRetryOrSwitchAction(e),e.errorAction.action=ut.SendAlternateToPenaltyBox;return}case D.PLAYLIST_UNCHANGED_ERROR:case D.LEVEL_EMPTY_ERROR:case D.LEVEL_PARSING_ERROR:{var n;const o=e.parent===j.MAIN?e.level:s.loadLevel;e.details===D.LEVEL_EMPTY_ERROR&&(n=e.context)!=null&&(n=n.levelDetails)!=null&&n.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,o):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,o))}return;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:typeof i?.level=="number"&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.level));return;case D.AUDIO_TRACK_LOAD_ERROR:case D.AUDIO_TRACK_LOAD_TIMEOUT:case D.SUBTITLE_LOAD_ERROR:case D.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const o=s.loadLevelObj;if(o&&(i.type===Q.AUDIO_TRACK&&o.hasAudioGroup(i.groupId)||i.type===Q.SUBTITLE_TRACK&&o.hasSubtitleGroup(i.groupId))){e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.loadLevel),e.errorAction.action=ut.SendAlternateToPenaltyBox,e.errorAction.flags=ht.MoveAllAlternatesMatchingHost;return}}return;case D.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:e.errorAction={action:ut.SendAlternateToPenaltyBox,flags:ht.MoveAllAlternatesMatchingHDCP};return;case D.KEY_SYSTEM_SESSION_UPDATE_FAILED:case D.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case D.KEY_SYSTEM_NO_SESSION:e.errorAction={action:ut.SendAlternateToPenaltyBox,flags:ht.MoveAllAlternatesMatchingKey};return;case D.BUFFER_ADD_CODEC_ERROR:case D.REMUX_ALLOC_ERROR:case D.BUFFER_APPEND_ERROR:e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level));return;case D.MEDIA_SOURCE_REQUIRES_RESET:e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)),e.errorAction.flags|=ht.ResetMediaSource|ht.SwitchToSDR;return;case D.INTERNAL_EXCEPTION:case D.BUFFER_APPENDING_ERROR:case D.BUFFER_APPEND_NO_PROGRESS:case D.BUFFER_FULL_ERROR:case D.LEVEL_SWITCH_ERROR:case D.BUFFER_STALLED_ERROR:case D.BUFFER_SEEK_OVER_HOLE:case D.BUFFER_NUDGE_ON_STALL:e.errorAction=Ue();return}e.type===Y.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=Ue())}getPlaylistRetryOrSwitchAction(t,e){const r=this.hls,s=hs(r.config.playlistLoadPolicy,t),i=this.playlistError++;if(de(s,i,De(t),t.response))return{action:ut.RetryRequest,flags:ht.None,retryConfig:s,retryCount:i};const n=this.getLevelSwitchAction(t,e);return s&&(n.retryConfig=s,n.retryCount=i),n}getFragRetryOrSwitchAction(t){const e=this.hls,r=this.getVariantLevelIndex(t.frag),s=e.levels[r],{fragLoadPolicy:i,keyLoadPolicy:n}=e.config,o=hs(os(t)?n:i,t),l=e.levels.reduce((d,u)=>d+u.fragmentError,0);if(s&&(t.details!==D.FRAG_GAP&&s.fragmentError++,!ls(t)&&de(o,l,De(t),t.response)))return{action:ut.RetryRequest,flags:ht.None,retryConfig:o,retryCount:l};const h=this.getLevelSwitchAction(t,r);return o&&(h.retryConfig=o,h.retryCount=l),h}getLevelSwitchAction(t,e){const r=this.hls;e==null&&(e=r.loadLevel);const s=this.hls.levels[e];if(s){var i,n;const h=t.details;s.loadError++,s.loadErrorTime=self.performance.now(),h===D.BUFFER_APPEND_ERROR&&s.fragmentError++;let d=-1;const{levels:u,loadLevel:c,minAutoLevel:f,maxAutoLevel:g}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const p=(i=t.frag)==null?void 0:i.type,m=(p===j.AUDIO&&h===D.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&Hs(t))&&u.some(({audioCodec:S})=>s.audioCodec!==S),T=t.sourceBufferName==="video"&&Hs(t)&&u.some(({codecSet:S,audioCodec:L})=>s.codecSet!==S&&s.audioCodec===L),{type:E,groupId:v}=(n=t.context)!=null?n:{};for(let S=u.length;S--;){const L=(S+c)%u.length;if(L!==c&&L>=f&&L<=g&&(u[L].loadError===0||us(u[L],r.config.errorPenaltyExpireMs))){var o,l;const R=u[L];if(h===D.FRAG_GAP&&p===j.MAIN&&t.frag){const A=u[L].details;if(A){const b=Dr(t.frag,A.fragments,t.frag.start);if(b!=null&&b.gap)continue}}else if(E===Q.AUDIO_TRACK&&R.hasAudioGroup(v)||E===Q.SUBTITLE_TRACK&&R.hasSubtitleGroup(v)||p===j.AUDIO&&(o=s.audioGroups)!=null&&o.some(A=>R.hasAudioGroup(A))||p===j.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some(A=>R.hasSubtitleGroup(A))||m&&s.audioCodec===R.audioCodec||T&&s.codecSet===R.codecSet||!m&&s.audioCodec!==R.audioCodec)continue;d=L;break}}if(d>-1&&r.loadLevel!==d)return t.levelRetry=!0,this.playlistError=0,{action:ut.SendAlternateToPenaltyBox,flags:ht.None,nextAutoLevel:d}}return{action:ut.SendAlternateToPenaltyBox,flags:ht.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var r,s;switch((r=e.errorAction)==null?void 0:r.action){case ut.DoNothing:break;case ut.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),!e.errorAction.resolved&&e.details!==D.FRAG_GAP&&e.details!==D.PLAYLIST_UNCHANGED_ERROR&&!Ks(e)&&(e.fatal=!0);break}if((((s=e.errorAction)==null?void 0:s.flags)||0)&ht.ResetMediaSource&&this.hls.recoverMediaError(),e.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const e=this.hls,r=t.errorAction;if(!r)return;let s=r.nextAutoLevel;if(r.flags===ht.None)this.switchLevel(t,s);else if(r.flags&ht.SwitchToSDR){const o=this.hls.levels,l=o.length;for(let h=l;h--;)o[h].videoRange!=="SDR"?(o[h].fragmentError++,o[h].loadError++):s===void 0&&(s=h)}else if(r.flags&ht.MoveAllAlternatesMatchingHDCP){const o=this.getVariantLevelIndex(t.frag),l=e.levels[o],h=l?.attrs["HDCP-LEVEL"];r.hdcpLevel=h;const d=h==="NONE";h&&!d?(e.maxHdcpLevel=Ar[Ar.indexOf(h)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)):(d&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),r.flags|=ht.MoveAllAlternatesMatchingKey)}if(r.flags&ht.MoveAllAlternatesMatchingKey){const o=t.decryptdata;if(o){const l=this.hls.levels,h=l.length;for(let u=h;u--;)if(this.variantHasKey(l[u],o)){var i,n;this.log(`Banned key found in level ${u} (${l[u].bitrate}bps) or audio group "${(i=l[u].audioGroups)==null?void 0:i.join(",")}" (${(n=t.frag)==null?void 0:n.type} fragment) ${ee(o.keyId||[])}`),l[u].fragmentError++,l[u].loadError++,this.log(`Removing level ${u} with key error (${t.error})`),this.hls.removeLevel(u)}const d=t.frag;if(this.hls.levels.length<h)r.resolved=!0;else if(d&&d.type!==j.MAIN){const u=d.decryptdata;u&&!o.matches(u)&&(r.resolved=!0)}}}r.resolved||this.switchLevel(t,s)}switchLevel(t,e){if(e!==void 0&&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===D.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&t.sourceBufferName!=="audiovideo")){const r=An(t.mimeType),s=this.hls.levels;for(let i=s.length;i--;)s[i][`${t.sourceBufferName}Codec`]===r&&(this.log(`Removing level ${i} for ${t.details} ("${r}" not supported)`),this.hls.removeLevel(i))}}}function Hs(a){const t=a.details;return t===D.BUFFER_ADD_CODEC_ERROR||t===D.MEDIA_SOURCE_REQUIRES_RESET||t===D.BUFFER_APPEND_ERROR&&!Ks(a)}function Ks(a){return a.details===D.BUFFER_APPEND_ERROR&&(a.error.name==="QuotaExceededError"||a.error.name==="InvalidStateError")}function Ue(a){const t={action:ut.DoNothing,flags:ht.None};return a&&(t.resolved=!0),t}const Fn=/^(\d+)x(\d+)$/,Ws=/(.+?)=(".*?"|.*?)(?:,|$)/g;class it{constructor(t,e){typeof t=="string"&&(t=it.parseAttrList(t,e)),lt(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}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=(e.length&1?"0":"")+e;const r=new Uint8Array(e.length/2);for(let s=0;s<e.length/2;s++)r[s]=parseInt(e.slice(s*2,s*2+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((s,i)=>(s[i.toLowerCase()]=!0,s),e)}bool(t){return this[t]==="YES"}decimalResolution(t){const e=Fn.exec(this[t]);if(e!==null)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let r;const s={};for(Ws.lastIndex=0;(r=Ws.exec(t))!==null;){const i=r[1].trim();let n=r[2];const o=n.indexOf('"')===0&&n.lastIndexOf('"')===n.length-1;let l=!1;if(o)n=n.slice(1,-1);else switch(i){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(!(e&&(o||l))&&!l&&!o)switch(i){case"CLOSED-CAPTIONS":if(n==="NONE")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":et.warn(`${t}: attribute ${i} is missing quotes`)}s[i]=n}return s}}const Nn="com.apple.hls.interstitial";function $n(a){return a!=="ID"&&a!=="CLASS"&&a!=="CUE"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function Bn(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"||a==="SCTE35-CMD"}class Ir{constructor(t,e,r=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=e?.tagAnchor||null,this.tagOrder=(s=e?.tagOrder)!=null?s:r,e){const i=e.attr;for(const n in i)if(Object.prototype.hasOwnProperty.call(t,n)&&t[n]!==i[n]){et.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=n;break}t=lt(new it({}),i,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in t){const i=e?.endDate||new Date(t["END-DATE"]);G(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return t===void 0?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 t===null||t.programDateTime===null?(et.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 e!==null?this._dateAtEnd=new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(G(t))return t}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 this.class===Nn}get isValid(){return!!this.id&&!this._badValueForSameId&&G(this.startDate.getTime())&&(this.duration===null||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`:G(this.startDate.getTime())?this.isInterstitial&&!("X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)?"Interstitial Date range missing X-ASSET-(LIST|URI)":this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Date range invalid start date":"Missing ID"}}const Ys=10;class js{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){this.advanced=!0,this.updated=!0;return}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||e===0&&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?G(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Ys}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?(this.driftEnd-this.driftStart)*1e3/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return(t=this.partList)!=null&&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(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(e!==-1){for(let r=t.length;r--;)if(t[r].index>e)return t[r].index;return e}}return 0}get lastPartSn(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.advancedDateTime!==void 0&&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&&this.advancedDateTime!==void 0&&this.misses<3?this.age>(this.partHoldBack||this.partTarget*3)*1.5:!1}}function qs(a,t){return a.length===t.length?!a.some((e,r)=>e!==t[r]):!1}function zs(a,t){return!a&&!t?!0:!a||!t?!1:qs(a,t)}var Kt={cbc:0,ctr:1};function ve(a){return a==="AES-128"||a==="AES-256"||a==="AES-256-CTR"}function Xs(a){switch(a){case"AES-128":case"AES-256":return Kt.cbc;case"AES-256-CTR":return Kt.ctr;default:throw new Error(`invalid full segment method ${a}`)}}let Ge={};class ne{static clearKeyUriToKeyIdMap(){Ge={}}static setKeyIdForUri(t,e){Ge[t]=e}static addKeyIdForUri(t){const e=Object.keys(Ge).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,e),Ge[t]=r,r}constructor(t,e,r,s=[1],i=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=s,this.iv=i,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!ve(t),n!=null&&n.startsWith("0x")&&(this.keyId=new Uint8Array(Ts(n)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&qs(t.keyFormatVersions,this.keyFormatVersions)&&zs(t.iv,this.iv)&&zs(t.keyId,this.keyId)}isSupported(){if(this.method){if(ve(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES"}return!1}getDecryptData(t,e){if(!this.encrypted||!this.uri)return null;if(ve(this.method)){let r=this.iv;return r||(typeof t!="number"&&(et.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),r=Un(t)),new ne(this.method,this.uri,"identity",this.keyFormatVersions,r)}return this}}function Un(a){const t=new Uint8Array(16);for(let e=12;e<16;e++)t[e]=a>>8*(15-e)&255;return t}const Qs=/#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,Zs=/#EXT-X-MEDIA:(.*)/g,Gn=/^#EXT(?:INF|-X-TARGETDURATION):/m,kr=new RegExp([/#EXTINF:\s*(\d+(?:\.\d*)?|\.\d+)?(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Vn=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 It{static findGroup(t,e){for(let r=0;r<t.length;r++){const s=t[r];if(s.id===e)return s}}static resolve(t,e){return sr.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Gn.test(t)}static parseMasterPlaylist(t,e){const r={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:!1},s=[];if(Qs.lastIndex=0,!t.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let i;for(;(i=Qs.exec(t))!=null;)if(i[1]){const o=new it(i[1],r),l=Js(o,i[2],e,r,s);l&&r.levels.push(l)}else if(i[3]){const o=i[3],l=i[4];switch(o){case"I-FRAME-STREAM-INF":{const h=new it(l,r),d=Js(h,h.URI,e,r,s,!0);d&&r.iframeVariants.push(d)}break;case"SESSION-DATA":{const h=new it(l,r),d=h["DATA-ID"];d&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[d]=h);break}case"SESSION-KEY":{const h=ei(l,e,r);h.encrypted&&h.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(h)):et.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${l}"`);break}case"DEFINE":break;case"CONTENT-STEERING":{const h=new it(l,r);r.contentSteering={uri:It.resolve(h["SERVER-URI"],e),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{r.startTimeOffset=ri(l);break}}}const n=s.length>0&&s.length<r.levels.length;return r.levels=n?s:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(t,e,r){let s;const i={},n=r.levels,o={AUDIO:n.map(h=>({id:h.attrs.AUDIO,audioCodec:h.audioCodec})),SUBTITLES:n.map(h=>({id:h.attrs.SUBTITLES,textCodec:h.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Zs.lastIndex=0;(s=Zs.exec(t))!==null;){const h=new it(s[1],r),d=h.TYPE;if(d){const u=o[d],c=i[d]||[];i[d]=c;const f=h.LANGUAGE,g=h["ASSOC-LANGUAGE"],p=h.CHANNELS,m=h.CHARACTERISTICS,T=h["INSTREAM-ID"],E={attrs:h,bitrate:0,id:l++,groupId:h["GROUP-ID"]||"",name:h.NAME||f||"",type:d,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:f,url:h.URI?It.resolve(h.URI,e):""};if(g&&(E.assocLang=g),p&&(E.channels=p),m&&(E.characteristics=m),T&&(E.instreamId=T),u!=null&&u.length){const v=It.findGroup(u,E.groupId)||u[0];ii(E,v,"audioCodec"),ii(E,v,"textCodec")}c.push(E)}}return i}static parseLevelPlaylist(t,e,r,s,i,n){var o;const l={url:e},h=new js(e),d=h.fragments,u=[];let c=null,f=0,g=0,p=0,m=0,T=0,E=null,v=new he(s,l),S,L,R,A=-1,b=!1,k=null,P;if(kr.lastIndex=0,h.m3u8=t,h.hasVariableRefs=!1,((o=kr.exec(t))==null?void 0:o[0])!=="#EXTM3U")return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;(S=kr.exec(t))!==null;){b&&(b=!1,v=new he(s,l),v.playlistOffset=p,v.setStart(p),v.sn=f,v.cc=m,T&&(v.bitrate=T),v.level=r,c&&(v.initSegment=c,c.rawProgramDateTime&&(v.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null),k&&(v.setByteRange(k),k=null)));const $=S[1];if($){v.duration=parseFloat($);const _=(" "+S[2]).slice(1);v.title=_||null,v.tagList.push(_?["INF",$,_]:["INF",$])}else if(S[3]){if(G(v.duration)){var M;v.playlistOffset=p,v.setStart(p),R&&ni(v,R,h),v.sn=f,v.level=r,v.cc=m;const _=(" "+S[3]).slice(1);v.relurl=_,_r(v,E,u),E=v,p+=v.duration,f++,g=0;const w=v.byteRange;if(w.length===2&&(v.bitrate=(w[1]-w[0])*8/v.duration|0),h.iframesOnly&&w[0]&&((M=c)==null?void 0:M.cc)!==m){const O=new he(s,l);O.relurl=v.relurl,O.setByteRange(`${Math.min(w[0],1316)}@0`),O.level=r,O.sn="initSegment",R&&(O.levelkeys=R,R.identity&&(O._decryptdata=R.identity.getDecryptData(0))),c=O,v.initSegment=c}d.push(v),b=!0}}else{if(S=S[0].match(Vn),!S){et.warn("No matches on slow regex match for level playlist!");continue}for(L=1;L<S.length&&S[L]===void 0;L++);const _=(" "+S[L]).slice(1),w=(" "+S[L+1]).slice(1),O=S[L+2]?(" "+S[L+2]).slice(1):null;switch(_){case"BYTERANGE":E?v.setByteRange(w,E):v.setByteRange(w);break;case"PROGRAM-DATE-TIME":v.rawProgramDateTime=w,v.tagList.push(["PROGRAM-DATE-TIME",w]),A===-1&&(A=d.length);break;case"PLAYLIST-TYPE":h.type&&Gt(h,_,S),h.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":h.startSN!==0?Gt(h,_,S):E!==null&&Wn(h,_,S),h.startSN=parseInt(w),f=h.startSN+h.skippedSegments;break;case"SKIP":{h.skippedSegments&&Gt(h,_,S);const I=new it(w,h),C=I.decimalInteger("SKIPPED-SEGMENTS");if(G(C)){h.skippedSegments+=C;for(let H=C;H--;)d.push(null);f+=C}const K=I.enumeratedString("RECENTLY-REMOVED-DATERANGES");K&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(K.split(" ")));break}case"TARGETDURATION":h.targetduration!==0&&Gt(h,_,S),h.targetduration=Math.max(parseInt(w),1);break;case"VERSION":h.version!==null&&Gt(h,_,S),h.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":h.iframesOnly=!0;break;case"ENDLIST":h.live||Gt(h,_,S),h.live=!1;break;case"#":(w||O)&&v.tagList.push(O?[w,O]:[w]);break;case"DISCONTINUITY":m++,v.tagList.push(["DIS"]);break;case"GAP":v.gap=!0,v.tagList.push([_]);break;case"BITRATE":v.tagList.push([_,w]),T=parseInt(w)*1e3,G(T)?v.bitrate=T:T=0;break;case"DATERANGE":{const I=new it(w,h),C=new Ir(I,h.dateRanges[I.ID],h.dateRangeTagCount);h.dateRangeTagCount++,C.isValid||h.skippedSegments?h.dateRanges[C.id]=C:et.log(`Ignoring invalid DATERANGE tag: ${C.invalidReason}: ${w}`),v.tagList.push(["EXT-X-DATERANGE",w]);break}case"DEFINE":break;case"DISCONTINUITY-SEQUENCE":h.startCC!==0&&Gt(h,_,S),h.startCC=m=parseInt(w),d.forEach(I=>I&&(I.cc=m));break;case"KEY":{const I=ei(w,e,h);if(I.isSupported()){if(I.method==="NONE"){R=void 0;break}R||(R={});const C=R[I.keyFormat];C!=null&&C.matches(I)||(C&&(R=lt({},R)),R[I.keyFormat]=I)}else et.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${w}" (light build)`);break}case"START":h.startTimeOffset=ri(w);break;case"MAP":{const I=new it(w,h);if(v.duration){const C=new he(s,l);ai(C,I,r,R),c=C,v.initSegment=c,c.rawProgramDateTime&&!v.rawProgramDateTime&&(v.rawProgramDateTime=c.rawProgramDateTime)}else{const C=v.byteRangeEndOffset;if(C){const K=v.byteRangeStartOffset;k=`${C-K}@${K}`}else k=null;ai(v,I,r,R),c=v,b=!0}c.cc=m;break}case"SERVER-CONTROL":{P&&Gt(h,_,S),P=new it(w),h.canBlockReload=P.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=P.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&P.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=P.optionalFloat("PART-HOLD-BACK",0),h.holdBack=P.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{h.partTarget&&Gt(h,_,S);const I=new it(w);h.partTarget=I.decimalFloatingPoint("PART-TARGET");break}case"PART":{let I=h.partList;I||(I=h.partList=[]);const C=g>0?I[I.length-1]:void 0,K=g++,H=new it(w,h),z=new is(H,v,l,K,C);I.push(z),v.duration+=z.duration;break}case"PRELOAD-HINT":{const I=new it(w,h);h.preloadHint=I;break}case"RENDITION-REPORT":{const I=new it(w,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(I);break}default:et.warn(`line parsed but not handled: ${S}`);break}}}E&&!E.relurl?(d.pop(),p-=E.duration,h.partList&&(h.fragmentHint=E)):h.partList&&(_r(v,E,u),v.cc=m,h.fragmentHint=v,R&&ni(v,R,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));const x=d.length,N=d[0],U=d[x-1];if(p+=h.skippedSegments*h.targetduration,p>0&&x&&U){h.averagetargetduration=p/x;const $=U.sn;h.endSN=$!=="initSegment"?$:0,h.live||(U.endList=!0),A>0&&(Kn(d,A,A>x-1?v:null),N&&u.unshift(N))}return h.fragmentHint&&(p+=h.fragmentHint.duration),h.totalduration=p,u.length&&h.dateRangeTagCount&&N&&ti(u,h),h.endCC=m,h}}function Js(a,t,e,r,s,i){var n;if(t===void 0)return null;const o=t,l={attrs:a,bitrate:a.decimalInteger("BANDWIDTH")||a.decimalInteger("AVERAGE-BANDWIDTH"),name:a.NAME,url:It.resolve(o,e)},h=a.decimalResolution("RESOLUTION");h&&(l.width=h.width,l.height=h.height),si(a.CODECS,l);const d=a["SUPPLEMENTAL-CODECS"];return d&&(l.supplemental={},si(d,l.supplemental)),(n=l.unknownCodecs)!=null&&n.length||s.push(l),i&&(l.iframes=!0),l}function ti(a,t){let e=a.length;if(!e)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];a.push(o),e++}else return;const r=a[e-1],s=t.live?1/0:t.totalduration,i=Object.keys(t.dateRanges);for(let o=i.length;o--;){const l=t.dateRanges[i[o]],h=l.startDate.getTime();l.tagAnchor=r.ref;for(let d=e;d--;){var n;if(((n=a[d])==null?void 0:n.sn)<t.startSN)break;const u=Hn(t,h,a,d,s);if(u){l.tagAnchor=u.ref;break}}}}function Hn(a,t,e,r,s){const i=e[r];if(i){const o=i.programDateTime;if(t>=o||r===0){var n;const l=(((n=e[r+1])==null?void 0:n.start)||s)-i.start;if(t<=o+l*1e3){const h=i.sn-a.startSN,d=a.fragments;if(h>=0&&h<d.length){if(d.length>e.length){const u=e[r+1]||d[d.length-1],c=Math.min(u.sn-a.startSN,d.length-1);for(let f=c;f>h;f--){const g=d[f].programDateTime;if(t>=g&&t<g+d[f].duration*1e3)return d[f]}}return d[h]}}}}return null}function ei(a,t,e){var r,s;const i=new it(a,e),n=(r=i.METHOD)!=null?r:"",o=i.URI,l=i.hexadecimalInteger("IV"),h=i.KEYFORMATVERSIONS,d=(s=i.KEYFORMAT)!=null?s:"identity";o&&i.IV&&!l&&et.error(`Invalid IV: ${i.IV}`);const u=o?It.resolve(o,t):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new ne(n,u,d,c,l,i.KEYID)}function ri(a){const t=new it(a).decimalFloatingPoint("TIME-OFFSET");return G(t)?t:null}function si(a,t){let e=(a||"").split(/[ ,]+/).filter(r=>r);["video","audio","text","image"].forEach(r=>{const s=e.filter(i=>yr(i,r));s.length&&(t[`${r}Codec`]=s.map(i=>i.split("/")[0]).join(","),e=e.filter(i=>s.indexOf(i)===-1))}),t.unknownCodecs=e}function ii(a,t,e){const r=t[e];r&&(a[e]=r)}function Kn(a,t,e){if(e||(e=a[t]),!!e)for(let r=t;r--;){const s=a[r];if(!s)return;s.programDateTime=e.programDateTime-s.duration*1e3,e=s}}function _r(a,t,e){a.rawProgramDateTime?e.push(a):t!=null&&t.programDateTime&&(a.programDateTime=t.endProgramDateTime)}function ai(a,t,e,r){a.relurl=t.URI,t.BYTERANGE&&a.setByteRange(t.BYTERANGE),a.level=e,a.sn="initSegment",r&&(a.levelkeys=r),a.initSegment=null}function ni(a,t,e){a.levelkeys=t;const{encryptedFragments:r}=e;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(s=>t[s].isCommonEncryption)&&r.push(a)}function Gt(a,t,e){a.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${e[0]})`)}function Wn(a,t,e){a.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${e[0]})`)}function Cr(a,t){const e=t.startPTS;if(G(e)){let r=0,s;t.sn>a.sn?(r=e-a.start,s=a):(r=a.start-e,s=t),s.duration!==r&&s.setDuration(r)}else t.sn>a.sn?a.cc===t.cc&&a.minEndPTS?t.setStart(a.start+(a.minEndPTS-a.start)):t.setStart(a.start+a.duration):t.setStart(Math.max(a.start-t.duration,0))}function oi(a,t,e,r,s,i,n,o){r-e<=0&&(o.warn("Fragment should have a positive duration",t),r=e+t.duration,i=s+t.duration);let l=e,h=r;const d=t.startPTS,u=t.endPTS;if(G(d)){const f=Math.abs(d-e);a&&f>a.totalduration?o.warn(`media timestamps and playlist times differ by ${f}s for level ${t.level} ${a.url}`):G(t.deltaPTS)?t.deltaPTS=Math.max(f,t.deltaPTS):t.deltaPTS=f,l=Math.max(e,d),e=Math.min(e,d),s=t.startDTS!==void 0?Math.min(s,t.startDTS):s,h=Math.min(r,u),r=Math.max(r,u),i=t.endDTS!==void 0?Math.max(i,t.endDTS):i}const c=e-t.start;return t.start!==0&&t.setStart(e),t.setDuration(r-t.start),t.startPTS=e,t.maxStartPTS=l,t.startDTS=s,t.endPTS=r,t.minEndPTS=h,t.endDTS=i,li(a,t,c)}function li(a,t,e){var r;const s=t.sn;if(!a||s<a.startSN||s>(((r=a.fragmentHint)==null?void 0:r.sn)||a.endSN))return 0;let i;const n=s-a.startSN,o=a.fragments;for(o[n]=t,i=n;i>0;i--)Cr(o[i],o[i-1]);for(i=n;i<o.length-1;i++)Cr(o[i],o[i+1]);return a.fragmentHint&&Cr(o[o.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,e}function Yn(a,t,e){if(a===t)return;let r=null;const s=a.fragments;for(let d=s.length-1;d>=0;d--){const u=s[d].initSegment;if(u){r=u;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let i;zn(a,t,(d,u,c,f)=>{if(u.cc!==d.cc&&(d.cc>u.cc||t.skippedSegments)){const g=d.cc-u.cc;for(let p=c;p<f.length;p++)f[p].cc+=g;t.endCC=f[f.length-1].cc}G(d.startPTS)&&G(d.endPTS)&&(u.setStart(u.startPTS=d.startPTS),u.startDTS=d.startDTS,u.maxStartPTS=d.maxStartPTS,u.endPTS=d.endPTS,u.endDTS=d.endDTS,u.minEndPTS=d.minEndPTS,u.setDuration(d.endPTS-d.startPTS),u.duration&&(i=u),t.PTSKnown=t.alignedSliding=!0),d.hasStreams&&(u.elementaryStreams=d.elementaryStreams),u.loader=d.loader,u.gap=d.gap||u.gap,d.hasStats&&(u.stats=d.stats),d.initSegment&&(u.initSegment=d.initSegment,r=d.initSegment)});const n=t.fragments,o=t.fragmentHint?n.concat(t.fragmentHint):n;if(r&&o.forEach(d=>{var u;d&&(!d.initSegment||d.initSegment.relurl===((u=r)==null?void 0:u.relurl))&&(d.initSegment=r)}),t.skippedSegments){if(t.deltaUpdateFailed=n.some(d=>!d),t.deltaUpdateFailed){e.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let d=t.skippedSegments;d--;)n.shift();t.startSN=n[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=jn(a.dateRanges,t,e));const d=a.fragments.filter(u=>u.rawProgramDateTime);if(a.hasProgramDateTime&&!t.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&_r(o[u],o[u-1],d);ti(d,t)}t.endCC=n[n.length-1].cc}else if(t.startSN>a.endSN&&n[0].cc<a.endCC){const d=a.endCC-n[0].cc;o.forEach(u=>{u.cc+=d}),t.endCC+=d}if(!t.startCC){var l;const d=Ve(a,t.startSN-1);t.startCC=(l=d?.cc)!=null?l:n[0].cc}if(qn(a.partList,t.partList,(d,u)=>{u.elementaryStreams=d.elementaryStreams,u.stats=d.stats,u.gap=d.gap||u.gap}),i){const d=t.iframesOnly&&i.type===j.MAIN;oi(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,d,e)}else di(a,t);n.length&&(t.totalduration=t.edge-n[0].start),t.driftStartTime=a.driftStartTime,t.driftStart=a.driftStart;const h=t.advancedDateTime;if(t.advanced&&h){const d=t.edge;t.driftStart||(t.driftStartTime=h,t.driftStart=d),t.driftEndTime=h,t.driftEnd=d}else t.driftEndTime=a.driftEndTime,t.driftEnd=a.driftEnd,t.advancedDateTime=a.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=a.requestScheduled)}function jn(a,t,e){const{dateRanges:r,recentlyRemovedDateranges:s}=t,i=lt({},a);s&&s.forEach(o=>{delete i[o]});const n=Object.keys(i).length;return n?(Object.keys(r).forEach(o=>{const l=i[o],h=new Ir(r[o].attr,l);h.isValid?(i[o]=h,l||(h.tagOrder+=n)):e.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${yt(r[o].attr)}"`)}),i):r}function qn(a,t,e){if(a&&t){let r=0;for(let s=0,i=a.length;s<i;s++){const n=a[s],o=t[s+r];n&&o&&n.index===o.index&&n.fragment.sn===o.fragment.sn?e(n,o):r--}}}function zn(a,t,e){var r;const s=t.skippedSegments,i=Math.max(a.startSN,t.startSN)-t.startSN,n=(a.fragmentHint?1:0)+(s?t.endSN:Math.min(a.endSN,t.endSN))-t.startSN,o=t.startSN-a.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,h=(r=a.fragmentHint)!=null&&r.duration?a.fragments.concat(a.fragmentHint):a.fragments;for(let d=i;d<=n;d++){const u=h[o+d];let c=l[d];if(s&&!c&&u&&(c=t.fragments[d]=u),u&&c){e(u,c,d,l);const f=u.relurl,g=c.relurl;if(f&&Qn(f,g)){t.playlistParsingError=hi(`media sequence mismatch ${c.sn}:`,a,t,u,c);return}else if(u.cc!==c.cc){t.playlistParsingError=hi(`discontinuity sequence mismatch (${u.cc}!=${c.cc})`,a,t,u,c);return}}}}function hi(a,t,e,r,s){return new Error(`${a} ${s.url}
|
|
12
|
+
Playlist starting @${t.startSN}
|
|
13
|
+
${t.m3u8}
|
|
14
|
+
|
|
15
|
+
Playlist starting @${e.startSN}
|
|
16
|
+
${e.m3u8}`)}function di(a,t,e=!0,r){const s=t.startSN+t.skippedSegments-a.startSN,i=a.fragments,n=s>=0;let o=0;if(n&&s<i.length)o=i[s].start,r?.log(`Aligning playlists based on SN ${t.startSN} (diff: ${o})`);else if(n&&t.startSN===a.endSN+1)o=a.fragmentEnd,r?.log(`Aligning playlists based on first/last SN ${t.startSN} (diff: ${o})`);else if(n&&e)o=a.fragmentStart+s*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)o=a.fragmentStart,r?.log(`Aligning playlists based on first SN ${t.startSN} (diff: ${o})`);else return o;return Xn(t,o),o}function Xn(a,t){if(t){const e=a.fragments;for(let r=a.skippedSegments;r<e.length;r++)e[r].addStart(t);a.fragmentHint&&a.fragmentHint.addStart(t)}}function ui(a,t=1/0){let e=1e3*a.targetduration;if(a.updated){const r=a.fragments;if(r.length&&e*4>t){const s=r[r.length-1].duration*1e3;s>0&&s<e&&(e=s)}}else e/=2;return Math.round(e)}function Ve(a,t,e){var r;if(!a)return null;let s=a.fragments[t-a.startSN];return s||(s=a.fragmentHint,((r=s)==null?void 0:r.sn)===t)?s:e&&t<a.startSN&&e.sn===t?e:null}function ci(a,t,e){return a?fi(a.partList,t,e):null}function fi(a,t,e){if(a)for(let r=a.length;r--;){const s=a[r];if(s.index===e&&s.fragment.sn===t)return s}return null}function gi(a){a.forEach((t,e)=>{var r;(r=t.details)==null||r.fragments.forEach(s=>{s.level=e,s.initSegment&&(s.initSegment.level=e)})})}function Qn(a,t){return a!==t&&t?mi(a)!==mi(t):!1}function mi(a){return a.replace(/\?[^?]*$/,"")}class pi extends $t{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(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,r){const s=e?.renditionReports;if(s){let i=-1;for(let n=0;n<s.length;n++){const o=s[n];let l;try{l=new self.URL(o.URI,e.url).href}catch(h){this.warn(`Could not construct new URL for Rendition Report: ${h}`),l=o.URI||""}if(l===t){i=n;break}else l===t.substring(0,l.length)&&(i=n)}if(i!==-1){const n=s[i],o=parseInt(n["LAST-MSN"])||e.lastPartSn;let l=parseInt(n["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const d=Math.min(e.age-e.partTarget,e.targetduration);l>=0&&d>e.partTarget&&(l+=1)}const h=r&&Ms(r);return new Rr(o,l>=0?l:void 0,h)}}}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(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}return t}playlistLoaded(t,e,r){const{details:s,stats:i}=e,n=s.fragments,o=self.performance.now(),l=i.loading.first?Math.max(0,Math.floor(o-i.loading.first)):0;s.advancedDateTime=Date.now()-l;const h=this.hls.config.timelineOffset;if(h!==s.appliedTimelineOffset){const u=Math.max(h||0,0);s.appliedTimelineOffset=u,n.forEach(c=>{c?.setStart(c.playlistOffset+u)})}if(s.live||r!=null&&r.live){var d;const u="levelInfo"in e?e.levelInfo:e.track;s.reloaded(r);const c=(d=n[n.length-1])==null?void 0:d.type;if(s.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const L=new Error(`${c} playlist ${u.id} hit max allowed unchanged reloads.`);this.warn(L);const{networkDetails:R,context:A}=e;this.hls.trigger(y.ERROR,{type:Y.NETWORK_ERROR,details:D.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:s.url,error:L,reason:L.message,level:e.level,parent:c,context:A,networkDetails:R,stats:i});return}if(r){Yn(r,s,this);const L=s.playlistParsingError;if(L){this.warn(L);const R=this.hls;if(!R.config.ignorePlaylistParsingErrors){const{networkDetails:A}=e;R.trigger(y.ERROR,{type:Y.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:L,reason:L.message,level:e.level,parent:c,networkDetails:A,stats:i});return}s.playlistParsingError=null}}s.requestScheduled===-1&&(s.requestScheduled=i.loading.start);const f=this.hls.mainForwardBufferInfo,g=f?f.end-f.len:0,p=(s.edge-g)*1e3,m=ui(s,p);s.requestScheduled+m<o?s.requestScheduled=o:s.requestScheduled<=o&&(s.requestScheduled+=m);const T=e.deliveryDirectives;if(this.log(`live playlist ${t} ${s.advanced?`REFRESHED ${s.lastPartSn} - ${s.lastPartIndex}`:s.updated?"UPDATED":`MISSED (received ${s.lastPartSn} - ${s.lastPartIndex}${T?` | requested ${T.msn} - ${T.part}`:""})`}`),!this.canLoad||!s.live)return;let E,v,S;if(s.canBlockReload&&s.advanced){const L=this.hls.config.lowLatencyMode,R=s.lastPartSn,A=s.endSN,b=s.lastPartIndex,k=b!==-1,P=R===A;k?P?(v=A+1,S=L?0:b):(v=R,S=L?b+1:s.maxPartIndex):v=A+1;const M=s.age,x=M+s.ageHeader;let N=Math.min(x-s.partTarget,s.targetduration*1.5);if(N>0){if(x>s.targetduration*3)this.log(`Playlist last advanced ${M.toFixed(2)}s ago. Omitting segment and part directives.`),v=void 0,S=void 0;else if(r!=null&&r.tuneInGoal&&x-s.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${N} with playlist age: ${s.age}`),N=0;else{const U=Math.floor(N/s.targetduration);if(v+=U,S!==void 0){const $=Math.round(N%s.targetduration/s.partTarget);S+=$}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${M.toFixed(2)}s goal: ${N} skip sn ${U} to part ${S}`)}s.tuneInGoal=N}if(E=this.getDeliveryDirectives(s,e.deliveryDirectives,v,S),L||!P){s.requestScheduled=o,this.loadingPlaylist(u,E);return}}else(s.canBlockReload||s.canSkipUntil)&&(E=this.getDeliveryDirectives(s,e.deliveryDirectives,v,S));E&&v!==void 0&&s.canBlockReload&&(s.requestScheduled=i.loading.first+Math.max(m-l*2,m/2)),this.scheduleLoading(u,E,s)}else this.clearTimer()}scheduleLoading(t,e,r){const s=r||t.details;if(!s){this.loadingPlaylist(t,e);return}const i=self.performance.now(),n=s.requestScheduled;if(i>=n&&!this.loadingSync){this.loadingSync=!0,this.loadingPlaylist(t,e),this.loadingSync=!1;return}const o=Math.max(n-i,0);this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),o)}getDeliveryDirectives(t,e,r,s){let i=Ms(t);return e!=null&&e.skip&&t.deltaUpdateFailed&&(r=e.msn,s=e.part,i=pe.No),new Rr(r,s,i)}checkRetry(t){const e=t.details,r=De(t),s=t.errorAction,{action:i,retryCount:n=0,retryConfig:o}=s||{},l=!!s&&!!o&&(i===ut.RetryRequest||!s.resolved&&i===ut.SendAlternateToPenaltyBox);if(l){var h;if(n>=o.maxNumRetry)return!1;if(r&&(h=t.context)!=null&&h.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{var d;const u=ue((d=t.response)==null?void 0:d.code);if(this.clearTimer(),u)this.log("Waiting for connection (offline)"),t.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const c=or(o,n);this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${e}" in ${c}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),c)}}t.levelRetry=!0,s.resolved=!0}return l}checkOfflineStatus(){this.clearTimer(),ue(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}class Zn{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(this.queues===null||this.tracks===null)return;const s=this.queues[e];s.push(t),s.length===1&&!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(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const r=(e=t[0])==null?void 0:e.label;r==="async-blocker"||r==="async-blocker-prepend"?(t[0].execute(),t.splice(0,1)):r==="block-audio"&&t.splice(0,1)})}insertNext(t,e){this.queues!==null&&this.queues[e].splice(1,0,...t)}unblockAudio(){var t;this.queues!==null&&((t=this.current("audio"))==null?void 0:t.label)==="block-audio"&&this.shiftAndExecuteNext("audio")}audioBlocking(){return this.queues===null?!1:this.queues.audio.some(t=>t.label==="block-audio")}executeNext(t){if(this.queues===null||this.tracks===null)return;const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(i){var r;if(s.onError(i),this.queues===null||this.tracks===null)return;const n=(r=this.tracks[t])==null?void 0:r.buffer;n!=null&&n.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues!==null&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return((e=this.queues)==null?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return t===null||e===null?"<destroyed>":`
|
|
17
|
+
${this.list("video")}
|
|
18
|
+
${this.list("audio")}
|
|
19
|
+
${this.list("audiovideo")}}`}list(t){var e,r;return(e=this.queues)!=null&&e[t]||(r=this.tracks)!=null&&r[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const r=(e=this.tracks)==null?void 0:e[t],s=r?.buffer;return s?`SourceBuffer${s.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(t){var e;return((e=this.queues)==null?void 0:e[t].map(r=>r.label).join(", "))||""}}const vi={length:0,start:()=>0,end:()=>0};class q{static isBuffered(t,e){if(t){const r=q.getBuffered(t);for(let s=r.length;s--;)if(e>=r.start(s)&&e<=r.end(s))return!0}return!1}static bufferedRanges(t){if(t){const e=q.getBuffered(t);return q.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 s=q.bufferedRanges(t);if(s.length)return q.bufferedInfo(s,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((d,u)=>d.start-u.start||u.end-d.end);let s=-1,i=[];if(r)for(let d=0;d<t.length;d++){e>=t[d].start&&e<=t[d].end&&(s=d);const u=i.length;if(u){const c=i[u-1].end;t[d].start-c<r?t[d].end>c&&(i[u-1].end=t[d].end):i.push(t[d])}else i.push(t[d])}else i=t;let n=0,o,l=e,h=e;for(let d=0;d<i.length;d++){const u=i[d].start,c=i[d].end;if(s===-1&&e>=u&&e<=c&&(s=d),e+r>=u&&e<c)l=u,h=c,n=h-e;else if(e+r<u){o=u;break}}return{len:n,start:l||0,end:h||0,nextStart:o,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||vi}catch(e){return et.log("failed to get media.buffered",e),vi}}}function mt(a,t,e){dt(a,t,e),a.addEventListener(t,e)}function dt(a,t,e){a.removeEventListener(t,e)}function Pr(a){let t="";const e=a.length;for(let r=0;r<e;r++)t+=`[${a.start(r).toFixed(3)}-${a.end(r).toFixed(3)}]`;return t}const Ei=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,yi="HlsJsTrackRemovedError",Ti="HlsJsSourceBufferError",Jn=.25,to=.001;class eo extends Error{constructor(t){super(t),this.name=yi}}class Si extends $t{constructor(t,e){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=r=>{var s;this.hls&&((s=this.mediaSource)==null?void 0:s.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=r=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=r=>{const{media:s,mediaSource:i}=this;r&&this.log("Media source opened"),!(!s||!i)&&(dt(i,"sourceopen",this._onMediaSourceOpen),dt(s,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(y.MEDIA_ATTACHED,{media:s,mediaSource:i}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){if(this.isMediaSourceReplaced()){const{currentSrc:l}=this.media,h=l&&l!==this._objectUrl?l:this.mediaSrc;this.warn(`MediaSource closed after media element switched to another source (${this._objectUrl} > ${h}) - detaching media`),this.hls.detachMedia();return}const r=this.media.error,{appendError:s,appendErrors:i}=this;let n=!1;!s&&r&&(n=Math.max(++i.audio,++i.video,++i.audiovideo)>=this.hls.config.appendErrorMaxRetry);const o=new Error(`MediaSource closed while media attached${Ai(n,r)}`);this.warn(o),this.hls.trigger(y.ERROR,lt({fatal:n},s,{type:Y.MEDIA_ERROR,details:D.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:r,_objectUrl:s}=this;r!==s&&this.error(`Media element src was set while attaching MediaSource (${s} > ${r})`)},this._onMediaError=()=>{const{media:r}=this;if(r){var s,i;this.log(`Media error (code: ${(s=r.error)==null?void 0:s.code}): ${(i=r.error)==null?void 0:i.message}`)}},this.hls=t,this.fragmentTracker=e,this.appendSource=Fa(Ut(t.config.preferManagedMediaSource)),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(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.BUFFER_RESET,this.onBufferReset,this),t.on(y.BUFFER_APPENDING,this.onBufferAppending,this),t.on(y.BUFFER_CODECS,this.onBufferCodecs,this),t.on(y.BUFFER_EOS,this.onBufferEos,this),t.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(y.FRAG_PARSED,this.onFragParsed,this),t.on(y.FRAG_CHANGED,this.onFragChanged,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.BUFFER_RESET,this.onBufferReset,this),t.off(y.BUFFER_APPENDING,this.onBufferAppending,this),t.off(y.BUFFER_CODECS,this.onBufferCodecs,this),t.off(y.BUFFER_EOS,this.onBufferEos,this),t.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(y.FRAG_PARSED,this.onFragParsed,this),t.off(y.FRAG_CHANGED,this.onFragChanged,this),t.off(y.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const r={};if(this.operationQueue){const i=this.isUpdating();i||this.operationQueue.removeBlockers();const n=this.isQueued();(i||n)&&this.warn(`Transfering MediaSource with${n?" operations in queue":""}${i?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return s&&!this.sourceBufferCount&&s.mediaSource===e?lt(r,s.tracks):this.sourceBuffers.forEach(i=>{const[n]=i;n&&(r[n]=lt({},this.tracks[n]),this.removeBuffer(n)),i[0]=i[1]=null}),{media:t,mediaSource:e,tracks:r}}initTracks(){const t={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=t,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 s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(r=this.transferData)!=null&&r.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(t,e){const r=this.media=e.media;this.transferData=this.overrides=void 0;const s=Ut(this.appendSource);if(s){const n=!!e.mediaSource;(n||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const o=this.mediaSource=e.mediaSource||new s;if(this.assignMediaSource(o),n)this._objectUrl=r.src,this.attachTransferred();else{var i;const l=this._objectUrl=self.URL.createObjectURL(o),h=this.hls.config,d=h.emeEnabled&&r.mediaKeys?(i=h.emeController)==null?void 0:i.CDMCleanupPromise:null;d?d.then(()=>{this.hls&&this.setSource(r,o,l)}).catch(()=>{}):this.setSource(r,o,l)}mt(r,"emptied",this._onMediaEmptied),mt(r,"error",this._onMediaError),this.appendSource&&mt(r,"seeking",this._onStartStreaming)}}setSource(t,e,r){if(this.appendSource)try{t.removeAttribute("src");const s=self.ManagedMediaSource;t.disableRemotePlayback=t.disableRemotePlayback||s&&e instanceof s,Li(t),ro(t,r),t.load()}catch{t.src=r}else t.src=r}assignMediaSource(t){var e,r;this.log(`${((e=this.transferData)==null?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${(r=t.constructor)==null?void 0:r.name}`),mt(t,"sourceopen",this._onMediaSourceOpen),mt(t,"sourceended",this._onMediaSourceEnded),mt(t,"sourceclose",this._onMediaSourceClose),this.appendSource&&(mt(t,"startstreaming",this._onStartStreaming),mt(t,"endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const r=this.tracks,s=e.tracks,i=s?Object.keys(s):null,n=i?i.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&i&&n){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
|
|
20
|
+
required tracks: ${yt(r,(l,h)=>l==="initSegment"?void 0:h)};
|
|
21
|
+
transfer tracks: ${yt(s,(l,h)=>l==="initSegment"?void 0:h)}}`),!Na(s,r)){e.mediaSource=null,e.tracks=void 0;const l=t.currentTime,h=this.details,d=Math.max(l,h?.fragments[0].start||0);if(d-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${d}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(r)}") start time: ${d} currentTime: ${l}`),this.onMediaDetaching(y.MEDIA_DETACHING,{}),this.onMediaAttaching(y.MEDIA_ATTACHING,e),t.currentTime=d;return}this.transferData=void 0,i.forEach(l=>{const h=l,d=s[h];if(d){const u=d.buffer;if(u){const c=this.fragmentTracker,f=d.id;if(c.hasFragments(f)||c.hasParts(f)){const m=q.getBuffered(u);c.detectEvictedFragments(h,m,f,null,null,!0)}const g=xr(h),p=[h,u];this.sourceBuffers[g]=p,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(h),this.trackSourceBuffer(h,d)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const e=(t=this.mediaSource)==null?void 0:t.readyState;return e==="open"||e==="ended"}onMediaDetaching(t,e){const r=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:i,_objectUrl:n}=this;if(i){if(this.log(`media source ${r?"transferring":"detaching"}`),r)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=i.readyState==="open";try{const l=i.sourceBuffers;for(let h=l.length;h--;)o&&l[h].abort(),i.removeSourceBuffer(l[h]);o&&i.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}dt(i,"sourceopen",this._onMediaSourceOpen),dt(i,"sourceended",this._onMediaSourceEnded),dt(i,"sourceclose",this._onMediaSourceClose),this.appendSource&&(dt(i,"startstreaming",this._onStartStreaming),dt(i,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(dt(s,"emptied",this._onMediaEmptied),dt(s,"error",this._onMediaError),dt(s,"seeking",this._onStartStreaming),r||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n&&!this.isMediaSourceReplaced(n)?(s.removeAttribute("src"),this.appendSource&&Li(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const r=(e=this.tracks[t])==null?void 0:e.buffer;if(this.removeBuffer(t),r)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(i){this.warn(`onBufferReset ${t}`,i)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[xr(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 Zn(this.tracks)}onBufferCodecs(t,e){var r;const s=this.tracks,i=Object.keys(e);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(s.audio||s.video)||s.audiovideo&&("audio"in e||"video"in e),o=!n&&this.sourceBufferCount&&this.media&&i.some(l=>!s[l]);if(n||o){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${i}" SourceBuffers`);return}i.forEach(l=>{var h,d;const u=e[l],{id:c,codec:f,levelCodec:g,container:p,metadata:m,supplemental:T}=u;let E=s[l];const v=(h=this.transferData)==null||(h=h.tracks)==null?void 0:h[l],S=v!=null&&v.buffer?v:E,L=S?.pendingCodec||S?.codec,R=S?.levelCodec;E||(E=s[l]={buffer:void 0,listeners:[],codec:f,supplemental:T,container:p,levelCodec:g,metadata:m,id:c});const A=$e(L,R),b=A?.replace(Ei,"$1");let k=$e(f,g);const P=(d=k)==null?void 0:d.replace(Ei,"$1");k&&A&&b!==P&&(l.slice(0,5)==="audio"&&(k=Ne(k,this.appendSource)),this.log(`switching codec ${L} to ${k}`),k!==(E.pendingCodec||E.codec)&&(E.pendingCodec=k),E.container=p,this.appendChangeType(l,p,k))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&((r=e.audio)==null?void 0:r.id)==="main"&&(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 s=`${e};codecs=${r}`,i={label:`change-type=${s}`,execute:()=>{const n=this.tracks[t];if(n){const o=n.buffer;o!=null&&o.changeType&&(this.log(`changing ${t} sourceBuffer type to ${s}`),o.changeType(s),n.codec=r,n.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${t} SourceBuffer type`,n)}};this.append(i,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const r=t.start,s=r+t.duration*.05;if(((e=this.fragmentTracker.getAppendedFrag(r,j.MAIN))==null?void 0:e.gap)===!0)return;const i={label:"block-audio",execute:()=>{var n,o;(this.lastVideoAppendEnd>s||q.isBuffered((n=this.tracks.video)==null?void 0:n.buffer,s)||((o=this.fragmentTracker.getAppendedFrag(s,j.MAIN))==null?void 0:o.gap)===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn("Error executing block-audio operation",n)}};this.append(i,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(t,e){const{tracks:r}=this,{data:s,type:i,parent:n,frag:o,part:l,chunkMeta:h,offset:d}=e,u=h.buffering[i],c=Et(o)&&!l&&!o.gap&&!h.partial&&!h.iframe;let f=null,g=!1;const{sn:p,cc:m}=o,T=self.performance.now();u.start=T;const E=o.stats.buffering,v=l?l.stats.buffering:null;E.start===0&&(E.start=T),v?.start===0&&(v.start=T);const S=r.audio;let L=!1;i==="audio"&&S?.container==="audio/mpeg"&&(L=!this.lastMpegAudioChunk||h.id===1||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const R=r.video,A=R?.buffer;if(A&&p!=="initSegment"&&d!==void 0){const P=S?.buffer,M=l||o;if(i==="audio"&&n!=="main"&&!(R.ending||R.ended)&&P&&q.getBuffered(P).length){const x=M.start+M.duration*.05,N=q.getBuffered(A),U=this.currentOp("video");!N.length&&!U?this.blockAudio(M):!q.isBuffered(A,x)&&this.lastVideoAppendEnd<x&&this.blockAudio(M)}else if(i==="video"){const x=M.end,N=this.lastVideoAppendEnd-x;this.lastVideoAppendEnd=x,N<0||N>M.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const b=(l||o).start,k={label:`append-${i}`,execute:()=>{var P;u.executeStart=self.performance.now();const M=(P=this.tracks[i])==null?void 0:P.buffer;M&&(c&&(f=q.timeRangesToArray(q.getBuffered(M)),g=bi(wr(f,o),o)),L?this.updateTimestampOffset(M,b,.1,i,p,m):d!==void 0&&G(d)&&this.updateTimestampOffset(M,d,1e-6,i,p,m)),this.appendExecutor(s,i)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[i]);const P=self.performance.now();u.executeEnd=u.end=P,E.first===0&&(E.first=P),v?.first===0&&(v.first=P);const M={};if(this.sourceBuffers.forEach(([x,N])=>{x&&(M[x]=q.getBuffered(N))}),c){const x=this.getFragmentAppendProgress(o),N=M[i];if(N&&f){const U=q.timeRangesToArray(N),$=wr(U,o);x.progressed||(x.progressed=$-wr(f,o)>to);const _=g&&bi($,o);x.fullyBuffered[i]=(x.fullyBuffered[i]===void 0||x.fullyBuffered[i])&&_}}this.hls.trigger(y.BUFFER_APPENDED,{type:i,frag:o,part:l,chunkMeta:h,parent:n,timeRanges:M})},onError:P=>{var M;this.clearBufferAppendTimeoutId(this.tracks[i]);const x=P.code===DOMException.QUOTA_EXCEEDED_ERR||P.name=="QuotaExceededError"||"quota"in P;if(x&&!this._quotaEvictionPending[i]){const _=this.getBackBufferEvictionTarget(i,s.byteLength,o.type);if(_>0){this._quotaEvictionPending[i]=!0,this.log(`QuotaExceededError on "${i}" append sn: ${p} - evicting back buffer to ${_.toFixed(3)}s and retrying`);const w=this.getFlushOp(i,0,_),O=this.getClearEvictionPendingOp(i);this.insertNext([w,k,O],i);return}this.warn(`QuotaExceededError on "${i}" sn: ${p} - no back buffer available to evict`)}c&&(this.getFragmentAppendProgress(o).errored=!0);const N={type:Y.MEDIA_ERROR,parent:n,details:D.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:l,chunkMeta:h,error:P,err:P,fatal:!1},U=(M=this.media)==null?void 0:M.error;if(P.name===yi&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))N.errorAction=Ue(!0);else{var $;x&&(N.details=D.BUFFER_FULL_ERROR);const _=++this.appendErrors[i],w=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${_}/${w+1} times to append segment in "${i}" sourceBuffer with error: ${P.message}`),_>=w&&(N.fatal=!x);const O=($=this.mediaSource)==null?void 0:$.readyState;(O==="ended"||O==="closed"||U)&&!this.isMediaSourceReplaced()&&(this.warn(`MediaSource readyState "${O}" during SourceBuffer${Ai(N.fatal,U)}`),N.details=D.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=N,this.hls.trigger(y.ERROR,N),x&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${i}" append sn: ${p}${l?" p: "+l.index:""} of ${n} playlist ${o.level} cc: ${m} offset: ${d} bytes: ${s.byteLength}`),this.append(k,i,this.isPending(this.tracks[i]))}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 s;const i=(s=this.tracks[t])==null?void 0:s.buffer;this.log(`Remove request ${e}-${r} from ${t} Source Buffer complete > buffer: ${i?Pr(q.getBuffered(i)):"(detached)"}`),this.hls.trigger(y.BUFFER_FLUSHED,{type:t,start:e,end:r})},onError:s=>{this.warn(`Failed to remove ${e}-${r} from "${t}" SourceBuffer`,s),this.hls.trigger(y.BUFFER_FLUSHED,{type:t,start:0,end:0,error:s})}}}onBufferFlushing(t,e){const{type:r,startOffset:s,endOffset:i}=e;(!r||r==="audio")&&this.unblockAudio(),r?this.append(this.getFlushOp(r,s,i),r):this.sourceBuffers.forEach(([n])=>{n&&this.append(this.getFlushOp(n,s,i),n)})}onFragParsed(t,e){const{frag:r,part:s,chunkMeta:i}=e,n=[],o=s?s.elementaryStreams:r.elementaryStreams;o[st.AUDIOVIDEO]?n.push("audiovideo"):(o[st.AUDIO]&&n.push("audio"),o[st.VIDEO]&&n.push("video"));const l=()=>{const h=self.performance.now();r.stats.buffering.end=h,s&&(s.stats.buffering.end=h);const d=s?s.stats:r.stats;this.checkAppendProgress(r,s,i,n),this.hls&&(this.hls.trigger(y.FRAG_BUFFERED,{frag:r,part:s,stats:d,id:r.type,chunkMeta:i}),!s&&r.gap&&d.retry&&this.log(`Nothing buffered for ${r.type} level: ${r.level} sn: ${r.sn} retries ${d.retry}`))};n.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${r.type} ${r.level} ${s?`part: ${s.index} of `:""}sn: ${r.sn}`),this.blockBuffers(l,n).catch(h=>{this.warn(`Fragment buffered callback ${h.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){var r,s;const i=(r=this.hls)==null?void 0:r.config;if(!i)return;const{backBufferLength:n,frontBufferFlushThreshold:o}=i;this.trimBuffers(o,n,e.frag,e.previousFrag);const l=e.frag.elementaryStreams,{appendErrors:h}=this,d=(s=this.appendError)==null?void 0:s.sourceBufferName;Object.keys(l).forEach(u=>{l[u]&&(h[u]=0,u===d&&(this.appendError=void 0),u==="audio"||u==="video"?(h.audiovideo=0,d==="audiovideo"&&(this.appendError=void 0)):(h.audio=0,h.video=0,d!=="audiovideo"&&(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(([i])=>{if(i){const n=this.tracks[i];(!e.type||e.type===i)&&(n.ending=!0,n.ended||(n.ended=!0,this.log(`${i} buffer reached EOS`)))}});const s=((r=this.overrides)==null?void 0:r.endOfStream)!==!1;this.allTracksEnding?(this.unblockAudio(),s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{if(this.tracksEnded(),!this.allTracksEnding){this.log("EOS cancelled");return}const{mediaSource:i}=this;if(i?.readyState!=="open"){i&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${i.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),i.endOfStream(),this.hls.trigger(y.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(y.BUFFERED_TO_END,void 0))):e.type==="video"&&this.unblockAudio()}get allTracksEnding(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!((e=this.tracks[t])!=null&&e.ended)})}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(t!==null){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(t,e){if(e.details===D.BUFFER_APPEND_ERROR&&e.frag){var r;const s=(r=e.errorAction)==null?void 0:r.nextAutoLevel;G(s)&&s!==e.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(t,e,r){const{media:s}=this;return s?this.fragmentTracker.getBackBufferEvictionEnd(s.currentTime,r,e):0}getFragmentAppendProgress(t){var e;const r=Ri(t);let s=this.fragmentAppendProgress[r];return((e=s)==null?void 0:e.stats)!==t.stats&&(s={stats:t.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[r]=s),s}checkAppendProgress(t,e,r,s){if(e||!Et(t)||t.gap||r.iframe||r.partial)return;const i=Ri(t),n=this.fragmentAppendProgress[i];delete this.fragmentAppendProgress[i];const o=t.stats.buffering;if(o.start&&!o.first)return;const l=n?.stats===t.stats?n:void 0;if(l!=null&&l.errored)return;const h=s.length>0&&s.every(c=>l?.fullyBuffered[c]===!0);if(l!=null&&l.progressed||h){delete this.appendsWithoutProgress[i];return}if(!l&&s.length===0)return;const d=(this.appendsWithoutProgress[i]||0)+1,u=this.hls;d>=u.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[i]:this.appendsWithoutProgress[i]=d,this.warn(`Fragment ${t.sn} of ${t.type} playlist ${t.level} appended ${d} time${d>1?"s":""} without buffered range growth`),u.trigger(y.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:t,chunkMeta:r,parent:t.type,appendsWithoutProgress:d,error:new Error(`Fragment append did not increase buffered coverage (${d})`)})}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(t,e,r,s){const{hls:i,details:n,media:o}=this;if(!o||n===null||!this.sourceBufferCount)return;const l=i.config,h=o.currentTime,d=n.levelTargetDuration;e=n.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:e;let u=-1/0;if(G(e)&&e>=0){const c=Math.max(e,d);u=Math.floor(h/d)*d-c}if(r){const c=this.getLoopBackBufferFlushEnd(r,s??null);c>0&&(u=Math.max(u,c))}if(u>0&&this.flushBackBuffer(h,d,u),G(t)&&t>0){const c=Math.max(l.maxBufferLength,t),f=Math.max(c,d),g=Math.floor(h/d)*d+f;this.flushFrontBuffer(h,d,g)}}getLoopBackBufferFlushEnd(t,e){var r;const{media:s}=this;if(((r=this.hls)==null?void 0:r.config.loopBackBufferFlush)===!1||!(s!=null&&s.loop)||!e||t.level<=e.level)return 0;const{video:i,audiovideo:n}=t.elementaryStreams;if(i!=null&&i.partial||n!=null&&n.partial)return 0;const o=this.getEarliestElementaryStreamStart(t)-Jn;return o<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${t.level}, range [0-${o.toFixed(3)}]`),o)}getEarliestElementaryStreamStart(t){const{audio:e,video:r,audiovideo:s}=t.elementaryStreams;let i=t.start;return s?i=Math.min(i,s.startDTS):(e&&(i=Math.min(i,e.startDTS)),r&&(i=Math.min(i,r.startDTS))),i}flushBackBuffer(t,e,r){this.sourceBuffers.forEach(([s,i])=>{if(i){const h=q.getBuffered(i);if(h.length>0&&r>h.start(0)){var n,o,l;this.hls.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:r});const d=this.tracks[s];if((n=this.details)!=null&&n.live)this.hls.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(d!=null&&d.ended&&!((o=this.media)!=null&&o.loop&&((l=this.hls)==null?void 0:l.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:s})}}})}flushFrontBuffer(t,e,r){this.sourceBuffers.forEach(([s,i])=>{if(i){const n=q.getBuffered(i),o=n.length;if(o<2)return;const l=n.start(o-1),h=n.end(o-1);if(r>l||t>=l&&t<=h)return;this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}})}getDurationAndRange(){var t;const{details:e,mediaSource:r}=this;if(!e||!this.media||r?.readyState!=="open")return null;const s=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&r.setLiveSeekableRange){const l=Math.max(0,e.fragmentStart),h=Math.max(l,s);return{duration:1/0,start:l,end:h}}return{duration:1/0}}const i=(t=this.overrides)==null?void 0:t.duration;if(i)return G(i)?{duration:i}:null;const n=this.media.duration,o=G(r.duration)?r.duration:0;return s>o&&s>n||!G(n)?{duration:s}:null}updateMediaSource({duration:t,start:e,end:r}){const s=this.mediaSource;!s||!this.media||s.readyState!=="open"||(s.duration!==t&&(G(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),s.duration=t),e!==void 0&&r!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${e}-${r}.`),s.setLiveSeekableRange(e,r)))}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}) ${yt(r)}`),this.tracksReady){var s;const i=(s=this.transferData)==null?void 0:s.tracks;i&&Object.keys(i).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,r])=>{if(e){const s=this.tracks[e];t[e]={buffer:r,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(y.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(y.ERROR,{type:Y.MEDIA_ERROR,details:D.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 i in t){const n=i,o=t[n];if(this.isPending(o)){const l=this.getTrackCodec(o,n),h=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${h})${this.currentOp(n)?" Queued":""} ${yt(o)}`);try{const d=r.addSourceBuffer(h),u=xr(n),c=[n,d];e[u]=c,o.buffer=d}catch(d){var s;this.error(`error while trying to add sourceBuffer: ${d.message}`),this.shiftAndExecuteNext(n),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[n],this.hls.trigger(y.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:d,sourceBufferName:n,mimeType:h,parent:o.id});return}this.trackSourceBuffer(n,o)}}this.bufferCreated()}clearBufferAppendTimeoutId(t){t&&(self.clearTimeout(t.bufferAppendTimeoutId),t.bufferAppendTimeoutId=void 0)}getTrackCodec(t,e){const r=t.supplemental;let s=t.codec;r&&(e==="video"||e==="audiovideo")&&me(r,"video")&&(s=Sn(s,r));const i=$e(s,t.levelCodec);return i?e.slice(0,5)==="audio"?Ne(i,this.appendSource):i:""}trackSourceBuffer(t,e){const r=e.buffer;if(!r)return;const s=this.getTrackCodec(e,t);this.tracks[t]={buffer:r,codec:s,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",(i,n)=>{const o=n.removedRanges;o!=null&&o.length&&(this.log(`${i} buffer removed ${Pr(o)}`),this.hls.trigger(y.BUFFER_FLUSHED,{type:i,start:o.start(0),end:o.end(o.length-1)}))})}get mediaSrc(){var t;const e=this.media;return e?(e.src?e:((t=e.querySelector)==null?void 0:t.call(e,"source"))||e).src:void 0}isMediaSourceReplaced(t=this._objectUrl){var e;if(!t)return!1;const r=(e=this.media)==null?void 0:e.currentSrc,s=this.mediaSrc;return!!r&&r!==t||!!s&&s!==t}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e,r;if(((e=this.mediaSource)==null?void 0:e.readyState)==="closed"){this.resetBuffer(t);return}const s=this.currentOp(t);if(s){if(s.onComplete(),(r=this.tracks[t])==null||(r=r.buffer)==null?void 0:r.updating){this.log(`${t} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(t)});return}this.shiftAndExecuteNext(t)}}onSBUpdateError(t,e){var r;const s=(r=this.mediaSource)==null?void 0:r.readyState,i=new Error(`${t} SourceBuffer error. MediaSource readyState: ${s}`);i.name=Ti,this.error(`${i.message}`,e),this.hls.trigger(y.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:i,fatal:!1});const n=this.currentOp(t);n&&n.onError(i)}updateTimestampOffset(t,e,r,s,i,n){const o=e-t.timestampOffset;Math.abs(o)>=r&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${e} (sn: ${i} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,e,r){const{media:s,mediaSource:i}=this,n=this.tracks[t],o=n?.buffer;if(!s||!i||!o)throw new Error(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`);const l=G(s.duration)?s.duration:1/0,h=G(i.duration)?i.duration:1/0,d=Math.max(0,e);if(d>=h){var u;(u=this.currentOp(t))==null||u.onComplete(),this.shiftAndExecuteNext(t);return}const c=Math.min(r,l,h);if(c>d&&(!n.ending||n.ended))n.ended=!1,this.log(`Removing [${d},${c}] from the ${t} SourceBuffer`),o.remove(d,c);else throw new Error(`Cannot remove ${c<=d?`invalid range (${d} >= ${c}) `:""}from the ${t} SourceBuffer${n.ending?" while track ending":""}`)}appendExecutor(t,e){const r=this.tracks[e],s=r?.buffer;if(!s)throw new eo(`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 i=this.calculateAppendTimeoutTime(s);r.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(e,s,i),i)}s.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{this.log(`Failed to abort append on ${t} source buffer after timeout.`)}const s=this.currentOp(t);s&&s.onError(new Error(`${t}-append-timeout`))}calculateAppendTimeoutTime(t){let e=Ys;this.details&&(e=this.details.levelTargetDuration);let r=2*e*1e3;if(this.media===null)return r;const s=q.bufferInfo(t,this.media.currentTime,0);return s.len?(r=Math.max(s.len*1e3,r),Math.max(this.hls.config.appendTimeout,r)):r}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}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((t=this.currentOp("audio"))==null?void 0:t.label)==="block-audio"}isAudioBlocking(){return this.operationQueue?this.operationQueue.audioBlocking():!1}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,s=e.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:e.map(i=>this.appendBlocker(i));return Promise.all(s).then(i=>{r===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(e=>{var r;const s=(r=this.tracks[e])==null?void 0:r.buffer;!s||s.updating||e==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(e)})}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 s=this.tracks[t];if(!s)return;const i=s.buffer;if(!i)return;const n=r.bind(this,t);s.listeners.push({event:e,listener:n}),mt(i,e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const r=e.buffer;r&&(e.listeners.forEach(s=>{dt(r,s.event,s.listener)}),e.listeners.length=0)}}function Li(a){const t=a.querySelectorAll("source");[].slice.call(t).forEach(e=>{a.removeChild(e)})}function ro(a,t){const e=self.document.createElement("source");e.type="video/mp4",e.src=t,a.appendChild(e)}function xr(a){return a==="audio"?1:0}function Ai(a,t){return`${a?"":" - triggering recovery"}${t?" with HTMLMediaElement Error: "+t.message:""}`}function Ri(a){return`${a.type}_${a.sn}_${a.level}`}function wr(a,t){const{start:e,end:r}=t;let s=0;for(let i=0;i<a.length;i++){const n=a[i];if(n.start>=r)break;const o=Math.max(e,n.start),l=Math.min(r,n.end);l>o&&(s+=l-o)}return s}function bi(a,t){return t.duration-a<=.05}var ct={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class so{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(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.BUFFER_APPENDED,this.onBufferAppended,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this),t.on(y.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.BUFFER_APPENDED,this.onBufferAppended,this),t.off(y.FRAG_BUFFERED,this.onFragBuffered,this),t.off(y.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 s=r.length;s--;){const i=r[s];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:s}=this,i=Object.keys(s);for(let n=i.length;n--;){const o=s[i[n]];if(o?.body.type===e&&(!r||o.buffered)){const l=o.body;if(l.start<=t&&t<=l.end)return l}}return null}detectEvictedFragments(t,e,r,s,i,n){this.timeRanges&&(this.timeRanges[t]=e);const o=i?.fragment.sn||-1;Object.keys(this.fragments).forEach(l=>{const h=this.fragments[l];if(!h||!this.hls)return;const d=h.body;if(o>=d.sn)return;if(!h.buffered&&(!h.loaded||n)){d.type===r&&this.removeFragment(d);return}const u=h.range[t];if(u){if(u.time.length===0){this.removeFragment(d);return}if(u.time.some(c=>{const f=!this.isTimeBuffered(c.startPTS,c.endPTS,e);return f&&this.removeFragment(d),f}),s&&s!==d&&ge()){const c=s.endPTS,f=d.startPTS;if(c&&f&&h.range.video){const g=f-c;g<0&&g>-.1&&(this.removeFragment(d),this.hls.trigger(y.BUFFER_FLUSHING,{startOffset:c+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(t){const e=this.timeRanges,{frag:r,part:s,id:i}=t;if(!e||!Et(r))return;const n=ie(r),o=this.fragments[n];if(!o||o.buffered&&r.gap)return;const l=!r.relurl;Object.keys(e).forEach(d=>{const u=r.elementaryStreams[d];if(!u)return;const c=e[d],f=l||u.partial===!0;o.range[d]=this.getBufferedTimes(r,s,f,c),this.detectEvictedFragments(d,c,i,r,s)}),o.loaded=null;const h=Object.keys(o.range);if(h.length){if(this.bufferedEnd(o,r),He(o)||this.removeParts(r.sn-1,r.type),!s){const d=Math.min(.004,r.duration);h.some(u=>{var c;const f=(c=o.range[u])==null?void 0:c.time,g=f.length===0||f.length===1&&f[0].endPTS-f[0].startPTS<d;return g&&this.addAsGap(r),g})}}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]=Di(r,s=>s.fragment.sn>=t))}fragBuffered(t,e){const r=ie(t);let s=this.fragments[r];return!s&&e&&(s=this.fragments[r]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,t)),s}getBufferedTimes(t,e,r,s){const i={time:[],partial:r},n=t.start,o=t.end,l=t.minEndPTS||o,h=t.maxStartPTS||n;for(let d=0;d<s.length;d++){const u=s.start(d)-this.bufferPadding,c=s.end(d)+this.bufferPadding;if(h>=u&&l<=c){i.time.push({startPTS:Math.max(n,s.start(d)),endPTS:Math.min(o,s.end(d))});break}else if(n<c&&o>u){const f=Math.max(n,s.start(d)),g=Math.min(o,s.end(d));g>f&&(i.partial=!0,i.time.push({startPTS:f,endPTS:g}))}else if(o<=u)break}return i}getPartialFragment(t){let e=null,r,s,i,n=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(h=>{const d=l[h];d&&He(d)&&(s=d.body.start-o,i=d.body.end+o,t>=s&&t<=i&&(r=Math.min(t-s,i-t),n<=r&&(e=d.body,n=r)))}),e}isEndListAppended(t){const e=this.endListFragments[t];return e!==void 0&&(e.buffered||He(e))}getState(t){const e=ie(t),r=this.fragments[e];return r?r.buffered?He(r)?ct.PARTIAL:ct.OK:ct.APPENDING:ct.NOT_LOADED}isTimeBuffered(t,e,r){let s,i;for(let n=0;n<r.length;n++){if(s=r.start(n)-this.bufferPadding,i=r.end(n)+this.bufferPadding,t>=s&&e<=i)return!0;if(e<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if(!Et(e.frag)||e.frag.bitrateTest)return;const r=e.frag,s=e.part?null:e,i=ie(r);this.fragments[i]={body:r,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:r,part:s,timeRanges:i}=e;if(!Et(r))return;const n=r.type;if(s){let o=this.activePartLists[n];o||(this.activePartLists[n]=o=[]),o.push(s)}this.timeRanges=i}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=ie(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,r=Object.keys(e);if(!t)return r.length>0;for(let s=r.length;s--;){const i=e[r[s]];if(i?.body.type===t)return!0}return!1}hasParts(t){var e;return!!((e=this.activePartLists[t])!=null&&e.length)}getBackBufferEvictionEnd(t,e,r){const{fragments:s}=this;let i=0,n=0;const o=Object.keys(s);for(let l=0;l<o.length;l++){const h=s[o[l]];if(!h||!h.buffered||h.body.type!==e)continue;const d=h.body;if(d.gap)return 0;const u=d.hasStats&&d.stats.loaded||d.byteLength||d.bitrate&&d.bitrate*8*d.duration;if(d.end<=t&&u&&(i+=u,n=Math.max(n,d.end),i>=r))return n}return n>0?n:0}removeFragmentsInRange(t,e,r,s,i){s&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];if(!o)return;const l=o.body;l.type!==r||s&&!l.gap||l.start<e&&l.end>t&&(o.buffered||i)&&this.removeFragment(l)})}removeFragment(t){const e=ie(t);t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const s=t.sn;this.activePartLists[t.type]=Di(r,i=>i.fragment.sn!==s)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}gapFragments(){return this.hasGaps?Object.keys(this.fragments).map(t=>{var e;return(e=this.fragments[t])==null?void 0:e.body}).filter(t=>!!(t!=null&&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=(t=this.hls)==null||(t=t.latestLevelDetails)==null?void 0:t.partList;e&&e.forEach(r=>r.clearElementaryStreamInfo())}}function He(a){var t,e,r,s;return a.buffered&&!!(a.body.gap||(t=a.range.video)!=null&&t.partial||(e=a.range.audio)!=null&&e.partial||(r=a.range.audiovideo)!=null&&r.partial||(s=a.range.subs)!=null&&s.partial)}function ie(a){return`${a.type}_${a.level}_${a.sn}`}function Di(a,t){return a.filter(e=>{const r=t(e);return r||e.clearElementaryStreamInfo(),r})}class io{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 Kt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case Kt.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function ao(a){const t=a.byteLength,e=t&&new DataView(a.buffer).getUint8(t-1);return e?a.slice(0,t-e):a}class no{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 s=0;s<4;s++)r[s]=e.getUint32(s*4);return r}initTable(){const t=this.sBox,e=this.invSBox,r=this.subMix,s=r[0],i=r[1],n=r[2],o=r[3],l=this.invSubMix,h=l[0],d=l[1],u=l[2],c=l[3],f=new Uint32Array(256);let g=0,p=0,m=0;for(m=0;m<256;m++)m<128?f[m]=m<<1:f[m]=m<<1^283;for(m=0;m<256;m++){let T=p^p<<1^p<<2^p<<3^p<<4;T=T>>>8^T&255^99,t[g]=T,e[T]=g;const E=f[g],v=f[E],S=f[v];let L=f[T]*257^T*16843008;s[g]=L<<24|L>>>8,i[g]=L<<16|L>>>16,n[g]=L<<8|L>>>24,o[g]=L,L=S*16843009^v*65537^E*257^g*16843008,h[T]=L<<24|L>>>8,d[T]=L<<16|L>>>16,u[T]=L<<8|L>>>24,c[T]=L,g?(g=E^f[f[f[S^E]]],p^=f[f[p]]):g=p=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let r=!0,s=0;for(;s<e.length&&r;)r=e[s]===this.key[s],s++;if(r)return;this.key=e;const i=this.keySize=e.length;if(i!==4&&i!==6&&i!==8)throw new Error("Invalid aes key size="+i);const n=this.ksRows=(i+6+1)*4;let o,l;const h=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),u=this.sBox,c=this.rcon,f=this.invSubMix,g=f[0],p=f[1],m=f[2],T=f[3];let E,v;for(o=0;o<n;o++){if(o<i){E=h[o]=e[o];continue}v=E,o%i===0?(v=v<<8|v>>>24,v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255],v^=c[o/i|0]<<24):i>6&&o%i===4&&(v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255]),h[o]=E=(h[o-i]^v)>>>0}for(l=0;l<n;l++)o=n-l,l&3?v=h[o]:v=h[o-4],l<4||o<=4?d[l]=v:d[l]=g[u[v>>>24]]^p[u[v>>>16&255]]^m[u[v>>>8&255]]^T[u[v&255]],d[l]=d[l]>>>0}networkToHostOrderSwap(t){return t<<24|(t&65280)<<8|(t&16711680)>>8|t>>>24}decrypt(t,e,r){const s=this.keySize+6,i=this.invKeySchedule,n=this.invSBox,o=this.invSubMix,l=o[0],h=o[1],d=o[2],u=o[3],c=this.uint8ArrayToUint32Array_(r);let f=c[0],g=c[1],p=c[2],m=c[3];const T=new Int32Array(t),E=new Int32Array(T.length);let v,S,L,R,A,b,k,P,M,x,N,U,$,_;const w=this.networkToHostOrderSwap;for(;e<T.length;){for(M=w(T[e]),x=w(T[e+1]),N=w(T[e+2]),U=w(T[e+3]),A=M^i[0],b=U^i[1],k=N^i[2],P=x^i[3],$=4,_=1;_<s;_++)v=l[A>>>24]^h[b>>16&255]^d[k>>8&255]^u[P&255]^i[$],S=l[b>>>24]^h[k>>16&255]^d[P>>8&255]^u[A&255]^i[$+1],L=l[k>>>24]^h[P>>16&255]^d[A>>8&255]^u[b&255]^i[$+2],R=l[P>>>24]^h[A>>16&255]^d[b>>8&255]^u[k&255]^i[$+3],A=v,b=S,k=L,P=R,$=$+4;v=n[A>>>24]<<24^n[b>>16&255]<<16^n[k>>8&255]<<8^n[P&255]^i[$],S=n[b>>>24]<<24^n[k>>16&255]<<16^n[P>>8&255]<<8^n[A&255]^i[$+1],L=n[k>>>24]<<24^n[P>>16&255]<<16^n[A>>8&255]<<8^n[b&255]^i[$+2],R=n[P>>>24]<<24^n[A>>16&255]<<16^n[b>>8&255]<<8^n[k&255]^i[$+3],E[e]=w(v^f),E[e+1]=w(R^g),E[e+2]=w(L^p),E[e+3]=w(S^m),f=M,g=x,p=N,m=U,e=e+4}return E.buffer}}class oo{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=lo(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}function lo(a){switch(a){case Kt.cbc:return"AES-CBC";case Kt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${a}`)}}const ho=16;class Or{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,e!==!0)try{const r=self.crypto;r&&(this.subtle=r.subtle||r.webkitSubtle)}catch{}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 s=this.decryptRange;return s?s.start===0&&s.end>=r.length?r:r.slice(s.start,s.end):ao(r)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,r,s,i){return this.decryptRange=i,this.useSoftware||i?new Promise((n,o)=>{const l=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(l,e,r,s);const h=this.flush();h?n(h.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,r,s)}softwareDecrypt(t,e,r,s){const{currentIV:i,currentResult:n,remainderData:o}=this;if(s!==Kt.cbc||e.byteLength!==16)return et.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=bt(o,t),this.remainderData=null);const l=this.getValidChunk(t);if(!l.length)return null;i&&(r=i);let h=this.softwareDecrypter;h||(h=this.softwareDecrypter=new no),h.expandKey(e);const d=n;return this.currentResult=h.decrypt(l.buffer,0,r),this.currentIV=l.slice(-16).buffer,d||null}webCryptoDecrypt(t,e,r,s){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,r,s));this.key=e,this.fastAesKey=new oo(this.subtle,e,s)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new io(this.subtle,new Uint8Array(r),s).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(et.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(t,e,r,s)))}onWebCryptoError(t,e,r,s){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,r,s);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const r=t.length-t.length%ho;return r!==t.length&&(e=t.slice(0,r),this.remainderData=t.slice(r)),e}logOnce(t){this.logEnabled&&(et.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Ii=Math.pow(2,17);class ki{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,s){const i=t.url;if(!i)return Promise.reject(new xt({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,o=n.fLoader,l=n.loader;return new Promise((h,d)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(m=>m[0]==="GAP")){d(Ci(t));return}else t.gap=!1;const u=this.loader=o?new o(n):new l(n),c=_i(t,null,e);t.loader=u;const f=ds(n.fragLoadPolicy.default),g={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:Ii};u.stats.retry=t.stats.retry,t.stats=u.stats;const p={onSuccess:(m,T,E,v)=>{this.resetLoader(t,u);let S=m.data;E.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(S.slice(0,16)),S=S.slice(16)),h({frag:t,part:null,payload:S,networkDetails:v})},onError:(m,T,E,v)=>{this.resetLoader(t,u),d(new xt({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:gt({url:i,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:E,stats:v}))},onAbort:(m,T,E)=>{this.resetLoader(t,u),d(new xt({type:Y.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:E,stats:m}))},onTimeout:(m,T,E)=>{this.resetLoader(t,u),d(new xt({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:E,stats:m}))}};if(r){const m=this.gateProgress(r,s);p.onProgress=(T,E,v,S)=>m({frag:t,part:null,payload:v,networkDetails:S})}u.load(c,g,p)})}gateProgress(t,e){let r=t;if(e){const s=[];let i=!1;e.then(()=>{i=!0,s.forEach(n=>t(n)),s.length=0}).catch(()=>{}),r=n=>{i?t(n):s.push(n)}}return r}loadPart(t,e,r){this.abort();const s=this.config,i=s.fLoader,n=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap){l(Ci(t,e));return}const h=this.loader=i?new i(s):new n(s),d=_i(t,e);t.loader=h;const u=ds(s.fragLoadPolicy.default),c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ii};e.stats=h.stats,h.load(d,c,{onSuccess:(f,g,p,m)=>{this.resetLoader(t,h),this.updateStatsFromPart(t,e);const T={frag:t,part:e,payload:f.data,networkDetails:m};r(T),o(T)},onError:(f,g,p,m)=>{this.resetLoader(t,h),l(new xt({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:gt({url:d.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:m}))},onAbort:(f,g,p)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,h),l(new xt({type:Y.NETWORK_ERROR,details:D.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(t,h),l(new xt({type:Y.NETWORK_ERROR,details:D.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(t,e){const r=t.stats,s=e.stats,i=s.total;if(r.loaded+=s.loaded,i){const l=Math.round(t.duration/e.duration),h=Math.min(Math.round(r.loaded/i),l),d=(l-h)*Math.round(r.loaded/h);r.total=r.loaded+d}else r.total=Math.max(r.loaded,r.total);const n=r.loading,o=s.loading;n.start?n.first+=o.first-o.start:(n.start=o.start,n.first=o.first),n.end=o.end}resetLoader(t,e){t.loader=null,t.url=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function _i(a,t=null,e){const r=t||a,s={type:Q.MEDIA_FRAGMENT,frag:a,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},i=Ke(a,t,e);return i.resetIV&&(s.resetIV=!0),i.byteRange&&(s.rangeStart=i.byteRange.start,s.rangeEnd=i.byteRange.end),s}function Ke(a,t=null,e){const r={},s=t||a,i=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(G(i)&&G(n)){var o;if((a.sn==="initSegment"||e)&&uo((o=a.decryptdata)==null?void 0:o.method)){let l=Math.floor(i/16)*16;const h=Math.ceil(n/16)*16;r.decryptRange={start:i-l,end:n-l},l>=16&&(r.resetIV=!0,l=l-16),r.byteRange={start:l,end:h}}else r.byteRange={start:i,end:n}}return r}function Ci(a,t){const e=new Error(`GAP ${a.gap?"tag":"attribute"} found`),r={type:Y.MEDIA_ERROR,details:D.FRAG_GAP,fatal:!1,frag:a,error:e,networkDetails:null};return t&&(r.part=t),(t||a).stats.aborted=!0,new xt(r)}function uo(a){return a==="AES-128"||a==="AES-256"}class xt extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Pi extends $t{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?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1?(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 Mr{constructor(t,e,r,s=0,i=-1,n=!1,o,l,h){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=We(),this.buffering={audio:We(),video:We(),audiovideo:We()},this.level=t,this.sn=e,this.id=r,this.size=s,this.part=i,this.partial=n,this.duration=o||0,this.decryptRange=h,this.iframe=l||!1}}function We(){return{start:0,executeStart:0,executeEnd:0,end:0}}function Ee(a,t){for(let r=0,s=a.length;r<s;r++){var e;if(((e=a[r])==null?void 0:e.cc)===t)return a[r]}return null}function co(a,t){return!!(a&&t.startCC<a.endCC&&t.endCC>a.startCC)}function xi(a,t){const e=a.start+t;a.setStart(e)}function wi(a,t){const e=t.fragments;for(let r=0,s=e.length;r<s;r++)xi(e[r],a);t.fragmentHint&&xi(t.fragmentHint,a),t.alignedSliding=!0}function fo(a,t,e){a&&(go(t,a,e),t.alignedSliding||mo(t,a,e),!t.alignedSliding&&!t.skippedSegments&&di(a,t,!1,e))}function go(a,t,e){if(!co(t,a))return;const r=Math.min(t.endCC,a.endCC),s=Ee(t.fragments,r),i=Ee(a.fragments,r);if(!s||!i)return;const n=s.start-i.start;e.log(`Aligning playlists using dicontinuity sequence ${r} (diff: ${n})`),wi(n,a)}function mo(a,t,e){if(!a.hasProgramDateTime||!t.hasProgramDateTime)return;const r=a.fragments,s=t.fragments;if(!r.length||!s.length)return;let i,n;const o=Math.min(t.endCC,a.endCC);t.startCC<o&&a.startCC<o&&(i=Ee(s,o),n=Ee(r,o)),(!i||!n)&&(i=s[Math.floor(s.length/2)]||s.filter(c=>!!c)[0],n=Ee(r,i.cc)||r[Math.floor(r.length/2)]);const l=i.programDateTime,h=n.programDateTime;if(!l||!h)return;const d=(h-l)/1e3;if(Math.abs(d)>Math.max(60,a.totalduration)){e.log(`Cannot align playlists using PDT without overlap (${Math.abs(d)} > ${a.totalduration})`);return}const u=d-(n.start-i.start);e.log(`Aligning playlists using PDT (diff: ${u})`),wi(u,a)}const F={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 Oi extends Pi{constructor(t,e,r,s,i){super(s,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=F.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:n,fragCurrent:o,media:l,mediaBuffer:h,state:d}=this,u=l?l.currentTime:0,c=q.bufferInfo(h||l,u,n.maxBufferHole),f=c.len;if(this.log(`Media seeking to ${u}, state: ${d}, ${f?"in":"out of"} buffer`),this.state===F.ENDED)this.resetLoadingState();else if(o){const m=n.maxFragLookUpTolerance,T=o.start-m,E=o.start+o.duration+m;if(!f||E<c.start||T>c.end){const v=u<T,S=u>E;(v||S)&&(o.loader&&(S||!this.isFragmentNearlyDownloaded(o))?(this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${v?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(l){var g;(g=this.hls)!=null&&g.hasEnoughToStart&&!f&&u!==this.startPosition&&this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const m=this.lastCurrentTime;if(u>m&&(this.lastCurrentTime=u),!this.loadingParts){const T=Math.max(c.end,u),E=this.shouldLoadParts(this.getLevelDetails(),T);E&&(this.log(`LL-Part loading ON after seeking to ${u} with buffer @${T}`),this.loadingParts=E)}}const p=!q.isBuffered(l,u);(!this.hls.hasEnoughToStart||p)&&(this.log(`Setting ${p?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,p?this.startPosition=u:this.lastCurrentTime=u),f<1&&this.state===F.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.nextLoadPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=t,this.fragmentLoader=new ki(t.config),this.initFragmentLoader=new ki(t.config),this.keyLoader=r,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Or(t.config)}registerListeners(){const{hls:t}=this;t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(y.ERROR,this.onError,this)}doTick(){}onTickEnd(){const{media:t}=this;t!=null&&t.readyState&&t.seeking===!1&&(this.lastCurrentTime=t.currentTime)}startLoad(t){}stopLoad(){if(this.state===F.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;t!=null&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=F.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;if(e===-1&&t){const r=this.getLevelDetails();return r!=null&&r.live?(this.hls.liveSyncPosition||r.fragmentStart)+this.timelineOffset: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,s=this.config.timelineOffset||0;if(r<=s)return!1;const i=t.buffered;this.config.maxBufferHole&&i&&i.length>1&&(t=q.bufferedInfo(i,t.start,0));const n=t.nextStart;if(n&&n>s&&n<e.edge||this.media.currentTime<t.start)return!1;const o=e.partList;if(o!=null&&o.length){const h=o[o.length-1];return q.isBuffered(this.media,h.start+h.duration/2)}const l=e.fragments[e.fragments.length-1];return this.fragmentTracker.isEndListAppended(l.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;if(t){var e;return((e=this.getLevelDetails())==null?void 0:e.appliedTimelineOffset)||t}return 0}onMediaAttached(t,e){const r=this.media=this.mediaBuffer=e.media;mt(r,"seeking",this.onMediaSeeking),mt(r,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===F.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(t,e){this.fragPlaying=null;const r=!!e.transferMedia,s=this.media;if(s===null)return;if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),dt(s,"seeking",this.onMediaSeeking),dt(s,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,r){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1;const{fragmentTracker:i}=this,n=i.gapFragments();i.removeAllFragments(),n.forEach(o=>i.addAsGap(o)),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=F.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){const s=i=>{const n=i.frag;if(this.fragContextChanged(n)){this.warn(`${n.type} sn: ${n.sn}${i.part?" part: "+i.part.index:""} of ${this.fragInfo(n,!1,i.part)} was dropped during download.`),this.fragmentTracker.removeFragment(n);return}const o=++n.stats.chunkCount;this.log(`load progress ${n.type} sn: ${n.sn}${i.part?" part: "+i.part.index:""} of ${this.fragInfo(n,!1,i.part)} chunk: ${o}`),this._handleFragmentLoadProgress(i)};this._doFragLoad(t,e,r,s).then(i=>{if(!i)return;const n=this.state,o=i.frag;if(this.fragContextChanged(o)){(n===F.FRAG_LOADING||!this.fragCurrent&&n===F.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=F.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level} (bytes ${o.stats.loaded})`),this.hls.trigger(y.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===F.STOPPED||this.state===F.ERROR||(this.log(`Frag error ${t.type} sn:${t.sn} cc:${t.cc}: ${i?.message||i}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:r}=this;if(r.getState(t)===ct.APPENDING){const s=t.type,i=this.getFwdBufferInfo(this.mediaBuffer,s),n=Math.max(t.duration,i?i.len:this.config.maxBufferLength),o=this.backtrackFragment;((o?t.sn-o.sn:0)===1||this.reduceMaxBufferLength(n,t.duration))&&r.removeFragment(t)}else((e=this.mediaBuffer)==null?void 0:e.buffered.length)===0?r.removeAllFragments():r.hasParts(t.type)&&(r.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),r.getState(t)===ct.PARTIAL&&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 s=e.getPartialFragment(r.end);s&&(e.removeFragment(s),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 e?.live&&e.type!=="EVENT"&&e.advancedDateTime!==void 0&&(e.expired||this.loadingParts&&e.partsExpired||e.misses<3&&e.partEnd<=this.getLoadPosition())}flushMainBuffer(t,e,r=null){if(!(t-e))return;const s={startOffset:t,endOffset:e,type:r};this.hls.trigger(y.BUFFER_FLUSHING,s)}_loadInitSegment(t){const{hls:e}=this;return this.initFragmentLoader.abort(),e.trigger(y.FRAG_LOADING,{frag:t,targetBufferTime:0}),this.initFragmentLoader.load(t).then(r=>{var s;const i=r.frag;if(!this.levels||!nr(i,(s=this.fragCurrent)==null?void 0:s.initSegment))throw new xt({type:Y.NETWORK_ERROR,details:D.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:i,networkDetails:null});return r}).then(r=>{const{frag:s,payload:i}=r,n=s.decryptdata;if(i&&i.byteLength>0&&n!=null&&n.key&&n.iv&&ve(n.method)){const o=self.performance.now(),{decryptRange:l}=Ke(s,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,Xs(n.method),l).catch(h=>{throw e.trigger(y.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_DECRYPT_ERROR,fatal:!1,error:h,reason:h.message,frag:s}),this.fragmentLoader.abort(),h}).then(h=>{const d=self.performance.now();return e.trigger(y.FRAG_DECRYPTED,{frag:s,part:null,payload:h,stats:{tstart:o,tdecrypt:d}}),r.payload=h,this.completeInitSegmentLoad(r)})}return this.completeInitSegmentLoad(r)})}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&&Et(t)&&e&&!e.data){var r;return(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?this.keyLoader.load(e).then(()=>this._loadInitSegment(e)):this._loadInitSegment(e)).catch(s=>{throw this.state===F.STOPPED||this.state===F.ERROR||("data"in s&&(this.fragmentLoader.abort(),this.handleFragLoadError(s,t)),this.resetFragmentLoading(t)),s})}}unhandledEncryptionError(t,e){var r,s;const i=t.tracks;if(i&&!e.encrypted&&((r=i.audio)!=null&&r.encrypted||(s=i.video)!=null&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const n=this.media,o=new Error("EME not supported (light build)");return this.warn(o.message),!n||n.mediaKeys?!1:(this.hls.trigger(y.ERROR,{type:Y.KEY_SYSTEM_ERROR,details:D.KEY_SYSTEM_NO_KEYS,fatal:!0,error:o,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!nr(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?Pr(q.getBuffered(r)):"(detached)"})`),Et(t)){var s;if(t.type!==j.SUBTITLE){const n=t.elementaryStreams;if(!Object.keys(n).some(o=>!!n[o])){this.state=F.IDLE;return}}const i=(s=this.levels)==null?void 0:s[t.level];i!=null&&i.fragmentError&&(e||this.fragmentTracker.getState(t)!==ct.PARTIAL)&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0,t.stats.retry=0)}this.state=F.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const r=t.frag,{part:s,partsLoaded:i}=t,n=!i||i.length===0||i.some(h=>!h),{decryptRange:o}=Ke(r,s),l=new Mr(r.level,r.sn,r.stats.chunkCount+1,0,s?s.index:-1,!n,r.duration,this.iframesOnly,o);this.log(`load complete ${r.type} sn: ${r.sn}${s?" part: "+s.index:""} of ${this.fragInfo(r,!1,s)}`),e.flush(l)}_handleFragmentLoadProgress(t){}loadKeyFor(t,e,r){var s;let i=null;return t.encrypted&&!((s=t.decryptdata)!=null&&s.key)?(this.log(`Loading key for ${t.sn} of [${e.startSN}-${e.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=F.KEY_LOADING,i=this.keyLoader.load(t,r).then(n=>{if(!this.fragContextChanged(n.frag))return this.hls.trigger(y.KEY_LOADED,n),this.state===F.KEY_LOADING&&(this.state=F.IDLE),n}),this.hls.trigger(y.KEY_LOADING,{frag:t})):t.encrypted||(i=this.keyLoader.loadClear(t,e.encryptedFragments,this.startFragRequested),i&&this.log(`[eme] blocking frag sn: ${t.sn} load until media-keys acquired`)),i}_doFragLoad(t,e,r=null,s){this.fragCurrent=t;const i=e.details;if(!this.levels||!i)throw new Error(`frag load aborted, missing level${i?"":" detail"}s`);const n=this.fragPrevious;if(!be(t,n)){const f=this.shouldLoadParts(e.details,t.end);f!==this.loadingParts&&(this.log(`LL-Part loading ${f?"ON":"OFF"} loading sn ${n?.sn}->${t.sn}`),this.loadingParts=f)}if(r=Math.max(t.start,r||0),this.loadingParts){const f=i.partList;if(f&&s){r>i.fragmentEnd&&i.fragmentHint&&(t=i.fragmentHint);const g=this.getNextPart(f,t,r);if(g>-1){const p=f[g];if(t=this.fragCurrent=p.fragment,!be(t,n)&&!this.shouldLoadParts(e.details,t.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(t,!1,p)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(p,e.details))return Promise.resolve(null);const m=this.loadKeyFor(t,i);if(this.fragContextChanged(t))return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} part: ${p.index} (${g}/${f.length-1}) of ${this.fragInfo(t,!1,p)} cc: ${t.cc} [${i.startSN}-${i.endSN}], target: ${r}${p.byteRange.length?` range:${p.byteRange.join("-")}`:""}`),this.nextLoadPosition=p.start+p.duration,this.state=F.FRAG_LOADING;let T;const E=this.loadInitSegmentIfNeeded(t);if(m||E){const v=!!m;T=Promise.all([m,E]).then(([S])=>v&&(!S||this.fragContextChanged(S.frag))?null:this.doFragPartsLoad(t,p,e,s)).catch(S=>this.handleFragLoadError(S,t))}else T=this.doFragPartsLoad(t,p,e,s).catch(v=>this.handleFragLoadError(v,t));return this.hls.trigger(y.FRAG_LOADING,{frag:t,part:p,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):T}else if(!t.url||this.loadedEndOfParts(f,r))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${r} Check buffer at sn: ${t.sn} loaded parts: ${(o=i.partList)==null?void 0:o.filter(f=>f.loaded).map(f=>`[${f.start}-${f.end}]`)}`),this.loadingParts=!1}else if(!t.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(t,e.details))return Promise.resolve(null);const l=this.loadInitSegmentIfNeeded(t),h=this.loadKeyFor(t,i,l);if(this.fragContextChanged(t)){var d;return this.log(`Context changed in KEY_LOADING sn: ${t.sn} ${t.relurl} > ${(d=this.fragCurrent)==null?void 0:d.relurl}`),l?.catch(()=>null),h?.catch(()=>null),Promise.resolve(null)}this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)} cc: ${t.cc} ${"["+i.startSN+"-"+i.endSN+"]"}, target: ${r}${t.byteRange.length?` range:${t.byteRange.join("-")}`:""}`),G(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=F.FRAG_LOADING;const u=this.config.progressive&&t.type!==j.SUBTITLE;let c;return u&&h?c=h.then(f=>!f||this.fragContextChanged(f.frag)?null:this.fragmentLoader.load(t,this.iframesOnly,s,l)).catch(f=>this.handleFragLoadError(f,t)):c=Promise.all([this.fragmentLoader.load(t,this.iframesOnly,u?s:void 0,u?l:void 0),h,l]).then(([f])=>(!u&&s&&s(f),f)).catch(f=>this.handleFragLoadError(f,t)),this.hls.trigger(y.FRAG_LOADING,{frag:t,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([c,l]).then(([f])=>f)}doFragPartsLoad(t,e,r,s){return new Promise((i,n)=>{var o;const l=[],h=(o=r.details)==null?void 0:o.partList,d=u=>{this.fragmentLoader.loadPart(t,u,s).then(c=>{l[u.index]=c;const f=c.part;this.hls.trigger(y.FRAG_LOADED,c);const g=ci(r.details,t.sn,u.index+1)||fi(h,t.sn,u.index+1);if(g)d(g);else return i({frag:t,part:f,partsLoaded:l})}).catch(n)};d(e)})}handleFragLoadError(t,e){if("data"in t){const r=t.data;r.details===D.INTERNAL_ABORTED?this.handleFragLoadAborted(e,r.part):r.type===Y.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(y.ERROR,gt(gt({},r),{},{frag:e}))):this.hls.trigger(y.ERROR,r)}else this.hls.trigger(y.ERROR,{type:Y.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==F.PARSING){!this.fragCurrent&&this.state!==F.STOPPED&&this.state!==F.ERROR&&(this.state=F.IDLE);return}const{frag:r,part:s,level:i}=e,n=self.performance.now();r.stats.parsing.end=n,s&&(s.stats.parsing.end=n);const o=this.getLevelDetails(),l=o&&r.sn>o.endSN||this.shouldLoadParts(o,r.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${r.end}`),this.loadingParts=l),this.updateLevelTiming(r,s,i,t)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList&&!this.iframesOnly){var r;const s=t.partList[0],i=s.end+(((r=t.fragmentHint)==null?void 0:r.duration)||0);if(e>=i&&this.playhead>s.start-s.fragment.duration)return!0}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:r}=this,{level:s,sn:i,part:n}=t;if(!(e!=null&&e[s]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const o=e[s],l=o.details,h=n>-1?ci(l,i,n):null,d=h?h.fragment:Ve(l,i,r);return d?(r&&r!==d&&(d.stats=r.stats),{frag:d,part:h,level:o}):null}bufferFragmentData(t,e,r,s,i){if(this.state!==F.PARSING)return;Et(e)&&!this.fragContextChanged(e)&&(this.fragPrevious=e);const{data1:n,data2:o}=t;let l=n;if(o&&(l=bt(n,o)),!l.length)return;const h=this.initPTS[e.cc],d=h?-h.baseTime/h.timescale:void 0,u={type:t.type,frag:e,part:r,chunkMeta:s,offset:d,parent:e.type,data:l};if(this.hls.trigger(y.BUFFER_APPENDING,u),t.dropped&&t.independent&&!r){if(i)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!q.isBuffered(e,e.currentTime)){this.flushMainBuffer(0,t.start);return}const r=e.currentTime,s=q.bufferInfo(e,r,0),i=t.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(t.start-n,s.end-n),r+n);t.start-o>n&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,e){var r;const s=this.playhead,i=this.lastCurrentTime>s||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,s,e,i)}getFwdBufferInfoAtPos(t,e,r,s){const i=q.bufferInfo(t,e,s);if(i.len===0&&i.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(e,r);if(n&&(i.nextStart<=n.end||n.gap)){const o=Math.max(Math.min(i.nextStart,n.end)-e,s);return q.bufferInfo(t,e,o)}}return i}getMaxBufferLength(t){const{config:e}=this;let r;return t?r=Math.max(8*e.maxBufferSize/t,e.maxBufferLength):r=e.maxBufferLength,Math.min(r,e.maxMaxBufferLength)}exceedsMaxBuffer(t,e,r){const s=t.nextStart;if(s&&r.start>s){const i=t.buffered;if(i){let n=t.len;const o=t.bufferedIndex;for(let l=i.length-1;l>o;l--)i[l].start<r.start&&(n+=i[l].end-i[l].start);return n>=e}}return!1}reduceMaxBufferLength(t,e){const r=this.config,s=Math.max(Math.min(t-e,r.maxBufferLength),e/2),i=Math.max(t-e*3,r.maxMaxBufferLength/2,s);return i>=s?(r.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}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,s=r.length;if(!s)return null;const{config:i}=this,n=e.fragmentStart,o=i.lowLatencyMode&&!!e.partList;let l=null;if(e.live){const u=i.initialLiveManifestSize;if(s<u)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${u})`),null;if(!this.startFragRequested&&o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!e.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||t<n){var h;l=this.getInitialLiveFragment(e);const c=this.config.startPosition,f=this.hls.startPosition,g=this.hls.liveSyncPosition,p=((h=l)==null?void 0:h.start)||0;let m,T;if(f!==-1&&f>=n?(m=f,T=f===c?"config":"next load start"):g?(m=g,T="live edge"):(m=t,T="buffer pos"),m<p&&(m=p,T="live frag start"),m<n&&(m=n,T="playlist start"),this.startPosition!=m||this.nextLoadPosition!=m){const E=e.live&&!this.filterReplacedPrimary(l,e)?-1:m;this.log(`Setting startPosition to ${E} next load ${m} ${f===-1?"":`(from ${c}) `}based on ${T}. live edge: ${g} live frag start: ${p} playlist start: ${n} buffer pos: ${t}`),this.startPosition=E,this.nextLoadPosition=m}}}else t<=n&&(l=r[0]);if(!l){const u=this.loadingParts?e.partEnd:e.fragmentEnd;l=this.getFragmentAtPosition(t,u,e)}let d=this.filterReplacedPrimary(l,e);return!d&&l&&(d=Mn(e,l.sn),d&&(this.nextLoadPosition=d.start)),d}isLoopLoading(t,e){if(this.nextLoadPosition<=e)return!1;const r=this.fragmentTracker.getState(t);return!!(r===ct.OK||r===ct.PARTIAL&&(t.gap||t.stats.retry>1))}getNextFragmentLoopLoading(t,e,r,s,i){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&r.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,s,0);if(o!==null&&r.len+o.len>=i){const l=n.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,n}get primaryPrefetch(){return Fr(this.config),!1}filterReplacedPrimary(t,e){return t&&(Fr(this.config),t)}getNextPart(t,e,r){let s=-1,i=!1,n=!0;for(let l=0,h=t.length;l<h;l++){const d=t[l];if(n=n&&!d.independent,s>-1&&r<d.start)break;const u=d.loaded||d.gap;u?s=-1:(i||(d.independent||n)&&d.fragment===e)&&(s=l),i=u&&!d.gap}const o=t[s];return o&&o.fragment!==e&&this.log(`Need buffer at ${r} but next unloaded part starts at ${o.start} (sn: ${e.sn} -> ${o.fragment.sn})`),s}loadedEndOfParts(t,e){let r;for(let s=t.length;s--;){if(r=t[s],!r.loaded)return!1;if(e>r.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,r=this.fragPrevious;let s=null;if(r){if(t.hasProgramDateTime&&(s=Pn(e,r.endProgramDateTime,this.config.maxFragLookUpTolerance),s&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`)),!s){const i=r.sn+1;if(i>=t.startSN&&i<=t.endSN){const n=e[i-t.startSN];r.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=On(t,r.cc,r.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const i=this.hls.liveSyncPosition;i!==null&&(s=this.getFragmentAtPosition(i,this.bitrateTest?t.fragmentEnd:t.edge,t))}return s}getFragmentAtPosition(t,e,r){const{config:s}=this;let{fragPrevious:i}=this,{fragments:n,endSN:o}=r;const{fragmentHint:l}=r,{maxFragLookUpTolerance:h}=s,d=r.partList,u=!!(this.loadingParts&&d!=null&&d.length&&l);u&&!this.bitrateTest&&d[d.length-1].fragment.sn===l.sn&&(n=n.concat(l),o=l.sn),i&&this.fragmentTracker.getState(i)===ct.NOT_LOADED&&(i=null);let c;if(t<e){var f;const g=t<this.lastCurrentTime||t>e-h||(f=this.media)!=null&&f.paused||this.loadingParts||!this.startFragRequested?0:h;c=Dr(i,n,t,g)}else c=n[n.length-1];if(c){const g=c.sn,p=g-r.startSN,m=this.fragmentTracker.getState(c);if((m===ct.OK||m===ct.PARTIAL&&c.gap)&&(i=c),be(c,i)&&(!u||d[0].fragment.sn>g||!r.live||!d.some(T=>T.fragment.sn===g&&!T.loaded&&!T.gap))){const T=n[p+1];c.sn<o&&this.fragmentTracker.getState(T)!==ct.OK?c=T:c=null}}return c}alignPlaylists(t,e,r){const s=t.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const i=t.fragmentStart,n=!e,o=t.alignedSliding&&G(i);if(n||!o&&!i){fo(r,t,this);const l=t.fragmentStart;return this.log(`Live playlist sliding: ${l} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${s}`),l}return i}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,e){let r=this.startPosition;r<e&&(r=-1);const s=this.timelineOffset;if(r===-1){const i=this.startTimeOffset!==null,n=i?this.startTimeOffset:t.startTimeOffset;if(n!==null&&G(n))r=e+n,n<0&&(r+=t.edge),r=Math.min(Math.max(e,r),e+t.totalduration),this.log(`Setting startPosition to ${r} for start time offset ${n} found in ${i?"multivariant":"media"} playlist`),this.startPosition=r;else if(t.live){const o=this.hls.liveSyncPosition;r=o||e,this.log(`Setting startPosition to -1 to start at ${o?"live edge":"playlist start"} ${r}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=r=0;this.lastCurrentTime=r+s}this.nextLoadPosition=r+s}getLoadPosition(){var t;const{media:e}=this;let r=0;return(t=this.hls)!=null&&t.hasEnoughToStart&&e&&!this.iframesOnly?r=e.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}get playhead(){var t;if((t=this.hls)!=null&&t.hasEnoughToStart){var e;const r=(e=this.media)==null?void 0:e.currentTime;return G(r)?r:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var t;if(this.playlistType!==j.MAIN)return!1;const e=this.getLevelDetails();return e?e.iframesOnly:(t=this.levelLastLoaded)==null?void 0:t.iframes}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&Et(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!==F.STOPPED&&(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==F.FRAG_LOADING_WAITING_RETRY)&&(this.state=F.IDLE)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const E=this.getCurrentContext(e.chunkMeta);E&&(e.frag=E.frag)}const{frag:r,part:s}=e;if(!r||!this.levels||r.type!==t)return;if(this.fragContextChanged(r)){var i;this.warn(`Frag load error must match current frag to retry ${r.relurl} > ${(i=this.fragCurrent)==null?void 0:i.relurl}`);return}const n=e.details===D.FRAG_GAP;n&&this.fragmentTracker.addAsGap(r);const o=e.errorAction;if(!o){this.state=F.ERROR;return}const{action:l,flags:h,retryCount:d=0,retryConfig:u}=o,c=!!u,f=c&&l===ut.RetryRequest,g=c&&!o.resolved&&h&ht.MoveAllAlternatesMatchingHost,p=this.hls.latestLevelDetails,m=p?.live;if(!f&&g&&Et(r)&&m&&r.sn<p.endSN&&!ls(e))this.resetFragmentErrors(t),s?s.gap=!0:this.treatAsGap(r),o.resolved=!0;else if((f||g)&&d<u.maxNumRetry){var T;const E=ue((T=e.response)==null?void 0:T.code),v=or(u,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+v,this.state=F.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,e.reason="offline";return}this.warn(`Fragment ${r.sn} of ${t} ${r.level} errored with ${e.details}, retrying loading ${d+1}/${u.maxNumRetry} in ${v}ms`)}else if(u)if(this.resetFragmentErrors(t),d<u.maxNumRetry)!n&&l!==ut.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${e.details} reached or exceeded max retry (${d})`);return}else l===ut.SendAlternateToPenaltyBox?this.state=F.WAITING_LEVEL:this.state=F.ERROR;this.tickImmediate()}onSourceBufferError(t,e){var r,s;const{frag:i,part:n,sourceBufferName:o}=e,l=i&&((r=this.levels)==null||(r=r[i.level])==null?void 0:r.details);if(e.error.name!==Ti||i?.type!==t||!Et(i)||!(l!=null&&l.live))return;const h=n?n.index===0?n:null:i,d=h&&o?(s=h.elementaryStreams[o])==null?void 0:s.startPTS:void 0;if(this.markSourceBufferErrorGap(Ve(l,i.sn)||i),d===void 0)return;const u=Ve(l,i.sn-1);u&&this.fragmentTracker.getState(u)!==ct.NOT_LOADED&&!q.isBuffered(this.mediaBuffer||this.media,d-this.config.maxBufferHole)&&this.markSourceBufferErrorGap(u)}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&&!ue(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=F.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===F.PARSING||this.state===F.PARSED){const e=t.frag,r=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,r),i=s&&s.len>.5;i&&this.reduceMaxBufferLength(s.len,e?.duration||10);const n=!i;return n?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${r} buffer`):s.nextStart&&e&&s.nextStart>e.start&&this.flushMainBuffer(s.nextStart,Number.POSITIVE_INFINITY,r===j.AUDIO?r:void 0),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===j.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==F.STOPPED&&(this.state=F.IDLE)}afterBufferFlushed(t,e){if(!t)return;const r=q.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,this.playlistType),this.state===F.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==F.STOPPED&&(this.state=F.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.getLevelDetails();t!=null&&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()} ${t.level===-1?"<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,s){const i=r.details;if(!i){this.warn("level.details undefined");return}if(this.log(`update level timing ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`),!Object.keys(t.elementaryStreams).reduce((d,u)=>{const c=t.elementaryStreams[u];if(c){const f=c.endPTS-c.startPTS;if(f<=0)return this.warn(`Could not parse fragment ${t.sn} ${u} duration reliably (${f})`),d||!1;let g=0;return s.partial?e&&s.part===0&&(g=e.start-c.startPTS,t.startPTS=t.maxStartPTS=c.startPTS,t.startDTS=c.startDTS,t.start!==0&&t.setStart(c.startPTS),li(i,t,g)):g=oi(i,t,c.startPTS,c.endPTS,c.startDTS,c.endDTS,this.iframesOnly,this),this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:i,level:r,drift:g,type:u,frag:t,part:e,start:c.startPTS,end:c.endPTS}),!0}return d},!1)){var n,o,l,h;const d=((n=this.transmuxer)==null?void 0:n.error)===null,u=((o=this.transmuxer)==null?void 0:o.error)!=null,c=((l=(h=this.levels)==null?void 0:h.length)!=null?l:0)>1;if((r.fragmentError===0||d&&(r.fragmentError<2||t.endList)||u&&c)&&this.treatAsGap(t,r),d){const f=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(f.message),this.hls.trigger(y.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:f,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=F.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`),this.hls.trigger(y.FRAG_PARSED,{frag:t,part:e,chunkMeta:s})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(t,e=!0,r){var s,i;return`${t.type} playlist ${t.level} (${r?"part":"frag"}:[${(s=e&&!r?t.startPTS:(r||t).start)!=null?s:NaN}-${(i=e&&!r?t.endPTS:(r||t).end)!=null?i:NaN}]${r&&t.type==="main"?"INDEPENDENT="+(r.independent?"YES":"NO"):""})`}treatAsGap(t,e){e&&e.fragmentError++,this.fragmentTracker.addAsGap(t)}resetTransmuxer(){var t;(t=this.transmuxer)==null||t.reset()}isFragmentNearlyDownloaded(t){var e;const r=(e=t.loader)==null?void 0:e.stats;if(!r||r.total<=0)return!1;const s=r.loading.first>0,i=(r.total-r.loaded)*8/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return s&&i<=.15}recoverWorkerError(t){t.event==="demuxerWorker"&&(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:s,media:i,config:n,levels:o,playlistType:l}=this,h=this.getLevelDetails();if(i&&!i.paused&&o){var d;const f=l===j.AUDIO?Bt.estimatedAudioBitrate(t.audioCodec,128e3):t.maxBitrate,g=1+s.ttfbEstimate/1e3,p=s.bandwidthEstimate*n.abrBandWidthUpFactor,m=h&&(this.loadingParts?h.partTarget:h.averagetargetduration)||((d=this.fragCurrent)==null?void 0:d.duration)||6;r=g+f*m/p,t.details||(r+=g)}const u=this.playhead,c=!(h!=null&&h.live)||e.end-u>r*1.5;return{fetchdelay:r,okToFlushForwardBuffer:c}}scheduleTrackSwitch(t,e,r){const{media:s,playlistType:i}=this;if(!s||!t)return;const n=r?this.getBufferedFrag(this.playhead+e):null;if(n){const l=this.followingBufferedFrag(n);if(l){var o;this.abortCurrentFrag();const h=l.maxStartPTS?l.maxStartPTS:l.start,d=l.duration,u=Math.max(n.end,h+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>u)return;const c=i===j.MAIN?null:"audio";this.flushMainBuffer(u,Number.POSITIVE_INFINITY,c),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:t,playlistType:e}=this;if(!t)return;const r=this.getAppendedFrag(this.playhead);if(r&&r.start>1){const s=e===j.AUDIO;this.flushMainBuffer(0,r.start-(s?0:1),s?"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 F.KEY_LOADING:case F.FRAG_LOADING:case F.FRAG_LOADING_WAITING_RETRY:case F.PARSING:case F.PARSED:this.state=F.IDLE;break}this.nextLoadPosition=(t=this.hls)!=null&&t.hasEnoughToStart?this.playhead:this.lastCurrentTime}checkFragPlaying(){const t=this.media;let e=null;if(t&&t.readyState>1&&t.seeking===!1){const r=t.currentTime;if(q.isBuffered(t,r)?e=this.getAppendedFrag(r):q.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e&&(this.backtrackFragment=void 0,!be(e,this.fragPlaying)))return this.fragPlaying=e,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:t,media:e,hls:r,config:s,playlistType:i}=this;if(e!=null&&e.readyState&&t&&r&&s){const n=this.getBufferOutput(),o=this.getFwdBufferInfo(n,i);if(!o)return;const l=i===j.AUDIO?r.nextAudioTrack:r.nextLoadLevel,h=t[l],{fetchdelay:d,okToFlushForwardBuffer:u}=this.calculateOptimalSwitchPoint(h,o);this.scheduleTrackSwitch(o,d,u)}this.tickImmediate()}}function Fr(a){return!1}class tr{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(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(y.BUFFER_CODECS,this.onBufferCodecs,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:t}=this;t&&(t.off(y.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(y.BUFFER_CODECS,this.onBufferCodecs,this),t.off(y.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)&&(G(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(this.observer===void 0&&this.timer===void 0){const t=this.hls.levels;t.length>1&&t.some(e=>!!e.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){this.clientRect=null;return}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 t.length===1&&this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;const e=this.hls.levels;if(!e.length)return-1;const r=e.filter((s,i)=>this.isLevelAllowed(s)&&i<=t);return this.observer||(this.clientRect=null),tr.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}observe(){const t=self.ResizeObserver;t&&(this.observer=new t(e=>{var r;const s=(r=e[0])==null?void 0:r.contentRect;s&&(this.clientRect=s,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var t;this.timer||this.observer||!((t=this.hls)!=null&&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{}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(!(t!=null&&t.length))return-1;const s=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let i=t.length-1;const n=Math.max(e,r);for(let o=0;o<t.length;o+=1){const l=t[o];if((l.width>=n||l.height>=n)&&s(l,t[o+1])){i=o;break}}return i}}const po=3e5;class Mi extends $t{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(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(t.indexOf(e.pathwayId)===-1&&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=this.timeToLoad*1e3-(performance.now()-this.updated);if(t>0){this.scheduleRefresh(this.uri,t);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(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(r=>r!==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;r!==null&&(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(r?.action===ut.SendAlternateToPenaltyBox&&r.flags&ht.MoveAllAlternatesMatchingHost){const s=this.levels;let i=this._pathwayPriority,n=this.pathwayId;if(e.context){const{groupId:o,pathwayId:l,type:h}=e.context;o&&s?n=this.getPathwayForGroupId(o,h,n):l&&(n=l)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!i&&s&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==n,!r.resolved&&(e.details!==D.BUFFER_APPEND_ERROR||e.fatal)&&this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${n} levels: ${s&&s.length} priorities: ${yt(i)} penalized: ${yt(this.penalizedPathways)}`))}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(e.length===0){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 this.levels===null?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){this._pathwayPriority=t;let e;const r=this.penalizedPathways,s=performance.now();Object.keys(r).forEach(i=>{s-r[i]>po&&delete r[i]});for(let i=0;i<t.length;i++){const n=t[i];if(n in r)continue;if(n===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(e=this.getLevelsForPathway(n),e.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,gi(e),this.hls.trigger(y.LEVELS_UPDATED,{levels:e});const h=this.hls.levels[o];l&&h&&this.levels&&(h.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&h.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${h.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(t,e,r){const s=this.getLevelsForPathway(r).concat(this.levels||[]);for(let i=0;i<s.length;i++)if(e===Q.AUDIO_TRACK&&s[i].hasAudioGroup(t)||e===Q.SUBTITLE_TRACK&&s[i].hasSubtitleGroup(t))return s[i].pathwayId;return r}clonePathways(t){const e=this.levels;if(!e)return;const r={},s={};t.forEach(i=>{const{ID:n,"BASE-ID":o,"URI-REPLACEMENT":l}=i;if(e.some(d=>d.pathwayId===n))return;const h=this.getLevelsForPathway(o).map(d=>{const u=new it(d.attrs);u["PATHWAY-ID"]=n;const c=u.AUDIO&&`${u.AUDIO}_clone_${n}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${n}`;c&&(r[u.AUDIO]=c,u.AUDIO=c),f&&(s[u.SUBTITLES]=f,u.SUBTITLES=f);const g=Ni(d.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new br({attrs:u,audioCodec:d.audioCodec,bitrate:d.bitrate,height:d.height,name:d.name,url:g,videoCodec:d.videoCodec,width:d.width});if(d.audioGroups)for(let m=1;m<d.audioGroups.length;m++)p.addGroupId("audio",`${d.audioGroups[m]}_clone_${n}`);if(d.subtitleGroups)for(let m=1;m<d.subtitleGroups.length;m++)p.addGroupId("text",`${d.subtitleGroups[m]}_clone_${n}`);return p});e.push(...h),Fi(this.audioTracks,r,l,n),Fi(this.subtitleTracks,s,l,n)})}loadSteeringManifest(t){const e=this.hls.config,r=e.loader;this.loader&&this.loader.destroy(),this.loader=new r(e);let s;try{s=new self.URL(t)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${t}`);return}if(s.protocol!=="data:"){const d=(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate)|0;se(s,"_HLS_pathway",this.pathwayId),se(s,"_HLS_throughput",""+d)}const i={type:Q.STEERING_MANIFEST,responseType:"json",url:s.href},n=e.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},l={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},h={onSuccess:(d,u,c,f)=>{this.log(`Loaded steering manifest: "${s}"`);const g=d.data;if(g?.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":m,"PATHWAY-PRIORITY":T}=g;if(p)try{this.uri=new self.URL(p,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||c.url),m&&this.clonePathways(m);const E={steeringManifest:g,url:s.toString()};this.hls.trigger(y.STEERING_MANIFEST_LOADED,E),T&&this.updatePathwayPriority(T)},onError:(d,u,c,f)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${u.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let g=this.timeToLoad*1e3;if(d.code===429){const p=this.loader;if(typeof p?.getResponseHeader=="function"){const m=p.getResponseHeader("Retry-After");m&&(g=parseFloat(m)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,g)},onTimeout:(d,u,c)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(i,l,h)}scheduleRefresh(t,e=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const s=(r=this.hls)==null?void 0:r.media;if(s&&!s.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},e)}}function Fi(a,t,e,r){a&&Object.keys(t).forEach(s=>{const i=a.filter(n=>n.groupId===s).map(n=>{const o=lt({},n);return o.details=void 0,o.attrs=new it(o.attrs),o.url=o.attrs.URI=Ni(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",e),o.groupId=o.attrs["GROUP-ID"]=t[s],o.attrs["PATHWAY-ID"]=r,o});a.push(...i)})}function Ni(a,t,e,r){if(t){const{[e]:o}=r;if(o){const l=o[t];if(l)return l}}const{HOST:s,PARAMS:i}=r,n=new self.URL(a);return s&&(n.hostname=s),i&&Object.keys(i).sort().forEach(o=>{o&&se(n,o,i[o])}),n.href}class $i{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(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(y.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(y.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 s=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(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 s=performance.now();if(e){if(this.lastTime){const i=s-this.lastTime,n=r-this.lastDroppedFrames,o=e-this.lastDecodedFrames,l=1e3*n/i,h=this.hls;if(h.trigger(y.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:r}),l>0&&n>h.config.fpsDroppedMonitoringThreshold*o){let d=h.currentLevel;h.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(h.autoLevelCapping===-1||h.autoLevelCapping>=d)&&(d=d-1,h.trigger(y.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:h.currentLevel}),h.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=s,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={exports:{}},Ui;function vo(){return Ui||(Ui=1,(function(a){var t=Object.prototype.hasOwnProperty,e="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(e=!1));function s(l,h,d){this.fn=l,this.context=h,this.once=d||!1}function i(l,h,d,u,c){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new s(d,u||l,c),g=e?e+h:h;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function n(l,h){--l._eventsCount===0?l._events=new r:delete l._events[h]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,d;if(this._eventsCount===0)return l;for(d in h=this._events)t.call(h,d)&&l.push(e?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=e?e+l:l,d=this._events[h];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,c=d.length,f=new Array(c);u<c;u++)f[u]=d[u].fn;return f},o.prototype.listenerCount=function(l){var h=e?e+l:l,d=this._events[h];return d?d.fn?1:d.length:0},o.prototype.emit=function(l,h,d,u,c,f){var g=e?e+l:l;if(!this._events[g])return!1;var p=this._events[g],m=arguments.length,T,E;if(p.fn){switch(p.once&&this.removeListener(l,p.fn,void 0,!0),m){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,h),!0;case 3:return p.fn.call(p.context,h,d),!0;case 4:return p.fn.call(p.context,h,d,u),!0;case 5:return p.fn.call(p.context,h,d,u,c),!0;case 6:return p.fn.call(p.context,h,d,u,c,f),!0}for(E=1,T=new Array(m-1);E<m;E++)T[E-1]=arguments[E];p.fn.apply(p.context,T)}else{var v=p.length,S;for(E=0;E<v;E++)switch(p[E].once&&this.removeListener(l,p[E].fn,void 0,!0),m){case 1:p[E].fn.call(p[E].context);break;case 2:p[E].fn.call(p[E].context,h);break;case 3:p[E].fn.call(p[E].context,h,d);break;case 4:p[E].fn.call(p[E].context,h,d,u);break;default:if(!T)for(S=1,T=new Array(m-1);S<m;S++)T[S-1]=arguments[S];p[E].fn.apply(p[E].context,T)}}return!0},o.prototype.on=function(l,h,d){return i(this,l,h,d,!1)},o.prototype.once=function(l,h,d){return i(this,l,h,d,!0)},o.prototype.removeListener=function(l,h,d,u){var c=e?e+l:l;if(!this._events[c])return this;if(!h)return n(this,c),this;var f=this._events[c];if(f.fn)f.fn===h&&(!u||f.once)&&(!d||f.context===d)&&n(this,c);else{for(var g=0,p=[],m=f.length;g<m;g++)(f[g].fn!==h||u&&!f[g].once||d&&f[g].context!==d)&&p.push(f[g]);p.length?this._events[c]=p.length===1?p[0]:p:n(this,c)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=e?e+l:l,this._events[h]&&n(this,h)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=e,o.EventEmitter=o,a.exports=o})(Bi)),Bi.exports}var Eo=vo(),Gi=es(Eo);const Ye=2,yo=100;class To extends Pi{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 r;(r=this.media)!=null&&r.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var r;this.ended=((r=this.media)==null?void 0:r.currentTime)||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=e,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.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(yo),this.mediaSource=e.mediaSource;const r=this.media=e.media;mt(r,"playing",this.onMediaPlaying),mt(r,"waiting",this.onMediaWaiting),mt(r,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:r}=this;r&&(dt(r,"playing",this.onMediaPlaying),dt(r,"waiting",this.onMediaWaiting),dt(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=((t=this.hls)==null?void 0:t.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,e):e}tick(){var t;if(!((t=this.media)!=null&&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,s;const i=(r=this.hls)==null?void 0:r.config;if(!i)return;const n=this.media;if(!n)return;const{seeking:o}=n,l=this.seeking&&!o,h=!this.seeking&&o,d=n.paused&&!o||n.ended||n.playbackRate===0;if(this.seeking=o,t!==e){e&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,i.nudgeOnVideoHole&&!d&&t>e&&this.nudgeOnVideoHole(t,e)),this.waiting===0&&this.stallResolved(t);return}if(h||l){l&&this.stallResolved(t);return}if(d){this.skipRetry=this.nudgeRetry=0,this.stallResolved(t),!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!1}));return}if(!q.getBuffered(n).length){this.skipRetry=this.nudgeRetry=0;return}const u=q.bufferInfo(n,t,0),c=this.fragmentTracker;c&&this.hls&&Ki(u,t,c,this.hls);const f=u.nextStart||0;if(o&&c&&this.hls){const R=Vi(this.hls.inFlightFragments,t),A=u.len>Ye,b=!f||R||f-t>Ye&&!c.getPartialFragment(t);if(A||b)return;this.moved=!1}const g=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&c){if(!(u.len>0)&&!f)return;const R=Math.max(f,u.start||0)-t,A=g!=null&&g.live?g.targetduration*2:Ye,b=ye(t,c);if(R>0&&(R<=A||b)){n.paused||this._trySkipBufferHole(b);return}}const p=i.detectStallWithCurrentTimeMs,m=self.performance.now(),T=this.waiting;let E=this.stalled;if(E===null)if(T>0&&m-T<p)E=this.stalled=T;else{this.stalled=m;return}const v=m-E;if(!o&&(v>=p||T&&this.moved)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(t-(g?.edge||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(y.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return;if(n.currentTime!==t){const R=t;t=n.currentTime,this.moved=!0,this.log(`currentTime changed ${R} > ${t}`);return}}const L=q.bufferInfo(n,t,i.maxBufferHole);this._tryFixBufferStall(L,v,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(y.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var r;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(r=this.buffered.audio)!=null&&r.length&&s&&s.length>1&&t>s.end(0)){const i=q.bufferedInfo(q.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&e>=i.start){const n=q.timeRangesToArray(s),o=q.bufferedInfo(n,e,0).bufferedIndex;if(o>-1&&o<n.length-1){const l=q.bufferedInfo(n,t,0).bufferedIndex,h=n[o].end,d=n[o+1].start;if((l===-1||l>o)&&d-h<1&&t-h<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${h} -> ${d} buffered index: ${l}`);this.warn(u.message),this.media.currentTime+=1e-6;let c=ye(t,this.fragmentTracker);c&&"fragment"in c?c=c.fragment:c||(c=void 0);const f=q.bufferInfo(this.media,t,0);this.hls.trigger(y.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:c,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(t,e,r){var s,i;const{fragmentTracker:n,media:o}=this,l=(s=this.hls)==null?void 0:s.config;if(!o||!n||!l)return;const h=(i=this.hls)==null?void 0:i.latestLevelDetails,d=ye(r,n);if((d||h!=null&&h.live&&r<h.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;const u=t.buffered,c=this.adjacentTraversal(t,r);(u&&u.length>1&&t.len>l.maxBufferHole||t.nextStart&&(t.nextStart-r<l.maxBufferHole||c))&&(e>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const r=this.fragmentTracker,s=t.nextStart;if(r&&s){const i=r.getFragAtPos(e,j.MAIN),n=r.getFragAtPos(s,j.MAIN);if(i&&n)return n.sn-i.sn<2}return!1}_reportStall(t){const{hls:e,media:r,stallReported:s,stalled:i}=this;if(!s&&i!==null&&r&&e){this.stallReported=!0;const n=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${yt(t)})`);this.warn(n.message),e.trigger(y.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:t.len,bufferInfo:t,stalled:{start:i}})}}_trySkipBufferHole(t){const{fragmentTracker:e,media:r,hls:s}=this,i=s?.config;if(!r||!e||!i)return 0;const n=r.currentTime,o=q.bufferInfo(r,n,0);Ki(o,n,e,s);const l=n<o.start?o.start:o.nextStart;if(l){const d=o.len<=i.maxBufferHole,u=o.len>0&&o.len<1&&r.readyState<3,c=l-n;if(c>0&&(d||u)){if(c>i.maxBufferHole){let T=!1;if(n===0){const E=e.getAppendedFrag(0,j.MAIN);E&&l<E.end&&(T=!0)}if(!T&&t){var h;if(!((h=s.loadLevelObj)!=null&&h.details)||Vi(s.inFlightFragments,l))return 0;let E=!1,v=t.end;for(;v<l;){const S=ye(v,e),L=S?S.duration:0;if(L>0)v+=L;else{E=!0;break}}if(E)return 0}}const{nudgeMaxRetry:f,skipBufferHolePadding:g}=i,p=++this.skipRetry>f,m=Math.max(l,n)+g;if(p||(this.warn(`skipping hole, adjusting currentTime from ${n} to ${m}`),this.moved=!0,r.currentTime=m),!(t!=null&&t.gap)||p){const T=new Error(p?`Playhead still not moving after seeking over buffer hole from ${n} to ${m} after ${i.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${n} to ${m}`),E={type:Y.MEDIA_ERROR,details:D.BUFFER_SEEK_OVER_HOLE,fatal:p,error:T,reason:T.message,buffer:o.len,bufferInfo:o};t&&("fragment"in t?E.part=t:E.frag=t),s.trigger(y.ERROR,E)}return m}}return 0}_tryNudgeBuffer(t){const{hls:e,media:r,nudgeRetry:s}=this,i=e?.config;if(!r||!i)return 0;const n=r.currentTime;if(this.nudgeRetry++,s<i.nudgeMaxRetry){const o=n+(s+1)*i.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${n} to ${o}`);this.warn(l.message),r.currentTime=o,e.trigger(y.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:t.len,bufferInfo:t})}else{const o=new Error(`Playhead still not moving while enough data buffered @${n} after ${i.nudgeMaxRetry} nudges`);this.error(o.message),e.trigger(y.ERROR,{type:Y.MEDIA_ERROR,details:D.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:t.len,bufferInfo:t})}}}function Vi(a,t){const e=Hi(a.main);if(e&&e.start<=t)return e;const r=Hi(a.audio);return r&&r.start<=t?r:null}function Hi(a){if(!a)return null;switch(a.state){case F.IDLE:case F.STOPPED:case F.ENDED:case F.ERROR:return null}return a.frag}function ye(a,t){return t.getAppendedFrag(a,j.MAIN)||t.getPartialFragment(a)}function Ki(a,t,e,r){r.latestLevelDetails,ye(t,e),Fr(r.config)}let pt=(function(a){return a.audioId3="org.id3",a.dateRange="com.apple.quicktime.HLS",a.emsg="https://aomedia.org/emsg/ID3",a.misbklv="urn:misb:KLV:bin:1910.1",a})({});function So(a,t,e,r="",s="disabled"){const i=a.ownerDocument.createElement("track");return i.kind=t,i.label=e,r&&(i.srclang=r),i.src="data:,WEBVTT",i.track.mode=s,a.appendChild(i),i}function Lo(a,t,e,r){const s=a.mode;if(s==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const i=Ro(a.cues,t,e);for(let n=0;n<i.length;n++)(!r||r(i[n]))&&a.removeCue(i[n])}s==="disabled"&&(a.mode=s)}function Ao(a,t){if(t<=a[0].startTime)return 0;const e=a.length-1;if(t>a[e].endTime)return-1;let r=0,s=e,i;for(;r<=s;)if(i=Math.floor((s+r)/2),t<a[i].startTime)s=i-1;else if(t>a[i].startTime&&r<e)r=i+1;else return i;return a[r].startTime-t<t-a[s].startTime?r:s}function Ro(a,t,e){const r=[],s=Ao(a,t);if(s>-1)for(let i=s,n=a.length;i<n;i++){const o=a[i];if(o.startTime>=t&&o.endTime<=e)r.push(o);else if(o.startTime>e)return r}return r}const bo=.25;function Nr(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Wi(a,t,e,r,s){let i=new a(t,e,"");try{i.value=r,s&&(i.type=s)}catch{i=new a(t,e,yt(s?gt({type:s},r):r))}return i}const je=(()=>{const a=Nr();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Do{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(y.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(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(y.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){this.media=e.media}onMediaAttached(){var t;const e=(t=this.hls)==null?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 So(t,"metadata","id3","","hidden")}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:r,enableID3MetadataCues:s}=this.hls.config;if(!r&&!s)return;const{samples:i}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Nr();if(n)for(let o=0;o<i.length;o++){const l=i[o].type;if(l===pt.emsg&&!r||!s)continue;const h=vs(i[o].data),d=i[o].pts;let u=d+i[o].duration;u>je&&(u=je),u-d<=0&&(u=d+bo);for(let c=0;c<h.length;c++){const f=h[c];if(!Es(f)){this.updateId3CueEnds(d,l);const g=Wi(n,d,u,f,l);g&&this.id3Track.track.addCue(g)}}}}updateId3CueEnds(t,e){var r;const s=(r=this.id3Track)==null?void 0:r.track.cues;if(s)for(let i=s.length;i--;){const n=s[i];n.type===e&&n.startTime<t&&n.endTime===je&&(n.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:r,type:s}){const{id3Track:i,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=n;if(i&&(o||l)){let h;s==="audio"?h=d=>d.type===pt.audioId3&&l:s==="video"?h=d=>d.type===pt.emsg&&o:h=d=>d.type===pt.audioId3&&l||d.type===pt.emsg&&o,Lo(i.track,e,r,h)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:s,enableDateRangeMetadataCues:i,interstitialsController:n}=this.hls.config;if(!i)return;const o=Nr();if(!t.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:h}=t,d=Object.keys(h);let u=this.dateRangeCuesAppended;if(l&&e){var c;if((c=l.track.cues)!=null&&c.length){const p=Object.keys(u).filter(m=>d.indexOf(m)===-1);for(let m=p.length;m--;){var f;const T=p[m],E=(f=u[T])==null?void 0:f.cues;delete u[T],E&&Object.keys(E).forEach(v=>{const S=E[v];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(S)}catch{}}})}}else u=this.dateRangeCuesAppended={}}const g=t.fragments[t.fragments.length-1];if(!(d.length===0||!G(g?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<d.length;p++){const m=d[p],T=h[m],E=T.startTime,v=u[m],S=v?.cues||{};let L=v?.durationKnown||!1,R=je;const{duration:A,endDate:b}=T;if(b&&A!==null)R=E+A,L=!0;else if(T.endOnNext&&!L){const P=d.reduce((M,x)=>{if(x!==T.id){const N=h[x];if(N.class===T.class&&N.startDate>T.startDate&&(!M||T.startDate<M.startDate))return N}return M},null);P&&(R=P.startTime,L=!0)}const k=Object.keys(T.attr);for(let P=0;P<k.length;P++){const M=k[P];if(!$n(M))continue;const x=S[M];if(x)L&&!(v!=null&&v.durationKnown)?x.endTime=R:Math.abs(x.startTime-E)>.01&&(x.startTime=E,x.endTime=R);else if(o){let N=T.attr[M];Bn(M)&&(N=Ts(N));const U=Wi(o,E,R,{key:M,data:N},pt.dateRange);U&&(U.id=m,this.id3Track.track.addCue(U),S[M]=U)}}u[m]={cues:S,dateRange:T,durationKnown:L}}}}}class Io{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:e}=this,r=this.levelDetails;if(!e||!r||!this.hls)return;this.currentTime=e.currentTime;const s=this.hls.config,i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:o}=s;if(!n||o===1||!r.live)return;const l=this.targetLatency;if(l===null)return;const h=i-l,d=Math.min(this.maxLatency,l+r.targetduration);if(h<d&&h>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,o)),c=Math.round(2/(1+Math.exp(-.75*h-this.edgeStalled))*20)/20,f=Math.min(u,Math.max(1,c));this.changeMediaPlaybackRate(e,f)}else e.playbackRate!==1&&e.playbackRate!==0&&this.changeMediaPlaybackRate(e,1)},this.hls=t,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var t;const e=(t=this.hls)==null?void 0:t.config;if(!e)return 0;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const r=this.levelDetails;return r?e.liveMaxLatencyDurationCount*r.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||!this.hls)return null;const e=this.hls.config,{holdBack:r,partHoldBack:s,targetduration:i}=t,{liveSyncDuration:n,liveSyncDurationCount:o,lowLatencyMode:l}=e,h=this.hls.userConfig;let d=l&&s||r;(this._targetLatencyUpdated||h.liveSyncDuration||h.liveSyncDurationCount||d===0)&&(d=n!==void 0?n:o*i);const u=i;return d+Math.min(this.stallCount*e.liveSyncOnStallIncrease,u)}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(t===null||e===null||!this.hls)return null;const r=this.levelDetails;if(r===null)return null;const s=r.edge,i=t-e-this.edgeStalled,n=s-r.totalduration,o=s-(this.hls.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(n,i),o)}get drift(){const t=this.levelDetails;return t===null?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(t===null||!this.hls)return 0;const e=(this.hls.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;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(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(y.ERROR,this.onError,this),t.on(y.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(y.ERROR,this.onError,this),t.off(y.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 s=this.hls,i=this.media||e.event.appendInPlace&&(s==null||(r=s.interstitialsManager)==null?void 0:r.playerQueue.reduce((n,o)=>n||o.media,null));s&&i&&i.playbackRate>1&&i.playbackRate<=s.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(i,1)}onError(t,e){var r;e.details===D.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(r=this.levelDetails)!=null&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var r,s;t.playbackRate!==e&&((r=this.hls)==null||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return t===null?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return t===null?null:t-this.currentTime}}const Te="1.7.4",ae={};function ko(){return typeof __HLS_WORKER_BUNDLE__=="function"}function _o(){const a=ae[Te];if(a)return a.clientCount++,a;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(t),r={worker:new self.Worker(e),objectURL:e,clientCount:1};return ae[Te]=r,r}function Co(a){const t=ae[a];if(t)return t.clientCount++,t;const e=new self.URL(a,self.location.href).href,r={worker:new self.Worker(e),scriptURL:e,clientCount:1};return ae[a]=r,r}function Po(a){const t=ae[a||Te];if(t&&t.clientCount--===1){const{worker:e,objectURL:r}=t;delete ae[a||Te],r&&self.URL.revokeObjectURL(r),e.terminate()}}function xo(a,t,e,r){const s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],i=t[e+2],n=i>>2&15;if(n>12){const m=new Error(`invalid ADTS sampling index:${n}`);a.emit(y.ERROR,y.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!0,error:m,reason:m.message});return}const o=(i>>6&3)+1,l=t[e+3]>>6&3|(i&1)<<2,h=s[n];let d=n;(o===5||o===29)&&(d-=3);let u;const c=(d&14)>>1,f=(d&1)<<7|l<<3;let g=0;if(o===1&&n>=6){g=5;const m=n-3;u=[g<<3|c,f|(m&14)>>1,(m&1)<<7|8,0]}else u=[o<<3|c,f];const p="mp4a.40."+(g||o);return et.log(`manifest codec:${r}, parsed codec:${p}, channels:${l}, rate:${h} (ADTS object type:${o} sampling index:${n} esds config:[${u.join(",")}])`),{config:u,samplerate:h,channelCount:l,codec:p,parsedCodec:p,manifestCodec:r}}function Yi(a,t){return a[t]===255&&(a[t+1]&246)===240}function ji(a,t){return a[t+1]&1?7:9}function $r(a,t){return(a[t+3]&3)<<11|a[t+4]<<3|(a[t+5]&224)>>>5}function wo(a,t){return t+5<a.length}function qe(a,t){return t+1<a.length&&Yi(a,t)}function Oo(a,t){return wo(a,t)&&Yi(a,t)&&$r(a,t)<=a.length-t}function Mo(a,t){if(qe(a,t)){const e=ji(a,t);if(t+e>=a.length)return!1;const r=$r(a,t);if(r<=e)return!1;const s=t+r;return s===a.length||qe(a,s)}return!1}function qi(a,t,e,r,s){if(!a.samplerate){const i=xo(t,e,r,s);if(!i)return;lt(a,i)}}function zi(a){return 1024*9e4/a}function Fo(a,t){const e=ji(a,t);if(t+e<=a.length){const r=$r(a,t)-e;if(r>0)return{headerLength:e,frameLength:r}}}function Xi(a,t,e,r,s){const i=zi(a.samplerate),n=r+s*i,o=Fo(t,e);let l;if(o){const{frameLength:d,headerLength:u}=o,c=u+d,f=Math.max(0,e+c-t.length);f?(l=new Uint8Array(c-u),l.set(t.subarray(e+u,t.length),0)):l=t.subarray(e+u,e+c);const g={unit:l,pts:n};return f||a.samples.push(g),{sample:g,length:c,missing:f}}const h=t.length-e;return l=new Uint8Array(h),l.set(t.subarray(e,t.length),0),{sample:{unit:l,pts:n},length:h,missing:-1}}function wt(a="",t=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Qi{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,s){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(t,e){this.cachedData&&(t=bt(this.cachedData,t),this.cachedData=null);let r=Ce(t,0),s=r?r.length:0,i;const n=this._audioTrack,o=this._id3Track,l=r?ys(r):void 0,h=t.length;for((this.basePTS===null||this.frameIndex===0&&G(l))&&(this.basePTS=No(l,e,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),r&&r.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:pt.audioId3,duration:Number.POSITIVE_INFINITY});s<h;){if(this.canParse(t,s)){const d=this.appendFrame(n,t,s);d?(this.frameIndex++,this.lastPTS=d.sample.pts,s+=d.length,i=s):s=h}else Ga(t,s)?(r=Ce(t,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:pt.audioId3,duration:Number.POSITIVE_INFINITY}),s+=r.length,i=s):s++;if(s===h&&i!==h){const d=t.slice(i);this.cachedData?this.cachedData=bt(this.cachedData,d):this.cachedData=d}}return{audioTrack:n,videoTrack:wt(),id3Track:o,textTrack:wt()}}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:wt(),id3Track:this._id3Track,textTrack:wt()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const No=(a,t,e)=>{if(G(a))return a*90;const r=e?e.baseTime*9e4/e.timescale:0;return t*9e4+r},$o=[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],Bo=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Uo=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Go=[0,1,1,4];function Zi(a,t,e,r,s){if(e+24>t.length)return;const i=Ji(t,e);if(i&&e+i.frameLength<=t.length){const n=i.samplesPerFrame*9e4/i.sampleRate,o=r+s*n,l={unit:t.subarray(e,e+i.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=i.channelCount,a.samplerate=i.sampleRate,a.samples.push(l),{sample:l,length:i.frameLength,missing:0}}}function Ji(a,t){const e=a[t+1]>>3&3,r=a[t+1]>>1&3,s=a[t+2]>>4&15,i=a[t+2]>>2&3;if(e!==1&&s!==0&&s!==15&&i!==3){const n=a[t+2]>>1&1,o=a[t+3]>>6,l=e===3?3-r:r===3?3:4,h=$o[l*14+s-1]*1e3,d=Bo[(e===3?0:e===2?1:2)*3+i],u=o===3?1:2,c=Uo[e][r],f=Go[r],g=c*8*f,p=Math.floor(c*h/d+n)*f,m=ge();return m&&m<=87&&r===2&&h>=224e3&&o===0&&(a[t+3]=a[t+3]|128),{sampleRate:d,channelCount:u,frameLength:p,samplesPerFrame:g}}}function Br(a,t){return a[t]===255&&(a[t+1]&224)===224&&(a[t+1]&6)!==0}function ta(a,t){return t+1<a.length&&Br(a,t)}function Vo(a,t){return Br(a,t)&&4<=a.length-t}function ea(a,t){if(t+1<a.length&&Br(a,t)){const e=Ji(a,t);let r=4;e!=null&&e.frameLength&&(r=e.frameLength);const s=t+r;return s===a.length||ta(a,s)}return!1}class ra{constructor(t,e,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Or(e,!0)}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,Kt.cbc,{start:0,end:t.byteLength})}decryptAacSample(t,e,r){const s=t[e].unit;if(s.length<=16)return;const i=s.subarray(16,s.length-s.length%16),n=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(n).then(o=>{const l=new Uint8Array(o);s.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,r)}).catch(r)}decryptAacSamples(t,e,r){for(;;e++){if(e>=t.length){r();return}if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=Math.floor((t.length-48)/160)*16+16,r=new Int8Array(e);let s=0;for(let i=32;i<t.length-16;i+=160,s+=16)r.set(t.subarray(i,i+16),s);return r}getAvcDecryptedUnit(t,e){const r=new Uint8Array(e);let s=0;for(let i=32;i<t.length-16;i+=160,s+=16)t.set(r.subarray(s,s+16),i);return t}decryptAvcSample(t,e,r,s,i){const n=Cs(i.data),o=this.getAvcEncryptedData(n);this.decryptBuffer(o.buffer).then(l=>{i.data=this.getAvcDecryptedUnit(n,l),this.decrypter.isSync()||this.decryptAvcSamples(t,e,r+1,s)}).catch(s)}decryptAvcSamples(t,e,r,s){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,r=0){if(e>=t.length){s();return}const i=t[e].units;for(;!(r>=i.length);r++){const n=i[r];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(t,e,r,s,n),!this.decrypter.isSync()))return}}}}class Ho extends Qi{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,s){super.resetInitSegment(t,e,r,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const r=Ce(t,0);let s=r?.length||0;if(ea(t,s))return!1;for(let i=t.length;s<i;s++)if(Mo(t,s))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return Oo(t,e)}appendFrame(t,e,r){qi(t,this.observer,e,r,t.manifestCodec);const s=Xi(t,e,r,this.basePTS,this.frameIndex);if(s?.missing===0)return s}demuxSampleAes(t,e,r){const s=this.demux(t,r),i=this.sampleAes=new ra(this.observer,this.config,e);return new Promise(n=>{i.decryptAacSamples(s.audioTrack.samples,0,()=>{n(s)})})}}const Ko=(a,t)=>{let e=0,r=5;t+=r;const s=new Uint32Array(1),i=new Uint32Array(1),n=new Uint8Array(1);for(;r>0;){n[0]=a[t];const o=Math.min(r,8),l=8-o;i[0]=4278190080>>>24+l<<l,s[0]=(n[0]&i[0])>>l,e=e?e<<o|s[0]:s[0],t+=1,r-=o}return e};class Wo extends Qi{resetInitSegment(t,e,r,s){super.resetInitSegment(t,e,r,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Ce(t,0);let r=e?.length||0;if(e&&t[r]===11&&t[r+1]===119&&ys(e)!==void 0&&Ko(t,r)<=16)return!1;for(let s=t.length;r<s;r++)if(ea(t,r))return et.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return Vo(t,e)}appendFrame(t,e,r){if(this.basePTS!==null)return Zi(t,e,r,this.basePTS,this.frameIndex)}}const Yo=/\/emsg[-/]ID3/i;class jo{constructor(t,e,r,s=et){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=s}resetTimeStamp(){}resetInitSegment(t,e,r,s){const i=this.videoTrack=wt("video",1),n=this.audioTrack=wt("audio",1),o=this.txtTrack=wt("text",1);if(this.id3Track=wt("id3",1),this.initData=void 0,this.timeOffset=0,!(t!=null&&t.byteLength))return;const l=this.initData=bs(t);if(l.video){const{id:h,timescale:d,codec:u,supplemental:c}=l.video;i.id=h,i.timescale=o.timescale=d,i.codec=u,i.supplemental=c}if(l.audio){const{id:h,timescale:d,codec:u}=l.audio;n.id=h,n.timescale=d,n.codec=u}o.id=Ss.text,i.sampleDuration=0,i.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return tn(t,"moof")}demux(t,e,r){this.timeOffset=e;let s=t;const i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=bt(this.remainderData,t));const h=cn(s);this.remainderData=h.remainder,i.samples=h.valid||new Uint8Array}else i.samples=s;const o=this.extractID3Track(i,e),l=this.parseFragment(i,n,e,r);return{videoTrack:i,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(t,e){const r=this.timeOffset,s=this.videoTrack,i=this.txtTrack;s.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(s,this.timeOffset),o=this.parseFragment(s,i,r,e);return{videoTrack:s,audioTrack:wt(),id3Track:n,textTrack:wt(),initData:this.initData,sampleData:o}}parseFragment(t,e,r,s){const i=this.initData;if(i&&s){const{samples:n,sampleData:o}=un(r,t,i,this.logger,!1);return e.samples=n,o}e.samples=fn(r,t)}extractID3Track(t,e){const r=this.id3Track;if(t.samples.length){const s=tt(t.samples,["emsg"]);s&&s.forEach(i=>{const n=gn(i);if(Yo.test(n.schemeIdUri)){const o=sa(n,e);let l=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const h=n.payload;r.samples.push({data:h,len:h.byteLength,dts:o,pts:o,type:pt.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){const o=this.config.emsgKLVSchemaUri||pt.misbklv;if(n.schemeIdUri.startsWith(o)){const l=sa(n,e);r.samples.push({data:n.payload,len:n.payload.byteLength,dts:l,pts:l,type:pt.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return r}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}}function sa(a,t){return G(a.presentationTime)?a.presentationTime/a.timeScale:t+a.presentationTimeDelta/a.timeScale}const qo=1,zo=2,Xo=3,Se=-1;class Qo{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=this.VideoSample,s;if((!r||r.units.length===0)&&(r=t[t.length-1]),(e=r)!=null&&e.units){const i=r.units;s=i[i.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(t.pts===void 0){const r=e.samples,s=r.length;if(s){const i=r[s-1];t.pts=i.pts,t.dts=i.dts}else{e.dropped++;return}}e.samples.push(t)}}parseNALu(t,e,r){const s=e.byteLength;if(s===0)return[];const i=t.naluState||0,n=i===Se?0:i,o=[];let l=0,h=0,d=-1,u=0;for(i===Se&&(d=0,u=this.getNALuType(e,0),h=1);h<s;){const c=e.indexOf(qo,h);if(c===-1)break;h=c+1;let f=c;for(;f>0&&e[f-1]===0;)f--;const g=c-f+(f===0?n:0);if(g<zo)continue;const p=Math.min(g,Xo),m=Math.min(c-f,p),T=p-m;if(f=c-m,d>=0)o.push({data:e.subarray(d,f),type:u});else{const E=this.getLastNalUnit(t.samples);E&&(f>0?E.data=bt(E.data,e.subarray(0,f)):T>0&&(E.data=E.data.subarray(0,E.data.byteLength-T)),E.state=0)}if(h<s)d=h,u=this.getNALuType(e,h);else{l=Se,d=-1;break}}if(l!==Se){let c=s;for(;c>0&&e[c-1]===0;)c--;l=s-c+(c===0?n:0)}if(d>=0)o.push({data:e.subarray(d),type:u,state:l});else if(o.length===0&&l!==Se){const c=this.getLastNalUnit(t.samples);c&&(c.data=bt(c.data,e),c.state=l)}return t.naluState=l,o}}class ia{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,s=new Uint8Array(4),i=Math.min(4,e);if(i===0)throw new Error("no bytes available");s.set(t.subarray(r,r+i)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}skipBits(t){let e;t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,e=t>>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&&et.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");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((this.word&2147483648>>>t)!==0)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 this.readBits(1)===1}readUByte(){return this.readBits(8)}}class Zo extends Qo{parsePES(t,e,r,s,i){const n=i.iframe,o=this.parseNALu(t,r.data,s);let l=this.VideoSample,h,d=!1;r.data=null,l&&o.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),o.forEach(u=>{var c,f;switch(u.type){case 1:{if(n)break;let T=!1;h=!0;const E=u.data;if(d&&E.length>4){const v=this.readSliceType(E);(v===2||v===4||v===7||v===9)&&(T=!0)}if(T){var g;(g=l)!=null&&g.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=T;break}case 5:h=!0,(c=l)!=null&&c.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;h=!0,Me(u.data,1,r.pts,e.samples);break}case 7:{var p,m;h=!0,d=!0;const T=u.data,E=this.readSPS(T);if(!t.sps||t.width!==E.width||t.height!==E.height||((p=t.pixelRatio)==null?void 0:p[0])!==E.pixelRatio[0]||((m=t.pixelRatio)==null?void 0:m[1])!==E.pixelRatio[1]){t.width=E.width,t.height=E.height,t.pixelRatio=E.pixelRatio,t.sps=[T];const v=T.subarray(1,4);let S="avc1.";for(let L=0;L<3;L++){let R=v[L].toString(16);R.length<2&&(R="0"+R),S+=R}t.codec=S}break}case 8:h=!0,t.pps=[u.data];break;case 9:h=!0,t.audFound=!0,(f=l)!=null&&f.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:h=!0;break;default:h=!1;break}l&&h&&l.units.push(u)}),s&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,e){return t[e]&31}readSliceType(t){const e=new ia(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let r=8,s=8,i;for(let n=0;n<t;n++)s!==0&&(i=e.readEG(),s=(r+i+256)%256),r=s===0?r:s}readSPS(t){const e=new ia(t);let r=0,s=0,i=0,n=0,o,l,h;const d=e.readUByte.bind(e),u=e.readBits.bind(e),c=e.readUEG.bind(e),f=e.readBoolean.bind(e),g=e.skipBits.bind(e),p=e.skipEG.bind(e),m=e.skipUEG.bind(e),T=this.skipScalingList.bind(this);d();const E=d();if(u(5),g(3),d(),m(),E===100||E===110||E===122||E===244||E===44||E===83||E===86||E===118||E===128){const b=c();if(b===3&&g(1),m(),m(),g(1),f())for(l=b!==3?8:12,h=0;h<l;h++)f()&&(h<6?T(16,e):T(64,e))}m();const v=c();if(v===0)c();else if(v===1)for(g(1),p(),p(),o=c(),h=0;h<o;h++)p();m(),g(1);const S=c(),L=c(),R=u(1);R===0&&g(1),g(1),f()&&(r=c(),s=c(),i=c(),n=c());let A=[1,1];if(f()&&f())switch(d()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[d()<<8|d(),d()<<8|d()];break}}return{width:Math.ceil((S+1)*16-r*2-s*2),height:(2-R)*(L+1)*16-(R?2:4)*(i+n),pixelRatio:A}}}const nt=188;class Vt{constructor(t,e,r,s){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=s,this.videoParser=null}static probe(t,e){const r=Vt.syncOffset(t);return r>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(t){const e=t.length;let r=Math.min(nt*5,e-nt)+1,s=0;for(;s<r;){let i=!1,n=-1,o=0;for(let l=s;l<e;l+=nt)if(t[l]===71&&(e-l===nt||t[l+nt]===71)){if(o++,n===-1&&(n=l,n!==0&&(r=Math.min(n+nt*99,t.length-nt)+1)),i||(i=ze(t,l)===0),i&&o>1&&(n===0&&o>2||l+nt>r))return n}else{if(o)return-1;break}s++}return-1}static createTrack(t,e){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:Ss[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?e:void 0}}resetInitSegment(t,e,r,s,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Vt.createTrack("video"),this._videoTrack.duration=s,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new el(this.logger):null,this._audioTrack=Vt.createTrack("audio",s),this._id3Track=Vt.createTrack("id3"),this._txtTrack=Vt.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,i?.method==="SAMPLE-AES")}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,s=!1,i=!1){s||(this.sampleAes=null);let n;const o=this._videoTrack,l=this.videoIntegrityChecker,h=this._audioTrack,d=this._id3Track,u=this._txtTrack,c=r.iframe;let f=o.pid,g=o.pesData,p=h.pid,m=d.pid,T=this._klvPid,E=h.pesData,v=d.pesData,S=null,L=null,R=this.pmtParsed,A=this._pmtId,b=t.length;if(this.remainderData&&(t=bt(this.remainderData,t),b=t.length,this.remainderData=null),b<nt&&!i)return this.remainderData=t,{audioTrack:h,videoTrack:o,id3Track:d,textTrack:u};const k=Math.max(0,Vt.syncOffset(t));b-=(b-k)%nt,b<t.byteLength&&!i&&(this.remainderData=new Uint8Array(t.buffer,b,t.buffer.byteLength-b));let P=0;for(let x=k;x<b;x+=nt)if(t[x]===71){const N=!!(t[x+1]&64),U=ze(t,x),$=(t[x+3]&48)>>4;let _;if($>1){if(_=x+5+t[x+4],_===x+nt)continue}else _=x+4;switch(U){case f:N&&(g&&!(l!=null&&l.isCorrupted)&&(n=Zt(g,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,u,n,!1,r)),g={data:[],size:0},l?.reset(f)),l?.handlePacket(t.subarray(x)),g&&(g.data.push(t.subarray(_,x+nt)),g.size+=x+nt-_);break;case p:if(c)break;if(N){if(E&&(n=Zt(E,this.logger)))switch(h.segmentCodec){case"aac":this.parseAACPES(h,n,r);break;case"mp3":this.parseMPEGPES(h,n);break}E={data:[],size:0}}E&&(E.data.push(t.subarray(_,x+nt)),E.size+=x+nt-_);break;case m:if(c)break;N&&(v&&(n=Zt(v,this.logger))&&this.parseID3PES(d,n),v={data:[],size:0}),v&&(v.data.push(t.subarray(_,x+nt)),v.size+=x+nt-_);break;case T:if(c)break;N&&(S&&(n=Zt(S,this.logger))&&this.parseKlvPES(d,n),S={data:[],size:0}),S&&(S.data.push(t.subarray(_,x+nt)),S.size+=x+nt-_);break;case 0:N&&(_+=t[_]+1),A=this._pmtId=Jo(t,_);break;case A:{N&&(_+=t[_]+1);const w=tl(t,_,this.typeSupported,s,this.observer,this.logger,this.config,r);f=w.videoPid,f>0&&(o.pid=f,o.segmentCodec=w.segmentVideoCodec),p=w.audioPid,p>0&&(h.pid=p,h.segmentCodec=w.segmentAudioCodec),m=w.id3Pid,m>0&&(d.pid=m),T=w.klvPid,T>0&&(this._klvPid=T),L!==null&&!R&&(this.logger.warn(`MPEG-TS PMT found at ${x} after unknown PID '${L}'. Backtracking to sync byte @${k} to parse all TS packets.`),L=null,x=k-188),R=this.pmtParsed=!0;break}case 17:case 8191:break;default:L=U;break}}else P++;P>0&&Xe(this.observer,new Error(`Found ${P} TS packet/s that do not start with 0x47`),r,void 0,this.logger),o.pesData=g,h.pesData=E,d.pesData=v;const M={audioTrack:h,videoTrack:o,id3Track:d,textTrack:u};return i&&this.extractRemainingSamples(M,r),M}flush(t,e){const{remainderData:r}=this;this.remainderData=null;let s;return r?s=this.demux(r,0,e,!1,!0):s={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(s,e),this.sampleAes?this.decrypt(s,this.sampleAes):s}extractRemainingSamples(t,e){const{audioTrack:r,videoTrack:s,id3Track:i,textTrack:n}=t,o=s.pesData,l=r.pesData,h=i.pesData,d=this.videoIntegrityChecker;let u;if(o&&!(d!=null&&d.isCorrupted)&&(u=Zt(o,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,n,u,!0,e),s.pesData=null)):s.pesData=o,l&&(u=Zt(l,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,u,e);break;case"mp3":this.parseMPEGPES(r,u);break}r.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=l;h&&(u=Zt(h,this.logger))?(this.parseID3PES(i,u),i.pesData=null):i.pesData=h}demuxSampleAes(t,e,r,s){const i=this.demux(t,r,s,!0,!this.config.progressive),n=this.sampleAes=new ra(this.observer,this.config,e);return this.decrypt(i,n)}readyVideoParser(t){this.videoParser===null&&t==="avc"&&(this.videoParser=new Zo)}decrypt(t,e){return new Promise(r=>{const{audioTrack:s,videoTrack:i}=t;s.samples&&s.segmentCodec==="aac"?e.decryptAacSamples(s.samples,0,()=>{i.samples?e.decryptAvcSamples(i.samples,0,0,()=>{r(t)}):r(t)}):i.samples&&e.decryptAvcSamples(i.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 s=0;const i=this.aacOverFlow;let n=e.data;if(i){this.aacOverFlow=null;const c=i.missing,f=i.sample.unit.byteLength;if(c===-1)n=bt(i.sample.unit,n);else{const g=f-c;i.sample.unit.set(n.subarray(0,c),g),t.samples.push(i.sample),s=i.missing}}let o,l;for(o=s,l=n.length;o<l-1&&!qe(n,o);o++);if(o!==s){let c;const f=o<l-1;if(f?c=`AAC PES did not start with ADTS header,offset:${o}`:c="No ADTS header found in AAC PES",Xe(this.observer,new Error(c),r,f,this.logger),!f)return}qi(t,this.observer,n,o,this.audioCodec);let h;if(e.pts!==void 0)h=e.pts;else if(i){const c=zi(t.samplerate);h=i.sample.pts+c}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,u;for(;o<l;)if(u=Xi(t,n,o,h,d),o+=u.length,u.missing){this.aacOverFlow=u;break}else for(d++;o<l-1&&!qe(n,o);o++);}parseMPEGPES(t,e){const r=e.data,s=r.length;let i=0,n=0;const o=e.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;n<s;)if(ta(r,n)){const l=Zi(t,r,n,o,i);if(l)n+=l.length,i++;else break}else n++}parseAC3PES(t,e){}parseID3PES(t,e){if(e.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const r=lt({},e,{type:this._videoTrack?pt.emsg:pt.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}parseKlvPES(t,e){var r;const s=(r=e.pts)!=null?r:e.dts;if(s===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}const i=e.data;if(i.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let n=0;for(;n<i.length;){var o;if(n+16>i.length)break;const l=n;if(n+=16,n>=i.length)break;const h=i[n];n+=1;let d=0;if(h&128){const g=h&127;if(g===0||g>4||n+g>i.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let p=0;p<g;p++)d=d<<8|i[n+p];n+=g}else d=h;if(n+d>i.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const u=n+d,c=i.subarray(l,u),f={data:c,len:c.byteLength,pts:s,dts:(o=e.dts)!=null?o:s,type:pt.misbklv,duration:Number.POSITIVE_INFINITY};t.samples.push(f),n=u}}}function ze(a,t){return((a[t+1]&31)<<8)+a[t+2]}function Jo(a,t){return(a[t+10]&31)<<8|a[t+11]}function tl(a,t,e,r,s,i,n,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},h=(a[t+1]&15)<<8|a[t+2],d=t+3+h-4,u=(a[t+10]&15)<<8|a[t+11];for(t+=12+u;t<d;){const c=ze(a,t),f=(a[t+3]&15)<<8|a[t+4];switch(a[t]){case 207:if(!r){Ur("ADTS AAC",i);break}case 15:l.audioPid===-1&&(l.audioPid=c);break;case 21:l.id3Pid===-1&&(l.id3Pid=c);break;case 219:if(!r){Ur("H.264",i);break}case 27:l.videoPid===-1&&(l.videoPid=c);break;case 3:case 4:!e.mpeg&&!e.mp3?i.log("MPEG audio found, not supported in this browser"):l.audioPid===-1&&(l.audioPid=c,l.segmentAudioCodec="mp3");break;case 193:if(!r){Ur("AC-3",i);break}case 129:i.warn("AC-3 in M2TS support not included in build");break;case 6:if(f>0){let g=t+5,p=f;for(;p>2;){switch(a[g]){case 106:l.audioPid===-1&&i.warn("AC-3 in M2TS support not included in build");break;case 5:l.klvPid===-1&&n.enableEmsgKLVMetadata&&(l.klvPid=c,i.log(`KLV metadata PID found: ${c}`));break}const m=a[g+1]+2;g+=m,p-=m}}break;case 194:case 135:return Xe(s,new Error("Unsupported EC-3 in M2TS found"),o,void 0,i),l;case 36:return Xe(s,new Error("Unsupported HEVC in M2TS found"),o,void 0,i),l}t+=f+5}return l}function Xe(a,t,e,r,s){s.warn(`parsing error: ${t.message}`),a.emit(y.ERROR,y.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,chunkMeta:e,error:t,reason:t.message})}function Ur(a,t){t.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function Zt(a,t){let e=0,r,s,i,n,o;const l=a.data;if(!a||a.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=bt(l[0],l[1]),l.splice(1,1);if(r=l[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(s=(r[4]<<8)+r[5],s&&s>a.size-6)return null;const h=r[7];h&192&&(n=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,h&64?(o=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,n-o>60*9e4&&(t.warn(`${Math.round((n-o)/9e4)}s delta between PTS and DTS, align them`),n=o)):o=n),i=r[8];let d=i+9;if(a.size<=d)return null;a.size-=d;const u=new Uint8Array(a.size);for(let c=0,f=l.length;c<f;c++){r=l[c];let g=r.byteLength;if(d)if(d>g){d-=g;continue}else r=r.subarray(d),g-=d,d=0;u.set(r,e),e+=g}return s&&(s-=i+3),{data:u,pts:n,dts:o,len:s}}return null}class el{constructor(t){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t}get isCorrupted(){return this.integrityState!=="ok"}reset(t){this.pid=t,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(t){if(t.byteLength<4)return;const e=ze(t,0);if(e!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${e}`);return}const r=(t[3]&48)>>4;if(r===0)return;const s=t[3]&15,i=this.lastContinuityCounter;this.lastContinuityCounter=s;const n=(r&1)!=0;if((r&2)!=0&&t[4]!=0&&(t[5]&128)!=0||i<0)return;const o=n?i+1&15:i;if(s!==o){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${e}', CC=${s}, Expected-CC=${o} Last-CC=${i}`),this.integrityState="cc-failed";return}if((t[1]&128)!==0){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${e}'`),this.integrityState="tei-bit";return}}}class rl{static getSilentFrame(t,e){switch(t){case"mp4a.40.2":if(e===1)return new Uint8Array([0,200,0,128,35,128]);if(e===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(e===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(e===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(e===5)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(e===6)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]);break;default:if(e===1)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(e===2)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(e===3)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]);break}}}var Qe;const sl={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])},Gr=new Uint8Array([0,0,0,0,0,0,0,0]),il=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),al=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),nl=new Uint8Array([0,0,0,0,0,0,0,0]),Vr=new Uint8Array([0,0,0,0,0,0,0,1]),aa=new Uint8Array([105,115,111,109]),ol=new Uint8Array([97,118,99,49]),ll=new Uint8Array([0,0,0,1]);class B{static box(t,...e){let r=8,s=e.length;const i=s;for(;s--;)r+=e[s].byteLength;const n=new Uint8Array(r);for(Qt(n,0,r),Qt(n,4,t),s=0,r=8;s<i;s++)n.set(e[s],r),r+=e[s].byteLength;return n}static hdlr(t){return B.box(X.hdlr,sl[t])}static mdat(t){return B.box(X.mdat,t)}static mdhd(t,e){e*=t;const r=Math.floor(e/(_t+1)),s=Math.floor(e%(_t+1));return B.box(X.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,t&255,r>>24,r>>16&255,r>>8&255,r&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(t){return B.box(X.mdia,B.mdhd(t.timescale||0,t.duration||0),B.hdlr(t.type),B.minf(t))}static mfhd(t){return B.box(X.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?B.box(X.minf,B.box(X.smhd,nl),B.DINF,B.stbl(t)):B.box(X.minf,B.box(X.vmhd,al),B.DINF,B.stbl(t))}static moof(t,e,r){return B.box(X.moof,B.mfhd(t),B.traf(r,e))}static moov(t){let e=t.length;const r=[];for(;e--;)r[e]=B.trak(t[e]);return B.box.apply(null,[X.moov,B.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(B.mvex(t)))}static mvex(t){let e=t.length;const r=[];for(;e--;)r[e]=B.trex(t[e]);return B.box.apply(null,[X.mvex,...r])}static mvhd(t,e){e*=t;const r=Math.floor(e/(_t+1)),s=Math.floor(e%(_t+1)),i=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,t&255,r>>24,r>>16&255,r>>8&255,r&255,s>>24,s>>16&255,s>>8&255,s&255,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 B.box(X.mvhd,i)}static sdtp(t){const e=t.samples||[],r=new Uint8Array(4+e.length);let s,i;for(s=0;s<e.length;s++)i=e[s].flags,r[s+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return B.box(X.sdtp,r)}static stbl(t){return B.box(X.stbl,B.stsd(t),B.box(X.stts,Gr),B.box(X.stsc,Gr),B.box(X.stsz,il),B.box(X.stco,Gr))}static avc1(t){let e=[],r=[],s,i,n;for(s=0;s<t.sps.length;s++)i=t.sps[s],n=i.byteLength,e.push(n>>>8&255),e.push(n&255),e=e.concat(Array.prototype.slice.call(i));for(s=0;s<t.pps.length;s++)i=t.pps[s],n=i.byteLength,r.push(n>>>8&255),r.push(n&255),r=r.concat(Array.prototype.slice.call(i));const o=B.box(X.avcC,new Uint8Array([1,e[3],e[4],e[5],255,224|t.sps.length].concat(e).concat([t.pps.length]).concat(r))),l=t.width,h=t.height,d=t.pixelRatio[0],u=t.pixelRatio[1];return B.box(X.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,l>>8&255,l&255,h>>8&255,h&255,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]),o,B.box(X.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),B.box(X.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,u>>24,u>>16&255,u>>8&255,u&255])))}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,e&255,0,0])}static mp4a(t){return B.box(X.mp4a,B.audioStsd(t),B.box(X.esds,B.esds(t)))}static mp3(t){return B.box(X[".mp3"],B.audioStsd(t))}static ac3(t){return B.box(X["ac-3"],B.audioStsd(t),B.box(X.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if(t.type==="audio"){if(e==="aac")return B.box(X.stsd,Vr,B.mp4a(t));if(e==="mp3"&&t.codec==="mp3")return B.box(X.stsd,Vr,B.mp3(t))}else if(t.pps&&t.sps){if(e==="avc")return B.box(X.stsd,Vr,B.avc1(t))}else throw new Error("video track missing pps or sps");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),s=t.width||0,i=t.height||0,n=Math.floor(r/(_t+1)),o=Math.floor(r%(_t+1));return B.box(X.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,e&255,0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,o>>24,o>>16&255,o>>8&255,o&255,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,s>>8&255,s&255,0,0,i>>8&255,i&255,0,0]))}static traf(t,e){const r=B.sdtp(t),s=t.id,i=Math.floor(e/(_t+1)),n=Math.floor(e%(_t+1));return B.box(X.traf,B.box(X.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),B.box(X.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255])),B.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,B.box(X.trak,B.tkhd(t),B.mdia(t))}static trex(t){const e=t.id;return B.box(X.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const r=t.samples||[],s=r.length,i=12+16*s,n=new Uint8Array(i);let o,l,h,d,u,c;for(e+=8+i,n.set([t.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255],0),o=0;o<s;o++)l=r[o],h=l.duration,d=l.size,u=l.flags,c=l.cts,n.set([h>>>24&255,h>>>16&255,h>>>8&255,h&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,c>>>24&255,c>>>16&255,c>>>8&255,c&255],12+16*o);return B.box(X.trun,n)}static initSegment(t){const e=B.moov(t);return bt(B.FTYP,e)}static hvc1(t){return new Uint8Array}}Qe=B,B.FTYP=Qe.box(X.ftyp,aa,ll,aa,ol),B.DINF=Qe.box(X.dinf,Qe.box(X.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));const hl=9e4;function dl(a,t,e=1,r=!1){const s=a*t*e;return r?Math.round(s):s}function Le(a,t=!1){return dl(a,1e3,1/hl,t)}function na(a){const{baseTime:t,timescale:e,trackId:r}=a;return`${t/e} (${t}/${e}) trackId: ${r}`}const ul=10*1e3,cl=1024,fl=1152,gl=1536,Hr=8589934592;function oa(a,t,e,r){return{duration:t,size:e,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:a?2:1,isNonSync:a?0:1,paddingValue:0}}}class Kr extends $t{constructor(t,e,r,s){super("mp4-remuxer",s),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&&na(e)} > ${t&&na(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,s=t.reduce((i,n)=>{let o=n.pts,l=o-i;return l<-4294967296&&(e=!0,o=Lt(o,r),l=o-i),l>0?i:o},r);return e&&this.debug("PTS rollover detected"),s}remux(t,e,r,s,i,n,o,l,h){let d,u,c,f,g,p,m=i,T=i;const E=!h.iframe&&t.pid>-1,v=e.pid>-1,S=e.samples.length,L=t.samples.length>0,R=o&&S>0||S>1;if((!E||L)&&(!v||R)||this.ISGenerated||o){if(this.ISGenerated){var A,b,k,P;const U=this.videoTrackConfig;(U&&(e.width!==U.width||e.height!==U.height||((A=e.pixelRatio)==null?void 0:A[0])!==((b=U.pixelRatio)==null?void 0:b[0])||((k=e.pixelRatio)==null?void 0:k[1])!==((P=U.pixelRatio)==null?void 0:P[1]))||!U&&R||this.nextAudioTs===null&&L)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(t,e,i,n));const M=this.isVideoContiguous;let x=-1,N;if(R&&(x=ml(e.samples),!M&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,x>0){this.warn(`Dropped ${x} out of ${S} video samples due to a missing keyframe`);const U=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(x),e.dropped+=x,T+=(e.samples[0].pts-U)/e.inputTimeScale,N=T}else x===-1&&(this.warn(`No keyframe found out of ${S} video samples`),p=!1);if(this.ISGenerated){if(L&&R&&i){const U=this.getVideoStartPts(e.samples),$=(Lt(t.samples[0].pts,U)-U)/e.inputTimeScale;m+=Math.max(0,$),T+=Math.max(0,-$)}if(L){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(t,e,i,n)),u=this.remuxAudio(t,m,this.isAudioContiguous,n,v||R||l===j.AUDIO?T:void 0,h),R){const U=u?u.endPTS-u.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(t,e,i,n)),d=this.remuxVideo(e,T,M,U,h)}}else R&&(d=this.remuxVideo(e,T,M,0,h));d&&(d.firstKeyFrame=x,d.independent=x!==-1,d.firstKeyFramePTS=N)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(g=la(r,i,this._initPTS,this._initDTS)),s.samples.length&&(f=ha(s,i,this._initPTS))),{audio:u,video:d,initSegment:c,independent:p,text:f,id3:g}}computeInitPts(t,e,r,s){const i=Math.round(r*e);let n=Lt(t,i);if(n<i)for(this.log(`Adjusting PTS for rollover in timeline near ${(i-n)/e} ${s}`);n<i;)n+=Hr;return n-i}generateIS(t,e,r,s){const i=t.samples,n=e.samples,o=this.typeSupported,l={},h=this._initPTS,d=!h||s;let u="audio/mp4",c,f,g,p=-1;if(d&&(c=f=1/0),t.config&&i.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",t.codec=""):o.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3";break}if(l.audio={id:"audio",container:u,codec:t.codec,initSegment:t.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):B.initSegment([t]),metadata:{channelCount:t.channelCount}},d){p=t.id,g=t.inputTimeScale;const m=this.computeInitPts(i[0].pts,g,r,"audio");(!h||g!==h.timescale||r===0&&m<h.baseTime)&&(c=f=m)}}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:B.initSegment([e]),metadata:{width:e.width,height:e.height}},d){p=e.id,g=e.inputTimeScale;const m=this.getVideoStartPts(n),T=Lt(n[0].dts,m),E=this.computeInitPts(T,g,r,"video"),v=this.computeInitPts(m,g,r,"video");if(!h||g!==h.timescale||G(c)||r===0&&v<h.baseTime){f=Math.min(f,E);const S=!h&&this.isVideoContiguous?v:E;c=Math.min(c,S)}}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,d&&G(c)?(h&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${r} ${c/g} != initPTS: ${h.baseTime/h.timescale} (${h.baseTime}/${h.timescale}) trackId: ${h.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${c/g} (${c}/${g}) trackId: ${p}`),this._initPTS={baseTime:c,timescale:g,trackId:p},this._initDTS={baseTime:f,timescale:g,trackId:p}):c=g=void 0,{tracks:l,initPTS:c,timescale:g,trackId:p}}remuxVideo(t,e,r,s,i){const n=t.inputTimeScale,o=t.samples,l=[],h=o.length,d=this._initPTS,u=d.baseTime*n/d.timescale;let c=this.nextVideoTs,f=8,g=this.videoSampleDuration,p,m,T=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,v=!1;if(!r||c===null){const I=u+e*n,C=o[0].pts-Lt(o[0].dts,o[0].pts);ge()&&c!==null&&Math.abs(I-C-(c+u))<15e3?r=!0:c=I-C-u}const S=c+u;for(let I=0;I<h;I++){const C=o[I];C.pts=Lt(C.pts,S),C.dts=Lt(C.dts,S),C.dts<o[I>0?I-1:I].dts&&(v=!0)}v&&o.sort(function(I,C){const K=I.dts-C.dts,H=I.pts-C.pts;return K||H}),p=o[0].dts,m=o[o.length-1].dts;const L=m-p,R=L?Math.round(L/(h-1)):g||t.inputTimeScale/30;if(r){const I=p-S,C=I>R,K=I<-1;if((C||K)&&(C?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Le(I,!0)} ms (${I}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Le(-I,!0)} ms (${I}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!K||S>=o[0].pts||ge())){p=S;const H=o[0].pts-I;if(C)o[0].dts=p,o[0].pts=H;else{let z=!0;for(let W=0;W<o.length&&!(o[W].dts>H&&z);W++){const Z=o[W].pts;if(o[W].dts-=I,o[W].pts-=I,W<o.length-1){const rt=o[W+1].pts,St=o[W].pts,J=rt<=St,ot=rt<=Z;z=J==ot}}}this.log(`Video: Initial PTS/DTS adjusted: ${Le(H,!0)}/${Le(p,!0)}, delta: ${Le(I,!0)} ms`)}}p=Math.max(0,p);let A=0,b=0,k=p;for(let I=0;I<h;I++){const C=o[I],K=C.units,H=K.length;let z=0;for(let W=0;W<H;W++)z+=K[W].data.length;b+=z,A+=H,C.length=z,C.dts<k?(C.dts=k,k+=R/4|0||1):k=C.dts,T=Math.min(C.pts,T),E=Math.max(C.pts,E)}m=o[h-1].dts;const P=b+4*A+8;let M;try{M=new Uint8Array(P)}catch(I){this.observer.emit(y.ERROR,y.ERROR,{type:Y.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:i,error:I,bytes:P,reason:`fail allocating video mdat ${P}`});return}Qt(M,0,P),Qt(M,4,X.mdat);let x=!1,N=Number.POSITIVE_INFINITY,U=Number.POSITIVE_INFINITY,$=Number.NEGATIVE_INFINITY,_=Number.NEGATIVE_INFINITY;for(let I=0;I<h;I++){const C=o[I],K=C.units;let H=0;for(let Z=0,rt=K.length;Z<rt;Z++){const St=K[Z],J=St.data,ot=St.data.byteLength;Qt(M,f,ot),f+=4,M.set(J,f),f+=ot,H+=4+ot}let z;if(I<h-1)g=o[I+1].dts-C.dts,z=o[I+1].pts-C.pts;else{const Z=this.config,rt=I>0?C.dts-o[I-1].dts:R;if(z=I>0?C.pts-o[I-1].pts:R,Z.stretchShortVideoTrack&&this.nextAudioTs!==null){const St=Math.floor(Z.maxBufferHole*n),J=(s?T+s*n:this.nextAudioTs+u)-C.pts;J>St?(g=J-rt,g<0?g=rt:x=!0,this.log(`It is approximately ${J/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=rt}else g=rt}let W=Math.round(C.pts-C.dts);if(N=Math.min(N,g),$=Math.max($,g),U=Math.min(U,z),_=Math.max(_,z),!r&&I===0&&W>g){const Z=Math.round(W/R)*R;Z-W===1&&(this.log(`pad first CTS ${W} -> ${Z} of sn: ${i.sn}`),W=Z)}l.push(oa(C.key,g,H,W))}if(l.length){const I=ge();if(I){if(I<70){const C=l[0].flags;C.dependsOn=2,C.isNonSync=0}}else if(mn()&&_-U<$-N&&R/$<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let C=p;for(let K=0,H=l.length;K<H;K++){const z=C+l[K].duration,W=C+l[K].cts;if(K<H-1){const Z=z+l[K+1].cts;l[K].duration=Z-W}else l[K].duration=K?l[K-1].duration:R;l[K].cts=0,C=z}}}g=x||!g?R:g;const w=m+g;this.nextVideoTs=c=w-u,this.videoSampleDuration=g,this.isVideoContiguous=!0;const O={data1:B.moof(i.sn,p,lt(t,{samples:l})),data2:M,startPTS:(T-u)/n,endPTS:(E+g-u)/n,startDTS:(p-u)/n,endDTS:c/n,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:t.dropped};return t.samples=[],t.dropped=0,O}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return fl;case"ac3":return gl;default:return cl}}remuxAudio(t,e,r,s,i,n){const o=t.inputTimeScale,l=t.samplerate?t.samplerate:o,h=o/l,d=this.getSamplesPerFrame(t),u=d*h,c=this._initPTS,f=t.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],p=i!==void 0;let m=t.samples,T=f?0:8,E=this.nextAudioTs||-1;const v=c.baseTime*o/c.timescale,S=v+e*o;if(this.isAudioContiguous=r=r||m.length&&E>0&&(s&&Math.abs(S-(E+v))<9e3||Math.abs(Lt(m[0].pts,S)-(E+v))<20*u),m.forEach(function(_){_.pts=Lt(_.pts,S)}),!r||E<0){const _=m.length;if(m=m.filter(w=>w.pts>=0),_!==m.length&&this.warn(`Removed ${m.length-_} of ${_} samples (initPTS ${v} / ${o})`),!m.length)return;i===0?E=0:s&&!p?E=Math.max(0,S-v):E=m[0].pts-v}if(t.segmentCodec==="aac"){const _=this.config.maxAudioFramesDrift;for(let w=0,O=E+v;w<m.length;w++){const I=m[w],C=I.pts,K=C-O,H=Math.abs(1e3*K/o);if(K<=-_*u&&p)w===0&&(this.warn(`Audio frame @ ${(C/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*K/o)} ms.`),this.nextAudioTs=E=C-v,O=C);else if(K>=_*u&&H<ul&&p){let z=Math.round(K/u);for(O=C-z*u;O<v&&z&&u;)z--,O+=u;w===0&&(this.nextAudioTs=E=O-v),this.warn(`Injecting ${z} audio frames @ ${((O-v)/o).toFixed(3)}s due to ${Math.round(1e3*K/o)} ms gap.`);for(let W=0;W<z;W++){let Z=rl.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);Z||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),Z=I.unit.subarray()),m.splice(w,0,{unit:Z,pts:O}),O+=u,w++}}I.pts=O,O+=u}}let L=null,R=null,A,b=0,k=m.length;for(;k--;)b+=m[k].unit.byteLength;for(let _=0,w=m.length;_<w;_++){const O=m[_],I=O.unit;let C=O.pts;if(R!==null){const H=g[_-1];H.duration=Math.round((C-R)/h)}else if(r&&t.segmentCodec==="aac"&&(C=E+v),L=C,b>0){b+=T;try{A=new Uint8Array(b)}catch(H){this.observer.emit(y.ERROR,y.ERROR,{type:Y.MUX_ERROR,details:D.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:H,bytes:b,reason:`fail allocating audio mdat ${b}`});return}f||(Qt(A,0,b),Qt(A,4,X.mdat))}else return;A&&A.set(I,T);const K=I.byteLength;T+=K,g.push(oa(!0,d,K,0)),R=C}const P=g.length;if(!P)return;const M=g[g.length-1];E=R-v,this.nextAudioTs=E+h*M.duration;const x=f?new Uint8Array(0):B.moof(t.sequenceNumber++,L/h,lt({},t,{samples:g}));t.samples=[];const N=(L-v)/o,U=this.nextAudioTs/o,$={data1:x,data2:A,startPTS:N,endPTS:U,startDTS:N,endDTS:U,type:"audio",hasAudio:!0,hasVideo:!1,nb:P};return this.isAudioContiguous=!0,$}}function Lt(a,t){let e;if(t===null)return a;for(t<a?e=-Hr:e=Hr;Math.abs(a-t)>4294967296;)a+=e;return a}function ml(a){for(let t=0;t<a.length;t++)if(a[t].key)return t;return-1}function la(a,t,e,r){const s=a.samples.length;if(!s)return;const i=a.inputTimeScale;for(let o=0;o<s;o++){const l=a.samples[o];l.pts=Lt(l.pts-e.baseTime*i/e.timescale,t*i)/i,l.dts=Lt(l.dts-r.baseTime*i/r.timescale,t*i)/i}const n=a.samples;return a.samples=[],{samples:n}}function ha(a,t,e){const r=a.samples.length;if(!r)return;const s=a.inputTimeScale;for(let n=0;n<r;n++){const o=a.samples[n];o.pts=Lt(o.pts-e.baseTime*s/e.timescale,t*s)/s}a.samples.sort((n,o)=>n.pts-o.pts);const i=a.samples;return a.samples=[],{samples:i}}class pl extends $t{constructor(t,e,r,s){super("passthrough-remuxer",s),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,s){this.audioCodec=e,this.videoCodec=r,this.decryptdata=s,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:s,videoCodec:i}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:n,video:o}=this.initData=r||bs(t);if(e)an(t,e);else{const h=n||o;h!=null&&h.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${h.codec}")!`)}n&&(s=da(n,st.AUDIO,this)),o&&(i=da(o,st.VIDEO,this));const l={};n&&o?l.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:t,id:"main"}:n?l.audio={container:"audio/mp4",codec:s,encrypted:n.encrypted,initSegment:t,id:"audio"}:o?l.video={container:"video/mp4",codec:i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}remux(t,e,r,s,i,n,o,l,h,d,u){var c,f;let{initPTS:g,lastEndTime:p}=this;const m={audio:void 0,video:void 0,text:void 0,id3:r,initSegment:void 0};G(p)||(p=this.lastEndTime=i||0);const T=e.samples;if(!T.length)return m;const E=this.pendingInitSegment;E&&(this.pendingInitSegment=void 0,this.generateInitSegment(E,this.decryptdata,d));const v={initPTS:void 0,timescale:void 0,trackId:void 0};let S=this.initData;if((c=S)!=null&&c.length||(this.generateInitSegment(T),S=this.initData),!((f=S)!=null&&f.length))return this.warn("Failed to generate initSegment."),m;this.emitInitSegment&&(v.tracks=this.initTracks,m.initSegment=v,this.emitInitSegment=!1);const L=!1,R=u&&!L?u.tracks:dn(T,S,h,this,L),A=S.audio?R[S.audio.id]:null,b=S.video?R[S.video.id]:null,k=!!S.audio,P=!!S.video;let M="";k&&(M+="audio"),P&&(M+="video");const x=Ze(b,1/0),N=Ze(A,1/0),U=Ze(b,0,!0),$=Ze(A,0,!0);let _=i,w=0;b&&A&&S.audio&&(N>U||x>$)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${x}-${U} a: ${N}-${$}}`,b,A);const O=!!A&&(!b||!g&&N<x||!!g&&g.trackId===S.audio.id),I=O?A:b;if(!I)return this.log(`No media samples found in ${l} ${h.level} ${h.part===-1?"":`part: ${h.part} of`} sn: ${h.sn} at playlist time: ${i}`),m;let C=T,K;w=O?$-N:U-x;const H=I.timescale,z=I.start-i*H,W=O?S.audio.id:S.video.id;if(_=I.start/H,!(g&&h.id>1)&&(n||!g)&&(vl(g,_,i,w)||H!==g.timescale)){let at=!1;const Tt=O?"audio":"video";if(g){const qt=i!==0?_/i:1+_/1;at=_>=0&&Math.abs(1-qt)<.001,this.log(`${Tt} timestamps in track ${W} at playlist time: ${n?"":"~"}${i} maps to ${_} with initPTS: ${g.baseTime/g.timescale} (${z/H-g.baseTime/g.timescale}s diff) (${M}) drift estimate: ${qt} ${at?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}at||(this.log(`Found initPTS in ${Tt} track ${W} at playlist time: ${i} offset: ${_-i} (${z}/${H})`),g=null,v.initPTS=z,v.timescale=H,v.trackId=W)}g?(v.initPTS=g.baseTime,v.timescale=g.timescale,v.trackId=g.trackId):((!v.timescale||v.trackId===void 0||v.initPTS===void 0)&&(this.warn("Could not set initPTS"),v.initPTS=_,v.timescale=1,v.trackId=-1),this.initPTS=g={baseTime:v.initPTS,timescale:v.timescale,trackId:v.trackId});const Z=_-g.baseTime/g.timescale,rt=Z+w,St=P&&I?.ptsMin!==void 0?I.ptsMin/I.timescale-g.baseTime/g.timescale:Z,J=P&&I!=null&&I.ptsMax?I.ptsMax/I.timescale-g.baseTime/g.timescale:rt;w>0?this.lastEndTime=rt:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const ot=(S.audio?S.audio.encrypted:!1)||(S.video?S.video.encrypted:!1),vt={data1:C,data2:K,startPTS:St,startDTS:Z,endPTS:J,endDTS:rt,type:M,hasAudio:k,hasVideo:P,nb:1,dropped:0,encrypted:ot};m.audio=k&&!P?vt:void 0,m.video=P?vt:void 0;const jt=this.isVideoContiguous,kt=b?.sampleCount;if(kt){const at=b.keyFrameIndex,Tt=at!==-1;vt.nb=kt,vt.dropped=at===0||jt?0:Tt?at:kt,vt.independent=Tt,vt.firstKeyFrame=at,Tt&&b.keyFrameStart&&(vt.firstKeyFramePTS=(b.keyFrameStart-g.baseTime)/g.timescale),jt||(m.independent=Tt),this.isVideoContiguous||(this.isVideoContiguous=Tt),vt.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${at}/${kt} dropped: ${vt.dropped} start: ${vt.firstKeyFramePTS||"NA"}`)}return m.initSegment=v,m.id3=la(r,i,g,g),s.samples.length&&(m.text=ha(s,i,g)),m}}function Ze(a,t,e=!1){return a?.start!==void 0?(a.start+(e?a.duration:0))/a.timescale:t}function vl(a,t,e,r){if(a===null)return!0;const s=Math.max(r,1),i=t-a.baseTime/a.timescale;return Math.abs(i-e)>=s}function da(a,t,e){const r=a.codec;return r&&r.length>4?r:t===st.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?Ne(r,!1):(e.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"):r==="mjpg"?r:(e.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1")}let Wt;try{Wt=self.performance.now.bind(self.performance)}catch{Wt=Date.now}const Wr=[{demux:jo,remux:pl},{demux:Vt,remux:Kr},{demux:Ho,remux:Kr},{demux:Wo,remux:Kr}];class ua{constructor(t,e,r,s,i,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=i,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,r,s){if(!this.observer)return Je(r);const i=r.transmuxing;i.executeStart=Wt();const n=new Uint8Array(t),{currentTransmuxState:o,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:h,discontinuity:d,trackSwitch:u,accurateTimeOffset:c,timeOffset:f,initSegmentChange:g}=s||o,{audioCodec:p,videoCodec:m,defaultInitPts:T,duration:E,initSegmentData:v}=l,S=El(n,e);if(S&&ve(S.method)){const b=this.getDecrypter(),k=Xs(S.method);return this.asyncResult=!0,this.decryptionPromise=b.decrypt(n,S.key.buffer,S.iv.buffer,k,r.decryptRange).then(P=>{const M=this.push(P,null,r);return this.decryptionPromise=null,M}),this.decryptionPromise}const L=this.needsProbing(d,u);if(L){const b=r.iframe&&v&&Vt.probe(v,this.logger)?v:n,k=this.configureTransmuxer(b);if(k)return this.logger.warn(`[transmuxer] ${k.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:Y.MEDIA_ERROR,details:D.FRAG_PARSING_ERROR,fatal:!1,error:k,reason:k.message}),i.executeEnd=Wt(),Je(r)}(d||u||g||L)&&this.resetInitSegment(v,p,m,E,e,r),(d||g||L)&&this.resetInitialTimestamp(T),h||this.resetContiguity();const R=this.transmux(n,S,f,c,r);this.asyncResult=Ae(R);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,i.executeEnd=Wt(),R}flush(t){const e=t.transmuxing;e.executeStart=Wt();const{decrypter:r,currentTransmuxState:s,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(t));const n=[],{timeOffset:o}=s;if(r){const u=r.flush();u&&n.push(this.push(u.buffer,null,t))}const{demuxer:l,remuxer:h}=this;if(!l||!h){e.executeEnd=Wt();const u=[Je(t)];return this.asyncResult?Promise.resolve(u):u}const d=l.flush(o,t);return Ae(d)?(this.asyncResult=!0,d.then(u=>(this.flushRemux(n,u,t),n))):(this.flushRemux(n,d,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,r){if(!this.remuxer)return;const{audioTrack:s,videoTrack:i,id3Track:n,textTrack:o}=e,{accurateTimeOffset:l,timeOffset:h}=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(s,i,n,o,h,l,!0,this.id,r,e.initData,e.sampleData);t.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=Wt()}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,s,i,n){const{demuxer:o,remuxer:l}=this;!o||!l||(o.resetInitSegment(t,e,r,s,i,n),l.resetInitSegment(t,e,r,i))}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,s,i){let n;return e?.method==="SAMPLE-AES"?n=this.transmuxSampleAes(t,e,r,s,i):n=this.transmuxUnencrypted(t,r,s,i),n}transmuxUnencrypted(t,e,r,s){const{demuxer:i,remuxer:n}=this;if(!i||!n)return Je(s);const o=i.demux(t,e,s,!1,!this.config.progressive),{audioTrack:l,videoTrack:h,id3Track:d,textTrack:u}=o;return{remuxResult:n.remux(l,h,d,u,e,r,!1,this.id,s,o.initData,o.sampleData),chunkMeta:s}}transmuxSampleAes(t,e,r,s,i){return this.demuxer?this.demuxer.demuxSampleAes(t,e,r,i).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,r,s,!1,this.id,i,n.initData,n.sampleData),chunkMeta:i})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(t){const{config:e,observer:r,typeSupported:s}=this;if(!r)return;let i;try{for(let u=0,c=Wr.length;u<c;u++){var n;if((n=Wr[u].demux)!=null&&n.probe(t,this.logger)){i=Wr[u];break}}}catch(u){return u}if(!i)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,h=i.demux,d=i.remux;(!o||!(o instanceof h))&&(this.logger.log(`Using ${h.name}`),this.demuxer=new h(r,e,s,this.logger),this.probe=h.probe),(!l||!(l instanceof d))&&(this.logger.log(`Using ${d.name}`),this.remuxer=new d(r,e,s,this.logger))}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Or(this.config)),t}}function El(a,t){let e=null;return a.byteLength>0&&t?.key!=null&&t.iv!==null&&t.method!=null&&(e=t),e}const Je=a=>({remuxResult:{},chunkMeta:a});function Ae(a){return"then"in a&&a.then instanceof Function}class yl{constructor(t,e,r,s,i){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=s,this.defaultInitPts=i||null}}class Tl{constructor(t,e,r,s,i,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=s,this.timeOffset=i,this.initSegmentChange=n}}let ca=0;class Sl{constructor(t,e,r,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=ca++,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=l=>{const h=l.data,d=this.hls;if(!(!d||!(h!=null&&h.event)||h.instanceNo!==this.instanceNo))switch(h.event){case"init":{var u;const c=(u=this.workerContext)==null?void 0:u.objectURL;c&&self.URL.revokeObjectURL(c);break}case"transmuxComplete":{this.handleTransmuxComplete(h.data);break}case"flush":{this.onFlush(h.data);break}case"workerLog":{d.logger[h.data.logType]&&d.logger[h.data.logType](h.data.message);break}default:{h.data=h.data||{},h.data.frag=this.frag,h.data.part=this.part,h.data.id=this.id,d.trigger(h.event,h.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const h=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(y.ERROR,{type:Y.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:h})};const i=t.config;this.hls=t,this.id=e,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=r,this.onFlush=s;const n=(l,h)=>{h=h||{},h.frag=this.frag||void 0,l===y.ERROR&&(h=h,h.parent=this.id,h.part=this.part,this.error=h.error),this.hls.trigger(l,h)};this.observer=new Gi,this.observer.on(y.FRAG_DECRYPTED,n),this.observer.on(y.ERROR,n);const o=Os(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(i.workerPath||ko()){try{i.workerPath?(l.log(`loading Web Worker ${i.workerPath} for "${e}"`),this.workerContext=Co(i.workerPath)):(l.log(`injecting Web Worker for "${e}"`),this.workerContext=_o());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:e,config:yt(i)})}catch(h){l.warn(`Error setting up "${e}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new ua(this.observer,o,i,"",e,t.logger)}return}}this.transmuxer=new ua(this.observer,o,i,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=ca++;const e=this.hls.config,r=Os(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:r,id:this.id,config:yt(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),Po(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.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,s,i,n,o,l,h,d){var u,c;h.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,p=n?n.start:i.start,m=i.decryptdata,T=this.frag,E=T?i.cc!==T.cc:!0,v=T?h.level!==T.level:!0,S=T?h.sn-T.sn:-1,L=this.part?h.part-this.part.index:-1,R=S===0&&h.id>1&&h.id===T?.stats.chunkCount,A=!v&&(S===1||S===0&&(L===1||R&&L<=0)),b=self.performance.now();(v||S||i.stats.parsing.start===0)&&(i.stats.parsing.start=b),n&&(L||!A)&&(n.stats.parsing.start=b);const k=!(T&&((u=i.initSegment)==null?void 0:u.url)===((c=T.initSegment)==null?void 0:c.url)),P=new Tl(E,A,l,v,p,k);if(!A||E||k){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${h.sn}${h.part>-1?" part: "+h.part:""} ${this.id} playlist: ${h.level} id: ${h.id}
|
|
22
|
+
discontinuity: ${E}
|
|
23
|
+
trackSwitch: ${v}
|
|
24
|
+
contiguous: ${A}
|
|
25
|
+
accurateTimeOffset: ${l}
|
|
26
|
+
timeOffset: ${p}
|
|
27
|
+
initSegmentChange: ${k}`);const M=new yl(r,s,e,o,d);this.configureTransmuxer(M)}if(this.frag=i,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:t,decryptdata:m,chunkMeta:h,state:P},t instanceof ArrayBuffer?[t]:[]);else if(g){const M=g.push(t,m,h,P);Ae(M)?M.then(x=>{this.handleTransmuxComplete(x)}).catch(x=>{this.transmuxerError(x,h,"transmuxer-interface push error")}):this.handleTransmuxComplete(M)}}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 s=r.flush(t);Ae(s)?s.then(i=>{this.handleFlushResult(i,t)}).catch(i=>{this.transmuxerError(i,t,"transmuxer-interface flush error")}):this.handleFlushResult(s,t)}}transmuxerError(t,e,r){this.hls&&(this.error=t,this.hls.trigger(y.ERROR,{type:Y.MEDIA_ERROR,details:D.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(r=>{this.handleTransmuxComplete(r)}),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 fa(){return self.SourceBuffer||self.WebKitSourceBuffer}function Yr(){if(!Ut())return!1;const a=fa();return!a||a.prototype&&typeof a.prototype.appendBuffer=="function"&&typeof a.prototype.remove=="function"}function ga(){if(!Yr())return!1;const a=Ut();return typeof a?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>a.isTypeSupported(Sr(t,"video")))||["mp4a.40.2","fLaC"].some(t=>a.isTypeSupported(Sr(t,"audio"))))}function Ll(){var a;const t=fa();return typeof(t==null||(a=t.prototype)==null?void 0:a.changeType)=="function"}var Dt={DISABLED:0,SWITCHING:1,SWITCHED:2};const Al=100;class Rl extends Oi{constructor(t,e,r){super(t,e,r,"stream-controller",j.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=Dt.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const s=this.media,i=s?s.currentTime:null;if(i===null||!G(i)||(this.log(`Media seeked to ${i}`),!this.getBufferedFrag(i)))return;const n=this.getFwdBufferInfoAtPos(s,i,j.MAIN,0);if(!n||n.len===0){this.log(`Main buffer empty at ${i} on "seeked" event: ${n&&n.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(y.MANIFEST_PARSED,this.onManifestParsed,this),t.on(y.LEVEL_LOADING,this.onLevelLoading,this),t.on(y.LEVEL_LOADED,this.onLevelLoaded,this),t.on(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(y.BUFFER_CREATED,this.onBufferCreated,this),t.on(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(y.MANIFEST_PARSED,this.onManifestParsed,this),t.off(y.LEVEL_LOADED,this.onLevelLoaded,this),t.off(y.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(y.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(y.BUFFER_CREATED,this.onBufferCreated,this),t.off(y.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(y.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:s}=this;if(this.stopLoad(),this.setInterval(Al),this.level=-1,!this.startFragRequested){let i=s.startLevel;i===-1&&(s.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=s.firstAutoLevel),s.nextLoadLevel=i,this.level=s.loadLevel,this._hasEnoughToStart=!!e}r>0&&t===-1&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${r}`),t=r),this.state=F.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=F.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case F.WAITING_LEVEL:{const{levels:t,level:e}=this,r=t?.[e],s=r?.details;if(s&&(!s.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(s))break;this.state=F.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=F.IDLE;break}break}case F.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===F.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:r,media:s}=this;if(e===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const i=this.buffering?t.nextLoadLevel:t.loadLevel;if(!(r!=null&&r[i]))return;const n=r[i],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)&&this.altAudio!==Dt.SWITCHING){const p={type:this.targetBufferType()};this.hls.trigger(y.BUFFER_EOS,p),this.state=F.ENDED;return}if(!this.buffering)return;t.loadLevel!==i&&t.manualLevel===-1&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=t.nextLoadLevel=i;const h=n.details;if(!h||this.state===F.WAITING_LEVEL||this.waitForLive(n)){this.level=i,this.state=F.WAITING_LEVEL,this.startFragRequested=!1;return}const d=o.len,u=this.getMaxBufferLength(n.maxBitrate);if(d>=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,h);if(this.couldBacktrack&&!this.fragPrevious&&f&&Et(f)&&this.fragmentTracker.getState(f)!==ct.OK){var g;const p=((g=this.backtrackFragment)!=null?g:f).sn-h.startSN,m=h.fragments[p-1];m&&f.cc===m.cc&&(f=m,this.fragmentTracker.removeFragment(m))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,c)){if(!f.gap){const p=this.audioOnly&&!this.altAudio?st.AUDIO:st.VIDEO,m=(p===st.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;m&&this.afterBufferFlushed(m,p)}f=this.getNextFragmentLoopLoading(f,h,o,j.MAIN,u)}f&&(this.exceedsMaxBuffer(o,u,f)||this.loadFragment(f,n,c))}loadFragment(t,e,r){const s=this.fragmentTracker.getState(t);s===ct.NOT_LOADED||s===ct.PARTIAL?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!==Dt.DISABLED){var t;(((t=this.getLevelDetails())==null?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===Dt.SWITCHED?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(y.FRAG_CHANGED,{frag:e,previousFrag:t}),t?.level!==r&&this.hls.trigger(y.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===Dt.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(t,e){super.onMediaAttached(t,e);const r=e.media;mt(r,"playing",this.onMediaPlaying),mt(r,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:r}=this;r&&(dt(r,"playing",this.onMediaPlaying),dt(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(y.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=Dt.DISABLED,this.audioOnly=!1}onManifestParsed(t,e){let r=!1,s=!1;for(let i=0;i<e.levels.length;i++){const n=e.levels[i].audioCodec;n&&(r=r||n.indexOf("mp4a.40.2")!==-1,s=s||n.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=r&&s&&!Ll(),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!==F.IDLE)return;const s=e.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=F.WAITING_LEVEL)}onLevelLoaded(t,e){var r;const{levels:s,startFragRequested:i}=this,n=e.level,o=e.details,l=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const h=e.levelInfo,d=this.fragCurrent;d&&(this.state===F.FRAG_LOADING||this.state===F.FRAG_LOADING_WAITING_RETRY)&&d.level!==e.level&&d.loader&&this.abortCurrentFrag();let u=0;if(o.live||(r=h.details)!=null&&r.live){var c;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,h.details,(c=this.levelLastLoaded)==null?void 0:c.details)}if(h.details=o,this.levelLastLoaded=h,i||this.setStartPosition(o,u),this.hls.trigger(y.LEVEL_UPDATED,{details:o,level:n}),this.state===F.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=F.IDLE}i&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((f,g)=>{if(g>=o.startCC)return!0;delete this.initPTS[g]}),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:r}=this;if(!r)return;const s=this.hls.liveSyncPosition,i=this.playhead,n=t.fragmentStart,o=t.edge,l=i>=n-e.maxFragLookUpTolerance&&i<=o;if(s!==null&&r.duration>s&&(i<s||!l)){const d=e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!l&&r.readyState<4||i<o-d)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),r.readyState))if(this.warn(`Playback: ${i} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s}`),this.config.liveSyncMode==="buffered"){var h;const u=q.bufferInfo(r,s,0);if(!((h=u.buffered)!=null&&h.length)){r.currentTime=s;return}if(u.start<=i){r.currentTime=s;return}const{nextStart:c}=q.bufferedInfo(u.buffered,i,0);c&&(r.currentTime=c)}else r.currentTime=s}}_handleFragmentLoadProgress(t){var e;const r=t.frag,{part:s,payload:i}=t,{levels:n}=this;if(!n){this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const o=n[r.level];if(!o){this.warn(`Level ${r.level} not found on progress`);return}const l=o.details;if(!l){this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),this.fragmentTracker.removeFragment(r);return}const h=o.videoCodec,d=l.PTSKnown||!l.live,u=(e=r.initSegment)==null?void 0:e.data,c=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Sl(this.hls,j.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,p=g!==-1,{decryptRange:m,byteRange:T}=Ke(r,s,this.iframesOnly),E=new Mr(r.level,r.sn,r.stats.chunkCount,T?T.end-T.start:i.byteLength,g,p,r.duration,this.iframesOnly,m),v=this.initPTS[r.cc];f.push(i,u,c,h,r,s,l.totalduration,d,E,v)}onAudioTrackSwitching(t,e){const r=this.hls,s=this.altAudio!==Dt.DISABLED;if($s(e.url,r))this.altAudio=Dt.SWITCHING;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 i=this.fragCurrent;i&&(this.log("Switching to main audio track, cancel main fragment load"),i.abortRequests(),this.fragmentTracker.removeFragment(i)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s){this.altAudio=Dt.DISABLED,this.fragmentTracker.removeAllFragments(),r.once(y.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(y.AUDIO_TRACK_SWITCHED,e)}),r.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(y.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const r=$s(e.url,this.hls);if(r){const s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=r?Dt.SWITCHED:Dt.DISABLED,this.tick()}onBufferCreated(t,e){const r=e.tracks;let s,i,n=!1;for(const o in r){const l=r[o];if(l.id==="main"){if(i=o,s=l,o==="video"){const h=r[o];h&&(this.videoBuffer=h.buffer)}}else n=!0}n&&s?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:r,part:s}=e,i=r.type===j.MAIN;if(i){if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${s?" p: "+s.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),this.state===F.PARSED&&(this.state=F.IDLE);return}let l=!1;if(Et(r)&&(l=!!r.gap&&!r.tagList.some(h=>h[0]==="GAP")),this.fragBufferedComplete(r,s),l){var n;r.stats.retry++;const h=(n=this.levels)==null?void 0:n[r.level];h&&h.fragmentError++}}const o=this.media;o&&(!this._hasEnoughToStart&&q.getBuffered(o).length&&(this.seekToStartPos(),this._hasEnoughToStart=!0),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var r;if(e.fatal){this.state=F.ERROR;return}switch(e.details){case D.FRAG_GAP:case D.FRAG_PARSING_ERROR:case D.FRAG_DECRYPT_ERROR:case D.FRAG_LOAD_ERROR:case D.FRAG_LOAD_TIMEOUT:case D.KEY_LOAD_ERROR:case D.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(j.MAIN,e);break;case D.LEVEL_LOAD_ERROR:case D.LEVEL_LOAD_TIMEOUT:case D.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===F.WAITING_LEVEL&&((r=e.context)==null?void 0:r.type)===Q.LEVEL&&(this.state=F.IDLE);break;case D.BUFFER_APPEND_NO_PROGRESS:if(e.parent!=="main")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 D.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(j.MAIN,e);break;case D.BUFFER_ADD_CODEC_ERROR:case D.BUFFER_APPEND_ERROR:if(e.parent!=="main")return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case D.BUFFER_FULL_ERROR:if(e.parent!=="main")return;this.reduceLengthAndFlushBuffer(e)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case D.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}onFragLoadEmergencyAborted(){this.state=F.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==st.AUDIO||!this.altAudio){const r=(e===st.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,e),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&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){this.log(`could not seek to ${r}, already seeking at ${e}`);return}const s=this.timelineOffset;s&&r&&(r+=s);const i=this.getLevelDetails(),n=q.getBuffered(t),o=n.length?n.start(0):0,l=o-r,h=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<h||this.loadingParts&&l<2*(i?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),r+=l,this.startPosition=r),e<r&&(this.log(`seek to target start position ${r} from current time ${e} buffer start ${o}`),t.currentTime=r)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e.indexOf("mp4a.40.5")!==-1?e="mp4a.40.2":e="mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(r=>{const{hls:s}=this,i=r?.frag;if(!i||this.fragContextChanged(i))return;e.fragmentError=0,this.state=F.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=i.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(y.FRAG_LOADED,r),i.bitrateTest=!1}).catch(r=>{this.state===F.STOPPED||this.state===F.ERROR||(this.warn(r),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const e=this.playlistType,{hls:r}=this,{remuxResult:s,chunkMeta:i}=t,n=this.getCurrentContext(i);if(!n){this.resetWhenMissingContext(i);return}const{frag:o,part:l,level:h}=n,{video:d,text:u,id3:c,initSegment:f}=s,{details:g}=h,p=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=F.PARSING,f){const m=f.tracks;if(m){const S=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(h,m,S,i),r.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:e,tracks:m})}const T=f.initPTS,E=f.timescale,v=this.initPTS[o.cc];if(G(T)&&(!v||v.baseTime!==T||v.timescale!==E)){const S=f.trackId;this.initPTS[o.cc]={baseTime:T,timescale:E,trackId:S};const L=this.initPTS.slice(0);r.trigger(y.INIT_PTS_FOUND,{timestampOffsets:L,frag:o,id:e,initPTS:T,timescale:E,trackId:S})}}if(d&&g){p&&d.type==="audiovideo"&&this.logMuxedErr(o);const m=g.fragments[o.sn-1-g.startSN],T=o.sn===g.startSN,E=!m||o.cc>m.cc;if(s.independent!==!1){const{startPTS:v,endPTS:S,startDTS:L,endDTS:R}=d;if(l)l.elementaryStreams[d.type]={startPTS:v,endPTS:S,startDTS:L,endDTS:R};else if(d.firstKeyFrame&&d.independent&&i.id===1&&!E&&(this.couldBacktrack=!0),d.dropped&&d.independent){const A=this.getMainFwdBufferInfo(),b=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,k=d.firstKeyFramePTS?d.firstKeyFramePTS:v;if(!T&&b<k-this.config.maxBufferHole&&!E){this.backtrack(o);return}else E&&(o.gap=!0);o.setElementaryStreamInfo(d.type,o.start,S,o.start,R,!0)}else T&&v-(g.appliedTimelineOffset||0)>Ye&&(o.gap=!0);o.setElementaryStreamInfo(d.type,v,S,L,R),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,i,T||E)}else if(T||E)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:m,endPTS:T,startDTS:E,endDTS:v}=p;l&&(l.elementaryStreams[st.AUDIO]={startPTS:m,endPTS:T,startDTS:E,endDTS:v}),o.setElementaryStreamInfo(st.AUDIO,m,T,E,v),this.bufferFragmentData(p,o,l,i)}if(g&&c!=null&&c.samples.length){const m={id:e,frag:o,details:g,samples:c.samples};r.trigger(y.FRAG_PARSING_METADATA,m)}if(g&&u){const m={id:e,frag:o,details:g,samples:u.samples};r.trigger(y.FRAG_PARSING_USERDATA,m)}}logMuxedErr(t){this.warn(`${Et(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,r,s){if(this.state!==F.PARSING)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(r));const{audio:i,video:n,audiovideo:o}=e;if(i){const h=t.audioCodec;let d=$e(i.codec,h);if(d==="mp4a"&&(d="mp4a.40.5"),this.audioCodecSwitch){d&&(d.indexOf("mp4a.40.5")!==-1?d="mp4a.40.2":d="mp4a.40.5");const u=i.metadata;u&&"channelCount"in u&&(u.channelCount||1)!==1&&!pn()&&(d="mp4a.40.5")}d&&d.indexOf("mp4a.40.5")!==-1&&En()&&i.container!=="audio/mpeg"&&(d="mp4a.40.2",this.log(`Android: force audio codec to ${d}`)),h&&h!==d&&this.log(`Swapping manifest audio codec "${h}" for "${d}"`),i.levelCodec=d,i.id=j.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${d||""}/${h||""}/${i.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=j.MAIN;const h=n.codec;if(h?.length===4)switch(h){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${h}]${n.codec!==h?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.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(y.BUFFER_CODECS,e),!this.hls)return;l.forEach(h=>{const d=e[h].initSegment;d!=null&&d.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:h,data:d,frag:r,part:null,chunkMeta:s,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.getBufferOutput();return this.getFwdBufferInfo(t,j.MAIN)}get maxBufferLength(){const{levels:t,level:e}=this,r=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=F.IDLE}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;return G(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(G(e)){const r=this.getLevelDetails(),s=this.currentFrag||(r?Dr(null,r.fragments,e):null);if(s){const i=s.programDateTime;if(i!==null){const n=i+(e-s.start)*1e3;return new Date(n)}}}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}}class jr{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new ir}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(t,e,r){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=r,this.loadInternal()}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,e=this.stats.retry;if(de(t,e,!0))this.retry(t);else{var r;et.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(t){const{context:e,stats:r}=this;this.retryDelay=or(t,r.retry),r.retry++,et.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${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 bl{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;if(t.length)t.length===1?r=t[0]:r=Dl(t,e);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function Dl(a,t){const e=new Uint8Array(t);let r=0;for(let s=0;s<a.length;s++){const i=a[s];e.set(i,r),r+=i.length}return e}function ma(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Il=/(\d+)-(\d+)\/(\d+)/;class qr extends jr{constructor(t){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=t.fetchSetup||Pl}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:t,context:e,stats:r}=this;if(!t||!e)return;r.loading.first=0,r.loaded=0,r.aborted=!1,this.controller=new self.AbortController;const s=kl(e,this.controller.signal),i=e.responseType==="arraybuffer",n=i?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=o&&G(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},t.timeout),(Ae(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var d;this.response=h;const u=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(u-r.loading.start)),!h.ok){const{status:f,statusText:g}=h;throw new xl(g||"fetch, bad network response",f,h)}r.loading.first=u,r.total=Cl(h.headers)||r.total;const c=(d=this.callbacks)==null?void 0:d.onProgress;return c&&G(t.highWaterMark)?this.loadProgressively(h,r,e,t.highWaterMark,c):i?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{var d,u;const c=this.response;if(!c)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const f=h[n];f&&(r.loaded=r.total=f);const g={url:c.url,data:h,code:c.status},p=(d=this.callbacks)==null?void 0:d.onProgress;p&&!G(t.highWaterMark)&&p(r,e,h,c),(u=this.callbacks)==null||u.onSuccess(g,r,e,c)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const d=h&&h.code||0,u=h?h.message:null,c=t.loadPolicy.errorRetry,f=r.retry,g={url:e.url,data:void 0,code:d};if(de(c,f,!1,g))this.retry(c);else{var p;et.error(`${d} while loading ${e.url}`),(p=this.callbacks)==null||p.onError({code:d,text:u},e,h?h.details:null,r)}})}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,s=0,i){const n=new bl,o=t.body.getReader(),l=()=>o.read().then(h=>{if(h.done)return n.dataLength&&i(e,r,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const d=h.value,u=d.length;return e.loaded+=u,u<s||n.dataLength?(n.push(d),n.dataLength>=s&&i(e,r,n.flush().buffer,t)):i(e,r,d.buffer,t),l()}).catch(()=>Promise.reject());return l()}}function kl(a,t){const e={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(lt({},a.headers))};return a.rangeEnd&&e.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),e}function _l(a){const t=Il.exec(a);if(t)return parseInt(t[2])-parseInt(t[1])+1}function Cl(a){const t=a.get("Content-Range");if(t){const r=_l(t);if(G(r))return r}const e=a.get("Content-Length");if(e)return parseInt(e)}function Pl(a,t){return new self.Request(a.url,t)}class xl extends Error{constructor(t,e,r){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=r}}const wl=(a,t,e)=>Math.max(t,Math.min(a,e)),Ol=/^age:\s*[\d.]+\s*$/im;class zr extends jr{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,t.readyState!==4&&(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,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return i.call(this,r,e.url,e)}).catch(n=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",e.url,!0),i.call(this,r,e.url,e)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,e,t)}).catch(n=>{var o;(o=this.callbacks)==null||o.onError({code:r.status,text:n.message},e,r,s)}):this.openAndSendXhr(r,e,t)}openAndSendXhr(t,e,r){t.readyState||t.open("GET",e.url,!0);const s=e.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:n}=r.loadPolicy;if(s)for(const o in s)t.setRequestHeader(o,s[o]);e.rangeEnd&&t.setRequestHeader("Range",`bytes=${e.rangeStart}-${e.rangeEnd-1}`),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),r.timeout=i&&G(i)?i:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:r}=this;if(!t||!e)return;const s=e.readyState,i=this.config;if(!r.aborted&&s>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const h=e.status,d=e.responseType==="text"?e.responseText:null;if(h>=200&&h<300){const g=d??e.response;if(g!=null){var n,o;r.loading.end=Math.max(self.performance.now(),r.loading.first);const p=e.responseType==="arraybuffer"?g.byteLength:g.length;r.loaded=r.total=p,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const m=(n=this.callbacks)==null?void 0:n.onProgress;m&&m(r,t,g,e);const T={url:e.responseURL,data:g,code:h};t.rangeEnd&&p!==t.rangeEnd-t.rangeStart&&et.warn(`Payload length ${p} does not match requested Range: bytes=${t.rangeStart}-${t.rangeEnd-1}`),(o=this.callbacks)==null||o.onSuccess(T,r,t,e);return}}const u=i.loadPolicy.errorRetry,c=r.retry,f={url:t.url,data:void 0,code:h};if(de(u,c,!1,f))this.retry(u);else{var l;et.error(`${h} while loading ${t.url}`),(l=this.callbacks)==null||l.onError({code:h,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&&Ol.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 pa={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Ml=gt(gt({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:60*1e3*1e3,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:zr,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:2*1024*1024,useMediaCapabilities:!1,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:pa},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:pa},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:Rl,abrController:Bs,bufferController:Si,capLevelController:tr,errorController:Vs,fpsController:$i,id3TrackController:Do,gapController:To,latencyController:Io},Fl()),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0,cmcdController:void 0,contentSteeringController:Mi,iframeController:void 0,interstitialsController:void 0});function Fl(){return{cueHandler:Xt,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Nl(a,t,e){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(t.liveMaxUnchangedPlaylistRefresh!==void 0){const n=t.liveMaxUnchangedPlaylistRefresh,o=wl(n,2,1/0);o!==n&&e.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${n} to ${o}.`),t.liveMaxUnchangedPlaylistRefresh=o}const r=Xr(a),s=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(n=>{const o=`${n==="level"?"playlist":n}LoadPolicy`,l=t[o]===void 0,h=[];i.forEach(d=>{const u=`${n}Loading${d}`,c=t[u];if(c!==void 0&&l){h.push(u);const f=r[o].default;switch(t[o]={default:f},d){case"TimeOut":f.maxLoadTimeMs=c,f.maxTimeToFirstByteMs=c;break;case"MaxRetry":f.errorRetry.maxNumRetry=c,f.timeoutRetry.maxNumRetry=c;break;case"RetryDelay":f.errorRetry.retryDelayMs=c,f.timeoutRetry.retryDelayMs=c;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=c,f.timeoutRetry.maxRetryDelayMs=c;break}}}),h.length&&e.warn(`hls.js config: "${h.join('", "')}" setting(s) are deprecated, use "${o}": ${yt(t[o])}`)}),gt(gt({},r),t)}function Xr(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(Xr):Object.keys(a).reduce((t,e)=>(t[e]=Xr(a[e]),t),{}):a}function $l(a,t){const e=a.loader;e!==qr&&e!==zr?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):ma()&&(a.loader=qr,a.progressive=!0,a.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}class Bl extends pi{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(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(y.LEVEL_LOADED,this.onLevelLoaded,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(y.FRAG_BUFFERED,this.onFragBuffered,this),t.on(y.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(y.LEVEL_LOADED,this.onLevelLoaded,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(y.FRAG_BUFFERED,this.onFragBuffered,this),t.off(y.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,s=[],i={},n={};let o=!1,l=!1,h=!1,d=!1;e.levels.forEach(u=>{const c=u.attrs,f=ya(u,r),{audioCodec:g,videoCodec:p,imageCodec:m,width:T,height:E}=u;if(!f){this.log(`Some or all CODECS not supported "${c.CODECS}"`);return}o||(o=!!(T&&E)),l||(l=!!p),h||(h=!!g),d||(d=!!m);const{CODECS:v,"FRAME-RATE":S,"HDCP-LEVEL":L,"PATHWAY-ID":R,RESOLUTION:A,"VIDEO-RANGE":b}=c,k=`${`${R||"."}-`}${u.bitrate}-${A}-${S}-${v}-${b}-${L}`;if(i[k])if(i[k].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const P=n[k]+=1;u.attrs["PATHWAY-ID"]=new Array(P+1).join(".");const M=this.createLevel(u);i[k]=M,s.push(M)}else u.iframes||(i[k].addGroupId("audio",c.AUDIO),i[k].addGroupId("text",c.SUBTITLES));else{const P=this.createLevel(u);i[k]=P,n[k]=1,s.push(P)}}),this.filterAndSortMediaOptions(s,e,o,l,h,d)}createLevel(t){const e=new br(t),r=t.supplemental;if(r!=null&&r.videoCodec&&!Ea(r.videoCodec,this.hls.config.preferManagedMediaSource)){const s=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(s.message),e.supportedResult=Bt.getUnsupportedResult(s,[])}return e}filterAndSortMediaOptions(t,e,r,s,i,n){var o;let l=[],h=[],d=t;const u=((o=e.stats)==null?void 0:o.parsing)||{},c=this.hls.config.preferManagedMediaSource;if((r||s)&&i&&(d=d.filter(({videoCodec:L,videoRange:R,width:A,height:b})=>(!!L||!!(A&&b))&&bn(R))),s&&n&&(d=d.filter(L=>!L.imageCodec)),d.length===0){Promise.resolve().then(()=>{if(this.hls){let L="no level with compatible codecs found in manifest",R=L;e.levels.length&&(R=`one or more CODECS in variant not supported: ${yt(e.levels.map(b=>b.attrs.CODECS).filter((b,k,P)=>P.indexOf(b)===k))}`,this.warn(R),L+=` (${R})`);const A=new Error(L);this.hls.trigger(y.ERROR,{type:Y.MEDIA_ERROR,details:D.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:A,reason:R})}}),u.end=performance.now();return}e.audioTracks&&(l=e.audioTracks.filter(L=>!L.audioCodec||va(L.audioCodec,c)),Ta(l)),e.subtitles&&(h=e.subtitles,Ta(h));const f=d.slice(0);d.sort((L,R)=>{if(L.attrs["HDCP-LEVEL"]!==R.attrs["HDCP-LEVEL"])return(L.attrs["HDCP-LEVEL"]||"")>(R.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&L.height!==R.height)return L.height-R.height;if(L.frameRate!==R.frameRate)return L.frameRate-R.frameRate;if(L.videoRange!==R.videoRange)return Be.indexOf(L.videoRange)-Be.indexOf(R.videoRange);if(L.videoCodec!==R.videoCodec){const A=xs(L.videoCodec),b=xs(R.videoCodec);if(A!==b)return b-A}if(L.uri===R.uri&&L.codecSet!==R.codecSet){const A=Fe(L.codecSet),b=Fe(R.codecSet);if(A!==b)return b-A}return L.averageBitrate!==R.averageBitrate?L.averageBitrate-R.averageBitrate:0});let g=f[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==f.length)){for(let L=0;L<f.length;L++)if(f[L].pathwayId===d[0].pathwayId){g=f[L];break}}this._levels=d;for(let L=0;L<d.length;L++)if(d[L]===g){var p;this._firstLevel=L;const R=g.bitrate,A=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${R}`),((p=this.hls.userConfig)==null?void 0:p.abrEwmaDefaultEstimate)===void 0){const b=Math.min(R,this.hls.config.abrEwmaDefaultEstimateMax);b>A&&A===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=b)}break}const m=e.iframeVariants.filter(L=>ya(L,c));this._iframeVariants=m;const T=i&&!s,E=this.hls.config,v=!!(E.audioStreamController&&E.audioTrackController),S={levels:d,audioTracks:l,subtitleTracks:h,iframeVariants:m,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:i,video:s,altAudio:v&&!T&&l.some(L=>!!L.url)};u.end=performance.now(),this.hls.trigger(y.MANIFEST_PARSED,S)}get iframeVariants(){return this._iframeVariants.length===0?null:this._iframeVariants}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(e.length===0)return;if(t<0||t>=e.length){const d=new Error("invalid level idx"),u=t<0;if(this.hls.trigger(y.ERROR,{type:Y.OTHER_ERROR,details:D.LEVEL_SWITCH_ERROR,level:t,fatal:u,error:d,reason:d.message}),u)return;t=Math.min(t,e.length-1)}const r=this.currentLevelIndex,s=this.currentLevel,i=s?s.attrs["PATHWAY-ID"]:void 0,n=e[t],o=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,r===t&&s&&i===o)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${o?" with Pathway "+o:""} from level ${r}${i?" with Pathway "+i:""}`);const l={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(y.LEVEL_SWITCHING,l);const h=n.details;if(!h||h.live){const d=this.switchParams(n.uri,s?.details,h);this.loadPlaylist(d)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,this._startLevel===void 0&&(this._startLevel=t),t!==-1&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(this._startLevel===void 0){const t=this.hls.config.startLevel;return t!==void 0?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(s=>e.indexOf(s)!==-1);if(t.length<1){this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);return}this.steering.pathwayPriority=r}}onError(t,e){e.fatal||!e.context||e.context.type===Q.LEVEL&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(e.type===j.MAIN){const r=e.elementaryStreams;if(!Object.keys(r).some(i=>!!r[i]))return;const s=this._levels[e.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var r;const{level:s,details:i}=e,n=e.levelInfo;if(!n){var o;this.warn(`Invalid level index ${s}`),(o=e.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(n===this.currentLevel||e.withoutMultiVariant){n.fragmentError===0&&(n.loadError=0);let l=n.details;l===e.details&&l.advanced&&(l=void 0),this.playlistLoaded(s,e,l)}else(r=e.deliveryDirectives)!=null&&r.skip&&(i.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),s=this.currentLevelIndex,i=t.attrs["PATHWAY-ID"],n=t.details,o=n?.age;this.log(`Loading level index ${s}${e?.msn!==void 0?" at sn "+e.msn+" part "+e.part:""}${i?" Pathway "+i:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(y.LEVEL_LOADING,{url:r,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){const e=this.currentLevelIndex;if(this.manualLevelIndex===-1&&t!==e&&t!==-1){const r=this.hls.config.abrSwitchInterval;if(r>0){const s=performance.now(),i=s-this.lastABRSwitchTime,n=r*1e3;if(this.lastABRSwitchTime>-1&&i<n){this.warn(`Preventing ABR level switch: ${e} -> ${t} (${Math.round(i)}ms < ${n}ms / ${r}s)`);return}this.lastABRSwitchTime=s,this.log(`Allowing ABR level switch: ${e} -> ${t} (${Math.round(i)}ms >= ${n}ms / ${r}s)`)}}this.level=t,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(this._levels.length===1)return;const r=this._levels.filter((i,n)=>n!==t?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(o=>o.level=-1)),!1));gi(r),this._levels=r,this.currentLevelIndex>-1&&(e=this.currentLevel)!=null&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=r.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(y.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(y.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function va(a,t){return me(a,"audio",t)}function Ea(a,t){return me(a,"video",t)}function ya(a,t){let{audioCodec:e,videoCodec:r}=a;e&&(a.audioCodec=e=Ne(e,t)||void 0),r&&(r=a.videoCodec=Ln(r));const{unknownCodecs:s}=a;return!(s?.length||e&&!va(e,t)||r&&!Ea(r,t))}function Ta(a){const t={};a.forEach(e=>{const r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++})}class Ul extends $t{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 s=this.keyLoaderInfo[r].loader;if(s){var e;if(t&&t!==((e=s.context)==null?void 0:e.frag.type))return;s.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 s=t.decryptdata;if(!s){const n=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(Yt(t,D.KEY_LOAD_ERROR,n))}const i=t;switch(s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return s.keyFormat==="identity"?this.loadKeyHTTP(i):e?e.then(()=>this.loadKeyEME(i)):this.loadKeyEME(i);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(i);default:return Promise.reject(Yt(t,D.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(t){if(this.emeController&&this.config.emeEnabled){var e;if(!t.decryptdata.keyId&&(e=t.initSegment)!=null&&e.data){const r=nn(t.initSegment.data);if(r.length){let s=r[0];const i=t.decryptdata.uri;if(s.some(n=>n!==0))this.log(`Using keyId found in init segment ${ee(s)} keyUri: ${i}`),ne.setKeyIdForUri(i,s);else{const n=ne.addKeyIdForUri(i);this.log(`Patching empty keyId with ${ee(n)} keyUri: ${i}`),s=n}t.decryptdata.keyId=s}}return this.emeController.loadKey(t).then(()=>({frag:t,keyInfo:{decryptdata:t.decryptdata}}))}return Promise.reject(Yt(t,D.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(Yt(t,D.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${r}"`)));const s=this.keyLoaderInfo[r];if(s){if(s.decryptdata.key)return e.key=s.decryptdata.key,s.keyLoadPromise=null,Promise.resolve({frag:t,keyInfo:s});if(s.keyLoadPromise)return s.keyLoadPromise.then(h=>(e.key=s.decryptdata.key,gt(gt({},h),{},{frag:t})))}this.log(`Loading${e.keyId?" keyId: "+ee(e.keyId):""} URI: ${e.uri} from ${t.type} ${t.level}`);const i=this.config,n=i.loader,o=new n(i);t.keyLoader=o;const l=this.keyLoaderInfo[r]={decryptdata:e,keyLoadPromise:null,loader:o};return l.keyLoadPromise=new Promise((h,d)=>{const u={type:Q.KEY,keyInfo:l,frag:t,responseType:"arraybuffer",url:r},c=i.keyLoadPolicy.default,f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(p,m,T,E)=>{const{frag:v,keyInfo:S,url:L}=T;if(!v.decryptdata||S!==this.keyLoaderInfo[L])return this.resetLoader(T),d(Yt(v,D.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),E));S.decryptdata.key=v.decryptdata.key=new Uint8Array(p.data),v.keyLoader=S.loader=S.keyLoadPromise=null,h({frag:v,keyInfo:S})},onError:(p,m,T,E)=>{this.resetLoader(m),d(Yt(t,D.KEY_LOAD_ERROR,new Error(`HTTP Error ${p.code} loading key ${p.text}`),T,gt({url:r,data:void 0},p)))},onTimeout:(p,m,T)=>{this.resetLoader(m),d(Yt(t,D.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),T))},onAbort:(p,m,T)=>{this.resetLoader(m),d(Yt(t,D.INTERNAL_ABORTED,new Error("key loading aborted"),T))}};o.load(u,f,g)})}resetLoader(t){const{frag:e,keyInfo:r,url:s}=t,i=r.loader;e.keyLoader===i&&(e.keyLoader=r.loader=r.keyLoadPromise=null),delete this.keyLoaderInfo[s],i&&i.destroy()}}function Yt(a,t=D.KEY_LOAD_ERROR,e,r,s){return new xt({type:Y.NETWORK_ERROR,details:t,fatal:!1,frag:a,response:s,error:e,networkDetails:r||null})}function Sa(a){const{type:t}=a;switch(t){case Q.AUDIO_TRACK:return j.AUDIO;case Q.SUBTITLE_TRACK:return j.SUBTITLE;default:return j.MAIN}}function Qr(a,t){let e=a.url;return(e===void 0||e.indexOf("data:")===0)&&(e=t.url),e}class Gl{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(y.MANIFEST_LOADING,this.onManifestLoading,this),t.on(y.LEVEL_LOADING,this.onLevelLoading,this),t.on(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(y.MANIFEST_LOADING,this.onManifestLoading,this),t.off(y.LEVEL_LOADING,this.onLevelLoading,this),t.off(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,r=e.pLoader,s=e.loader,i=r||s,n=new i(e);return this.loaders[t.type]=n,n}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:Q.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:r,level:s,pathwayId:i,url:n,deliveryDirectives:o,levelInfo:l}=e;this.load({id:r,level:s,pathwayId:i,responseType:"text",type:Q.LEVEL,url:n,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(t,e){const{id:r,groupId:s,url:i,deliveryDirectives:n,track:o}=e;this.load({id:r,groupId:s,level:null,responseType:"text",type:Q.AUDIO_TRACK,url:i,deliveryDirectives:n,levelOrTrack:o})}onSubtitleTrackLoading(t,e){const{id:r,groupId:s,url:i,deliveryDirectives:n,track:o}=e;this.load({id:r,groupId:s,level:null,responseType:"text",type:Q.SUBTITLE_TRACK,url:i,deliveryDirectives:n,levelOrTrack:o})}onLevelsUpdated(t,e){const r=this.loaders[Q.LEVEL];if(r){const s=r.context;s&&!e.levels.some(i=>i===s.levelOrTrack)&&(r.abort(),delete this.loaders[Q.LEVEL])}}load(t){var e;const r=this.hls.config;let s=this.getInternalLoader(t);if(s){const h=this.hls.logger,d=s.context;if(d?.levelOrTrack===t.levelOrTrack&&(d.url===t.url||d.deliveryDirectives&&!t.deliveryDirectives)){d.url===t.url?h.log(`[playlist-loader]: ignore ${t.url} ongoing request`):h.log(`[playlist-loader]: ignore ${t.url} in favor of ${d.url}`);return}h.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),s.abort()}let i;if(t.type===Q.MANIFEST?i=r.manifestLoadPolicy.default:i=lt({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(t),G((e=t.deliveryDirectives)==null?void 0:e.part)){let h;if(t.type===Q.LEVEL&&t.level!==null?h=this.hls.levels[t.level].details:t.type===Q.AUDIO_TRACK&&t.id!==null?h=this.hls.audioTracks[t.id].details:t.type===Q.SUBTITLE_TRACK&&t.id!==null&&(h=this.hls.subtitleTracks[t.id].details),h){const d=h.partTarget,u=h.targetduration;if(d&&u){const c=Math.max(d*3,u*.8)*1e3;i=lt({},i,{maxTimeToFirstByteMs:Math.min(c,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},l={onSuccess:(h,d,u,c)=>{const f=this.getInternalLoader(u);this.resetInternalLoader(u.type);const g=h.data;d.parsing.start=performance.now(),It.isMediaPlaylist(g)||u.type!==Q.MANIFEST?this.handleTrackOrLevelPlaylist(h,d,u,c||null,f):this.handleMasterPlaylist(h,d,u,c)},onError:(h,d,u,c)=>{this.handleNetworkError(d,u,!1,h,c)},onTimeout:(h,d,u)=>{this.handleNetworkError(d,u,!0,void 0,h)}};s.load(t,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,s){const i=this.hls,n=t.data,o=Qr(t,r),l=It.parseMasterPlaylist(n,o);if(l.playlistParsingError){e.parsing.end=performance.now(),this.handleManifestParsingError(t,r,l.playlistParsingError,s,e);return}const{contentSteering:h,levels:d,iframeVariants:u,sessionData:c,sessionKeys:f,startTimeOffset:g,variableList:p}=l;this.variableList=p,d.forEach(v=>{const{unknownCodecs:S}=v;if(S){const{preferManagedMediaSource:L}=this.hls.config;let{audioCodec:R,videoCodec:A}=v;for(let b=S.length;b--;){const k=S[b];me(k,"audio",L)?(v.audioCodec=R=R?`${R},${k}`:k,re.audio[R.substring(0,4)]=2,S.splice(b,1)):me(k,"video",L)&&(v.videoCodec=A=A?`${A},${k}`:k,re.video[A.substring(0,4)]=2,S.splice(b,1))}}});const{AUDIO:m=[],SUBTITLES:T,"CLOSED-CAPTIONS":E}=It.parseMasterPlaylistMedia(n,o,l);m.length&&!m.some(v=>!v.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new it({}),bitrate:0,url:""})),i.trigger(y.MANIFEST_LOADED,{levels:d,audioTracks:m,subtitles:T,iframeVariants:u,captions:E,contentSteering:h,url:o,stats:e,networkDetails:s,sessionData:c,sessionKeys:f,startTimeOffset:g,variableList:p})}handleTrackOrLevelPlaylist(t,e,r,s,i){const n=this.hls,{id:o,level:l,type:h}=r,d=Qr(t,r),u=G(l)?l:G(o)?o:0,c=Sa(r),f=It.parseLevelPlaylist(t.data,d,u,c,0,this.variableList);if(h===Q.MANIFEST){const g={attrs:new it({}),bitrate:0,details:f,name:"",url:d};f.requestScheduled=e.loading.start+ui(f,0),n.trigger(y.MANIFEST_LOADED,{levels:[g],audioTracks:[],iframeVariants:[],url:d,stats:e,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,t,e,r,s,i)}handleManifestParsingError(t,e,r,s,i){this.hls.trigger(y.ERROR,{type:Y.NETWORK_ERROR,details:D.MANIFEST_PARSING_ERROR,fatal:e.type===Q.MANIFEST,url:t.url,err:r,error:r,reason:r.message,response:t,context:e,networkDetails:s,stats:i})}handleNetworkError(t,e,r=!1,s,i){let n=`A network ${r?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===Q.LEVEL?n+=`: ${t.level} id: ${t.id}`:(t.type===Q.AUDIO_TRACK||t.type===Q.SUBTITLE_TRACK)&&(n+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let l=D.UNKNOWN,h=!1;const d=this.getInternalLoader(t);switch(t.type){case Q.MANIFEST:l=r?D.MANIFEST_LOAD_TIMEOUT:D.MANIFEST_LOAD_ERROR,h=!0;break;case Q.LEVEL:l=r?D.LEVEL_LOAD_TIMEOUT:D.LEVEL_LOAD_ERROR,h=!1;break;case Q.AUDIO_TRACK:l=r?D.AUDIO_TRACK_LOAD_TIMEOUT:D.AUDIO_TRACK_LOAD_ERROR,h=!1;break;case Q.SUBTITLE_TRACK:l=r?D.SUBTITLE_TRACK_LOAD_TIMEOUT:D.SUBTITLE_LOAD_ERROR,h=!1;break}d&&this.resetInternalLoader(t.type);const u={type:Y.NETWORK_ERROR,details:l,fatal:h,url:t.url,loader:d,context:t,error:o,networkDetails:e,stats:i};if(s){let c=t.url;e&&"url"in e&&(c=e.url),u.response=gt({url:c,data:void 0},s)}this.hls.trigger(y.ERROR,u)}handlePlaylistLoaded(t,e,r,s,i,n){const o=this.hls,{type:l,level:h,levelOrTrack:d,id:u,groupId:c,deliveryDirectives:f}=s,g=Qr(e,s),p=Sa(s);let m=typeof s.level=="number"&&p===j.MAIN?h:void 0;const T=t.playlistParsingError;if(T){if(this.hls.logger.warn(`${T} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(y.ERROR,{type:Y.NETWORK_ERROR,details:D.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:T,reason:T.message,response:e,context:s,level:m,parent:p,networkDetails:i,stats:r});return}t.playlistParsingError=null}if(!t.fragments.length){const E=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(y.ERROR,{type:Y.NETWORK_ERROR,details:D.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:E,reason:E.message,response:e,context:s,level:m,parent:p,networkDetails:i,stats:r});return}switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),l){case Q.MANIFEST:case Q.LEVEL:if(m){if(!d)m=0;else if(d!==o.levels[m]){const E=o.levels.indexOf(d);E>-1&&(m=E)}}o.trigger(y.LEVEL_LOADED,{details:t,levelInfo:d||o.levels[0],level:m||0,id:u||0,stats:r,networkDetails:i,deliveryDirectives:f,withoutMultiVariant:l===Q.MANIFEST,context:s});break;case Q.AUDIO_TRACK:o.trigger(y.AUDIO_TRACK_LOADED,{details:t,track:d,id:u||0,groupId:c||"",stats:r,networkDetails:i,deliveryDirectives:f,context:s});break;case Q.SUBTITLE_TRACK:o.trigger(y.SUBTITLE_TRACK_LOADED,{details:t,track:d,id:u||0,groupId:c||"",stats:r,networkDetails:i,deliveryDirectives:f,context:s});break}}}class Ot{static get version(){return Te}static isMSESupported(){return Yr()}static isSupported(){return ga()}static getMediaSource(){return Ut()}static get Events(){return y}static get MetadataSchema(){return pt}static get ErrorTypes(){return Y}static get ErrorDetails(){return D}static get DefaultConfig(){return Ot.defaultConfig?Ot.defaultConfig:Ml}static set DefaultConfig(t){Ot.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 Gi,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=Oa(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),r=this.config=Nl(Ot.DefaultConfig,t,e);this.userConfig=t,r.progressive&&$l(r,e);const{streamController:s,abrController:i,bufferController:n,capLevelController:o,errorController:l,fpsController:h,id3TrackController:d,iframeController:u,gapController:c}=r,f=new l(this),g=this.abrController=new i(this),p=new so(this),m=r.interstitialsController,T=m?this.interstitialsController=new m(this,Ot):null,E=n?this.bufferController=new n(this,p):null,v=o?this.capLevelController=new o(this):null,S=h?new h(this):null,L=r.cmcdController,R=L?this.cmcdController=new L(this):null,A=new Gl(this),b=r.contentSteeringController,k=b?new b(this):null,P=this.levelController=new Bl(this,k),M=d?new d(this):void 0,x=new Ul(this.config,this.logger),N=this.streamController=new s(this,p,x),U=this.gapController=c?new c(this,p):void 0;v&&v.setStreamController(N);const $=[A,P,N];T&&$.splice(1,0,T),k&&$.splice(1,0,k),this.networkControllers=$;const _=[g];E&&_.push(E),U&&_.push(U),v&&_.push(v),S&&(S.setStreamController(N),_.push(S)),M&&_.push(M),_.push(p),this.audioTrackController=this.createController(r.audioTrackController,$);const w=r.audioStreamController;w&&$.push(this.audioStreamController=new w(this,p,x)),this.subtitleTrackController=this.createController(r.subtitleTrackController,$);const O=r.subtitleStreamController;O&&$.push(this.subtititleStreamController=new O(this,p,x)),this.createController(r.timelineController,_),x.emeController=this.emeController=this.createController(r.emeController,_),R&&_.push(R),this.latencyController=this.createController(r.latencyController,_),this.coreComponents=_,this.iframeController=u?new u(this,Ot):void 0,$.push(f);const I=f.onErrorOut;typeof I=="function"&&this.on(y.ERROR,I,f),this.on(y.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,s){this._emitter.off(t,e,r,s)}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(r){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const s=t===y.ERROR;this.trigger(y.ERROR,{type:Y.OTHER_ERROR,details:D.INTERNAL_EXCEPTION,fatal:s,event:t,error:r}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(y.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.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 i=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger(y.ERROR,{type:Y.OTHER_ERROR,details:D.ATTACH_MEDIA_ERROR,fatal:!0,error:i});return}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,s=e?t:{media:r};this._media=r,this.trigger(y.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia");const t={};this.trigger(y.MEDIA_DETACHING,t),this._media=null,this.trigger(y.MEDIA_DETACHED,t)}transferMedia(){var t;this._media=null;const e=((t=this.bufferController)==null?void 0:t.transferMedia())||null,r={transferMedia:e};return this.trigger(y.MEDIA_DETACHING,r),this.trigger(y.MEDIA_DETACHED,r),e}loadSource(t){var e;this.stopLoad();const r=this.media,s=this._url,i=this._url=sr.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),r&&s&&(s!==i||(e=this.bufferController)!=null&&e.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(y.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!==F.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={[j.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[j.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[j.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=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=Ua()),t}get levels(){return this.levelController.levels||[]}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 t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(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){Rn(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}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 s=0;s<r;s++)if(t[s].maxBitrate>=e)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:r}=this;let s;if(e===-1&&t!=null&&t.length?s=t.length-1:s=e,r)for(let i=s;i--;){const n=t[i].attrs["HDCP-LEVEL"];if(n&&n<=r)return i}return s}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((t=this.audioStreamController)==null?void 0:t.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return((e=this.audioTrackController)==null?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return((e=this.subtitleTrackController)==null?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(t=(e=this.audioStreamController)==null?void 0:e.nextAudioTrack)!=null?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:!1}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(t=(e=this.latencyController)==null?void 0:e.liveSyncPosition)!=null?t:null}get latency(){var t;return((t=this.latencyController)==null?void 0:t.latency)||0}get maxLatency(){var t;return((t=this.latencyController)==null?void 0:t.maxLatency)||0}get targetLatency(){var t;return((t=this.latencyController)==null?void 0:t.targetLatency)||null}set targetLatency(t){this.latencyController&&(this.latencyController.targetLatency=t)}get drift(){var t;return((t=this.latencyController)==null?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!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){return null}get iframeVariants(){return this.levelController.iframeVariants||[]}createIFramePlayer(t){return null}createImageIFramePlayer(t){return null}getMediaDecodingInfo(t,e=this.allAudioTracks){const r=Ns(e);return Bt.getMediaDecodingInfoPromise(t,r,navigator.mediaCapabilities)}}Ot.defaultConfig=void 0,Bt.KeySystemFormats,Bt.KeySystems,Bt.SubtitleStreamController,Bt.TimelineController,Bt.requestMediaKeySystemAccess;export{Bs as AbrController,it as AttrList,Xt as AudioStreamController,Xt as AudioTrackController,jr as BaseLoader,pi as BasePlaylistController,ar as BaseSegment,Oi as BaseStreamController,Si as BufferController,Xt as CMCDController,tr as CapLevelController,Mr as ChunkMetadata,Mi as ContentSteeringController,Xt as Cues,Ir as DateRange,Xt as EMEController,ht as ErrorActionFlags,Vs as ErrorController,D as ErrorDetails,Y as ErrorTypes,y as Events,$i as FPSController,qr as FetchLoader,he as Fragment,Ot as Hls,pe as HlsSkip,Rr as HlsUrlParameters,br as Level,js as LevelDetails,ne as LevelKey,ir as LoadStats,Q as LoaderContextType,It as M3U8Parser,pt as MetadataSchema,ut as NetworkErrorAction,is as Part,j as PlaylistLevelType,Xt as SubtitleTrackController,zr as XhrLoader,Ot as default,ma as fetchSupported,Ut as getMediaSource,Yr as isMSESupported,ga as isSupported};
|
|
28
|
+
//# sourceMappingURL=hlsLight-CCe_8eOw.js.map
|